1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.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                       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   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
64                                                  VK_LValue, Loc, LocInfo);
65   if (HadMultipleCandidates)
66     DRE->setHadMultipleCandidates(true);
67 
68   S.MarkDeclRefReferenced(DRE);
69   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
70                              CK_FunctionToPointerDecay);
71 }
72 
73 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
74                                  bool InOverloadResolution,
75                                  StandardConversionSequence &SCS,
76                                  bool CStyle,
77                                  bool AllowObjCWritebackConversion);
78 
79 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
80                                                  QualType &ToType,
81                                                  bool InOverloadResolution,
82                                                  StandardConversionSequence &SCS,
83                                                  bool CStyle);
84 static OverloadingResult
85 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
86                         UserDefinedConversionSequence& User,
87                         OverloadCandidateSet& Conversions,
88                         bool AllowExplicit,
89                         bool AllowObjCConversionOnExplicit);
90 
91 
92 static ImplicitConversionSequence::CompareKind
93 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
94                                    const StandardConversionSequence& SCS1,
95                                    const StandardConversionSequence& SCS2);
96 
97 static ImplicitConversionSequence::CompareKind
98 CompareQualificationConversions(Sema &S,
99                                 const StandardConversionSequence& SCS1,
100                                 const StandardConversionSequence& SCS2);
101 
102 static ImplicitConversionSequence::CompareKind
103 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
104                                 const StandardConversionSequence& SCS1,
105                                 const StandardConversionSequence& SCS2);
106 
107 /// GetConversionRank - Retrieve the implicit conversion rank
108 /// corresponding to the given implicit conversion kind.
109 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
110   static const ImplicitConversionRank
111     Rank[(int)ICK_Num_Conversion_Kinds] = {
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Promotion,
119     ICR_Promotion,
120     ICR_Promotion,
121     ICR_Conversion,
122     ICR_Conversion,
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_Complex_Real_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Writeback_Conversion,
136     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
137                      // it was omitted by the patch that added
138                      // ICK_Zero_Event_Conversion
139     ICR_C_Conversion,
140     ICR_C_Conversion_Extension
141   };
142   return Rank[(int)Kind];
143 }
144 
145 /// GetImplicitConversionName - Return the name of this kind of
146 /// implicit conversion.
147 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
148   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
149     "No conversion",
150     "Lvalue-to-rvalue",
151     "Array-to-pointer",
152     "Function-to-pointer",
153     "Noreturn adjustment",
154     "Qualification",
155     "Integral promotion",
156     "Floating point promotion",
157     "Complex promotion",
158     "Integral conversion",
159     "Floating conversion",
160     "Complex conversion",
161     "Floating-integral conversion",
162     "Pointer conversion",
163     "Pointer-to-member conversion",
164     "Boolean conversion",
165     "Compatible-types conversion",
166     "Derived-to-base conversion",
167     "Vector conversion",
168     "Vector splat",
169     "Complex-real conversion",
170     "Block Pointer conversion",
171     "Transparent Union Conversion",
172     "Writeback conversion",
173     "OpenCL Zero Event Conversion",
174     "C specific type conversion",
175     "Incompatible pointer conversion"
176   };
177   return Name[Kind];
178 }
179 
180 /// StandardConversionSequence - Set the standard conversion
181 /// sequence to the identity conversion.
182 void StandardConversionSequence::setAsIdentityConversion() {
183   First = ICK_Identity;
184   Second = ICK_Identity;
185   Third = ICK_Identity;
186   DeprecatedStringLiteralToCharPtr = false;
187   QualificationIncludesObjCLifetime = false;
188   ReferenceBinding = false;
189   DirectBinding = false;
190   IsLvalueReference = true;
191   BindsToFunctionLvalue = false;
192   BindsToRvalue = false;
193   BindsImplicitObjectArgumentWithoutRefQualifier = false;
194   ObjCLifetimeConversionBinding = false;
195   CopyConstructor = nullptr;
196 }
197 
198 /// getRank - Retrieve the rank of this standard conversion sequence
199 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
200 /// implicit conversions.
201 ImplicitConversionRank StandardConversionSequence::getRank() const {
202   ImplicitConversionRank Rank = ICR_Exact_Match;
203   if  (GetConversionRank(First) > Rank)
204     Rank = GetConversionRank(First);
205   if  (GetConversionRank(Second) > Rank)
206     Rank = GetConversionRank(Second);
207   if  (GetConversionRank(Third) > Rank)
208     Rank = GetConversionRank(Third);
209   return Rank;
210 }
211 
212 /// isPointerConversionToBool - Determines whether this conversion is
213 /// a conversion of a pointer or pointer-to-member to bool. This is
214 /// used as part of the ranking of standard conversion sequences
215 /// (C++ 13.3.3.2p4).
216 bool StandardConversionSequence::isPointerConversionToBool() const {
217   // Note that FromType has not necessarily been transformed by the
218   // array-to-pointer or function-to-pointer implicit conversions, so
219   // check for their presence as well as checking whether FromType is
220   // a pointer.
221   if (getToType(1)->isBooleanType() &&
222       (getFromType()->isPointerType() ||
223        getFromType()->isObjCObjectPointerType() ||
224        getFromType()->isBlockPointerType() ||
225        getFromType()->isNullPtrType() ||
226        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
227     return true;
228 
229   return false;
230 }
231 
232 /// isPointerConversionToVoidPointer - Determines whether this
233 /// conversion is a conversion of a pointer to a void pointer. This is
234 /// used as part of the ranking of standard conversion sequences (C++
235 /// 13.3.3.2p4).
236 bool
237 StandardConversionSequence::
238 isPointerConversionToVoidPointer(ASTContext& Context) const {
239   QualType FromType = getFromType();
240   QualType ToType = getToType(1);
241 
242   // Note that FromType has not necessarily been transformed by the
243   // array-to-pointer implicit conversion, so check for its presence
244   // and redo the conversion to get a pointer.
245   if (First == ICK_Array_To_Pointer)
246     FromType = Context.getArrayDecayedType(FromType);
247 
248   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
249     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
250       return ToPtrType->getPointeeType()->isVoidType();
251 
252   return false;
253 }
254 
255 /// Skip any implicit casts which could be either part of a narrowing conversion
256 /// or after one in an implicit conversion.
257 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
258   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
259     switch (ICE->getCastKind()) {
260     case CK_NoOp:
261     case CK_IntegralCast:
262     case CK_IntegralToBoolean:
263     case CK_IntegralToFloating:
264     case CK_BooleanToSignedIntegral:
265     case CK_FloatingToIntegral:
266     case CK_FloatingToBoolean:
267     case CK_FloatingCast:
268       Converted = ICE->getSubExpr();
269       continue;
270 
271     default:
272       return Converted;
273     }
274   }
275 
276   return Converted;
277 }
278 
279 /// Check if this standard conversion sequence represents a narrowing
280 /// conversion, according to C++11 [dcl.init.list]p7.
281 ///
282 /// \param Ctx  The AST context.
283 /// \param Converted  The result of applying this standard conversion sequence.
284 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
285 ///        value of the expression prior to the narrowing conversion.
286 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
287 ///        type of the expression prior to the narrowing conversion.
288 NarrowingKind
289 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
290                                              const Expr *Converted,
291                                              APValue &ConstantValue,
292                                              QualType &ConstantType) const {
293   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
294 
295   // C++11 [dcl.init.list]p7:
296   //   A narrowing conversion is an implicit conversion ...
297   QualType FromType = getToType(0);
298   QualType ToType = getToType(1);
299 
300   // A conversion to an enumeration type is narrowing if the conversion to
301   // the underlying type is narrowing. This only arises for expressions of
302   // the form 'Enum{init}'.
303   if (auto *ET = ToType->getAs<EnumType>())
304     ToType = ET->getDecl()->getIntegerType();
305 
306   switch (Second) {
307   // 'bool' is an integral type; dispatch to the right place to handle it.
308   case ICK_Boolean_Conversion:
309     if (FromType->isRealFloatingType())
310       goto FloatingIntegralConversion;
311     if (FromType->isIntegralOrUnscopedEnumerationType())
312       goto IntegralConversion;
313     // Boolean conversions can be from pointers and pointers to members
314     // [conv.bool], and those aren't considered narrowing conversions.
315     return NK_Not_Narrowing;
316 
317   // -- from a floating-point type to an integer type, or
318   //
319   // -- from an integer type or unscoped enumeration type to a floating-point
320   //    type, except where the source is a constant expression and the actual
321   //    value after conversion will fit into the target type and will produce
322   //    the original value when converted back to the original type, or
323   case ICK_Floating_Integral:
324   FloatingIntegralConversion:
325     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
326       return NK_Type_Narrowing;
327     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
328       llvm::APSInt IntConstantValue;
329       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
330       if (Initializer &&
331           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
332         // Convert the integer to the floating type.
333         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
334         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
335                                 llvm::APFloat::rmNearestTiesToEven);
336         // And back.
337         llvm::APSInt ConvertedValue = IntConstantValue;
338         bool ignored;
339         Result.convertToInteger(ConvertedValue,
340                                 llvm::APFloat::rmTowardZero, &ignored);
341         // If the resulting value is different, this was a narrowing conversion.
342         if (IntConstantValue != ConvertedValue) {
343           ConstantValue = APValue(IntConstantValue);
344           ConstantType = Initializer->getType();
345           return NK_Constant_Narrowing;
346         }
347       } else {
348         // Variables are always narrowings.
349         return NK_Variable_Narrowing;
350       }
351     }
352     return NK_Not_Narrowing;
353 
354   // -- from long double to double or float, or from double to float, except
355   //    where the source is a constant expression and the actual value after
356   //    conversion is within the range of values that can be represented (even
357   //    if it cannot be represented exactly), or
358   case ICK_Floating_Conversion:
359     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
360         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
361       // FromType is larger than ToType.
362       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
363       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
364         // Constant!
365         assert(ConstantValue.isFloat());
366         llvm::APFloat FloatVal = ConstantValue.getFloat();
367         // Convert the source value into the target type.
368         bool ignored;
369         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
370           Ctx.getFloatTypeSemantics(ToType),
371           llvm::APFloat::rmNearestTiesToEven, &ignored);
372         // If there was no overflow, the source value is within the range of
373         // values that can be represented.
374         if (ConvertStatus & llvm::APFloat::opOverflow) {
375           ConstantType = Initializer->getType();
376           return NK_Constant_Narrowing;
377         }
378       } else {
379         return NK_Variable_Narrowing;
380       }
381     }
382     return NK_Not_Narrowing;
383 
384   // -- from an integer type or unscoped enumeration type to an integer type
385   //    that cannot represent all the values of the original type, except where
386   //    the source is a constant expression and the actual value after
387   //    conversion will fit into the target type and will produce the original
388   //    value when converted back to the original type.
389   case ICK_Integral_Conversion:
390   IntegralConversion: {
391     assert(FromType->isIntegralOrUnscopedEnumerationType());
392     assert(ToType->isIntegralOrUnscopedEnumerationType());
393     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
394     const unsigned FromWidth = Ctx.getIntWidth(FromType);
395     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
396     const unsigned ToWidth = Ctx.getIntWidth(ToType);
397 
398     if (FromWidth > ToWidth ||
399         (FromWidth == ToWidth && FromSigned != ToSigned) ||
400         (FromSigned && !ToSigned)) {
401       // Not all values of FromType can be represented in ToType.
402       llvm::APSInt InitializerValue;
403       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
404       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
405         // Such conversions on variables are always narrowing.
406         return NK_Variable_Narrowing;
407       }
408       bool Narrowing = false;
409       if (FromWidth < ToWidth) {
410         // Negative -> unsigned is narrowing. Otherwise, more bits is never
411         // narrowing.
412         if (InitializerValue.isSigned() && InitializerValue.isNegative())
413           Narrowing = true;
414       } else {
415         // Add a bit to the InitializerValue so we don't have to worry about
416         // signed vs. unsigned comparisons.
417         InitializerValue = InitializerValue.extend(
418           InitializerValue.getBitWidth() + 1);
419         // Convert the initializer to and from the target width and signed-ness.
420         llvm::APSInt ConvertedValue = InitializerValue;
421         ConvertedValue = ConvertedValue.trunc(ToWidth);
422         ConvertedValue.setIsSigned(ToSigned);
423         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
424         ConvertedValue.setIsSigned(InitializerValue.isSigned());
425         // If the result is different, this was a narrowing conversion.
426         if (ConvertedValue != InitializerValue)
427           Narrowing = true;
428       }
429       if (Narrowing) {
430         ConstantType = Initializer->getType();
431         ConstantValue = APValue(InitializerValue);
432         return NK_Constant_Narrowing;
433       }
434     }
435     return NK_Not_Narrowing;
436   }
437 
438   default:
439     // Other kinds of conversions are not narrowings.
440     return NK_Not_Narrowing;
441   }
442 }
443 
444 /// dump - Print this standard conversion sequence to standard
445 /// error. Useful for debugging overloading issues.
446 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
447   raw_ostream &OS = llvm::errs();
448   bool PrintedSomething = false;
449   if (First != ICK_Identity) {
450     OS << GetImplicitConversionName(First);
451     PrintedSomething = true;
452   }
453 
454   if (Second != ICK_Identity) {
455     if (PrintedSomething) {
456       OS << " -> ";
457     }
458     OS << GetImplicitConversionName(Second);
459 
460     if (CopyConstructor) {
461       OS << " (by copy constructor)";
462     } else if (DirectBinding) {
463       OS << " (direct reference binding)";
464     } else if (ReferenceBinding) {
465       OS << " (reference binding)";
466     }
467     PrintedSomething = true;
468   }
469 
470   if (Third != ICK_Identity) {
471     if (PrintedSomething) {
472       OS << " -> ";
473     }
474     OS << GetImplicitConversionName(Third);
475     PrintedSomething = true;
476   }
477 
478   if (!PrintedSomething) {
479     OS << "No conversions required";
480   }
481 }
482 
483 /// dump - Print this user-defined conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 void UserDefinedConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   if (Before.First || Before.Second || Before.Third) {
488     Before.dump();
489     OS << " -> ";
490   }
491   if (ConversionFunction)
492     OS << '\'' << *ConversionFunction << '\'';
493   else
494     OS << "aggregate initialization";
495   if (After.First || After.Second || After.Third) {
496     OS << " -> ";
497     After.dump();
498   }
499 }
500 
501 /// dump - Print this implicit conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void ImplicitConversionSequence::dump() const {
504   raw_ostream &OS = llvm::errs();
505   if (isStdInitializerListElement())
506     OS << "Worst std::initializer_list element conversion: ";
507   switch (ConversionKind) {
508   case StandardConversion:
509     OS << "Standard conversion: ";
510     Standard.dump();
511     break;
512   case UserDefinedConversion:
513     OS << "User-defined conversion: ";
514     UserDefined.dump();
515     break;
516   case EllipsisConversion:
517     OS << "Ellipsis conversion";
518     break;
519   case AmbiguousConversion:
520     OS << "Ambiguous conversion";
521     break;
522   case BadConversion:
523     OS << "Bad conversion";
524     break;
525   }
526 
527   OS << "\n";
528 }
529 
530 void AmbiguousConversionSequence::construct() {
531   new (&conversions()) ConversionSet();
532 }
533 
534 void AmbiguousConversionSequence::destruct() {
535   conversions().~ConversionSet();
536 }
537 
538 void
539 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
540   FromTypePtr = O.FromTypePtr;
541   ToTypePtr = O.ToTypePtr;
542   new (&conversions()) ConversionSet(O.conversions());
543 }
544 
545 namespace {
546   // Structure used by DeductionFailureInfo to store
547   // template argument information.
548   struct DFIArguments {
549     TemplateArgument FirstArg;
550     TemplateArgument SecondArg;
551   };
552   // Structure used by DeductionFailureInfo to store
553   // template parameter and template argument information.
554   struct DFIParamWithArguments : DFIArguments {
555     TemplateParameter Param;
556   };
557   // Structure used by DeductionFailureInfo to store template argument
558   // information and the index of the problematic call argument.
559   struct DFIDeducedMismatchArgs : DFIArguments {
560     TemplateArgumentList *TemplateArgs;
561     unsigned CallArgIndex;
562   };
563 }
564 
565 /// \brief Convert from Sema's representation of template deduction information
566 /// to the form used in overload-candidate information.
567 DeductionFailureInfo
568 clang::MakeDeductionFailureInfo(ASTContext &Context,
569                                 Sema::TemplateDeductionResult TDK,
570                                 TemplateDeductionInfo &Info) {
571   DeductionFailureInfo Result;
572   Result.Result = static_cast<unsigned>(TDK);
573   Result.HasDiagnostic = false;
574   switch (TDK) {
575   case Sema::TDK_Success:
576   case Sema::TDK_Invalid:
577   case Sema::TDK_InstantiationDepth:
578   case Sema::TDK_TooManyArguments:
579   case Sema::TDK_TooFewArguments:
580   case Sema::TDK_MiscellaneousDeductionFailure:
581     Result.Data = nullptr;
582     break;
583 
584   case Sema::TDK_Incomplete:
585   case Sema::TDK_InvalidExplicitArguments:
586     Result.Data = Info.Param.getOpaqueValue();
587     break;
588 
589   case Sema::TDK_DeducedMismatch: {
590     // FIXME: Should allocate from normal heap so that we can free this later.
591     auto *Saved = new (Context) DFIDeducedMismatchArgs;
592     Saved->FirstArg = Info.FirstArg;
593     Saved->SecondArg = Info.SecondArg;
594     Saved->TemplateArgs = Info.take();
595     Saved->CallArgIndex = Info.CallArgIndex;
596     Result.Data = Saved;
597     break;
598   }
599 
600   case Sema::TDK_NonDeducedMismatch: {
601     // FIXME: Should allocate from normal heap so that we can free this later.
602     DFIArguments *Saved = new (Context) DFIArguments;
603     Saved->FirstArg = Info.FirstArg;
604     Saved->SecondArg = Info.SecondArg;
605     Result.Data = Saved;
606     break;
607   }
608 
609   case Sema::TDK_Inconsistent:
610   case Sema::TDK_Underqualified: {
611     // FIXME: Should allocate from normal heap so that we can free this later.
612     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
613     Saved->Param = Info.Param;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Result.Data = Saved;
617     break;
618   }
619 
620   case Sema::TDK_SubstitutionFailure:
621     Result.Data = Info.take();
622     if (Info.hasSFINAEDiagnostic()) {
623       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
624           SourceLocation(), PartialDiagnostic::NullDiagnostic());
625       Info.takeSFINAEDiagnostic(*Diag);
626       Result.HasDiagnostic = true;
627     }
628     break;
629 
630   case Sema::TDK_FailedOverloadResolution:
631     Result.Data = Info.Expression;
632     break;
633   }
634 
635   return Result;
636 }
637 
638 void DeductionFailureInfo::Destroy() {
639   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
640   case Sema::TDK_Success:
641   case Sema::TDK_Invalid:
642   case Sema::TDK_InstantiationDepth:
643   case Sema::TDK_Incomplete:
644   case Sema::TDK_TooManyArguments:
645   case Sema::TDK_TooFewArguments:
646   case Sema::TDK_InvalidExplicitArguments:
647   case Sema::TDK_FailedOverloadResolution:
648     break;
649 
650   case Sema::TDK_Inconsistent:
651   case Sema::TDK_Underqualified:
652   case Sema::TDK_DeducedMismatch:
653   case Sema::TDK_NonDeducedMismatch:
654     // FIXME: Destroy the data?
655     Data = nullptr;
656     break;
657 
658   case Sema::TDK_SubstitutionFailure:
659     // FIXME: Destroy the template argument list?
660     Data = nullptr;
661     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
662       Diag->~PartialDiagnosticAt();
663       HasDiagnostic = false;
664     }
665     break;
666 
667   // Unhandled
668   case Sema::TDK_MiscellaneousDeductionFailure:
669     break;
670   }
671 }
672 
673 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
674   if (HasDiagnostic)
675     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
676   return nullptr;
677 }
678 
679 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
680   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
681   case Sema::TDK_Success:
682   case Sema::TDK_Invalid:
683   case Sema::TDK_InstantiationDepth:
684   case Sema::TDK_TooManyArguments:
685   case Sema::TDK_TooFewArguments:
686   case Sema::TDK_SubstitutionFailure:
687   case Sema::TDK_DeducedMismatch:
688   case Sema::TDK_NonDeducedMismatch:
689   case Sema::TDK_FailedOverloadResolution:
690     return TemplateParameter();
691 
692   case Sema::TDK_Incomplete:
693   case Sema::TDK_InvalidExplicitArguments:
694     return TemplateParameter::getFromOpaqueValue(Data);
695 
696   case Sema::TDK_Inconsistent:
697   case Sema::TDK_Underqualified:
698     return static_cast<DFIParamWithArguments*>(Data)->Param;
699 
700   // Unhandled
701   case Sema::TDK_MiscellaneousDeductionFailure:
702     break;
703   }
704 
705   return TemplateParameter();
706 }
707 
708 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
709   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
710   case Sema::TDK_Success:
711   case Sema::TDK_Invalid:
712   case Sema::TDK_InstantiationDepth:
713   case Sema::TDK_TooManyArguments:
714   case Sema::TDK_TooFewArguments:
715   case Sema::TDK_Incomplete:
716   case Sema::TDK_InvalidExplicitArguments:
717   case Sema::TDK_Inconsistent:
718   case Sema::TDK_Underqualified:
719   case Sema::TDK_NonDeducedMismatch:
720   case Sema::TDK_FailedOverloadResolution:
721     return nullptr;
722 
723   case Sema::TDK_DeducedMismatch:
724     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
725 
726   case Sema::TDK_SubstitutionFailure:
727     return static_cast<TemplateArgumentList*>(Data);
728 
729   // Unhandled
730   case Sema::TDK_MiscellaneousDeductionFailure:
731     break;
732   }
733 
734   return nullptr;
735 }
736 
737 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
738   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
739   case Sema::TDK_Success:
740   case Sema::TDK_Invalid:
741   case Sema::TDK_InstantiationDepth:
742   case Sema::TDK_Incomplete:
743   case Sema::TDK_TooManyArguments:
744   case Sema::TDK_TooFewArguments:
745   case Sema::TDK_InvalidExplicitArguments:
746   case Sema::TDK_SubstitutionFailure:
747   case Sema::TDK_FailedOverloadResolution:
748     return nullptr;
749 
750   case Sema::TDK_Inconsistent:
751   case Sema::TDK_Underqualified:
752   case Sema::TDK_DeducedMismatch:
753   case Sema::TDK_NonDeducedMismatch:
754     return &static_cast<DFIArguments*>(Data)->FirstArg;
755 
756   // Unhandled
757   case Sema::TDK_MiscellaneousDeductionFailure:
758     break;
759   }
760 
761   return nullptr;
762 }
763 
764 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
765   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
766   case Sema::TDK_Success:
767   case Sema::TDK_Invalid:
768   case Sema::TDK_InstantiationDepth:
769   case Sema::TDK_Incomplete:
770   case Sema::TDK_TooManyArguments:
771   case Sema::TDK_TooFewArguments:
772   case Sema::TDK_InvalidExplicitArguments:
773   case Sema::TDK_SubstitutionFailure:
774   case Sema::TDK_FailedOverloadResolution:
775     return nullptr;
776 
777   case Sema::TDK_Inconsistent:
778   case Sema::TDK_Underqualified:
779   case Sema::TDK_DeducedMismatch:
780   case Sema::TDK_NonDeducedMismatch:
781     return &static_cast<DFIArguments*>(Data)->SecondArg;
782 
783   // Unhandled
784   case Sema::TDK_MiscellaneousDeductionFailure:
785     break;
786   }
787 
788   return nullptr;
789 }
790 
791 Expr *DeductionFailureInfo::getExpr() {
792   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
793         Sema::TDK_FailedOverloadResolution)
794     return static_cast<Expr*>(Data);
795 
796   return nullptr;
797 }
798 
799 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
800   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
801         Sema::TDK_DeducedMismatch)
802     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
803 
804   return llvm::None;
805 }
806 
807 void OverloadCandidateSet::destroyCandidates() {
808   for (iterator i = begin(), e = end(); i != e; ++i) {
809     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
810       i->Conversions[ii].~ImplicitConversionSequence();
811     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
812       i->DeductionFailure.Destroy();
813   }
814 }
815 
816 void OverloadCandidateSet::clear() {
817   destroyCandidates();
818   NumInlineSequences = 0;
819   Candidates.clear();
820   Functions.clear();
821 }
822 
823 namespace {
824   class UnbridgedCastsSet {
825     struct Entry {
826       Expr **Addr;
827       Expr *Saved;
828     };
829     SmallVector<Entry, 2> Entries;
830 
831   public:
832     void save(Sema &S, Expr *&E) {
833       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
834       Entry entry = { &E, E };
835       Entries.push_back(entry);
836       E = S.stripARCUnbridgedCast(E);
837     }
838 
839     void restore() {
840       for (SmallVectorImpl<Entry>::iterator
841              i = Entries.begin(), e = Entries.end(); i != e; ++i)
842         *i->Addr = i->Saved;
843     }
844   };
845 }
846 
847 /// checkPlaceholderForOverload - Do any interesting placeholder-like
848 /// preprocessing on the given expression.
849 ///
850 /// \param unbridgedCasts a collection to which to add unbridged casts;
851 ///   without this, they will be immediately diagnosed as errors
852 ///
853 /// Return true on unrecoverable error.
854 static bool
855 checkPlaceholderForOverload(Sema &S, Expr *&E,
856                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
857   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
858     // We can't handle overloaded expressions here because overload
859     // resolution might reasonably tweak them.
860     if (placeholder->getKind() == BuiltinType::Overload) return false;
861 
862     // If the context potentially accepts unbridged ARC casts, strip
863     // the unbridged cast and add it to the collection for later restoration.
864     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
865         unbridgedCasts) {
866       unbridgedCasts->save(S, E);
867       return false;
868     }
869 
870     // Go ahead and check everything else.
871     ExprResult result = S.CheckPlaceholderExpr(E);
872     if (result.isInvalid())
873       return true;
874 
875     E = result.get();
876     return false;
877   }
878 
879   // Nothing to do.
880   return false;
881 }
882 
883 /// checkArgPlaceholdersForOverload - Check a set of call operands for
884 /// placeholders.
885 static bool checkArgPlaceholdersForOverload(Sema &S,
886                                             MultiExprArg Args,
887                                             UnbridgedCastsSet &unbridged) {
888   for (unsigned i = 0, e = Args.size(); i != e; ++i)
889     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
890       return true;
891 
892   return false;
893 }
894 
895 // IsOverload - Determine whether the given New declaration is an
896 // overload of the declarations in Old. This routine returns false if
897 // New and Old cannot be overloaded, e.g., if New has the same
898 // signature as some function in Old (C++ 1.3.10) or if the Old
899 // declarations aren't functions (or function templates) at all. When
900 // it does return false, MatchedDecl will point to the decl that New
901 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
902 // top of the underlying declaration.
903 //
904 // Example: Given the following input:
905 //
906 //   void f(int, float); // #1
907 //   void f(int, int); // #2
908 //   int f(int, int); // #3
909 //
910 // When we process #1, there is no previous declaration of "f",
911 // so IsOverload will not be used.
912 //
913 // When we process #2, Old contains only the FunctionDecl for #1.  By
914 // comparing the parameter types, we see that #1 and #2 are overloaded
915 // (since they have different signatures), so this routine returns
916 // false; MatchedDecl is unchanged.
917 //
918 // When we process #3, Old is an overload set containing #1 and #2. We
919 // compare the signatures of #3 to #1 (they're overloaded, so we do
920 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
921 // identical (return types of functions are not part of the
922 // signature), IsOverload returns false and MatchedDecl will be set to
923 // point to the FunctionDecl for #2.
924 //
925 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
926 // into a class by a using declaration.  The rules for whether to hide
927 // shadow declarations ignore some properties which otherwise figure
928 // into a function template's signature.
929 Sema::OverloadKind
930 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
931                     NamedDecl *&Match, bool NewIsUsingDecl) {
932   for (LookupResult::iterator I = Old.begin(), E = Old.end();
933          I != E; ++I) {
934     NamedDecl *OldD = *I;
935 
936     bool OldIsUsingDecl = false;
937     if (isa<UsingShadowDecl>(OldD)) {
938       OldIsUsingDecl = true;
939 
940       // We can always introduce two using declarations into the same
941       // context, even if they have identical signatures.
942       if (NewIsUsingDecl) continue;
943 
944       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
945     }
946 
947     // A using-declaration does not conflict with another declaration
948     // if one of them is hidden.
949     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
950       continue;
951 
952     // If either declaration was introduced by a using declaration,
953     // we'll need to use slightly different rules for matching.
954     // Essentially, these rules are the normal rules, except that
955     // function templates hide function templates with different
956     // return types or template parameter lists.
957     bool UseMemberUsingDeclRules =
958       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
959       !New->getFriendObjectKind();
960 
961     if (FunctionDecl *OldF = OldD->getAsFunction()) {
962       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
963         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
964           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
965           continue;
966         }
967 
968         if (!isa<FunctionTemplateDecl>(OldD) &&
969             !shouldLinkPossiblyHiddenDecl(*I, New))
970           continue;
971 
972         Match = *I;
973         return Ovl_Match;
974       }
975     } else if (isa<UsingDecl>(OldD)) {
976       // We can overload with these, which can show up when doing
977       // redeclaration checks for UsingDecls.
978       assert(Old.getLookupKind() == LookupUsingDeclName);
979     } else if (isa<TagDecl>(OldD)) {
980       // We can always overload with tags by hiding them.
981     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
982       // Optimistically assume that an unresolved using decl will
983       // overload; if it doesn't, we'll have to diagnose during
984       // template instantiation.
985     } else {
986       // (C++ 13p1):
987       //   Only function declarations can be overloaded; object and type
988       //   declarations cannot be overloaded.
989       Match = *I;
990       return Ovl_NonFunction;
991     }
992   }
993 
994   return Ovl_Overload;
995 }
996 
997 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
998                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
999   // C++ [basic.start.main]p2: This function shall not be overloaded.
1000   if (New->isMain())
1001     return false;
1002 
1003   // MSVCRT user defined entry points cannot be overloaded.
1004   if (New->isMSVCRTEntryPoint())
1005     return false;
1006 
1007   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1008   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1009 
1010   // C++ [temp.fct]p2:
1011   //   A function template can be overloaded with other function templates
1012   //   and with normal (non-template) functions.
1013   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1014     return true;
1015 
1016   // Is the function New an overload of the function Old?
1017   QualType OldQType = Context.getCanonicalType(Old->getType());
1018   QualType NewQType = Context.getCanonicalType(New->getType());
1019 
1020   // Compare the signatures (C++ 1.3.10) of the two functions to
1021   // determine whether they are overloads. If we find any mismatch
1022   // in the signature, they are overloads.
1023 
1024   // If either of these functions is a K&R-style function (no
1025   // prototype), then we consider them to have matching signatures.
1026   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1027       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1028     return false;
1029 
1030   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1031   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1032 
1033   // The signature of a function includes the types of its
1034   // parameters (C++ 1.3.10), which includes the presence or absence
1035   // of the ellipsis; see C++ DR 357).
1036   if (OldQType != NewQType &&
1037       (OldType->getNumParams() != NewType->getNumParams() ||
1038        OldType->isVariadic() != NewType->isVariadic() ||
1039        !FunctionParamTypesAreEqual(OldType, NewType)))
1040     return true;
1041 
1042   // C++ [temp.over.link]p4:
1043   //   The signature of a function template consists of its function
1044   //   signature, its return type and its template parameter list. The names
1045   //   of the template parameters are significant only for establishing the
1046   //   relationship between the template parameters and the rest of the
1047   //   signature.
1048   //
1049   // We check the return type and template parameter lists for function
1050   // templates first; the remaining checks follow.
1051   //
1052   // However, we don't consider either of these when deciding whether
1053   // a member introduced by a shadow declaration is hidden.
1054   if (!UseMemberUsingDeclRules && NewTemplate &&
1055       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1056                                        OldTemplate->getTemplateParameters(),
1057                                        false, TPL_TemplateMatch) ||
1058        OldType->getReturnType() != NewType->getReturnType()))
1059     return true;
1060 
1061   // If the function is a class member, its signature includes the
1062   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1063   //
1064   // As part of this, also check whether one of the member functions
1065   // is static, in which case they are not overloads (C++
1066   // 13.1p2). While not part of the definition of the signature,
1067   // this check is important to determine whether these functions
1068   // can be overloaded.
1069   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1070   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1071   if (OldMethod && NewMethod &&
1072       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1073     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1074       if (!UseMemberUsingDeclRules &&
1075           (OldMethod->getRefQualifier() == RQ_None ||
1076            NewMethod->getRefQualifier() == RQ_None)) {
1077         // C++0x [over.load]p2:
1078         //   - Member function declarations with the same name and the same
1079         //     parameter-type-list as well as member function template
1080         //     declarations with the same name, the same parameter-type-list, and
1081         //     the same template parameter lists cannot be overloaded if any of
1082         //     them, but not all, have a ref-qualifier (8.3.5).
1083         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1084           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1085         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1086       }
1087       return true;
1088     }
1089 
1090     // We may not have applied the implicit const for a constexpr member
1091     // function yet (because we haven't yet resolved whether this is a static
1092     // or non-static member function). Add it now, on the assumption that this
1093     // is a redeclaration of OldMethod.
1094     unsigned OldQuals = OldMethod->getTypeQualifiers();
1095     unsigned NewQuals = NewMethod->getTypeQualifiers();
1096     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1097         !isa<CXXConstructorDecl>(NewMethod))
1098       NewQuals |= Qualifiers::Const;
1099 
1100     // We do not allow overloading based off of '__restrict'.
1101     OldQuals &= ~Qualifiers::Restrict;
1102     NewQuals &= ~Qualifiers::Restrict;
1103     if (OldQuals != NewQuals)
1104       return true;
1105   }
1106 
1107   // Though pass_object_size is placed on parameters and takes an argument, we
1108   // consider it to be a function-level modifier for the sake of function
1109   // identity. Either the function has one or more parameters with
1110   // pass_object_size or it doesn't.
1111   if (functionHasPassObjectSizeParams(New) !=
1112       functionHasPassObjectSizeParams(Old))
1113     return true;
1114 
1115   // enable_if attributes are an order-sensitive part of the signature.
1116   for (specific_attr_iterator<EnableIfAttr>
1117          NewI = New->specific_attr_begin<EnableIfAttr>(),
1118          NewE = New->specific_attr_end<EnableIfAttr>(),
1119          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1120          OldE = Old->specific_attr_end<EnableIfAttr>();
1121        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1122     if (NewI == NewE || OldI == OldE)
1123       return true;
1124     llvm::FoldingSetNodeID NewID, OldID;
1125     NewI->getCond()->Profile(NewID, Context, true);
1126     OldI->getCond()->Profile(OldID, Context, true);
1127     if (NewID != OldID)
1128       return true;
1129   }
1130 
1131   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1132     // Don't allow overloading of destructors.  (In theory we could, but it
1133     // would be a giant change to clang.)
1134     if (isa<CXXDestructorDecl>(New))
1135       return false;
1136 
1137     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1138                        OldTarget = IdentifyCUDATarget(Old);
1139     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1140       return false;
1141 
1142     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1143 
1144     // Don't allow HD and global functions to overload other functions with the
1145     // same signature.  We allow overloading based on CUDA attributes so that
1146     // functions can have different implementations on the host and device, but
1147     // HD/global functions "exist" in some sense on both the host and device, so
1148     // should have the same implementation on both sides.
1149     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1150         (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1151       return false;
1152 
1153     // Allow overloading of functions with same signature and different CUDA
1154     // target attributes.
1155     return NewTarget != OldTarget;
1156   }
1157 
1158   // The signatures match; this is not an overload.
1159   return false;
1160 }
1161 
1162 /// \brief Checks availability of the function depending on the current
1163 /// function context. Inside an unavailable function, unavailability is ignored.
1164 ///
1165 /// \returns true if \arg FD is unavailable and current context is inside
1166 /// an available function, false otherwise.
1167 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1168   if (!FD->isUnavailable())
1169     return false;
1170 
1171   // Walk up the context of the caller.
1172   Decl *C = cast<Decl>(CurContext);
1173   do {
1174     if (C->isUnavailable())
1175       return false;
1176   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1177   return true;
1178 }
1179 
1180 /// \brief Tries a user-defined conversion from From to ToType.
1181 ///
1182 /// Produces an implicit conversion sequence for when a standard conversion
1183 /// is not an option. See TryImplicitConversion for more information.
1184 static ImplicitConversionSequence
1185 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1186                          bool SuppressUserConversions,
1187                          bool AllowExplicit,
1188                          bool InOverloadResolution,
1189                          bool CStyle,
1190                          bool AllowObjCWritebackConversion,
1191                          bool AllowObjCConversionOnExplicit) {
1192   ImplicitConversionSequence ICS;
1193 
1194   if (SuppressUserConversions) {
1195     // We're not in the case above, so there is no conversion that
1196     // we can perform.
1197     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1198     return ICS;
1199   }
1200 
1201   // Attempt user-defined conversion.
1202   OverloadCandidateSet Conversions(From->getExprLoc(),
1203                                    OverloadCandidateSet::CSK_Normal);
1204   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1205                                   Conversions, AllowExplicit,
1206                                   AllowObjCConversionOnExplicit)) {
1207   case OR_Success:
1208   case OR_Deleted:
1209     ICS.setUserDefined();
1210     // C++ [over.ics.user]p4:
1211     //   A conversion of an expression of class type to the same class
1212     //   type is given Exact Match rank, and a conversion of an
1213     //   expression of class type to a base class of that type is
1214     //   given Conversion rank, in spite of the fact that a copy
1215     //   constructor (i.e., a user-defined conversion function) is
1216     //   called for those cases.
1217     if (CXXConstructorDecl *Constructor
1218           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1219       QualType FromCanon
1220         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1221       QualType ToCanon
1222         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1223       if (Constructor->isCopyConstructor() &&
1224           (FromCanon == ToCanon ||
1225            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1226         // Turn this into a "standard" conversion sequence, so that it
1227         // gets ranked with standard conversion sequences.
1228         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1229         ICS.setStandard();
1230         ICS.Standard.setAsIdentityConversion();
1231         ICS.Standard.setFromType(From->getType());
1232         ICS.Standard.setAllToTypes(ToType);
1233         ICS.Standard.CopyConstructor = Constructor;
1234         ICS.Standard.FoundCopyConstructor = Found;
1235         if (ToCanon != FromCanon)
1236           ICS.Standard.Second = ICK_Derived_To_Base;
1237       }
1238     }
1239     break;
1240 
1241   case OR_Ambiguous:
1242     ICS.setAmbiguous();
1243     ICS.Ambiguous.setFromType(From->getType());
1244     ICS.Ambiguous.setToType(ToType);
1245     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1246          Cand != Conversions.end(); ++Cand)
1247       if (Cand->Viable)
1248         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1249     break;
1250 
1251     // Fall through.
1252   case OR_No_Viable_Function:
1253     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1254     break;
1255   }
1256 
1257   return ICS;
1258 }
1259 
1260 /// TryImplicitConversion - Attempt to perform an implicit conversion
1261 /// from the given expression (Expr) to the given type (ToType). This
1262 /// function returns an implicit conversion sequence that can be used
1263 /// to perform the initialization. Given
1264 ///
1265 ///   void f(float f);
1266 ///   void g(int i) { f(i); }
1267 ///
1268 /// this routine would produce an implicit conversion sequence to
1269 /// describe the initialization of f from i, which will be a standard
1270 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1271 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1272 //
1273 /// Note that this routine only determines how the conversion can be
1274 /// performed; it does not actually perform the conversion. As such,
1275 /// it will not produce any diagnostics if no conversion is available,
1276 /// but will instead return an implicit conversion sequence of kind
1277 /// "BadConversion".
1278 ///
1279 /// If @p SuppressUserConversions, then user-defined conversions are
1280 /// not permitted.
1281 /// If @p AllowExplicit, then explicit user-defined conversions are
1282 /// permitted.
1283 ///
1284 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1285 /// writeback conversion, which allows __autoreleasing id* parameters to
1286 /// be initialized with __strong id* or __weak id* arguments.
1287 static ImplicitConversionSequence
1288 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1289                       bool SuppressUserConversions,
1290                       bool AllowExplicit,
1291                       bool InOverloadResolution,
1292                       bool CStyle,
1293                       bool AllowObjCWritebackConversion,
1294                       bool AllowObjCConversionOnExplicit) {
1295   ImplicitConversionSequence ICS;
1296   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1297                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1298     ICS.setStandard();
1299     return ICS;
1300   }
1301 
1302   if (!S.getLangOpts().CPlusPlus) {
1303     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1304     return ICS;
1305   }
1306 
1307   // C++ [over.ics.user]p4:
1308   //   A conversion of an expression of class type to the same class
1309   //   type is given Exact Match rank, and a conversion of an
1310   //   expression of class type to a base class of that type is
1311   //   given Conversion rank, in spite of the fact that a copy/move
1312   //   constructor (i.e., a user-defined conversion function) is
1313   //   called for those cases.
1314   QualType FromType = From->getType();
1315   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1316       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1317        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1318     ICS.setStandard();
1319     ICS.Standard.setAsIdentityConversion();
1320     ICS.Standard.setFromType(FromType);
1321     ICS.Standard.setAllToTypes(ToType);
1322 
1323     // We don't actually check at this point whether there is a valid
1324     // copy/move constructor, since overloading just assumes that it
1325     // exists. When we actually perform initialization, we'll find the
1326     // appropriate constructor to copy the returned object, if needed.
1327     ICS.Standard.CopyConstructor = nullptr;
1328 
1329     // Determine whether this is considered a derived-to-base conversion.
1330     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1331       ICS.Standard.Second = ICK_Derived_To_Base;
1332 
1333     return ICS;
1334   }
1335 
1336   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1337                                   AllowExplicit, InOverloadResolution, CStyle,
1338                                   AllowObjCWritebackConversion,
1339                                   AllowObjCConversionOnExplicit);
1340 }
1341 
1342 ImplicitConversionSequence
1343 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1344                             bool SuppressUserConversions,
1345                             bool AllowExplicit,
1346                             bool InOverloadResolution,
1347                             bool CStyle,
1348                             bool AllowObjCWritebackConversion) {
1349   return ::TryImplicitConversion(*this, From, ToType,
1350                                  SuppressUserConversions, AllowExplicit,
1351                                  InOverloadResolution, CStyle,
1352                                  AllowObjCWritebackConversion,
1353                                  /*AllowObjCConversionOnExplicit=*/false);
1354 }
1355 
1356 /// PerformImplicitConversion - Perform an implicit conversion of the
1357 /// expression From to the type ToType. Returns the
1358 /// converted expression. Flavor is the kind of conversion we're
1359 /// performing, used in the error message. If @p AllowExplicit,
1360 /// explicit user-defined conversions are permitted.
1361 ExprResult
1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1363                                 AssignmentAction Action, bool AllowExplicit) {
1364   ImplicitConversionSequence ICS;
1365   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1366 }
1367 
1368 ExprResult
1369 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1370                                 AssignmentAction Action, bool AllowExplicit,
1371                                 ImplicitConversionSequence& ICS) {
1372   if (checkPlaceholderForOverload(*this, From))
1373     return ExprError();
1374 
1375   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1376   bool AllowObjCWritebackConversion
1377     = getLangOpts().ObjCAutoRefCount &&
1378       (Action == AA_Passing || Action == AA_Sending);
1379   if (getLangOpts().ObjC1)
1380     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1381                                       ToType, From->getType(), From);
1382   ICS = ::TryImplicitConversion(*this, From, ToType,
1383                                 /*SuppressUserConversions=*/false,
1384                                 AllowExplicit,
1385                                 /*InOverloadResolution=*/false,
1386                                 /*CStyle=*/false,
1387                                 AllowObjCWritebackConversion,
1388                                 /*AllowObjCConversionOnExplicit=*/false);
1389   return PerformImplicitConversion(From, ToType, ICS, Action);
1390 }
1391 
1392 /// \brief Determine whether the conversion from FromType to ToType is a valid
1393 /// conversion that strips "noreturn" off the nested function type.
1394 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1395                                 QualType &ResultTy) {
1396   if (Context.hasSameUnqualifiedType(FromType, ToType))
1397     return false;
1398 
1399   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1400   // where F adds one of the following at most once:
1401   //   - a pointer
1402   //   - a member pointer
1403   //   - a block pointer
1404   CanQualType CanTo = Context.getCanonicalType(ToType);
1405   CanQualType CanFrom = Context.getCanonicalType(FromType);
1406   Type::TypeClass TyClass = CanTo->getTypeClass();
1407   if (TyClass != CanFrom->getTypeClass()) return false;
1408   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1409     if (TyClass == Type::Pointer) {
1410       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1411       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1412     } else if (TyClass == Type::BlockPointer) {
1413       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1414       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1415     } else if (TyClass == Type::MemberPointer) {
1416       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1417       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1418     } else {
1419       return false;
1420     }
1421 
1422     TyClass = CanTo->getTypeClass();
1423     if (TyClass != CanFrom->getTypeClass()) return false;
1424     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1425       return false;
1426   }
1427 
1428   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1429   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1430   if (!EInfo.getNoReturn()) return false;
1431 
1432   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1433   assert(QualType(FromFn, 0).isCanonical());
1434   if (QualType(FromFn, 0) != CanTo) return false;
1435 
1436   ResultTy = ToType;
1437   return true;
1438 }
1439 
1440 /// \brief Determine whether the conversion from FromType to ToType is a valid
1441 /// vector conversion.
1442 ///
1443 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1444 /// conversion.
1445 static bool IsVectorConversion(Sema &S, QualType FromType,
1446                                QualType ToType, ImplicitConversionKind &ICK) {
1447   // We need at least one of these types to be a vector type to have a vector
1448   // conversion.
1449   if (!ToType->isVectorType() && !FromType->isVectorType())
1450     return false;
1451 
1452   // Identical types require no conversions.
1453   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1454     return false;
1455 
1456   // There are no conversions between extended vector types, only identity.
1457   if (ToType->isExtVectorType()) {
1458     // There are no conversions between extended vector types other than the
1459     // identity conversion.
1460     if (FromType->isExtVectorType())
1461       return false;
1462 
1463     // Vector splat from any arithmetic type to a vector.
1464     if (FromType->isArithmeticType()) {
1465       ICK = ICK_Vector_Splat;
1466       return true;
1467     }
1468   }
1469 
1470   // We can perform the conversion between vector types in the following cases:
1471   // 1)vector types are equivalent AltiVec and GCC vector types
1472   // 2)lax vector conversions are permitted and the vector types are of the
1473   //   same size
1474   if (ToType->isVectorType() && FromType->isVectorType()) {
1475     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1476         S.isLaxVectorConversion(FromType, ToType)) {
1477       ICK = ICK_Vector_Conversion;
1478       return true;
1479     }
1480   }
1481 
1482   return false;
1483 }
1484 
1485 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1486                                 bool InOverloadResolution,
1487                                 StandardConversionSequence &SCS,
1488                                 bool CStyle);
1489 
1490 /// IsStandardConversion - Determines whether there is a standard
1491 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1492 /// expression From to the type ToType. Standard conversion sequences
1493 /// only consider non-class types; for conversions that involve class
1494 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1495 /// contain the standard conversion sequence required to perform this
1496 /// conversion and this routine will return true. Otherwise, this
1497 /// routine will return false and the value of SCS is unspecified.
1498 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1499                                  bool InOverloadResolution,
1500                                  StandardConversionSequence &SCS,
1501                                  bool CStyle,
1502                                  bool AllowObjCWritebackConversion) {
1503   QualType FromType = From->getType();
1504 
1505   // Standard conversions (C++ [conv])
1506   SCS.setAsIdentityConversion();
1507   SCS.IncompatibleObjC = false;
1508   SCS.setFromType(FromType);
1509   SCS.CopyConstructor = nullptr;
1510 
1511   // There are no standard conversions for class types in C++, so
1512   // abort early. When overloading in C, however, we do permit them.
1513   if (S.getLangOpts().CPlusPlus &&
1514       (FromType->isRecordType() || ToType->isRecordType()))
1515     return false;
1516 
1517   // The first conversion can be an lvalue-to-rvalue conversion,
1518   // array-to-pointer conversion, or function-to-pointer conversion
1519   // (C++ 4p1).
1520 
1521   if (FromType == S.Context.OverloadTy) {
1522     DeclAccessPair AccessPair;
1523     if (FunctionDecl *Fn
1524           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1525                                                  AccessPair)) {
1526       // We were able to resolve the address of the overloaded function,
1527       // so we can convert to the type of that function.
1528       FromType = Fn->getType();
1529       SCS.setFromType(FromType);
1530 
1531       // we can sometimes resolve &foo<int> regardless of ToType, so check
1532       // if the type matches (identity) or we are converting to bool
1533       if (!S.Context.hasSameUnqualifiedType(
1534                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1535         QualType resultTy;
1536         // if the function type matches except for [[noreturn]], it's ok
1537         if (!S.IsNoReturnConversion(FromType,
1538               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1539           // otherwise, only a boolean conversion is standard
1540           if (!ToType->isBooleanType())
1541             return false;
1542       }
1543 
1544       // Check if the "from" expression is taking the address of an overloaded
1545       // function and recompute the FromType accordingly. Take advantage of the
1546       // fact that non-static member functions *must* have such an address-of
1547       // expression.
1548       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1549       if (Method && !Method->isStatic()) {
1550         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1551                "Non-unary operator on non-static member address");
1552         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1553                == UO_AddrOf &&
1554                "Non-address-of operator on non-static member address");
1555         const Type *ClassType
1556           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1557         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1558       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1559         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1560                UO_AddrOf &&
1561                "Non-address-of operator for overloaded function expression");
1562         FromType = S.Context.getPointerType(FromType);
1563       }
1564 
1565       // Check that we've computed the proper type after overload resolution.
1566       assert(S.Context.hasSameType(
1567         FromType,
1568         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1569     } else {
1570       return false;
1571     }
1572   }
1573   // Lvalue-to-rvalue conversion (C++11 4.1):
1574   //   A glvalue (3.10) of a non-function, non-array type T can
1575   //   be converted to a prvalue.
1576   bool argIsLValue = From->isGLValue();
1577   if (argIsLValue &&
1578       !FromType->isFunctionType() && !FromType->isArrayType() &&
1579       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1580     SCS.First = ICK_Lvalue_To_Rvalue;
1581 
1582     // C11 6.3.2.1p2:
1583     //   ... if the lvalue has atomic type, the value has the non-atomic version
1584     //   of the type of the lvalue ...
1585     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1586       FromType = Atomic->getValueType();
1587 
1588     // If T is a non-class type, the type of the rvalue is the
1589     // cv-unqualified version of T. Otherwise, the type of the rvalue
1590     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1591     // just strip the qualifiers because they don't matter.
1592     FromType = FromType.getUnqualifiedType();
1593   } else if (FromType->isArrayType()) {
1594     // Array-to-pointer conversion (C++ 4.2)
1595     SCS.First = ICK_Array_To_Pointer;
1596 
1597     // An lvalue or rvalue of type "array of N T" or "array of unknown
1598     // bound of T" can be converted to an rvalue of type "pointer to
1599     // T" (C++ 4.2p1).
1600     FromType = S.Context.getArrayDecayedType(FromType);
1601 
1602     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1603       // This conversion is deprecated in C++03 (D.4)
1604       SCS.DeprecatedStringLiteralToCharPtr = true;
1605 
1606       // For the purpose of ranking in overload resolution
1607       // (13.3.3.1.1), this conversion is considered an
1608       // array-to-pointer conversion followed by a qualification
1609       // conversion (4.4). (C++ 4.2p2)
1610       SCS.Second = ICK_Identity;
1611       SCS.Third = ICK_Qualification;
1612       SCS.QualificationIncludesObjCLifetime = false;
1613       SCS.setAllToTypes(FromType);
1614       return true;
1615     }
1616   } else if (FromType->isFunctionType() && argIsLValue) {
1617     // Function-to-pointer conversion (C++ 4.3).
1618     SCS.First = ICK_Function_To_Pointer;
1619 
1620     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1621       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1622         if (!S.checkAddressOfFunctionIsAvailable(FD))
1623           return false;
1624 
1625     // An lvalue of function type T can be converted to an rvalue of
1626     // type "pointer to T." The result is a pointer to the
1627     // function. (C++ 4.3p1).
1628     FromType = S.Context.getPointerType(FromType);
1629   } else {
1630     // We don't require any conversions for the first step.
1631     SCS.First = ICK_Identity;
1632   }
1633   SCS.setToType(0, FromType);
1634 
1635   // The second conversion can be an integral promotion, floating
1636   // point promotion, integral conversion, floating point conversion,
1637   // floating-integral conversion, pointer conversion,
1638   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1639   // For overloading in C, this can also be a "compatible-type"
1640   // conversion.
1641   bool IncompatibleObjC = false;
1642   ImplicitConversionKind SecondICK = ICK_Identity;
1643   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1644     // The unqualified versions of the types are the same: there's no
1645     // conversion to do.
1646     SCS.Second = ICK_Identity;
1647   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1648     // Integral promotion (C++ 4.5).
1649     SCS.Second = ICK_Integral_Promotion;
1650     FromType = ToType.getUnqualifiedType();
1651   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1652     // Floating point promotion (C++ 4.6).
1653     SCS.Second = ICK_Floating_Promotion;
1654     FromType = ToType.getUnqualifiedType();
1655   } else if (S.IsComplexPromotion(FromType, ToType)) {
1656     // Complex promotion (Clang extension)
1657     SCS.Second = ICK_Complex_Promotion;
1658     FromType = ToType.getUnqualifiedType();
1659   } else if (ToType->isBooleanType() &&
1660              (FromType->isArithmeticType() ||
1661               FromType->isAnyPointerType() ||
1662               FromType->isBlockPointerType() ||
1663               FromType->isMemberPointerType() ||
1664               FromType->isNullPtrType())) {
1665     // Boolean conversions (C++ 4.12).
1666     SCS.Second = ICK_Boolean_Conversion;
1667     FromType = S.Context.BoolTy;
1668   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1669              ToType->isIntegralType(S.Context)) {
1670     // Integral conversions (C++ 4.7).
1671     SCS.Second = ICK_Integral_Conversion;
1672     FromType = ToType.getUnqualifiedType();
1673   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1674     // Complex conversions (C99 6.3.1.6)
1675     SCS.Second = ICK_Complex_Conversion;
1676     FromType = ToType.getUnqualifiedType();
1677   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1678              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1679     // Complex-real conversions (C99 6.3.1.7)
1680     SCS.Second = ICK_Complex_Real;
1681     FromType = ToType.getUnqualifiedType();
1682   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1683     // FIXME: disable conversions between long double and __float128 if
1684     // their representation is different until there is back end support
1685     // We of course allow this conversion if long double is really double.
1686     if (&S.Context.getFloatTypeSemantics(FromType) !=
1687         &S.Context.getFloatTypeSemantics(ToType)) {
1688       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1689                                     ToType == S.Context.LongDoubleTy) ||
1690                                    (FromType == S.Context.LongDoubleTy &&
1691                                     ToType == S.Context.Float128Ty));
1692       if (Float128AndLongDouble &&
1693           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1694            &llvm::APFloat::IEEEdouble))
1695         return false;
1696     }
1697     // Floating point conversions (C++ 4.8).
1698     SCS.Second = ICK_Floating_Conversion;
1699     FromType = ToType.getUnqualifiedType();
1700   } else if ((FromType->isRealFloatingType() &&
1701               ToType->isIntegralType(S.Context)) ||
1702              (FromType->isIntegralOrUnscopedEnumerationType() &&
1703               ToType->isRealFloatingType())) {
1704     // Floating-integral conversions (C++ 4.9).
1705     SCS.Second = ICK_Floating_Integral;
1706     FromType = ToType.getUnqualifiedType();
1707   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1708     SCS.Second = ICK_Block_Pointer_Conversion;
1709   } else if (AllowObjCWritebackConversion &&
1710              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1711     SCS.Second = ICK_Writeback_Conversion;
1712   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1713                                    FromType, IncompatibleObjC)) {
1714     // Pointer conversions (C++ 4.10).
1715     SCS.Second = ICK_Pointer_Conversion;
1716     SCS.IncompatibleObjC = IncompatibleObjC;
1717     FromType = FromType.getUnqualifiedType();
1718   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1719                                          InOverloadResolution, FromType)) {
1720     // Pointer to member conversions (4.11).
1721     SCS.Second = ICK_Pointer_Member;
1722   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1723     SCS.Second = SecondICK;
1724     FromType = ToType.getUnqualifiedType();
1725   } else if (!S.getLangOpts().CPlusPlus &&
1726              S.Context.typesAreCompatible(ToType, FromType)) {
1727     // Compatible conversions (Clang extension for C function overloading)
1728     SCS.Second = ICK_Compatible_Conversion;
1729     FromType = ToType.getUnqualifiedType();
1730   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1731     // Treat a conversion that strips "noreturn" as an identity conversion.
1732     SCS.Second = ICK_NoReturn_Adjustment;
1733   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1734                                              InOverloadResolution,
1735                                              SCS, CStyle)) {
1736     SCS.Second = ICK_TransparentUnionConversion;
1737     FromType = ToType;
1738   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1739                                  CStyle)) {
1740     // tryAtomicConversion has updated the standard conversion sequence
1741     // appropriately.
1742     return true;
1743   } else if (ToType->isEventT() &&
1744              From->isIntegerConstantExpr(S.getASTContext()) &&
1745              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1746     SCS.Second = ICK_Zero_Event_Conversion;
1747     FromType = ToType;
1748   } else {
1749     // No second conversion required.
1750     SCS.Second = ICK_Identity;
1751   }
1752   SCS.setToType(1, FromType);
1753 
1754   QualType CanonFrom;
1755   QualType CanonTo;
1756   // The third conversion can be a qualification conversion (C++ 4p1).
1757   bool ObjCLifetimeConversion;
1758   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1759                                   ObjCLifetimeConversion)) {
1760     SCS.Third = ICK_Qualification;
1761     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1762     FromType = ToType;
1763     CanonFrom = S.Context.getCanonicalType(FromType);
1764     CanonTo = S.Context.getCanonicalType(ToType);
1765   } else {
1766     // No conversion required
1767     SCS.Third = ICK_Identity;
1768 
1769     // C++ [over.best.ics]p6:
1770     //   [...] Any difference in top-level cv-qualification is
1771     //   subsumed by the initialization itself and does not constitute
1772     //   a conversion. [...]
1773     CanonFrom = S.Context.getCanonicalType(FromType);
1774     CanonTo = S.Context.getCanonicalType(ToType);
1775     if (CanonFrom.getLocalUnqualifiedType()
1776                                        == CanonTo.getLocalUnqualifiedType() &&
1777         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1778       FromType = ToType;
1779       CanonFrom = CanonTo;
1780     }
1781   }
1782   SCS.setToType(2, FromType);
1783 
1784   if (CanonFrom == CanonTo)
1785     return true;
1786 
1787   // If we have not converted the argument type to the parameter type,
1788   // this is a bad conversion sequence, unless we're resolving an overload in C.
1789   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1790     return false;
1791 
1792   ExprResult ER = ExprResult{From};
1793   Sema::AssignConvertType Conv =
1794       S.CheckSingleAssignmentConstraints(ToType, ER,
1795                                          /*Diagnose=*/false,
1796                                          /*DiagnoseCFAudited=*/false,
1797                                          /*ConvertRHS=*/false);
1798   ImplicitConversionKind SecondConv;
1799   switch (Conv) {
1800   case Sema::Compatible:
1801     SecondConv = ICK_C_Only_Conversion;
1802     break;
1803   // For our purposes, discarding qualifiers is just as bad as using an
1804   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1805   // qualifiers, as well.
1806   case Sema::CompatiblePointerDiscardsQualifiers:
1807   case Sema::IncompatiblePointer:
1808   case Sema::IncompatiblePointerSign:
1809     SecondConv = ICK_Incompatible_Pointer_Conversion;
1810     break;
1811   default:
1812     return false;
1813   }
1814 
1815   // First can only be an lvalue conversion, so we pretend that this was the
1816   // second conversion. First should already be valid from earlier in the
1817   // function.
1818   SCS.Second = SecondConv;
1819   SCS.setToType(1, ToType);
1820 
1821   // Third is Identity, because Second should rank us worse than any other
1822   // conversion. This could also be ICK_Qualification, but it's simpler to just
1823   // lump everything in with the second conversion, and we don't gain anything
1824   // from making this ICK_Qualification.
1825   SCS.Third = ICK_Identity;
1826   SCS.setToType(2, ToType);
1827   return true;
1828 }
1829 
1830 static bool
1831 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1832                                      QualType &ToType,
1833                                      bool InOverloadResolution,
1834                                      StandardConversionSequence &SCS,
1835                                      bool CStyle) {
1836 
1837   const RecordType *UT = ToType->getAsUnionType();
1838   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1839     return false;
1840   // The field to initialize within the transparent union.
1841   RecordDecl *UD = UT->getDecl();
1842   // It's compatible if the expression matches any of the fields.
1843   for (const auto *it : UD->fields()) {
1844     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1845                              CStyle, /*ObjCWritebackConversion=*/false)) {
1846       ToType = it->getType();
1847       return true;
1848     }
1849   }
1850   return false;
1851 }
1852 
1853 /// IsIntegralPromotion - Determines whether the conversion from the
1854 /// expression From (whose potentially-adjusted type is FromType) to
1855 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1856 /// sets PromotedType to the promoted type.
1857 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1858   const BuiltinType *To = ToType->getAs<BuiltinType>();
1859   // All integers are built-in.
1860   if (!To) {
1861     return false;
1862   }
1863 
1864   // An rvalue of type char, signed char, unsigned char, short int, or
1865   // unsigned short int can be converted to an rvalue of type int if
1866   // int can represent all the values of the source type; otherwise,
1867   // the source rvalue can be converted to an rvalue of type unsigned
1868   // int (C++ 4.5p1).
1869   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1870       !FromType->isEnumeralType()) {
1871     if (// We can promote any signed, promotable integer type to an int
1872         (FromType->isSignedIntegerType() ||
1873          // We can promote any unsigned integer type whose size is
1874          // less than int to an int.
1875          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1876       return To->getKind() == BuiltinType::Int;
1877     }
1878 
1879     return To->getKind() == BuiltinType::UInt;
1880   }
1881 
1882   // C++11 [conv.prom]p3:
1883   //   A prvalue of an unscoped enumeration type whose underlying type is not
1884   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1885   //   following types that can represent all the values of the enumeration
1886   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1887   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1888   //   long long int. If none of the types in that list can represent all the
1889   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1890   //   type can be converted to an rvalue a prvalue of the extended integer type
1891   //   with lowest integer conversion rank (4.13) greater than the rank of long
1892   //   long in which all the values of the enumeration can be represented. If
1893   //   there are two such extended types, the signed one is chosen.
1894   // C++11 [conv.prom]p4:
1895   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1896   //   can be converted to a prvalue of its underlying type. Moreover, if
1897   //   integral promotion can be applied to its underlying type, a prvalue of an
1898   //   unscoped enumeration type whose underlying type is fixed can also be
1899   //   converted to a prvalue of the promoted underlying type.
1900   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1901     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1902     // provided for a scoped enumeration.
1903     if (FromEnumType->getDecl()->isScoped())
1904       return false;
1905 
1906     // We can perform an integral promotion to the underlying type of the enum,
1907     // even if that's not the promoted type. Note that the check for promoting
1908     // the underlying type is based on the type alone, and does not consider
1909     // the bitfield-ness of the actual source expression.
1910     if (FromEnumType->getDecl()->isFixed()) {
1911       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1912       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1913              IsIntegralPromotion(nullptr, Underlying, ToType);
1914     }
1915 
1916     // We have already pre-calculated the promotion type, so this is trivial.
1917     if (ToType->isIntegerType() &&
1918         isCompleteType(From->getLocStart(), FromType))
1919       return Context.hasSameUnqualifiedType(
1920           ToType, FromEnumType->getDecl()->getPromotionType());
1921   }
1922 
1923   // C++0x [conv.prom]p2:
1924   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1925   //   to an rvalue a prvalue of the first of the following types that can
1926   //   represent all the values of its underlying type: int, unsigned int,
1927   //   long int, unsigned long int, long long int, or unsigned long long int.
1928   //   If none of the types in that list can represent all the values of its
1929   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1930   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1931   //   type.
1932   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1933       ToType->isIntegerType()) {
1934     // Determine whether the type we're converting from is signed or
1935     // unsigned.
1936     bool FromIsSigned = FromType->isSignedIntegerType();
1937     uint64_t FromSize = Context.getTypeSize(FromType);
1938 
1939     // The types we'll try to promote to, in the appropriate
1940     // order. Try each of these types.
1941     QualType PromoteTypes[6] = {
1942       Context.IntTy, Context.UnsignedIntTy,
1943       Context.LongTy, Context.UnsignedLongTy ,
1944       Context.LongLongTy, Context.UnsignedLongLongTy
1945     };
1946     for (int Idx = 0; Idx < 6; ++Idx) {
1947       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1948       if (FromSize < ToSize ||
1949           (FromSize == ToSize &&
1950            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1951         // We found the type that we can promote to. If this is the
1952         // type we wanted, we have a promotion. Otherwise, no
1953         // promotion.
1954         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1955       }
1956     }
1957   }
1958 
1959   // An rvalue for an integral bit-field (9.6) can be converted to an
1960   // rvalue of type int if int can represent all the values of the
1961   // bit-field; otherwise, it can be converted to unsigned int if
1962   // unsigned int can represent all the values of the bit-field. If
1963   // the bit-field is larger yet, no integral promotion applies to
1964   // it. If the bit-field has an enumerated type, it is treated as any
1965   // other value of that type for promotion purposes (C++ 4.5p3).
1966   // FIXME: We should delay checking of bit-fields until we actually perform the
1967   // conversion.
1968   if (From) {
1969     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1970       llvm::APSInt BitWidth;
1971       if (FromType->isIntegralType(Context) &&
1972           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1973         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1974         ToSize = Context.getTypeSize(ToType);
1975 
1976         // Are we promoting to an int from a bitfield that fits in an int?
1977         if (BitWidth < ToSize ||
1978             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1979           return To->getKind() == BuiltinType::Int;
1980         }
1981 
1982         // Are we promoting to an unsigned int from an unsigned bitfield
1983         // that fits into an unsigned int?
1984         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1985           return To->getKind() == BuiltinType::UInt;
1986         }
1987 
1988         return false;
1989       }
1990     }
1991   }
1992 
1993   // An rvalue of type bool can be converted to an rvalue of type int,
1994   // with false becoming zero and true becoming one (C++ 4.5p4).
1995   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1996     return true;
1997   }
1998 
1999   return false;
2000 }
2001 
2002 /// IsFloatingPointPromotion - Determines whether the conversion from
2003 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2004 /// returns true and sets PromotedType to the promoted type.
2005 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2006   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2007     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2008       /// An rvalue of type float can be converted to an rvalue of type
2009       /// double. (C++ 4.6p1).
2010       if (FromBuiltin->getKind() == BuiltinType::Float &&
2011           ToBuiltin->getKind() == BuiltinType::Double)
2012         return true;
2013 
2014       // C99 6.3.1.5p1:
2015       //   When a float is promoted to double or long double, or a
2016       //   double is promoted to long double [...].
2017       if (!getLangOpts().CPlusPlus &&
2018           (FromBuiltin->getKind() == BuiltinType::Float ||
2019            FromBuiltin->getKind() == BuiltinType::Double) &&
2020           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2021            ToBuiltin->getKind() == BuiltinType::Float128))
2022         return true;
2023 
2024       // Half can be promoted to float.
2025       if (!getLangOpts().NativeHalfType &&
2026            FromBuiltin->getKind() == BuiltinType::Half &&
2027           ToBuiltin->getKind() == BuiltinType::Float)
2028         return true;
2029     }
2030 
2031   return false;
2032 }
2033 
2034 /// \brief Determine if a conversion is a complex promotion.
2035 ///
2036 /// A complex promotion is defined as a complex -> complex conversion
2037 /// where the conversion between the underlying real types is a
2038 /// floating-point or integral promotion.
2039 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2040   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2041   if (!FromComplex)
2042     return false;
2043 
2044   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2045   if (!ToComplex)
2046     return false;
2047 
2048   return IsFloatingPointPromotion(FromComplex->getElementType(),
2049                                   ToComplex->getElementType()) ||
2050     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2051                         ToComplex->getElementType());
2052 }
2053 
2054 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2055 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2056 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2057 /// if non-empty, will be a pointer to ToType that may or may not have
2058 /// the right set of qualifiers on its pointee.
2059 ///
2060 static QualType
2061 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2062                                    QualType ToPointee, QualType ToType,
2063                                    ASTContext &Context,
2064                                    bool StripObjCLifetime = false) {
2065   assert((FromPtr->getTypeClass() == Type::Pointer ||
2066           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2067          "Invalid similarly-qualified pointer type");
2068 
2069   /// Conversions to 'id' subsume cv-qualifier conversions.
2070   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2071     return ToType.getUnqualifiedType();
2072 
2073   QualType CanonFromPointee
2074     = Context.getCanonicalType(FromPtr->getPointeeType());
2075   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2076   Qualifiers Quals = CanonFromPointee.getQualifiers();
2077 
2078   if (StripObjCLifetime)
2079     Quals.removeObjCLifetime();
2080 
2081   // Exact qualifier match -> return the pointer type we're converting to.
2082   if (CanonToPointee.getLocalQualifiers() == Quals) {
2083     // ToType is exactly what we need. Return it.
2084     if (!ToType.isNull())
2085       return ToType.getUnqualifiedType();
2086 
2087     // Build a pointer to ToPointee. It has the right qualifiers
2088     // already.
2089     if (isa<ObjCObjectPointerType>(ToType))
2090       return Context.getObjCObjectPointerType(ToPointee);
2091     return Context.getPointerType(ToPointee);
2092   }
2093 
2094   // Just build a canonical type that has the right qualifiers.
2095   QualType QualifiedCanonToPointee
2096     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2097 
2098   if (isa<ObjCObjectPointerType>(ToType))
2099     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2100   return Context.getPointerType(QualifiedCanonToPointee);
2101 }
2102 
2103 static bool isNullPointerConstantForConversion(Expr *Expr,
2104                                                bool InOverloadResolution,
2105                                                ASTContext &Context) {
2106   // Handle value-dependent integral null pointer constants correctly.
2107   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2108   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2109       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2110     return !InOverloadResolution;
2111 
2112   return Expr->isNullPointerConstant(Context,
2113                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2114                                         : Expr::NPC_ValueDependentIsNull);
2115 }
2116 
2117 /// IsPointerConversion - Determines whether the conversion of the
2118 /// expression From, which has the (possibly adjusted) type FromType,
2119 /// can be converted to the type ToType via a pointer conversion (C++
2120 /// 4.10). If so, returns true and places the converted type (that
2121 /// might differ from ToType in its cv-qualifiers at some level) into
2122 /// ConvertedType.
2123 ///
2124 /// This routine also supports conversions to and from block pointers
2125 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2126 /// pointers to interfaces. FIXME: Once we've determined the
2127 /// appropriate overloading rules for Objective-C, we may want to
2128 /// split the Objective-C checks into a different routine; however,
2129 /// GCC seems to consider all of these conversions to be pointer
2130 /// conversions, so for now they live here. IncompatibleObjC will be
2131 /// set if the conversion is an allowed Objective-C conversion that
2132 /// should result in a warning.
2133 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2134                                bool InOverloadResolution,
2135                                QualType& ConvertedType,
2136                                bool &IncompatibleObjC) {
2137   IncompatibleObjC = false;
2138   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2139                               IncompatibleObjC))
2140     return true;
2141 
2142   // Conversion from a null pointer constant to any Objective-C pointer type.
2143   if (ToType->isObjCObjectPointerType() &&
2144       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2145     ConvertedType = ToType;
2146     return true;
2147   }
2148 
2149   // Blocks: Block pointers can be converted to void*.
2150   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2151       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2152     ConvertedType = ToType;
2153     return true;
2154   }
2155   // Blocks: A null pointer constant can be converted to a block
2156   // pointer type.
2157   if (ToType->isBlockPointerType() &&
2158       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2159     ConvertedType = ToType;
2160     return true;
2161   }
2162 
2163   // If the left-hand-side is nullptr_t, the right side can be a null
2164   // pointer constant.
2165   if (ToType->isNullPtrType() &&
2166       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2167     ConvertedType = ToType;
2168     return true;
2169   }
2170 
2171   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2172   if (!ToTypePtr)
2173     return false;
2174 
2175   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2176   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2177     ConvertedType = ToType;
2178     return true;
2179   }
2180 
2181   // Beyond this point, both types need to be pointers
2182   // , including objective-c pointers.
2183   QualType ToPointeeType = ToTypePtr->getPointeeType();
2184   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2185       !getLangOpts().ObjCAutoRefCount) {
2186     ConvertedType = BuildSimilarlyQualifiedPointerType(
2187                                       FromType->getAs<ObjCObjectPointerType>(),
2188                                                        ToPointeeType,
2189                                                        ToType, Context);
2190     return true;
2191   }
2192   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2193   if (!FromTypePtr)
2194     return false;
2195 
2196   QualType FromPointeeType = FromTypePtr->getPointeeType();
2197 
2198   // If the unqualified pointee types are the same, this can't be a
2199   // pointer conversion, so don't do all of the work below.
2200   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2201     return false;
2202 
2203   // An rvalue of type "pointer to cv T," where T is an object type,
2204   // can be converted to an rvalue of type "pointer to cv void" (C++
2205   // 4.10p2).
2206   if (FromPointeeType->isIncompleteOrObjectType() &&
2207       ToPointeeType->isVoidType()) {
2208     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2209                                                        ToPointeeType,
2210                                                        ToType, Context,
2211                                                    /*StripObjCLifetime=*/true);
2212     return true;
2213   }
2214 
2215   // MSVC allows implicit function to void* type conversion.
2216   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2217       ToPointeeType->isVoidType()) {
2218     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2219                                                        ToPointeeType,
2220                                                        ToType, Context);
2221     return true;
2222   }
2223 
2224   // When we're overloading in C, we allow a special kind of pointer
2225   // conversion for compatible-but-not-identical pointee types.
2226   if (!getLangOpts().CPlusPlus &&
2227       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2228     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2229                                                        ToPointeeType,
2230                                                        ToType, Context);
2231     return true;
2232   }
2233 
2234   // C++ [conv.ptr]p3:
2235   //
2236   //   An rvalue of type "pointer to cv D," where D is a class type,
2237   //   can be converted to an rvalue of type "pointer to cv B," where
2238   //   B is a base class (clause 10) of D. If B is an inaccessible
2239   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2240   //   necessitates this conversion is ill-formed. The result of the
2241   //   conversion is a pointer to the base class sub-object of the
2242   //   derived class object. The null pointer value is converted to
2243   //   the null pointer value of the destination type.
2244   //
2245   // Note that we do not check for ambiguity or inaccessibility
2246   // here. That is handled by CheckPointerConversion.
2247   if (getLangOpts().CPlusPlus &&
2248       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2249       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2250       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2251     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2252                                                        ToPointeeType,
2253                                                        ToType, Context);
2254     return true;
2255   }
2256 
2257   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2258       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2259     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2260                                                        ToPointeeType,
2261                                                        ToType, Context);
2262     return true;
2263   }
2264 
2265   return false;
2266 }
2267 
2268 /// \brief Adopt the given qualifiers for the given type.
2269 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2270   Qualifiers TQs = T.getQualifiers();
2271 
2272   // Check whether qualifiers already match.
2273   if (TQs == Qs)
2274     return T;
2275 
2276   if (Qs.compatiblyIncludes(TQs))
2277     return Context.getQualifiedType(T, Qs);
2278 
2279   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2280 }
2281 
2282 /// isObjCPointerConversion - Determines whether this is an
2283 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2284 /// with the same arguments and return values.
2285 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2286                                    QualType& ConvertedType,
2287                                    bool &IncompatibleObjC) {
2288   if (!getLangOpts().ObjC1)
2289     return false;
2290 
2291   // The set of qualifiers on the type we're converting from.
2292   Qualifiers FromQualifiers = FromType.getQualifiers();
2293 
2294   // First, we handle all conversions on ObjC object pointer types.
2295   const ObjCObjectPointerType* ToObjCPtr =
2296     ToType->getAs<ObjCObjectPointerType>();
2297   const ObjCObjectPointerType *FromObjCPtr =
2298     FromType->getAs<ObjCObjectPointerType>();
2299 
2300   if (ToObjCPtr && FromObjCPtr) {
2301     // If the pointee types are the same (ignoring qualifications),
2302     // then this is not a pointer conversion.
2303     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2304                                        FromObjCPtr->getPointeeType()))
2305       return false;
2306 
2307     // Conversion between Objective-C pointers.
2308     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2309       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2310       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2311       if (getLangOpts().CPlusPlus && LHS && RHS &&
2312           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2313                                                 FromObjCPtr->getPointeeType()))
2314         return false;
2315       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2316                                                    ToObjCPtr->getPointeeType(),
2317                                                          ToType, Context);
2318       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2319       return true;
2320     }
2321 
2322     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2323       // Okay: this is some kind of implicit downcast of Objective-C
2324       // interfaces, which is permitted. However, we're going to
2325       // complain about it.
2326       IncompatibleObjC = true;
2327       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2328                                                    ToObjCPtr->getPointeeType(),
2329                                                          ToType, Context);
2330       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2331       return true;
2332     }
2333   }
2334   // Beyond this point, both types need to be C pointers or block pointers.
2335   QualType ToPointeeType;
2336   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2337     ToPointeeType = ToCPtr->getPointeeType();
2338   else if (const BlockPointerType *ToBlockPtr =
2339             ToType->getAs<BlockPointerType>()) {
2340     // Objective C++: We're able to convert from a pointer to any object
2341     // to a block pointer type.
2342     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2343       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2344       return true;
2345     }
2346     ToPointeeType = ToBlockPtr->getPointeeType();
2347   }
2348   else if (FromType->getAs<BlockPointerType>() &&
2349            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2350     // Objective C++: We're able to convert from a block pointer type to a
2351     // pointer to any object.
2352     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2353     return true;
2354   }
2355   else
2356     return false;
2357 
2358   QualType FromPointeeType;
2359   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2360     FromPointeeType = FromCPtr->getPointeeType();
2361   else if (const BlockPointerType *FromBlockPtr =
2362            FromType->getAs<BlockPointerType>())
2363     FromPointeeType = FromBlockPtr->getPointeeType();
2364   else
2365     return false;
2366 
2367   // If we have pointers to pointers, recursively check whether this
2368   // is an Objective-C conversion.
2369   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2370       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2371                               IncompatibleObjC)) {
2372     // We always complain about this conversion.
2373     IncompatibleObjC = true;
2374     ConvertedType = Context.getPointerType(ConvertedType);
2375     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2376     return true;
2377   }
2378   // Allow conversion of pointee being objective-c pointer to another one;
2379   // as in I* to id.
2380   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2381       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2382       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2383                               IncompatibleObjC)) {
2384 
2385     ConvertedType = Context.getPointerType(ConvertedType);
2386     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2387     return true;
2388   }
2389 
2390   // If we have pointers to functions or blocks, check whether the only
2391   // differences in the argument and result types are in Objective-C
2392   // pointer conversions. If so, we permit the conversion (but
2393   // complain about it).
2394   const FunctionProtoType *FromFunctionType
2395     = FromPointeeType->getAs<FunctionProtoType>();
2396   const FunctionProtoType *ToFunctionType
2397     = ToPointeeType->getAs<FunctionProtoType>();
2398   if (FromFunctionType && ToFunctionType) {
2399     // If the function types are exactly the same, this isn't an
2400     // Objective-C pointer conversion.
2401     if (Context.getCanonicalType(FromPointeeType)
2402           == Context.getCanonicalType(ToPointeeType))
2403       return false;
2404 
2405     // Perform the quick checks that will tell us whether these
2406     // function types are obviously different.
2407     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2408         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2409         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2410       return false;
2411 
2412     bool HasObjCConversion = false;
2413     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2414         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2415       // Okay, the types match exactly. Nothing to do.
2416     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2417                                        ToFunctionType->getReturnType(),
2418                                        ConvertedType, IncompatibleObjC)) {
2419       // Okay, we have an Objective-C pointer conversion.
2420       HasObjCConversion = true;
2421     } else {
2422       // Function types are too different. Abort.
2423       return false;
2424     }
2425 
2426     // Check argument types.
2427     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2428          ArgIdx != NumArgs; ++ArgIdx) {
2429       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2430       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2431       if (Context.getCanonicalType(FromArgType)
2432             == Context.getCanonicalType(ToArgType)) {
2433         // Okay, the types match exactly. Nothing to do.
2434       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2435                                          ConvertedType, IncompatibleObjC)) {
2436         // Okay, we have an Objective-C pointer conversion.
2437         HasObjCConversion = true;
2438       } else {
2439         // Argument types are too different. Abort.
2440         return false;
2441       }
2442     }
2443 
2444     if (HasObjCConversion) {
2445       // We had an Objective-C conversion. Allow this pointer
2446       // conversion, but complain about it.
2447       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2448       IncompatibleObjC = true;
2449       return true;
2450     }
2451   }
2452 
2453   return false;
2454 }
2455 
2456 /// \brief Determine whether this is an Objective-C writeback conversion,
2457 /// used for parameter passing when performing automatic reference counting.
2458 ///
2459 /// \param FromType The type we're converting form.
2460 ///
2461 /// \param ToType The type we're converting to.
2462 ///
2463 /// \param ConvertedType The type that will be produced after applying
2464 /// this conversion.
2465 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2466                                      QualType &ConvertedType) {
2467   if (!getLangOpts().ObjCAutoRefCount ||
2468       Context.hasSameUnqualifiedType(FromType, ToType))
2469     return false;
2470 
2471   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2472   QualType ToPointee;
2473   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2474     ToPointee = ToPointer->getPointeeType();
2475   else
2476     return false;
2477 
2478   Qualifiers ToQuals = ToPointee.getQualifiers();
2479   if (!ToPointee->isObjCLifetimeType() ||
2480       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2481       !ToQuals.withoutObjCLifetime().empty())
2482     return false;
2483 
2484   // Argument must be a pointer to __strong to __weak.
2485   QualType FromPointee;
2486   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2487     FromPointee = FromPointer->getPointeeType();
2488   else
2489     return false;
2490 
2491   Qualifiers FromQuals = FromPointee.getQualifiers();
2492   if (!FromPointee->isObjCLifetimeType() ||
2493       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2494        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2495     return false;
2496 
2497   // Make sure that we have compatible qualifiers.
2498   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2499   if (!ToQuals.compatiblyIncludes(FromQuals))
2500     return false;
2501 
2502   // Remove qualifiers from the pointee type we're converting from; they
2503   // aren't used in the compatibility check belong, and we'll be adding back
2504   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2505   FromPointee = FromPointee.getUnqualifiedType();
2506 
2507   // The unqualified form of the pointee types must be compatible.
2508   ToPointee = ToPointee.getUnqualifiedType();
2509   bool IncompatibleObjC;
2510   if (Context.typesAreCompatible(FromPointee, ToPointee))
2511     FromPointee = ToPointee;
2512   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2513                                     IncompatibleObjC))
2514     return false;
2515 
2516   /// \brief Construct the type we're converting to, which is a pointer to
2517   /// __autoreleasing pointee.
2518   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2519   ConvertedType = Context.getPointerType(FromPointee);
2520   return true;
2521 }
2522 
2523 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2524                                     QualType& ConvertedType) {
2525   QualType ToPointeeType;
2526   if (const BlockPointerType *ToBlockPtr =
2527         ToType->getAs<BlockPointerType>())
2528     ToPointeeType = ToBlockPtr->getPointeeType();
2529   else
2530     return false;
2531 
2532   QualType FromPointeeType;
2533   if (const BlockPointerType *FromBlockPtr =
2534       FromType->getAs<BlockPointerType>())
2535     FromPointeeType = FromBlockPtr->getPointeeType();
2536   else
2537     return false;
2538   // We have pointer to blocks, check whether the only
2539   // differences in the argument and result types are in Objective-C
2540   // pointer conversions. If so, we permit the conversion.
2541 
2542   const FunctionProtoType *FromFunctionType
2543     = FromPointeeType->getAs<FunctionProtoType>();
2544   const FunctionProtoType *ToFunctionType
2545     = ToPointeeType->getAs<FunctionProtoType>();
2546 
2547   if (!FromFunctionType || !ToFunctionType)
2548     return false;
2549 
2550   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2551     return true;
2552 
2553   // Perform the quick checks that will tell us whether these
2554   // function types are obviously different.
2555   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2556       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2557     return false;
2558 
2559   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2560   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2561   if (FromEInfo != ToEInfo)
2562     return false;
2563 
2564   bool IncompatibleObjC = false;
2565   if (Context.hasSameType(FromFunctionType->getReturnType(),
2566                           ToFunctionType->getReturnType())) {
2567     // Okay, the types match exactly. Nothing to do.
2568   } else {
2569     QualType RHS = FromFunctionType->getReturnType();
2570     QualType LHS = ToFunctionType->getReturnType();
2571     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2572         !RHS.hasQualifiers() && LHS.hasQualifiers())
2573        LHS = LHS.getUnqualifiedType();
2574 
2575      if (Context.hasSameType(RHS,LHS)) {
2576        // OK exact match.
2577      } else if (isObjCPointerConversion(RHS, LHS,
2578                                         ConvertedType, IncompatibleObjC)) {
2579      if (IncompatibleObjC)
2580        return false;
2581      // Okay, we have an Objective-C pointer conversion.
2582      }
2583      else
2584        return false;
2585    }
2586 
2587    // Check argument types.
2588    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2589         ArgIdx != NumArgs; ++ArgIdx) {
2590      IncompatibleObjC = false;
2591      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2592      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2593      if (Context.hasSameType(FromArgType, ToArgType)) {
2594        // Okay, the types match exactly. Nothing to do.
2595      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2596                                         ConvertedType, IncompatibleObjC)) {
2597        if (IncompatibleObjC)
2598          return false;
2599        // Okay, we have an Objective-C pointer conversion.
2600      } else
2601        // Argument types are too different. Abort.
2602        return false;
2603    }
2604    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2605                                                         ToFunctionType))
2606      return false;
2607 
2608    ConvertedType = ToType;
2609    return true;
2610 }
2611 
2612 enum {
2613   ft_default,
2614   ft_different_class,
2615   ft_parameter_arity,
2616   ft_parameter_mismatch,
2617   ft_return_type,
2618   ft_qualifer_mismatch
2619 };
2620 
2621 /// Attempts to get the FunctionProtoType from a Type. Handles
2622 /// MemberFunctionPointers properly.
2623 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2624   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2625     return FPT;
2626 
2627   if (auto *MPT = FromType->getAs<MemberPointerType>())
2628     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2629 
2630   return nullptr;
2631 }
2632 
2633 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2634 /// function types.  Catches different number of parameter, mismatch in
2635 /// parameter types, and different return types.
2636 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2637                                       QualType FromType, QualType ToType) {
2638   // If either type is not valid, include no extra info.
2639   if (FromType.isNull() || ToType.isNull()) {
2640     PDiag << ft_default;
2641     return;
2642   }
2643 
2644   // Get the function type from the pointers.
2645   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2646     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2647                             *ToMember = ToType->getAs<MemberPointerType>();
2648     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2649       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2650             << QualType(FromMember->getClass(), 0);
2651       return;
2652     }
2653     FromType = FromMember->getPointeeType();
2654     ToType = ToMember->getPointeeType();
2655   }
2656 
2657   if (FromType->isPointerType())
2658     FromType = FromType->getPointeeType();
2659   if (ToType->isPointerType())
2660     ToType = ToType->getPointeeType();
2661 
2662   // Remove references.
2663   FromType = FromType.getNonReferenceType();
2664   ToType = ToType.getNonReferenceType();
2665 
2666   // Don't print extra info for non-specialized template functions.
2667   if (FromType->isInstantiationDependentType() &&
2668       !FromType->getAs<TemplateSpecializationType>()) {
2669     PDiag << ft_default;
2670     return;
2671   }
2672 
2673   // No extra info for same types.
2674   if (Context.hasSameType(FromType, ToType)) {
2675     PDiag << ft_default;
2676     return;
2677   }
2678 
2679   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2680                           *ToFunction = tryGetFunctionProtoType(ToType);
2681 
2682   // Both types need to be function types.
2683   if (!FromFunction || !ToFunction) {
2684     PDiag << ft_default;
2685     return;
2686   }
2687 
2688   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2689     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2690           << FromFunction->getNumParams();
2691     return;
2692   }
2693 
2694   // Handle different parameter types.
2695   unsigned ArgPos;
2696   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2697     PDiag << ft_parameter_mismatch << ArgPos + 1
2698           << ToFunction->getParamType(ArgPos)
2699           << FromFunction->getParamType(ArgPos);
2700     return;
2701   }
2702 
2703   // Handle different return type.
2704   if (!Context.hasSameType(FromFunction->getReturnType(),
2705                            ToFunction->getReturnType())) {
2706     PDiag << ft_return_type << ToFunction->getReturnType()
2707           << FromFunction->getReturnType();
2708     return;
2709   }
2710 
2711   unsigned FromQuals = FromFunction->getTypeQuals(),
2712            ToQuals = ToFunction->getTypeQuals();
2713   if (FromQuals != ToQuals) {
2714     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2715     return;
2716   }
2717 
2718   // Unable to find a difference, so add no extra info.
2719   PDiag << ft_default;
2720 }
2721 
2722 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2723 /// for equality of their argument types. Caller has already checked that
2724 /// they have same number of arguments.  If the parameters are different,
2725 /// ArgPos will have the parameter index of the first different parameter.
2726 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2727                                       const FunctionProtoType *NewType,
2728                                       unsigned *ArgPos) {
2729   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2730                                               N = NewType->param_type_begin(),
2731                                               E = OldType->param_type_end();
2732        O && (O != E); ++O, ++N) {
2733     if (!Context.hasSameType(O->getUnqualifiedType(),
2734                              N->getUnqualifiedType())) {
2735       if (ArgPos)
2736         *ArgPos = O - OldType->param_type_begin();
2737       return false;
2738     }
2739   }
2740   return true;
2741 }
2742 
2743 /// CheckPointerConversion - Check the pointer conversion from the
2744 /// expression From to the type ToType. This routine checks for
2745 /// ambiguous or inaccessible derived-to-base pointer
2746 /// conversions for which IsPointerConversion has already returned
2747 /// true. It returns true and produces a diagnostic if there was an
2748 /// error, or returns false otherwise.
2749 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2750                                   CastKind &Kind,
2751                                   CXXCastPath& BasePath,
2752                                   bool IgnoreBaseAccess,
2753                                   bool Diagnose) {
2754   QualType FromType = From->getType();
2755   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2756 
2757   Kind = CK_BitCast;
2758 
2759   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2760       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2761           Expr::NPCK_ZeroExpression) {
2762     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2763       DiagRuntimeBehavior(From->getExprLoc(), From,
2764                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2765                             << ToType << From->getSourceRange());
2766     else if (!isUnevaluatedContext())
2767       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2768         << ToType << From->getSourceRange();
2769   }
2770   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2771     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2772       QualType FromPointeeType = FromPtrType->getPointeeType(),
2773                ToPointeeType   = ToPtrType->getPointeeType();
2774 
2775       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2776           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2777         // We must have a derived-to-base conversion. Check an
2778         // ambiguous or inaccessible conversion.
2779         unsigned InaccessibleID = 0;
2780         unsigned AmbigiousID = 0;
2781         if (Diagnose) {
2782           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2783           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2784         }
2785         if (CheckDerivedToBaseConversion(
2786                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2787                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2788                 &BasePath, IgnoreBaseAccess))
2789           return true;
2790 
2791         // The conversion was successful.
2792         Kind = CK_DerivedToBase;
2793       }
2794 
2795       if (Diagnose && !IsCStyleOrFunctionalCast &&
2796           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2797         assert(getLangOpts().MSVCCompat &&
2798                "this should only be possible with MSVCCompat!");
2799         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2800             << From->getSourceRange();
2801       }
2802     }
2803   } else if (const ObjCObjectPointerType *ToPtrType =
2804                ToType->getAs<ObjCObjectPointerType>()) {
2805     if (const ObjCObjectPointerType *FromPtrType =
2806           FromType->getAs<ObjCObjectPointerType>()) {
2807       // Objective-C++ conversions are always okay.
2808       // FIXME: We should have a different class of conversions for the
2809       // Objective-C++ implicit conversions.
2810       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2811         return false;
2812     } else if (FromType->isBlockPointerType()) {
2813       Kind = CK_BlockPointerToObjCPointerCast;
2814     } else {
2815       Kind = CK_CPointerToObjCPointerCast;
2816     }
2817   } else if (ToType->isBlockPointerType()) {
2818     if (!FromType->isBlockPointerType())
2819       Kind = CK_AnyPointerToBlockPointerCast;
2820   }
2821 
2822   // We shouldn't fall into this case unless it's valid for other
2823   // reasons.
2824   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2825     Kind = CK_NullToPointer;
2826 
2827   return false;
2828 }
2829 
2830 /// IsMemberPointerConversion - Determines whether the conversion of the
2831 /// expression From, which has the (possibly adjusted) type FromType, can be
2832 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2833 /// If so, returns true and places the converted type (that might differ from
2834 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2835 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2836                                      QualType ToType,
2837                                      bool InOverloadResolution,
2838                                      QualType &ConvertedType) {
2839   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2840   if (!ToTypePtr)
2841     return false;
2842 
2843   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2844   if (From->isNullPointerConstant(Context,
2845                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2846                                         : Expr::NPC_ValueDependentIsNull)) {
2847     ConvertedType = ToType;
2848     return true;
2849   }
2850 
2851   // Otherwise, both types have to be member pointers.
2852   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2853   if (!FromTypePtr)
2854     return false;
2855 
2856   // A pointer to member of B can be converted to a pointer to member of D,
2857   // where D is derived from B (C++ 4.11p2).
2858   QualType FromClass(FromTypePtr->getClass(), 0);
2859   QualType ToClass(ToTypePtr->getClass(), 0);
2860 
2861   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2862       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2863     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2864                                                  ToClass.getTypePtr());
2865     return true;
2866   }
2867 
2868   return false;
2869 }
2870 
2871 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2872 /// expression From to the type ToType. This routine checks for ambiguous or
2873 /// virtual or inaccessible base-to-derived member pointer conversions
2874 /// for which IsMemberPointerConversion has already returned true. It returns
2875 /// true and produces a diagnostic if there was an error, or returns false
2876 /// otherwise.
2877 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2878                                         CastKind &Kind,
2879                                         CXXCastPath &BasePath,
2880                                         bool IgnoreBaseAccess) {
2881   QualType FromType = From->getType();
2882   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2883   if (!FromPtrType) {
2884     // This must be a null pointer to member pointer conversion
2885     assert(From->isNullPointerConstant(Context,
2886                                        Expr::NPC_ValueDependentIsNull) &&
2887            "Expr must be null pointer constant!");
2888     Kind = CK_NullToMemberPointer;
2889     return false;
2890   }
2891 
2892   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2893   assert(ToPtrType && "No member pointer cast has a target type "
2894                       "that is not a member pointer.");
2895 
2896   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2897   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2898 
2899   // FIXME: What about dependent types?
2900   assert(FromClass->isRecordType() && "Pointer into non-class.");
2901   assert(ToClass->isRecordType() && "Pointer into non-class.");
2902 
2903   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2904                      /*DetectVirtual=*/true);
2905   bool DerivationOkay =
2906       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2907   assert(DerivationOkay &&
2908          "Should not have been called if derivation isn't OK.");
2909   (void)DerivationOkay;
2910 
2911   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2912                                   getUnqualifiedType())) {
2913     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2914     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2915       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2916     return true;
2917   }
2918 
2919   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2920     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2921       << FromClass << ToClass << QualType(VBase, 0)
2922       << From->getSourceRange();
2923     return true;
2924   }
2925 
2926   if (!IgnoreBaseAccess)
2927     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2928                          Paths.front(),
2929                          diag::err_downcast_from_inaccessible_base);
2930 
2931   // Must be a base to derived member conversion.
2932   BuildBasePathArray(Paths, BasePath);
2933   Kind = CK_BaseToDerivedMemberPointer;
2934   return false;
2935 }
2936 
2937 /// Determine whether the lifetime conversion between the two given
2938 /// qualifiers sets is nontrivial.
2939 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2940                                                Qualifiers ToQuals) {
2941   // Converting anything to const __unsafe_unretained is trivial.
2942   if (ToQuals.hasConst() &&
2943       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2944     return false;
2945 
2946   return true;
2947 }
2948 
2949 /// IsQualificationConversion - Determines whether the conversion from
2950 /// an rvalue of type FromType to ToType is a qualification conversion
2951 /// (C++ 4.4).
2952 ///
2953 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2954 /// when the qualification conversion involves a change in the Objective-C
2955 /// object lifetime.
2956 bool
2957 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2958                                 bool CStyle, bool &ObjCLifetimeConversion) {
2959   FromType = Context.getCanonicalType(FromType);
2960   ToType = Context.getCanonicalType(ToType);
2961   ObjCLifetimeConversion = false;
2962 
2963   // If FromType and ToType are the same type, this is not a
2964   // qualification conversion.
2965   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2966     return false;
2967 
2968   // (C++ 4.4p4):
2969   //   A conversion can add cv-qualifiers at levels other than the first
2970   //   in multi-level pointers, subject to the following rules: [...]
2971   bool PreviousToQualsIncludeConst = true;
2972   bool UnwrappedAnyPointer = false;
2973   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2974     // Within each iteration of the loop, we check the qualifiers to
2975     // determine if this still looks like a qualification
2976     // conversion. Then, if all is well, we unwrap one more level of
2977     // pointers or pointers-to-members and do it all again
2978     // until there are no more pointers or pointers-to-members left to
2979     // unwrap.
2980     UnwrappedAnyPointer = true;
2981 
2982     Qualifiers FromQuals = FromType.getQualifiers();
2983     Qualifiers ToQuals = ToType.getQualifiers();
2984 
2985     // Ignore __unaligned qualifier if this type is void.
2986     if (ToType.getUnqualifiedType()->isVoidType())
2987       FromQuals.removeUnaligned();
2988 
2989     // Objective-C ARC:
2990     //   Check Objective-C lifetime conversions.
2991     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2992         UnwrappedAnyPointer) {
2993       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2994         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2995           ObjCLifetimeConversion = true;
2996         FromQuals.removeObjCLifetime();
2997         ToQuals.removeObjCLifetime();
2998       } else {
2999         // Qualification conversions cannot cast between different
3000         // Objective-C lifetime qualifiers.
3001         return false;
3002       }
3003     }
3004 
3005     // Allow addition/removal of GC attributes but not changing GC attributes.
3006     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3007         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3008       FromQuals.removeObjCGCAttr();
3009       ToQuals.removeObjCGCAttr();
3010     }
3011 
3012     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3013     //      2,j, and similarly for volatile.
3014     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3015       return false;
3016 
3017     //   -- if the cv 1,j and cv 2,j are different, then const is in
3018     //      every cv for 0 < k < j.
3019     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3020         && !PreviousToQualsIncludeConst)
3021       return false;
3022 
3023     // Keep track of whether all prior cv-qualifiers in the "to" type
3024     // include const.
3025     PreviousToQualsIncludeConst
3026       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3027   }
3028 
3029   // We are left with FromType and ToType being the pointee types
3030   // after unwrapping the original FromType and ToType the same number
3031   // of types. If we unwrapped any pointers, and if FromType and
3032   // ToType have the same unqualified type (since we checked
3033   // qualifiers above), then this is a qualification conversion.
3034   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3035 }
3036 
3037 /// \brief - Determine whether this is a conversion from a scalar type to an
3038 /// atomic type.
3039 ///
3040 /// If successful, updates \c SCS's second and third steps in the conversion
3041 /// sequence to finish the conversion.
3042 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3043                                 bool InOverloadResolution,
3044                                 StandardConversionSequence &SCS,
3045                                 bool CStyle) {
3046   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3047   if (!ToAtomic)
3048     return false;
3049 
3050   StandardConversionSequence InnerSCS;
3051   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3052                             InOverloadResolution, InnerSCS,
3053                             CStyle, /*AllowObjCWritebackConversion=*/false))
3054     return false;
3055 
3056   SCS.Second = InnerSCS.Second;
3057   SCS.setToType(1, InnerSCS.getToType(1));
3058   SCS.Third = InnerSCS.Third;
3059   SCS.QualificationIncludesObjCLifetime
3060     = InnerSCS.QualificationIncludesObjCLifetime;
3061   SCS.setToType(2, InnerSCS.getToType(2));
3062   return true;
3063 }
3064 
3065 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3066                                               CXXConstructorDecl *Constructor,
3067                                               QualType Type) {
3068   const FunctionProtoType *CtorType =
3069       Constructor->getType()->getAs<FunctionProtoType>();
3070   if (CtorType->getNumParams() > 0) {
3071     QualType FirstArg = CtorType->getParamType(0);
3072     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3073       return true;
3074   }
3075   return false;
3076 }
3077 
3078 static OverloadingResult
3079 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3080                                        CXXRecordDecl *To,
3081                                        UserDefinedConversionSequence &User,
3082                                        OverloadCandidateSet &CandidateSet,
3083                                        bool AllowExplicit) {
3084   for (auto *D : S.LookupConstructors(To)) {
3085     auto Info = getConstructorInfo(D);
3086     if (!Info)
3087       continue;
3088 
3089     bool Usable = !Info.Constructor->isInvalidDecl() &&
3090                   S.isInitListConstructor(Info.Constructor) &&
3091                   (AllowExplicit || !Info.Constructor->isExplicit());
3092     if (Usable) {
3093       // If the first argument is (a reference to) the target type,
3094       // suppress conversions.
3095       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3096           S.Context, Info.Constructor, ToType);
3097       if (Info.ConstructorTmpl)
3098         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3099                                        /*ExplicitArgs*/ nullptr, From,
3100                                        CandidateSet, SuppressUserConversions);
3101       else
3102         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3103                                CandidateSet, SuppressUserConversions);
3104     }
3105   }
3106 
3107   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3108 
3109   OverloadCandidateSet::iterator Best;
3110   switch (auto Result =
3111             CandidateSet.BestViableFunction(S, From->getLocStart(),
3112                                             Best, true)) {
3113   case OR_Deleted:
3114   case OR_Success: {
3115     // Record the standard conversion we used and the conversion function.
3116     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3117     QualType ThisType = Constructor->getThisType(S.Context);
3118     // Initializer lists don't have conversions as such.
3119     User.Before.setAsIdentityConversion();
3120     User.HadMultipleCandidates = HadMultipleCandidates;
3121     User.ConversionFunction = Constructor;
3122     User.FoundConversionFunction = Best->FoundDecl;
3123     User.After.setAsIdentityConversion();
3124     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3125     User.After.setAllToTypes(ToType);
3126     return Result;
3127   }
3128 
3129   case OR_No_Viable_Function:
3130     return OR_No_Viable_Function;
3131   case OR_Ambiguous:
3132     return OR_Ambiguous;
3133   }
3134 
3135   llvm_unreachable("Invalid OverloadResult!");
3136 }
3137 
3138 /// Determines whether there is a user-defined conversion sequence
3139 /// (C++ [over.ics.user]) that converts expression From to the type
3140 /// ToType. If such a conversion exists, User will contain the
3141 /// user-defined conversion sequence that performs such a conversion
3142 /// and this routine will return true. Otherwise, this routine returns
3143 /// false and User is unspecified.
3144 ///
3145 /// \param AllowExplicit  true if the conversion should consider C++0x
3146 /// "explicit" conversion functions as well as non-explicit conversion
3147 /// functions (C++0x [class.conv.fct]p2).
3148 ///
3149 /// \param AllowObjCConversionOnExplicit true if the conversion should
3150 /// allow an extra Objective-C pointer conversion on uses of explicit
3151 /// constructors. Requires \c AllowExplicit to also be set.
3152 static OverloadingResult
3153 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3154                         UserDefinedConversionSequence &User,
3155                         OverloadCandidateSet &CandidateSet,
3156                         bool AllowExplicit,
3157                         bool AllowObjCConversionOnExplicit) {
3158   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3159 
3160   // Whether we will only visit constructors.
3161   bool ConstructorsOnly = false;
3162 
3163   // If the type we are conversion to is a class type, enumerate its
3164   // constructors.
3165   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3166     // C++ [over.match.ctor]p1:
3167     //   When objects of class type are direct-initialized (8.5), or
3168     //   copy-initialized from an expression of the same or a
3169     //   derived class type (8.5), overload resolution selects the
3170     //   constructor. [...] For copy-initialization, the candidate
3171     //   functions are all the converting constructors (12.3.1) of
3172     //   that class. The argument list is the expression-list within
3173     //   the parentheses of the initializer.
3174     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3175         (From->getType()->getAs<RecordType>() &&
3176          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3177       ConstructorsOnly = true;
3178 
3179     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3180       // We're not going to find any constructors.
3181     } else if (CXXRecordDecl *ToRecordDecl
3182                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3183 
3184       Expr **Args = &From;
3185       unsigned NumArgs = 1;
3186       bool ListInitializing = false;
3187       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3188         // But first, see if there is an init-list-constructor that will work.
3189         OverloadingResult Result = IsInitializerListConstructorConversion(
3190             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3191         if (Result != OR_No_Viable_Function)
3192           return Result;
3193         // Never mind.
3194         CandidateSet.clear();
3195 
3196         // If we're list-initializing, we pass the individual elements as
3197         // arguments, not the entire list.
3198         Args = InitList->getInits();
3199         NumArgs = InitList->getNumInits();
3200         ListInitializing = true;
3201       }
3202 
3203       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3204         auto Info = getConstructorInfo(D);
3205         if (!Info)
3206           continue;
3207 
3208         bool Usable = !Info.Constructor->isInvalidDecl();
3209         if (ListInitializing)
3210           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3211         else
3212           Usable = Usable &&
3213                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3214         if (Usable) {
3215           bool SuppressUserConversions = !ConstructorsOnly;
3216           if (SuppressUserConversions && ListInitializing) {
3217             SuppressUserConversions = false;
3218             if (NumArgs == 1) {
3219               // If the first argument is (a reference to) the target type,
3220               // suppress conversions.
3221               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3222                   S.Context, Info.Constructor, ToType);
3223             }
3224           }
3225           if (Info.ConstructorTmpl)
3226             S.AddTemplateOverloadCandidate(
3227                 Info.ConstructorTmpl, Info.FoundDecl,
3228                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3229                 CandidateSet, SuppressUserConversions);
3230           else
3231             // Allow one user-defined conversion when user specifies a
3232             // From->ToType conversion via an static cast (c-style, etc).
3233             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3234                                    llvm::makeArrayRef(Args, NumArgs),
3235                                    CandidateSet, SuppressUserConversions);
3236         }
3237       }
3238     }
3239   }
3240 
3241   // Enumerate conversion functions, if we're allowed to.
3242   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3243   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3244     // No conversion functions from incomplete types.
3245   } else if (const RecordType *FromRecordType
3246                                    = From->getType()->getAs<RecordType>()) {
3247     if (CXXRecordDecl *FromRecordDecl
3248          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3249       // Add all of the conversion functions as candidates.
3250       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3251       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3252         DeclAccessPair FoundDecl = I.getPair();
3253         NamedDecl *D = FoundDecl.getDecl();
3254         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3255         if (isa<UsingShadowDecl>(D))
3256           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3257 
3258         CXXConversionDecl *Conv;
3259         FunctionTemplateDecl *ConvTemplate;
3260         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3261           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3262         else
3263           Conv = cast<CXXConversionDecl>(D);
3264 
3265         if (AllowExplicit || !Conv->isExplicit()) {
3266           if (ConvTemplate)
3267             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3268                                              ActingContext, From, ToType,
3269                                              CandidateSet,
3270                                              AllowObjCConversionOnExplicit);
3271           else
3272             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3273                                      From, ToType, CandidateSet,
3274                                      AllowObjCConversionOnExplicit);
3275         }
3276       }
3277     }
3278   }
3279 
3280   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3281 
3282   OverloadCandidateSet::iterator Best;
3283   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3284                                                         Best, true)) {
3285   case OR_Success:
3286   case OR_Deleted:
3287     // Record the standard conversion we used and the conversion function.
3288     if (CXXConstructorDecl *Constructor
3289           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3290       // C++ [over.ics.user]p1:
3291       //   If the user-defined conversion is specified by a
3292       //   constructor (12.3.1), the initial standard conversion
3293       //   sequence converts the source type to the type required by
3294       //   the argument of the constructor.
3295       //
3296       QualType ThisType = Constructor->getThisType(S.Context);
3297       if (isa<InitListExpr>(From)) {
3298         // Initializer lists don't have conversions as such.
3299         User.Before.setAsIdentityConversion();
3300       } else {
3301         if (Best->Conversions[0].isEllipsis())
3302           User.EllipsisConversion = true;
3303         else {
3304           User.Before = Best->Conversions[0].Standard;
3305           User.EllipsisConversion = false;
3306         }
3307       }
3308       User.HadMultipleCandidates = HadMultipleCandidates;
3309       User.ConversionFunction = Constructor;
3310       User.FoundConversionFunction = Best->FoundDecl;
3311       User.After.setAsIdentityConversion();
3312       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3313       User.After.setAllToTypes(ToType);
3314       return Result;
3315     }
3316     if (CXXConversionDecl *Conversion
3317                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3318       // C++ [over.ics.user]p1:
3319       //
3320       //   [...] If the user-defined conversion is specified by a
3321       //   conversion function (12.3.2), the initial standard
3322       //   conversion sequence converts the source type to the
3323       //   implicit object parameter of the conversion function.
3324       User.Before = Best->Conversions[0].Standard;
3325       User.HadMultipleCandidates = HadMultipleCandidates;
3326       User.ConversionFunction = Conversion;
3327       User.FoundConversionFunction = Best->FoundDecl;
3328       User.EllipsisConversion = false;
3329 
3330       // C++ [over.ics.user]p2:
3331       //   The second standard conversion sequence converts the
3332       //   result of the user-defined conversion to the target type
3333       //   for the sequence. Since an implicit conversion sequence
3334       //   is an initialization, the special rules for
3335       //   initialization by user-defined conversion apply when
3336       //   selecting the best user-defined conversion for a
3337       //   user-defined conversion sequence (see 13.3.3 and
3338       //   13.3.3.1).
3339       User.After = Best->FinalConversion;
3340       return Result;
3341     }
3342     llvm_unreachable("Not a constructor or conversion function?");
3343 
3344   case OR_No_Viable_Function:
3345     return OR_No_Viable_Function;
3346 
3347   case OR_Ambiguous:
3348     return OR_Ambiguous;
3349   }
3350 
3351   llvm_unreachable("Invalid OverloadResult!");
3352 }
3353 
3354 bool
3355 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3356   ImplicitConversionSequence ICS;
3357   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3358                                     OverloadCandidateSet::CSK_Normal);
3359   OverloadingResult OvResult =
3360     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3361                             CandidateSet, false, false);
3362   if (OvResult == OR_Ambiguous)
3363     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3364         << From->getType() << ToType << From->getSourceRange();
3365   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3366     if (!RequireCompleteType(From->getLocStart(), ToType,
3367                              diag::err_typecheck_nonviable_condition_incomplete,
3368                              From->getType(), From->getSourceRange()))
3369       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3370           << false << From->getType() << From->getSourceRange() << ToType;
3371   } else
3372     return false;
3373   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3374   return true;
3375 }
3376 
3377 /// \brief Compare the user-defined conversion functions or constructors
3378 /// of two user-defined conversion sequences to determine whether any ordering
3379 /// is possible.
3380 static ImplicitConversionSequence::CompareKind
3381 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3382                            FunctionDecl *Function2) {
3383   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3384     return ImplicitConversionSequence::Indistinguishable;
3385 
3386   // Objective-C++:
3387   //   If both conversion functions are implicitly-declared conversions from
3388   //   a lambda closure type to a function pointer and a block pointer,
3389   //   respectively, always prefer the conversion to a function pointer,
3390   //   because the function pointer is more lightweight and is more likely
3391   //   to keep code working.
3392   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3393   if (!Conv1)
3394     return ImplicitConversionSequence::Indistinguishable;
3395 
3396   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3397   if (!Conv2)
3398     return ImplicitConversionSequence::Indistinguishable;
3399 
3400   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3401     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3402     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3403     if (Block1 != Block2)
3404       return Block1 ? ImplicitConversionSequence::Worse
3405                     : ImplicitConversionSequence::Better;
3406   }
3407 
3408   return ImplicitConversionSequence::Indistinguishable;
3409 }
3410 
3411 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3412     const ImplicitConversionSequence &ICS) {
3413   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3414          (ICS.isUserDefined() &&
3415           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3416 }
3417 
3418 /// CompareImplicitConversionSequences - Compare two implicit
3419 /// conversion sequences to determine whether one is better than the
3420 /// other or if they are indistinguishable (C++ 13.3.3.2).
3421 static ImplicitConversionSequence::CompareKind
3422 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3423                                    const ImplicitConversionSequence& ICS1,
3424                                    const ImplicitConversionSequence& ICS2)
3425 {
3426   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3427   // conversion sequences (as defined in 13.3.3.1)
3428   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3429   //      conversion sequence than a user-defined conversion sequence or
3430   //      an ellipsis conversion sequence, and
3431   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3432   //      conversion sequence than an ellipsis conversion sequence
3433   //      (13.3.3.1.3).
3434   //
3435   // C++0x [over.best.ics]p10:
3436   //   For the purpose of ranking implicit conversion sequences as
3437   //   described in 13.3.3.2, the ambiguous conversion sequence is
3438   //   treated as a user-defined sequence that is indistinguishable
3439   //   from any other user-defined conversion sequence.
3440 
3441   // String literal to 'char *' conversion has been deprecated in C++03. It has
3442   // been removed from C++11. We still accept this conversion, if it happens at
3443   // the best viable function. Otherwise, this conversion is considered worse
3444   // than ellipsis conversion. Consider this as an extension; this is not in the
3445   // standard. For example:
3446   //
3447   // int &f(...);    // #1
3448   // void f(char*);  // #2
3449   // void g() { int &r = f("foo"); }
3450   //
3451   // In C++03, we pick #2 as the best viable function.
3452   // In C++11, we pick #1 as the best viable function, because ellipsis
3453   // conversion is better than string-literal to char* conversion (since there
3454   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3455   // convert arguments, #2 would be the best viable function in C++11.
3456   // If the best viable function has this conversion, a warning will be issued
3457   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3458 
3459   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3460       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3461       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3462     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3463                ? ImplicitConversionSequence::Worse
3464                : ImplicitConversionSequence::Better;
3465 
3466   if (ICS1.getKindRank() < ICS2.getKindRank())
3467     return ImplicitConversionSequence::Better;
3468   if (ICS2.getKindRank() < ICS1.getKindRank())
3469     return ImplicitConversionSequence::Worse;
3470 
3471   // The following checks require both conversion sequences to be of
3472   // the same kind.
3473   if (ICS1.getKind() != ICS2.getKind())
3474     return ImplicitConversionSequence::Indistinguishable;
3475 
3476   ImplicitConversionSequence::CompareKind Result =
3477       ImplicitConversionSequence::Indistinguishable;
3478 
3479   // Two implicit conversion sequences of the same form are
3480   // indistinguishable conversion sequences unless one of the
3481   // following rules apply: (C++ 13.3.3.2p3):
3482 
3483   // List-initialization sequence L1 is a better conversion sequence than
3484   // list-initialization sequence L2 if:
3485   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3486   //   if not that,
3487   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3488   //   and N1 is smaller than N2.,
3489   // even if one of the other rules in this paragraph would otherwise apply.
3490   if (!ICS1.isBad()) {
3491     if (ICS1.isStdInitializerListElement() &&
3492         !ICS2.isStdInitializerListElement())
3493       return ImplicitConversionSequence::Better;
3494     if (!ICS1.isStdInitializerListElement() &&
3495         ICS2.isStdInitializerListElement())
3496       return ImplicitConversionSequence::Worse;
3497   }
3498 
3499   if (ICS1.isStandard())
3500     // Standard conversion sequence S1 is a better conversion sequence than
3501     // standard conversion sequence S2 if [...]
3502     Result = CompareStandardConversionSequences(S, Loc,
3503                                                 ICS1.Standard, ICS2.Standard);
3504   else if (ICS1.isUserDefined()) {
3505     // User-defined conversion sequence U1 is a better conversion
3506     // sequence than another user-defined conversion sequence U2 if
3507     // they contain the same user-defined conversion function or
3508     // constructor and if the second standard conversion sequence of
3509     // U1 is better than the second standard conversion sequence of
3510     // U2 (C++ 13.3.3.2p3).
3511     if (ICS1.UserDefined.ConversionFunction ==
3512           ICS2.UserDefined.ConversionFunction)
3513       Result = CompareStandardConversionSequences(S, Loc,
3514                                                   ICS1.UserDefined.After,
3515                                                   ICS2.UserDefined.After);
3516     else
3517       Result = compareConversionFunctions(S,
3518                                           ICS1.UserDefined.ConversionFunction,
3519                                           ICS2.UserDefined.ConversionFunction);
3520   }
3521 
3522   return Result;
3523 }
3524 
3525 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3526   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3527     Qualifiers Quals;
3528     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3529     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3530   }
3531 
3532   return Context.hasSameUnqualifiedType(T1, T2);
3533 }
3534 
3535 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3536 // determine if one is a proper subset of the other.
3537 static ImplicitConversionSequence::CompareKind
3538 compareStandardConversionSubsets(ASTContext &Context,
3539                                  const StandardConversionSequence& SCS1,
3540                                  const StandardConversionSequence& SCS2) {
3541   ImplicitConversionSequence::CompareKind Result
3542     = ImplicitConversionSequence::Indistinguishable;
3543 
3544   // the identity conversion sequence is considered to be a subsequence of
3545   // any non-identity conversion sequence
3546   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3547     return ImplicitConversionSequence::Better;
3548   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3549     return ImplicitConversionSequence::Worse;
3550 
3551   if (SCS1.Second != SCS2.Second) {
3552     if (SCS1.Second == ICK_Identity)
3553       Result = ImplicitConversionSequence::Better;
3554     else if (SCS2.Second == ICK_Identity)
3555       Result = ImplicitConversionSequence::Worse;
3556     else
3557       return ImplicitConversionSequence::Indistinguishable;
3558   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3559     return ImplicitConversionSequence::Indistinguishable;
3560 
3561   if (SCS1.Third == SCS2.Third) {
3562     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3563                              : ImplicitConversionSequence::Indistinguishable;
3564   }
3565 
3566   if (SCS1.Third == ICK_Identity)
3567     return Result == ImplicitConversionSequence::Worse
3568              ? ImplicitConversionSequence::Indistinguishable
3569              : ImplicitConversionSequence::Better;
3570 
3571   if (SCS2.Third == ICK_Identity)
3572     return Result == ImplicitConversionSequence::Better
3573              ? ImplicitConversionSequence::Indistinguishable
3574              : ImplicitConversionSequence::Worse;
3575 
3576   return ImplicitConversionSequence::Indistinguishable;
3577 }
3578 
3579 /// \brief Determine whether one of the given reference bindings is better
3580 /// than the other based on what kind of bindings they are.
3581 static bool
3582 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3583                              const StandardConversionSequence &SCS2) {
3584   // C++0x [over.ics.rank]p3b4:
3585   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3586   //      implicit object parameter of a non-static member function declared
3587   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3588   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3589   //      lvalue reference to a function lvalue and S2 binds an rvalue
3590   //      reference*.
3591   //
3592   // FIXME: Rvalue references. We're going rogue with the above edits,
3593   // because the semantics in the current C++0x working paper (N3225 at the
3594   // time of this writing) break the standard definition of std::forward
3595   // and std::reference_wrapper when dealing with references to functions.
3596   // Proposed wording changes submitted to CWG for consideration.
3597   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3598       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3599     return false;
3600 
3601   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3602           SCS2.IsLvalueReference) ||
3603          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3604           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3605 }
3606 
3607 /// CompareStandardConversionSequences - Compare two standard
3608 /// conversion sequences to determine whether one is better than the
3609 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3610 static ImplicitConversionSequence::CompareKind
3611 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3612                                    const StandardConversionSequence& SCS1,
3613                                    const StandardConversionSequence& SCS2)
3614 {
3615   // Standard conversion sequence S1 is a better conversion sequence
3616   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3617 
3618   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3619   //     sequences in the canonical form defined by 13.3.3.1.1,
3620   //     excluding any Lvalue Transformation; the identity conversion
3621   //     sequence is considered to be a subsequence of any
3622   //     non-identity conversion sequence) or, if not that,
3623   if (ImplicitConversionSequence::CompareKind CK
3624         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3625     return CK;
3626 
3627   //  -- the rank of S1 is better than the rank of S2 (by the rules
3628   //     defined below), or, if not that,
3629   ImplicitConversionRank Rank1 = SCS1.getRank();
3630   ImplicitConversionRank Rank2 = SCS2.getRank();
3631   if (Rank1 < Rank2)
3632     return ImplicitConversionSequence::Better;
3633   else if (Rank2 < Rank1)
3634     return ImplicitConversionSequence::Worse;
3635 
3636   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3637   // are indistinguishable unless one of the following rules
3638   // applies:
3639 
3640   //   A conversion that is not a conversion of a pointer, or
3641   //   pointer to member, to bool is better than another conversion
3642   //   that is such a conversion.
3643   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3644     return SCS2.isPointerConversionToBool()
3645              ? ImplicitConversionSequence::Better
3646              : ImplicitConversionSequence::Worse;
3647 
3648   // C++ [over.ics.rank]p4b2:
3649   //
3650   //   If class B is derived directly or indirectly from class A,
3651   //   conversion of B* to A* is better than conversion of B* to
3652   //   void*, and conversion of A* to void* is better than conversion
3653   //   of B* to void*.
3654   bool SCS1ConvertsToVoid
3655     = SCS1.isPointerConversionToVoidPointer(S.Context);
3656   bool SCS2ConvertsToVoid
3657     = SCS2.isPointerConversionToVoidPointer(S.Context);
3658   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3659     // Exactly one of the conversion sequences is a conversion to
3660     // a void pointer; it's the worse conversion.
3661     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3662                               : ImplicitConversionSequence::Worse;
3663   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3664     // Neither conversion sequence converts to a void pointer; compare
3665     // their derived-to-base conversions.
3666     if (ImplicitConversionSequence::CompareKind DerivedCK
3667           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3668       return DerivedCK;
3669   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3670              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3671     // Both conversion sequences are conversions to void
3672     // pointers. Compare the source types to determine if there's an
3673     // inheritance relationship in their sources.
3674     QualType FromType1 = SCS1.getFromType();
3675     QualType FromType2 = SCS2.getFromType();
3676 
3677     // Adjust the types we're converting from via the array-to-pointer
3678     // conversion, if we need to.
3679     if (SCS1.First == ICK_Array_To_Pointer)
3680       FromType1 = S.Context.getArrayDecayedType(FromType1);
3681     if (SCS2.First == ICK_Array_To_Pointer)
3682       FromType2 = S.Context.getArrayDecayedType(FromType2);
3683 
3684     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3685     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3686 
3687     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3688       return ImplicitConversionSequence::Better;
3689     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3690       return ImplicitConversionSequence::Worse;
3691 
3692     // Objective-C++: If one interface is more specific than the
3693     // other, it is the better one.
3694     const ObjCObjectPointerType* FromObjCPtr1
3695       = FromType1->getAs<ObjCObjectPointerType>();
3696     const ObjCObjectPointerType* FromObjCPtr2
3697       = FromType2->getAs<ObjCObjectPointerType>();
3698     if (FromObjCPtr1 && FromObjCPtr2) {
3699       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3700                                                           FromObjCPtr2);
3701       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3702                                                            FromObjCPtr1);
3703       if (AssignLeft != AssignRight) {
3704         return AssignLeft? ImplicitConversionSequence::Better
3705                          : ImplicitConversionSequence::Worse;
3706       }
3707     }
3708   }
3709 
3710   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3711   // bullet 3).
3712   if (ImplicitConversionSequence::CompareKind QualCK
3713         = CompareQualificationConversions(S, SCS1, SCS2))
3714     return QualCK;
3715 
3716   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3717     // Check for a better reference binding based on the kind of bindings.
3718     if (isBetterReferenceBindingKind(SCS1, SCS2))
3719       return ImplicitConversionSequence::Better;
3720     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3721       return ImplicitConversionSequence::Worse;
3722 
3723     // C++ [over.ics.rank]p3b4:
3724     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3725     //      which the references refer are the same type except for
3726     //      top-level cv-qualifiers, and the type to which the reference
3727     //      initialized by S2 refers is more cv-qualified than the type
3728     //      to which the reference initialized by S1 refers.
3729     QualType T1 = SCS1.getToType(2);
3730     QualType T2 = SCS2.getToType(2);
3731     T1 = S.Context.getCanonicalType(T1);
3732     T2 = S.Context.getCanonicalType(T2);
3733     Qualifiers T1Quals, T2Quals;
3734     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3735     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3736     if (UnqualT1 == UnqualT2) {
3737       // Objective-C++ ARC: If the references refer to objects with different
3738       // lifetimes, prefer bindings that don't change lifetime.
3739       if (SCS1.ObjCLifetimeConversionBinding !=
3740                                           SCS2.ObjCLifetimeConversionBinding) {
3741         return SCS1.ObjCLifetimeConversionBinding
3742                                            ? ImplicitConversionSequence::Worse
3743                                            : ImplicitConversionSequence::Better;
3744       }
3745 
3746       // If the type is an array type, promote the element qualifiers to the
3747       // type for comparison.
3748       if (isa<ArrayType>(T1) && T1Quals)
3749         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3750       if (isa<ArrayType>(T2) && T2Quals)
3751         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3752       if (T2.isMoreQualifiedThan(T1))
3753         return ImplicitConversionSequence::Better;
3754       else if (T1.isMoreQualifiedThan(T2))
3755         return ImplicitConversionSequence::Worse;
3756     }
3757   }
3758 
3759   // In Microsoft mode, prefer an integral conversion to a
3760   // floating-to-integral conversion if the integral conversion
3761   // is between types of the same size.
3762   // For example:
3763   // void f(float);
3764   // void f(int);
3765   // int main {
3766   //    long a;
3767   //    f(a);
3768   // }
3769   // Here, MSVC will call f(int) instead of generating a compile error
3770   // as clang will do in standard mode.
3771   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3772       SCS2.Second == ICK_Floating_Integral &&
3773       S.Context.getTypeSize(SCS1.getFromType()) ==
3774           S.Context.getTypeSize(SCS1.getToType(2)))
3775     return ImplicitConversionSequence::Better;
3776 
3777   return ImplicitConversionSequence::Indistinguishable;
3778 }
3779 
3780 /// CompareQualificationConversions - Compares two standard conversion
3781 /// sequences to determine whether they can be ranked based on their
3782 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3783 static ImplicitConversionSequence::CompareKind
3784 CompareQualificationConversions(Sema &S,
3785                                 const StandardConversionSequence& SCS1,
3786                                 const StandardConversionSequence& SCS2) {
3787   // C++ 13.3.3.2p3:
3788   //  -- S1 and S2 differ only in their qualification conversion and
3789   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3790   //     cv-qualification signature of type T1 is a proper subset of
3791   //     the cv-qualification signature of type T2, and S1 is not the
3792   //     deprecated string literal array-to-pointer conversion (4.2).
3793   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3794       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3795     return ImplicitConversionSequence::Indistinguishable;
3796 
3797   // FIXME: the example in the standard doesn't use a qualification
3798   // conversion (!)
3799   QualType T1 = SCS1.getToType(2);
3800   QualType T2 = SCS2.getToType(2);
3801   T1 = S.Context.getCanonicalType(T1);
3802   T2 = S.Context.getCanonicalType(T2);
3803   Qualifiers T1Quals, T2Quals;
3804   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3805   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3806 
3807   // If the types are the same, we won't learn anything by unwrapped
3808   // them.
3809   if (UnqualT1 == UnqualT2)
3810     return ImplicitConversionSequence::Indistinguishable;
3811 
3812   // If the type is an array type, promote the element qualifiers to the type
3813   // for comparison.
3814   if (isa<ArrayType>(T1) && T1Quals)
3815     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3816   if (isa<ArrayType>(T2) && T2Quals)
3817     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3818 
3819   ImplicitConversionSequence::CompareKind Result
3820     = ImplicitConversionSequence::Indistinguishable;
3821 
3822   // Objective-C++ ARC:
3823   //   Prefer qualification conversions not involving a change in lifetime
3824   //   to qualification conversions that do not change lifetime.
3825   if (SCS1.QualificationIncludesObjCLifetime !=
3826                                       SCS2.QualificationIncludesObjCLifetime) {
3827     Result = SCS1.QualificationIncludesObjCLifetime
3828                ? ImplicitConversionSequence::Worse
3829                : ImplicitConversionSequence::Better;
3830   }
3831 
3832   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3833     // Within each iteration of the loop, we check the qualifiers to
3834     // determine if this still looks like a qualification
3835     // conversion. Then, if all is well, we unwrap one more level of
3836     // pointers or pointers-to-members and do it all again
3837     // until there are no more pointers or pointers-to-members left
3838     // to unwrap. This essentially mimics what
3839     // IsQualificationConversion does, but here we're checking for a
3840     // strict subset of qualifiers.
3841     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3842       // The qualifiers are the same, so this doesn't tell us anything
3843       // about how the sequences rank.
3844       ;
3845     else if (T2.isMoreQualifiedThan(T1)) {
3846       // T1 has fewer qualifiers, so it could be the better sequence.
3847       if (Result == ImplicitConversionSequence::Worse)
3848         // Neither has qualifiers that are a subset of the other's
3849         // qualifiers.
3850         return ImplicitConversionSequence::Indistinguishable;
3851 
3852       Result = ImplicitConversionSequence::Better;
3853     } else if (T1.isMoreQualifiedThan(T2)) {
3854       // T2 has fewer qualifiers, so it could be the better sequence.
3855       if (Result == ImplicitConversionSequence::Better)
3856         // Neither has qualifiers that are a subset of the other's
3857         // qualifiers.
3858         return ImplicitConversionSequence::Indistinguishable;
3859 
3860       Result = ImplicitConversionSequence::Worse;
3861     } else {
3862       // Qualifiers are disjoint.
3863       return ImplicitConversionSequence::Indistinguishable;
3864     }
3865 
3866     // If the types after this point are equivalent, we're done.
3867     if (S.Context.hasSameUnqualifiedType(T1, T2))
3868       break;
3869   }
3870 
3871   // Check that the winning standard conversion sequence isn't using
3872   // the deprecated string literal array to pointer conversion.
3873   switch (Result) {
3874   case ImplicitConversionSequence::Better:
3875     if (SCS1.DeprecatedStringLiteralToCharPtr)
3876       Result = ImplicitConversionSequence::Indistinguishable;
3877     break;
3878 
3879   case ImplicitConversionSequence::Indistinguishable:
3880     break;
3881 
3882   case ImplicitConversionSequence::Worse:
3883     if (SCS2.DeprecatedStringLiteralToCharPtr)
3884       Result = ImplicitConversionSequence::Indistinguishable;
3885     break;
3886   }
3887 
3888   return Result;
3889 }
3890 
3891 /// CompareDerivedToBaseConversions - Compares two standard conversion
3892 /// sequences to determine whether they can be ranked based on their
3893 /// various kinds of derived-to-base conversions (C++
3894 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3895 /// conversions between Objective-C interface types.
3896 static ImplicitConversionSequence::CompareKind
3897 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3898                                 const StandardConversionSequence& SCS1,
3899                                 const StandardConversionSequence& SCS2) {
3900   QualType FromType1 = SCS1.getFromType();
3901   QualType ToType1 = SCS1.getToType(1);
3902   QualType FromType2 = SCS2.getFromType();
3903   QualType ToType2 = SCS2.getToType(1);
3904 
3905   // Adjust the types we're converting from via the array-to-pointer
3906   // conversion, if we need to.
3907   if (SCS1.First == ICK_Array_To_Pointer)
3908     FromType1 = S.Context.getArrayDecayedType(FromType1);
3909   if (SCS2.First == ICK_Array_To_Pointer)
3910     FromType2 = S.Context.getArrayDecayedType(FromType2);
3911 
3912   // Canonicalize all of the types.
3913   FromType1 = S.Context.getCanonicalType(FromType1);
3914   ToType1 = S.Context.getCanonicalType(ToType1);
3915   FromType2 = S.Context.getCanonicalType(FromType2);
3916   ToType2 = S.Context.getCanonicalType(ToType2);
3917 
3918   // C++ [over.ics.rank]p4b3:
3919   //
3920   //   If class B is derived directly or indirectly from class A and
3921   //   class C is derived directly or indirectly from B,
3922   //
3923   // Compare based on pointer conversions.
3924   if (SCS1.Second == ICK_Pointer_Conversion &&
3925       SCS2.Second == ICK_Pointer_Conversion &&
3926       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3927       FromType1->isPointerType() && FromType2->isPointerType() &&
3928       ToType1->isPointerType() && ToType2->isPointerType()) {
3929     QualType FromPointee1
3930       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3931     QualType ToPointee1
3932       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3933     QualType FromPointee2
3934       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3935     QualType ToPointee2
3936       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3937 
3938     //   -- conversion of C* to B* is better than conversion of C* to A*,
3939     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3940       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3941         return ImplicitConversionSequence::Better;
3942       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3943         return ImplicitConversionSequence::Worse;
3944     }
3945 
3946     //   -- conversion of B* to A* is better than conversion of C* to A*,
3947     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3948       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3949         return ImplicitConversionSequence::Better;
3950       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3951         return ImplicitConversionSequence::Worse;
3952     }
3953   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3954              SCS2.Second == ICK_Pointer_Conversion) {
3955     const ObjCObjectPointerType *FromPtr1
3956       = FromType1->getAs<ObjCObjectPointerType>();
3957     const ObjCObjectPointerType *FromPtr2
3958       = FromType2->getAs<ObjCObjectPointerType>();
3959     const ObjCObjectPointerType *ToPtr1
3960       = ToType1->getAs<ObjCObjectPointerType>();
3961     const ObjCObjectPointerType *ToPtr2
3962       = ToType2->getAs<ObjCObjectPointerType>();
3963 
3964     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3965       // Apply the same conversion ranking rules for Objective-C pointer types
3966       // that we do for C++ pointers to class types. However, we employ the
3967       // Objective-C pseudo-subtyping relationship used for assignment of
3968       // Objective-C pointer types.
3969       bool FromAssignLeft
3970         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3971       bool FromAssignRight
3972         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3973       bool ToAssignLeft
3974         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3975       bool ToAssignRight
3976         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3977 
3978       // A conversion to an a non-id object pointer type or qualified 'id'
3979       // type is better than a conversion to 'id'.
3980       if (ToPtr1->isObjCIdType() &&
3981           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3982         return ImplicitConversionSequence::Worse;
3983       if (ToPtr2->isObjCIdType() &&
3984           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3985         return ImplicitConversionSequence::Better;
3986 
3987       // A conversion to a non-id object pointer type is better than a
3988       // conversion to a qualified 'id' type
3989       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3990         return ImplicitConversionSequence::Worse;
3991       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3992         return ImplicitConversionSequence::Better;
3993 
3994       // A conversion to an a non-Class object pointer type or qualified 'Class'
3995       // type is better than a conversion to 'Class'.
3996       if (ToPtr1->isObjCClassType() &&
3997           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3998         return ImplicitConversionSequence::Worse;
3999       if (ToPtr2->isObjCClassType() &&
4000           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4001         return ImplicitConversionSequence::Better;
4002 
4003       // A conversion to a non-Class object pointer type is better than a
4004       // conversion to a qualified 'Class' type.
4005       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4006         return ImplicitConversionSequence::Worse;
4007       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4008         return ImplicitConversionSequence::Better;
4009 
4010       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4011       if (S.Context.hasSameType(FromType1, FromType2) &&
4012           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4013           (ToAssignLeft != ToAssignRight))
4014         return ToAssignLeft? ImplicitConversionSequence::Worse
4015                            : ImplicitConversionSequence::Better;
4016 
4017       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4018       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4019           (FromAssignLeft != FromAssignRight))
4020         return FromAssignLeft? ImplicitConversionSequence::Better
4021         : ImplicitConversionSequence::Worse;
4022     }
4023   }
4024 
4025   // Ranking of member-pointer types.
4026   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4027       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4028       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4029     const MemberPointerType * FromMemPointer1 =
4030                                         FromType1->getAs<MemberPointerType>();
4031     const MemberPointerType * ToMemPointer1 =
4032                                           ToType1->getAs<MemberPointerType>();
4033     const MemberPointerType * FromMemPointer2 =
4034                                           FromType2->getAs<MemberPointerType>();
4035     const MemberPointerType * ToMemPointer2 =
4036                                           ToType2->getAs<MemberPointerType>();
4037     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4038     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4039     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4040     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4041     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4042     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4043     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4044     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4045     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4046     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4047       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4048         return ImplicitConversionSequence::Worse;
4049       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4050         return ImplicitConversionSequence::Better;
4051     }
4052     // conversion of B::* to C::* is better than conversion of A::* to C::*
4053     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4054       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4055         return ImplicitConversionSequence::Better;
4056       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4057         return ImplicitConversionSequence::Worse;
4058     }
4059   }
4060 
4061   if (SCS1.Second == ICK_Derived_To_Base) {
4062     //   -- conversion of C to B is better than conversion of C to A,
4063     //   -- binding of an expression of type C to a reference of type
4064     //      B& is better than binding an expression of type C to a
4065     //      reference of type A&,
4066     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4067         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4068       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4069         return ImplicitConversionSequence::Better;
4070       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4071         return ImplicitConversionSequence::Worse;
4072     }
4073 
4074     //   -- conversion of B to A is better than conversion of C to A.
4075     //   -- binding of an expression of type B to a reference of type
4076     //      A& is better than binding an expression of type C to a
4077     //      reference of type A&,
4078     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4079         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4080       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4081         return ImplicitConversionSequence::Better;
4082       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4083         return ImplicitConversionSequence::Worse;
4084     }
4085   }
4086 
4087   return ImplicitConversionSequence::Indistinguishable;
4088 }
4089 
4090 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4091 /// C++ class.
4092 static bool isTypeValid(QualType T) {
4093   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4094     return !Record->isInvalidDecl();
4095 
4096   return true;
4097 }
4098 
4099 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4100 /// determine whether they are reference-related,
4101 /// reference-compatible, reference-compatible with added
4102 /// qualification, or incompatible, for use in C++ initialization by
4103 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4104 /// type, and the first type (T1) is the pointee type of the reference
4105 /// type being initialized.
4106 Sema::ReferenceCompareResult
4107 Sema::CompareReferenceRelationship(SourceLocation Loc,
4108                                    QualType OrigT1, QualType OrigT2,
4109                                    bool &DerivedToBase,
4110                                    bool &ObjCConversion,
4111                                    bool &ObjCLifetimeConversion) {
4112   assert(!OrigT1->isReferenceType() &&
4113     "T1 must be the pointee type of the reference type");
4114   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4115 
4116   QualType T1 = Context.getCanonicalType(OrigT1);
4117   QualType T2 = Context.getCanonicalType(OrigT2);
4118   Qualifiers T1Quals, T2Quals;
4119   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4120   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4121 
4122   // C++ [dcl.init.ref]p4:
4123   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4124   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4125   //   T1 is a base class of T2.
4126   DerivedToBase = false;
4127   ObjCConversion = false;
4128   ObjCLifetimeConversion = false;
4129   if (UnqualT1 == UnqualT2) {
4130     // Nothing to do.
4131   } else if (isCompleteType(Loc, OrigT2) &&
4132              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4133              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4134     DerivedToBase = true;
4135   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4136            UnqualT2->isObjCObjectOrInterfaceType() &&
4137            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4138     ObjCConversion = true;
4139   else
4140     return Ref_Incompatible;
4141 
4142   // At this point, we know that T1 and T2 are reference-related (at
4143   // least).
4144 
4145   // If the type is an array type, promote the element qualifiers to the type
4146   // for comparison.
4147   if (isa<ArrayType>(T1) && T1Quals)
4148     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4149   if (isa<ArrayType>(T2) && T2Quals)
4150     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4151 
4152   // C++ [dcl.init.ref]p4:
4153   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4154   //   reference-related to T2 and cv1 is the same cv-qualification
4155   //   as, or greater cv-qualification than, cv2. For purposes of
4156   //   overload resolution, cases for which cv1 is greater
4157   //   cv-qualification than cv2 are identified as
4158   //   reference-compatible with added qualification (see 13.3.3.2).
4159   //
4160   // Note that we also require equivalence of Objective-C GC and address-space
4161   // qualifiers when performing these computations, so that e.g., an int in
4162   // address space 1 is not reference-compatible with an int in address
4163   // space 2.
4164   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4165       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4166     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4167       ObjCLifetimeConversion = true;
4168 
4169     T1Quals.removeObjCLifetime();
4170     T2Quals.removeObjCLifetime();
4171   }
4172 
4173   // MS compiler ignores __unaligned qualifier for references; do the same.
4174   T1Quals.removeUnaligned();
4175   T2Quals.removeUnaligned();
4176 
4177   if (T1Quals == T2Quals)
4178     return Ref_Compatible;
4179   else if (T1Quals.compatiblyIncludes(T2Quals))
4180     return Ref_Compatible_With_Added_Qualification;
4181   else
4182     return Ref_Related;
4183 }
4184 
4185 /// \brief Look for a user-defined conversion to an value reference-compatible
4186 ///        with DeclType. Return true if something definite is found.
4187 static bool
4188 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4189                          QualType DeclType, SourceLocation DeclLoc,
4190                          Expr *Init, QualType T2, bool AllowRvalues,
4191                          bool AllowExplicit) {
4192   assert(T2->isRecordType() && "Can only find conversions of record types.");
4193   CXXRecordDecl *T2RecordDecl
4194     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4195 
4196   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4197   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4198   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4199     NamedDecl *D = *I;
4200     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4201     if (isa<UsingShadowDecl>(D))
4202       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4203 
4204     FunctionTemplateDecl *ConvTemplate
4205       = dyn_cast<FunctionTemplateDecl>(D);
4206     CXXConversionDecl *Conv;
4207     if (ConvTemplate)
4208       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4209     else
4210       Conv = cast<CXXConversionDecl>(D);
4211 
4212     // If this is an explicit conversion, and we're not allowed to consider
4213     // explicit conversions, skip it.
4214     if (!AllowExplicit && Conv->isExplicit())
4215       continue;
4216 
4217     if (AllowRvalues) {
4218       bool DerivedToBase = false;
4219       bool ObjCConversion = false;
4220       bool ObjCLifetimeConversion = false;
4221 
4222       // If we are initializing an rvalue reference, don't permit conversion
4223       // functions that return lvalues.
4224       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4225         const ReferenceType *RefType
4226           = Conv->getConversionType()->getAs<LValueReferenceType>();
4227         if (RefType && !RefType->getPointeeType()->isFunctionType())
4228           continue;
4229       }
4230 
4231       if (!ConvTemplate &&
4232           S.CompareReferenceRelationship(
4233             DeclLoc,
4234             Conv->getConversionType().getNonReferenceType()
4235               .getUnqualifiedType(),
4236             DeclType.getNonReferenceType().getUnqualifiedType(),
4237             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4238           Sema::Ref_Incompatible)
4239         continue;
4240     } else {
4241       // If the conversion function doesn't return a reference type,
4242       // it can't be considered for this conversion. An rvalue reference
4243       // is only acceptable if its referencee is a function type.
4244 
4245       const ReferenceType *RefType =
4246         Conv->getConversionType()->getAs<ReferenceType>();
4247       if (!RefType ||
4248           (!RefType->isLValueReferenceType() &&
4249            !RefType->getPointeeType()->isFunctionType()))
4250         continue;
4251     }
4252 
4253     if (ConvTemplate)
4254       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4255                                        Init, DeclType, CandidateSet,
4256                                        /*AllowObjCConversionOnExplicit=*/false);
4257     else
4258       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4259                                DeclType, CandidateSet,
4260                                /*AllowObjCConversionOnExplicit=*/false);
4261   }
4262 
4263   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4264 
4265   OverloadCandidateSet::iterator Best;
4266   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4267   case OR_Success:
4268     // C++ [over.ics.ref]p1:
4269     //
4270     //   [...] If the parameter binds directly to the result of
4271     //   applying a conversion function to the argument
4272     //   expression, the implicit conversion sequence is a
4273     //   user-defined conversion sequence (13.3.3.1.2), with the
4274     //   second standard conversion sequence either an identity
4275     //   conversion or, if the conversion function returns an
4276     //   entity of a type that is a derived class of the parameter
4277     //   type, a derived-to-base Conversion.
4278     if (!Best->FinalConversion.DirectBinding)
4279       return false;
4280 
4281     ICS.setUserDefined();
4282     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4283     ICS.UserDefined.After = Best->FinalConversion;
4284     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4285     ICS.UserDefined.ConversionFunction = Best->Function;
4286     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4287     ICS.UserDefined.EllipsisConversion = false;
4288     assert(ICS.UserDefined.After.ReferenceBinding &&
4289            ICS.UserDefined.After.DirectBinding &&
4290            "Expected a direct reference binding!");
4291     return true;
4292 
4293   case OR_Ambiguous:
4294     ICS.setAmbiguous();
4295     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4296          Cand != CandidateSet.end(); ++Cand)
4297       if (Cand->Viable)
4298         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4299     return true;
4300 
4301   case OR_No_Viable_Function:
4302   case OR_Deleted:
4303     // There was no suitable conversion, or we found a deleted
4304     // conversion; continue with other checks.
4305     return false;
4306   }
4307 
4308   llvm_unreachable("Invalid OverloadResult!");
4309 }
4310 
4311 /// \brief Compute an implicit conversion sequence for reference
4312 /// initialization.
4313 static ImplicitConversionSequence
4314 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4315                  SourceLocation DeclLoc,
4316                  bool SuppressUserConversions,
4317                  bool AllowExplicit) {
4318   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4319 
4320   // Most paths end in a failed conversion.
4321   ImplicitConversionSequence ICS;
4322   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4323 
4324   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4325   QualType T2 = Init->getType();
4326 
4327   // If the initializer is the address of an overloaded function, try
4328   // to resolve the overloaded function. If all goes well, T2 is the
4329   // type of the resulting function.
4330   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4331     DeclAccessPair Found;
4332     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4333                                                                 false, Found))
4334       T2 = Fn->getType();
4335   }
4336 
4337   // Compute some basic properties of the types and the initializer.
4338   bool isRValRef = DeclType->isRValueReferenceType();
4339   bool DerivedToBase = false;
4340   bool ObjCConversion = false;
4341   bool ObjCLifetimeConversion = false;
4342   Expr::Classification InitCategory = Init->Classify(S.Context);
4343   Sema::ReferenceCompareResult RefRelationship
4344     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4345                                      ObjCConversion, ObjCLifetimeConversion);
4346 
4347 
4348   // C++0x [dcl.init.ref]p5:
4349   //   A reference to type "cv1 T1" is initialized by an expression
4350   //   of type "cv2 T2" as follows:
4351 
4352   //     -- If reference is an lvalue reference and the initializer expression
4353   if (!isRValRef) {
4354     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4355     //        reference-compatible with "cv2 T2," or
4356     //
4357     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4358     if (InitCategory.isLValue() &&
4359         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4360       // C++ [over.ics.ref]p1:
4361       //   When a parameter of reference type binds directly (8.5.3)
4362       //   to an argument expression, the implicit conversion sequence
4363       //   is the identity conversion, unless the argument expression
4364       //   has a type that is a derived class of the parameter type,
4365       //   in which case the implicit conversion sequence is a
4366       //   derived-to-base Conversion (13.3.3.1).
4367       ICS.setStandard();
4368       ICS.Standard.First = ICK_Identity;
4369       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4370                          : ObjCConversion? ICK_Compatible_Conversion
4371                          : ICK_Identity;
4372       ICS.Standard.Third = ICK_Identity;
4373       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4374       ICS.Standard.setToType(0, T2);
4375       ICS.Standard.setToType(1, T1);
4376       ICS.Standard.setToType(2, T1);
4377       ICS.Standard.ReferenceBinding = true;
4378       ICS.Standard.DirectBinding = true;
4379       ICS.Standard.IsLvalueReference = !isRValRef;
4380       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4381       ICS.Standard.BindsToRvalue = false;
4382       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4383       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4384       ICS.Standard.CopyConstructor = nullptr;
4385       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4386 
4387       // Nothing more to do: the inaccessibility/ambiguity check for
4388       // derived-to-base conversions is suppressed when we're
4389       // computing the implicit conversion sequence (C++
4390       // [over.best.ics]p2).
4391       return ICS;
4392     }
4393 
4394     //       -- has a class type (i.e., T2 is a class type), where T1 is
4395     //          not reference-related to T2, and can be implicitly
4396     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4397     //          is reference-compatible with "cv3 T3" 92) (this
4398     //          conversion is selected by enumerating the applicable
4399     //          conversion functions (13.3.1.6) and choosing the best
4400     //          one through overload resolution (13.3)),
4401     if (!SuppressUserConversions && T2->isRecordType() &&
4402         S.isCompleteType(DeclLoc, T2) &&
4403         RefRelationship == Sema::Ref_Incompatible) {
4404       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4405                                    Init, T2, /*AllowRvalues=*/false,
4406                                    AllowExplicit))
4407         return ICS;
4408     }
4409   }
4410 
4411   //     -- Otherwise, the reference shall be an lvalue reference to a
4412   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4413   //        shall be an rvalue reference.
4414   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4415     return ICS;
4416 
4417   //       -- If the initializer expression
4418   //
4419   //            -- is an xvalue, class prvalue, array prvalue or function
4420   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4421   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4422       (InitCategory.isXValue() ||
4423       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4424       (InitCategory.isLValue() && T2->isFunctionType()))) {
4425     ICS.setStandard();
4426     ICS.Standard.First = ICK_Identity;
4427     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4428                       : ObjCConversion? ICK_Compatible_Conversion
4429                       : ICK_Identity;
4430     ICS.Standard.Third = ICK_Identity;
4431     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4432     ICS.Standard.setToType(0, T2);
4433     ICS.Standard.setToType(1, T1);
4434     ICS.Standard.setToType(2, T1);
4435     ICS.Standard.ReferenceBinding = true;
4436     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4437     // binding unless we're binding to a class prvalue.
4438     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4439     // allow the use of rvalue references in C++98/03 for the benefit of
4440     // standard library implementors; therefore, we need the xvalue check here.
4441     ICS.Standard.DirectBinding =
4442       S.getLangOpts().CPlusPlus11 ||
4443       !(InitCategory.isPRValue() || T2->isRecordType());
4444     ICS.Standard.IsLvalueReference = !isRValRef;
4445     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4446     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4447     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4448     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4449     ICS.Standard.CopyConstructor = nullptr;
4450     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4451     return ICS;
4452   }
4453 
4454   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4455   //               reference-related to T2, and can be implicitly converted to
4456   //               an xvalue, class prvalue, or function lvalue of type
4457   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4458   //               "cv3 T3",
4459   //
4460   //          then the reference is bound to the value of the initializer
4461   //          expression in the first case and to the result of the conversion
4462   //          in the second case (or, in either case, to an appropriate base
4463   //          class subobject).
4464   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4465       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4466       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4467                                Init, T2, /*AllowRvalues=*/true,
4468                                AllowExplicit)) {
4469     // In the second case, if the reference is an rvalue reference
4470     // and the second standard conversion sequence of the
4471     // user-defined conversion sequence includes an lvalue-to-rvalue
4472     // conversion, the program is ill-formed.
4473     if (ICS.isUserDefined() && isRValRef &&
4474         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4475       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4476 
4477     return ICS;
4478   }
4479 
4480   // A temporary of function type cannot be created; don't even try.
4481   if (T1->isFunctionType())
4482     return ICS;
4483 
4484   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4485   //          initialized from the initializer expression using the
4486   //          rules for a non-reference copy initialization (8.5). The
4487   //          reference is then bound to the temporary. If T1 is
4488   //          reference-related to T2, cv1 must be the same
4489   //          cv-qualification as, or greater cv-qualification than,
4490   //          cv2; otherwise, the program is ill-formed.
4491   if (RefRelationship == Sema::Ref_Related) {
4492     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4493     // we would be reference-compatible or reference-compatible with
4494     // added qualification. But that wasn't the case, so the reference
4495     // initialization fails.
4496     //
4497     // Note that we only want to check address spaces and cvr-qualifiers here.
4498     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4499     Qualifiers T1Quals = T1.getQualifiers();
4500     Qualifiers T2Quals = T2.getQualifiers();
4501     T1Quals.removeObjCGCAttr();
4502     T1Quals.removeObjCLifetime();
4503     T2Quals.removeObjCGCAttr();
4504     T2Quals.removeObjCLifetime();
4505     // MS compiler ignores __unaligned qualifier for references; do the same.
4506     T1Quals.removeUnaligned();
4507     T2Quals.removeUnaligned();
4508     if (!T1Quals.compatiblyIncludes(T2Quals))
4509       return ICS;
4510   }
4511 
4512   // If at least one of the types is a class type, the types are not
4513   // related, and we aren't allowed any user conversions, the
4514   // reference binding fails. This case is important for breaking
4515   // recursion, since TryImplicitConversion below will attempt to
4516   // create a temporary through the use of a copy constructor.
4517   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4518       (T1->isRecordType() || T2->isRecordType()))
4519     return ICS;
4520 
4521   // If T1 is reference-related to T2 and the reference is an rvalue
4522   // reference, the initializer expression shall not be an lvalue.
4523   if (RefRelationship >= Sema::Ref_Related &&
4524       isRValRef && Init->Classify(S.Context).isLValue())
4525     return ICS;
4526 
4527   // C++ [over.ics.ref]p2:
4528   //   When a parameter of reference type is not bound directly to
4529   //   an argument expression, the conversion sequence is the one
4530   //   required to convert the argument expression to the
4531   //   underlying type of the reference according to
4532   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4533   //   to copy-initializing a temporary of the underlying type with
4534   //   the argument expression. Any difference in top-level
4535   //   cv-qualification is subsumed by the initialization itself
4536   //   and does not constitute a conversion.
4537   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4538                               /*AllowExplicit=*/false,
4539                               /*InOverloadResolution=*/false,
4540                               /*CStyle=*/false,
4541                               /*AllowObjCWritebackConversion=*/false,
4542                               /*AllowObjCConversionOnExplicit=*/false);
4543 
4544   // Of course, that's still a reference binding.
4545   if (ICS.isStandard()) {
4546     ICS.Standard.ReferenceBinding = true;
4547     ICS.Standard.IsLvalueReference = !isRValRef;
4548     ICS.Standard.BindsToFunctionLvalue = false;
4549     ICS.Standard.BindsToRvalue = true;
4550     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4551     ICS.Standard.ObjCLifetimeConversionBinding = false;
4552   } else if (ICS.isUserDefined()) {
4553     const ReferenceType *LValRefType =
4554         ICS.UserDefined.ConversionFunction->getReturnType()
4555             ->getAs<LValueReferenceType>();
4556 
4557     // C++ [over.ics.ref]p3:
4558     //   Except for an implicit object parameter, for which see 13.3.1, a
4559     //   standard conversion sequence cannot be formed if it requires [...]
4560     //   binding an rvalue reference to an lvalue other than a function
4561     //   lvalue.
4562     // Note that the function case is not possible here.
4563     if (DeclType->isRValueReferenceType() && LValRefType) {
4564       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4565       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4566       // reference to an rvalue!
4567       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4568       return ICS;
4569     }
4570 
4571     ICS.UserDefined.After.ReferenceBinding = true;
4572     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4573     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4574     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4575     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4576     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4577   }
4578 
4579   return ICS;
4580 }
4581 
4582 static ImplicitConversionSequence
4583 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4584                       bool SuppressUserConversions,
4585                       bool InOverloadResolution,
4586                       bool AllowObjCWritebackConversion,
4587                       bool AllowExplicit = false);
4588 
4589 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4590 /// initializer list From.
4591 static ImplicitConversionSequence
4592 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4593                   bool SuppressUserConversions,
4594                   bool InOverloadResolution,
4595                   bool AllowObjCWritebackConversion) {
4596   // C++11 [over.ics.list]p1:
4597   //   When an argument is an initializer list, it is not an expression and
4598   //   special rules apply for converting it to a parameter type.
4599 
4600   ImplicitConversionSequence Result;
4601   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4602 
4603   // We need a complete type for what follows. Incomplete types can never be
4604   // initialized from init lists.
4605   if (!S.isCompleteType(From->getLocStart(), ToType))
4606     return Result;
4607 
4608   // Per DR1467:
4609   //   If the parameter type is a class X and the initializer list has a single
4610   //   element of type cv U, where U is X or a class derived from X, the
4611   //   implicit conversion sequence is the one required to convert the element
4612   //   to the parameter type.
4613   //
4614   //   Otherwise, if the parameter type is a character array [... ]
4615   //   and the initializer list has a single element that is an
4616   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4617   //   implicit conversion sequence is the identity conversion.
4618   if (From->getNumInits() == 1) {
4619     if (ToType->isRecordType()) {
4620       QualType InitType = From->getInit(0)->getType();
4621       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4622           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4623         return TryCopyInitialization(S, From->getInit(0), ToType,
4624                                      SuppressUserConversions,
4625                                      InOverloadResolution,
4626                                      AllowObjCWritebackConversion);
4627     }
4628     // FIXME: Check the other conditions here: array of character type,
4629     // initializer is a string literal.
4630     if (ToType->isArrayType()) {
4631       InitializedEntity Entity =
4632         InitializedEntity::InitializeParameter(S.Context, ToType,
4633                                                /*Consumed=*/false);
4634       if (S.CanPerformCopyInitialization(Entity, From)) {
4635         Result.setStandard();
4636         Result.Standard.setAsIdentityConversion();
4637         Result.Standard.setFromType(ToType);
4638         Result.Standard.setAllToTypes(ToType);
4639         return Result;
4640       }
4641     }
4642   }
4643 
4644   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4645   // C++11 [over.ics.list]p2:
4646   //   If the parameter type is std::initializer_list<X> or "array of X" and
4647   //   all the elements can be implicitly converted to X, the implicit
4648   //   conversion sequence is the worst conversion necessary to convert an
4649   //   element of the list to X.
4650   //
4651   // C++14 [over.ics.list]p3:
4652   //   Otherwise, if the parameter type is "array of N X", if the initializer
4653   //   list has exactly N elements or if it has fewer than N elements and X is
4654   //   default-constructible, and if all the elements of the initializer list
4655   //   can be implicitly converted to X, the implicit conversion sequence is
4656   //   the worst conversion necessary to convert an element of the list to X.
4657   //
4658   // FIXME: We're missing a lot of these checks.
4659   bool toStdInitializerList = false;
4660   QualType X;
4661   if (ToType->isArrayType())
4662     X = S.Context.getAsArrayType(ToType)->getElementType();
4663   else
4664     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4665   if (!X.isNull()) {
4666     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4667       Expr *Init = From->getInit(i);
4668       ImplicitConversionSequence ICS =
4669           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4670                                 InOverloadResolution,
4671                                 AllowObjCWritebackConversion);
4672       // If a single element isn't convertible, fail.
4673       if (ICS.isBad()) {
4674         Result = ICS;
4675         break;
4676       }
4677       // Otherwise, look for the worst conversion.
4678       if (Result.isBad() ||
4679           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4680                                              Result) ==
4681               ImplicitConversionSequence::Worse)
4682         Result = ICS;
4683     }
4684 
4685     // For an empty list, we won't have computed any conversion sequence.
4686     // Introduce the identity conversion sequence.
4687     if (From->getNumInits() == 0) {
4688       Result.setStandard();
4689       Result.Standard.setAsIdentityConversion();
4690       Result.Standard.setFromType(ToType);
4691       Result.Standard.setAllToTypes(ToType);
4692     }
4693 
4694     Result.setStdInitializerListElement(toStdInitializerList);
4695     return Result;
4696   }
4697 
4698   // C++14 [over.ics.list]p4:
4699   // C++11 [over.ics.list]p3:
4700   //   Otherwise, if the parameter is a non-aggregate class X and overload
4701   //   resolution chooses a single best constructor [...] the implicit
4702   //   conversion sequence is a user-defined conversion sequence. If multiple
4703   //   constructors are viable but none is better than the others, the
4704   //   implicit conversion sequence is a user-defined conversion sequence.
4705   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4706     // This function can deal with initializer lists.
4707     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4708                                     /*AllowExplicit=*/false,
4709                                     InOverloadResolution, /*CStyle=*/false,
4710                                     AllowObjCWritebackConversion,
4711                                     /*AllowObjCConversionOnExplicit=*/false);
4712   }
4713 
4714   // C++14 [over.ics.list]p5:
4715   // C++11 [over.ics.list]p4:
4716   //   Otherwise, if the parameter has an aggregate type which can be
4717   //   initialized from the initializer list [...] the implicit conversion
4718   //   sequence is a user-defined conversion sequence.
4719   if (ToType->isAggregateType()) {
4720     // Type is an aggregate, argument is an init list. At this point it comes
4721     // down to checking whether the initialization works.
4722     // FIXME: Find out whether this parameter is consumed or not.
4723     InitializedEntity Entity =
4724         InitializedEntity::InitializeParameter(S.Context, ToType,
4725                                                /*Consumed=*/false);
4726     if (S.CanPerformCopyInitialization(Entity, From)) {
4727       Result.setUserDefined();
4728       Result.UserDefined.Before.setAsIdentityConversion();
4729       // Initializer lists don't have a type.
4730       Result.UserDefined.Before.setFromType(QualType());
4731       Result.UserDefined.Before.setAllToTypes(QualType());
4732 
4733       Result.UserDefined.After.setAsIdentityConversion();
4734       Result.UserDefined.After.setFromType(ToType);
4735       Result.UserDefined.After.setAllToTypes(ToType);
4736       Result.UserDefined.ConversionFunction = nullptr;
4737     }
4738     return Result;
4739   }
4740 
4741   // C++14 [over.ics.list]p6:
4742   // C++11 [over.ics.list]p5:
4743   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4744   if (ToType->isReferenceType()) {
4745     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4746     // mention initializer lists in any way. So we go by what list-
4747     // initialization would do and try to extrapolate from that.
4748 
4749     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4750 
4751     // If the initializer list has a single element that is reference-related
4752     // to the parameter type, we initialize the reference from that.
4753     if (From->getNumInits() == 1) {
4754       Expr *Init = From->getInit(0);
4755 
4756       QualType T2 = Init->getType();
4757 
4758       // If the initializer is the address of an overloaded function, try
4759       // to resolve the overloaded function. If all goes well, T2 is the
4760       // type of the resulting function.
4761       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4762         DeclAccessPair Found;
4763         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4764                                    Init, ToType, false, Found))
4765           T2 = Fn->getType();
4766       }
4767 
4768       // Compute some basic properties of the types and the initializer.
4769       bool dummy1 = false;
4770       bool dummy2 = false;
4771       bool dummy3 = false;
4772       Sema::ReferenceCompareResult RefRelationship
4773         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4774                                          dummy2, dummy3);
4775 
4776       if (RefRelationship >= Sema::Ref_Related) {
4777         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4778                                 SuppressUserConversions,
4779                                 /*AllowExplicit=*/false);
4780       }
4781     }
4782 
4783     // Otherwise, we bind the reference to a temporary created from the
4784     // initializer list.
4785     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4786                                InOverloadResolution,
4787                                AllowObjCWritebackConversion);
4788     if (Result.isFailure())
4789       return Result;
4790     assert(!Result.isEllipsis() &&
4791            "Sub-initialization cannot result in ellipsis conversion.");
4792 
4793     // Can we even bind to a temporary?
4794     if (ToType->isRValueReferenceType() ||
4795         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4796       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4797                                             Result.UserDefined.After;
4798       SCS.ReferenceBinding = true;
4799       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4800       SCS.BindsToRvalue = true;
4801       SCS.BindsToFunctionLvalue = false;
4802       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4803       SCS.ObjCLifetimeConversionBinding = false;
4804     } else
4805       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4806                     From, ToType);
4807     return Result;
4808   }
4809 
4810   // C++14 [over.ics.list]p7:
4811   // C++11 [over.ics.list]p6:
4812   //   Otherwise, if the parameter type is not a class:
4813   if (!ToType->isRecordType()) {
4814     //    - if the initializer list has one element that is not itself an
4815     //      initializer list, the implicit conversion sequence is the one
4816     //      required to convert the element to the parameter type.
4817     unsigned NumInits = From->getNumInits();
4818     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4819       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4820                                      SuppressUserConversions,
4821                                      InOverloadResolution,
4822                                      AllowObjCWritebackConversion);
4823     //    - if the initializer list has no elements, the implicit conversion
4824     //      sequence is the identity conversion.
4825     else if (NumInits == 0) {
4826       Result.setStandard();
4827       Result.Standard.setAsIdentityConversion();
4828       Result.Standard.setFromType(ToType);
4829       Result.Standard.setAllToTypes(ToType);
4830     }
4831     return Result;
4832   }
4833 
4834   // C++14 [over.ics.list]p8:
4835   // C++11 [over.ics.list]p7:
4836   //   In all cases other than those enumerated above, no conversion is possible
4837   return Result;
4838 }
4839 
4840 /// TryCopyInitialization - Try to copy-initialize a value of type
4841 /// ToType from the expression From. Return the implicit conversion
4842 /// sequence required to pass this argument, which may be a bad
4843 /// conversion sequence (meaning that the argument cannot be passed to
4844 /// a parameter of this type). If @p SuppressUserConversions, then we
4845 /// do not permit any user-defined conversion sequences.
4846 static ImplicitConversionSequence
4847 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4848                       bool SuppressUserConversions,
4849                       bool InOverloadResolution,
4850                       bool AllowObjCWritebackConversion,
4851                       bool AllowExplicit) {
4852   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4853     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4854                              InOverloadResolution,AllowObjCWritebackConversion);
4855 
4856   if (ToType->isReferenceType())
4857     return TryReferenceInit(S, From, ToType,
4858                             /*FIXME:*/From->getLocStart(),
4859                             SuppressUserConversions,
4860                             AllowExplicit);
4861 
4862   return TryImplicitConversion(S, From, ToType,
4863                                SuppressUserConversions,
4864                                /*AllowExplicit=*/false,
4865                                InOverloadResolution,
4866                                /*CStyle=*/false,
4867                                AllowObjCWritebackConversion,
4868                                /*AllowObjCConversionOnExplicit=*/false);
4869 }
4870 
4871 static bool TryCopyInitialization(const CanQualType FromQTy,
4872                                   const CanQualType ToQTy,
4873                                   Sema &S,
4874                                   SourceLocation Loc,
4875                                   ExprValueKind FromVK) {
4876   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4877   ImplicitConversionSequence ICS =
4878     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4879 
4880   return !ICS.isBad();
4881 }
4882 
4883 /// TryObjectArgumentInitialization - Try to initialize the object
4884 /// parameter of the given member function (@c Method) from the
4885 /// expression @p From.
4886 static ImplicitConversionSequence
4887 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4888                                 Expr::Classification FromClassification,
4889                                 CXXMethodDecl *Method,
4890                                 CXXRecordDecl *ActingContext) {
4891   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4892   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4893   //                 const volatile object.
4894   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4895     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4896   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4897 
4898   // Set up the conversion sequence as a "bad" conversion, to allow us
4899   // to exit early.
4900   ImplicitConversionSequence ICS;
4901 
4902   // We need to have an object of class type.
4903   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4904     FromType = PT->getPointeeType();
4905 
4906     // When we had a pointer, it's implicitly dereferenced, so we
4907     // better have an lvalue.
4908     assert(FromClassification.isLValue());
4909   }
4910 
4911   assert(FromType->isRecordType());
4912 
4913   // C++0x [over.match.funcs]p4:
4914   //   For non-static member functions, the type of the implicit object
4915   //   parameter is
4916   //
4917   //     - "lvalue reference to cv X" for functions declared without a
4918   //        ref-qualifier or with the & ref-qualifier
4919   //     - "rvalue reference to cv X" for functions declared with the &&
4920   //        ref-qualifier
4921   //
4922   // where X is the class of which the function is a member and cv is the
4923   // cv-qualification on the member function declaration.
4924   //
4925   // However, when finding an implicit conversion sequence for the argument, we
4926   // are not allowed to create temporaries or perform user-defined conversions
4927   // (C++ [over.match.funcs]p5). We perform a simplified version of
4928   // reference binding here, that allows class rvalues to bind to
4929   // non-constant references.
4930 
4931   // First check the qualifiers.
4932   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4933   if (ImplicitParamType.getCVRQualifiers()
4934                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4935       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4936     ICS.setBad(BadConversionSequence::bad_qualifiers,
4937                FromType, ImplicitParamType);
4938     return ICS;
4939   }
4940 
4941   // Check that we have either the same type or a derived type. It
4942   // affects the conversion rank.
4943   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4944   ImplicitConversionKind SecondKind;
4945   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4946     SecondKind = ICK_Identity;
4947   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4948     SecondKind = ICK_Derived_To_Base;
4949   else {
4950     ICS.setBad(BadConversionSequence::unrelated_class,
4951                FromType, ImplicitParamType);
4952     return ICS;
4953   }
4954 
4955   // Check the ref-qualifier.
4956   switch (Method->getRefQualifier()) {
4957   case RQ_None:
4958     // Do nothing; we don't care about lvalueness or rvalueness.
4959     break;
4960 
4961   case RQ_LValue:
4962     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4963       // non-const lvalue reference cannot bind to an rvalue
4964       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4965                  ImplicitParamType);
4966       return ICS;
4967     }
4968     break;
4969 
4970   case RQ_RValue:
4971     if (!FromClassification.isRValue()) {
4972       // rvalue reference cannot bind to an lvalue
4973       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4974                  ImplicitParamType);
4975       return ICS;
4976     }
4977     break;
4978   }
4979 
4980   // Success. Mark this as a reference binding.
4981   ICS.setStandard();
4982   ICS.Standard.setAsIdentityConversion();
4983   ICS.Standard.Second = SecondKind;
4984   ICS.Standard.setFromType(FromType);
4985   ICS.Standard.setAllToTypes(ImplicitParamType);
4986   ICS.Standard.ReferenceBinding = true;
4987   ICS.Standard.DirectBinding = true;
4988   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4989   ICS.Standard.BindsToFunctionLvalue = false;
4990   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4991   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4992     = (Method->getRefQualifier() == RQ_None);
4993   return ICS;
4994 }
4995 
4996 /// PerformObjectArgumentInitialization - Perform initialization of
4997 /// the implicit object parameter for the given Method with the given
4998 /// expression.
4999 ExprResult
5000 Sema::PerformObjectArgumentInitialization(Expr *From,
5001                                           NestedNameSpecifier *Qualifier,
5002                                           NamedDecl *FoundDecl,
5003                                           CXXMethodDecl *Method) {
5004   QualType FromRecordType, DestType;
5005   QualType ImplicitParamRecordType  =
5006     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5007 
5008   Expr::Classification FromClassification;
5009   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5010     FromRecordType = PT->getPointeeType();
5011     DestType = Method->getThisType(Context);
5012     FromClassification = Expr::Classification::makeSimpleLValue();
5013   } else {
5014     FromRecordType = From->getType();
5015     DestType = ImplicitParamRecordType;
5016     FromClassification = From->Classify(Context);
5017   }
5018 
5019   // Note that we always use the true parent context when performing
5020   // the actual argument initialization.
5021   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5022       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5023       Method->getParent());
5024   if (ICS.isBad()) {
5025     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5026       Qualifiers FromQs = FromRecordType.getQualifiers();
5027       Qualifiers ToQs = DestType.getQualifiers();
5028       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5029       if (CVR) {
5030         Diag(From->getLocStart(),
5031              diag::err_member_function_call_bad_cvr)
5032           << Method->getDeclName() << FromRecordType << (CVR - 1)
5033           << From->getSourceRange();
5034         Diag(Method->getLocation(), diag::note_previous_decl)
5035           << Method->getDeclName();
5036         return ExprError();
5037       }
5038     }
5039 
5040     return Diag(From->getLocStart(),
5041                 diag::err_implicit_object_parameter_init)
5042        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5043   }
5044 
5045   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5046     ExprResult FromRes =
5047       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5048     if (FromRes.isInvalid())
5049       return ExprError();
5050     From = FromRes.get();
5051   }
5052 
5053   if (!Context.hasSameType(From->getType(), DestType))
5054     From = ImpCastExprToType(From, DestType, CK_NoOp,
5055                              From->getValueKind()).get();
5056   return From;
5057 }
5058 
5059 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5060 /// expression From to bool (C++0x [conv]p3).
5061 static ImplicitConversionSequence
5062 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5063   return TryImplicitConversion(S, From, S.Context.BoolTy,
5064                                /*SuppressUserConversions=*/false,
5065                                /*AllowExplicit=*/true,
5066                                /*InOverloadResolution=*/false,
5067                                /*CStyle=*/false,
5068                                /*AllowObjCWritebackConversion=*/false,
5069                                /*AllowObjCConversionOnExplicit=*/false);
5070 }
5071 
5072 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5073 /// of the expression From to bool (C++0x [conv]p3).
5074 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5075   if (checkPlaceholderForOverload(*this, From))
5076     return ExprError();
5077 
5078   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5079   if (!ICS.isBad())
5080     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5081 
5082   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5083     return Diag(From->getLocStart(),
5084                 diag::err_typecheck_bool_condition)
5085                   << From->getType() << From->getSourceRange();
5086   return ExprError();
5087 }
5088 
5089 /// Check that the specified conversion is permitted in a converted constant
5090 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5091 /// is acceptable.
5092 static bool CheckConvertedConstantConversions(Sema &S,
5093                                               StandardConversionSequence &SCS) {
5094   // Since we know that the target type is an integral or unscoped enumeration
5095   // type, most conversion kinds are impossible. All possible First and Third
5096   // conversions are fine.
5097   switch (SCS.Second) {
5098   case ICK_Identity:
5099   case ICK_NoReturn_Adjustment:
5100   case ICK_Integral_Promotion:
5101   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5102     return true;
5103 
5104   case ICK_Boolean_Conversion:
5105     // Conversion from an integral or unscoped enumeration type to bool is
5106     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5107     // conversion, so we allow it in a converted constant expression.
5108     //
5109     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5110     // a lot of popular code. We should at least add a warning for this
5111     // (non-conforming) extension.
5112     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5113            SCS.getToType(2)->isBooleanType();
5114 
5115   case ICK_Pointer_Conversion:
5116   case ICK_Pointer_Member:
5117     // C++1z: null pointer conversions and null member pointer conversions are
5118     // only permitted if the source type is std::nullptr_t.
5119     return SCS.getFromType()->isNullPtrType();
5120 
5121   case ICK_Floating_Promotion:
5122   case ICK_Complex_Promotion:
5123   case ICK_Floating_Conversion:
5124   case ICK_Complex_Conversion:
5125   case ICK_Floating_Integral:
5126   case ICK_Compatible_Conversion:
5127   case ICK_Derived_To_Base:
5128   case ICK_Vector_Conversion:
5129   case ICK_Vector_Splat:
5130   case ICK_Complex_Real:
5131   case ICK_Block_Pointer_Conversion:
5132   case ICK_TransparentUnionConversion:
5133   case ICK_Writeback_Conversion:
5134   case ICK_Zero_Event_Conversion:
5135   case ICK_C_Only_Conversion:
5136   case ICK_Incompatible_Pointer_Conversion:
5137     return false;
5138 
5139   case ICK_Lvalue_To_Rvalue:
5140   case ICK_Array_To_Pointer:
5141   case ICK_Function_To_Pointer:
5142     llvm_unreachable("found a first conversion kind in Second");
5143 
5144   case ICK_Qualification:
5145     llvm_unreachable("found a third conversion kind in Second");
5146 
5147   case ICK_Num_Conversion_Kinds:
5148     break;
5149   }
5150 
5151   llvm_unreachable("unknown conversion kind");
5152 }
5153 
5154 /// CheckConvertedConstantExpression - Check that the expression From is a
5155 /// converted constant expression of type T, perform the conversion and produce
5156 /// the converted expression, per C++11 [expr.const]p3.
5157 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5158                                                    QualType T, APValue &Value,
5159                                                    Sema::CCEKind CCE,
5160                                                    bool RequireInt) {
5161   assert(S.getLangOpts().CPlusPlus11 &&
5162          "converted constant expression outside C++11");
5163 
5164   if (checkPlaceholderForOverload(S, From))
5165     return ExprError();
5166 
5167   // C++1z [expr.const]p3:
5168   //  A converted constant expression of type T is an expression,
5169   //  implicitly converted to type T, where the converted
5170   //  expression is a constant expression and the implicit conversion
5171   //  sequence contains only [... list of conversions ...].
5172   // C++1z [stmt.if]p2:
5173   //  If the if statement is of the form if constexpr, the value of the
5174   //  condition shall be a contextually converted constant expression of type
5175   //  bool.
5176   ImplicitConversionSequence ICS =
5177       CCE == Sema::CCEK_ConstexprIf
5178           ? TryContextuallyConvertToBool(S, From)
5179           : TryCopyInitialization(S, From, T,
5180                                   /*SuppressUserConversions=*/false,
5181                                   /*InOverloadResolution=*/false,
5182                                   /*AllowObjcWritebackConversion=*/false,
5183                                   /*AllowExplicit=*/false);
5184   StandardConversionSequence *SCS = nullptr;
5185   switch (ICS.getKind()) {
5186   case ImplicitConversionSequence::StandardConversion:
5187     SCS = &ICS.Standard;
5188     break;
5189   case ImplicitConversionSequence::UserDefinedConversion:
5190     // We are converting to a non-class type, so the Before sequence
5191     // must be trivial.
5192     SCS = &ICS.UserDefined.After;
5193     break;
5194   case ImplicitConversionSequence::AmbiguousConversion:
5195   case ImplicitConversionSequence::BadConversion:
5196     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5197       return S.Diag(From->getLocStart(),
5198                     diag::err_typecheck_converted_constant_expression)
5199                 << From->getType() << From->getSourceRange() << T;
5200     return ExprError();
5201 
5202   case ImplicitConversionSequence::EllipsisConversion:
5203     llvm_unreachable("ellipsis conversion in converted constant expression");
5204   }
5205 
5206   // Check that we would only use permitted conversions.
5207   if (!CheckConvertedConstantConversions(S, *SCS)) {
5208     return S.Diag(From->getLocStart(),
5209                   diag::err_typecheck_converted_constant_expression_disallowed)
5210              << From->getType() << From->getSourceRange() << T;
5211   }
5212   // [...] and where the reference binding (if any) binds directly.
5213   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5214     return S.Diag(From->getLocStart(),
5215                   diag::err_typecheck_converted_constant_expression_indirect)
5216              << From->getType() << From->getSourceRange() << T;
5217   }
5218 
5219   ExprResult Result =
5220       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5221   if (Result.isInvalid())
5222     return Result;
5223 
5224   // Check for a narrowing implicit conversion.
5225   APValue PreNarrowingValue;
5226   QualType PreNarrowingType;
5227   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5228                                 PreNarrowingType)) {
5229   case NK_Variable_Narrowing:
5230     // Implicit conversion to a narrower type, and the value is not a constant
5231     // expression. We'll diagnose this in a moment.
5232   case NK_Not_Narrowing:
5233     break;
5234 
5235   case NK_Constant_Narrowing:
5236     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5237       << CCE << /*Constant*/1
5238       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5239     break;
5240 
5241   case NK_Type_Narrowing:
5242     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5243       << CCE << /*Constant*/0 << From->getType() << T;
5244     break;
5245   }
5246 
5247   // Check the expression is a constant expression.
5248   SmallVector<PartialDiagnosticAt, 8> Notes;
5249   Expr::EvalResult Eval;
5250   Eval.Diag = &Notes;
5251 
5252   if ((T->isReferenceType()
5253            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5254            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5255       (RequireInt && !Eval.Val.isInt())) {
5256     // The expression can't be folded, so we can't keep it at this position in
5257     // the AST.
5258     Result = ExprError();
5259   } else {
5260     Value = Eval.Val;
5261 
5262     if (Notes.empty()) {
5263       // It's a constant expression.
5264       return Result;
5265     }
5266   }
5267 
5268   // It's not a constant expression. Produce an appropriate diagnostic.
5269   if (Notes.size() == 1 &&
5270       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5271     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5272   else {
5273     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5274       << CCE << From->getSourceRange();
5275     for (unsigned I = 0; I < Notes.size(); ++I)
5276       S.Diag(Notes[I].first, Notes[I].second);
5277   }
5278   return ExprError();
5279 }
5280 
5281 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5282                                                   APValue &Value, CCEKind CCE) {
5283   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5284 }
5285 
5286 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5287                                                   llvm::APSInt &Value,
5288                                                   CCEKind CCE) {
5289   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5290 
5291   APValue V;
5292   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5293   if (!R.isInvalid())
5294     Value = V.getInt();
5295   return R;
5296 }
5297 
5298 
5299 /// dropPointerConversions - If the given standard conversion sequence
5300 /// involves any pointer conversions, remove them.  This may change
5301 /// the result type of the conversion sequence.
5302 static void dropPointerConversion(StandardConversionSequence &SCS) {
5303   if (SCS.Second == ICK_Pointer_Conversion) {
5304     SCS.Second = ICK_Identity;
5305     SCS.Third = ICK_Identity;
5306     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5307   }
5308 }
5309 
5310 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5311 /// convert the expression From to an Objective-C pointer type.
5312 static ImplicitConversionSequence
5313 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5314   // Do an implicit conversion to 'id'.
5315   QualType Ty = S.Context.getObjCIdType();
5316   ImplicitConversionSequence ICS
5317     = TryImplicitConversion(S, From, Ty,
5318                             // FIXME: Are these flags correct?
5319                             /*SuppressUserConversions=*/false,
5320                             /*AllowExplicit=*/true,
5321                             /*InOverloadResolution=*/false,
5322                             /*CStyle=*/false,
5323                             /*AllowObjCWritebackConversion=*/false,
5324                             /*AllowObjCConversionOnExplicit=*/true);
5325 
5326   // Strip off any final conversions to 'id'.
5327   switch (ICS.getKind()) {
5328   case ImplicitConversionSequence::BadConversion:
5329   case ImplicitConversionSequence::AmbiguousConversion:
5330   case ImplicitConversionSequence::EllipsisConversion:
5331     break;
5332 
5333   case ImplicitConversionSequence::UserDefinedConversion:
5334     dropPointerConversion(ICS.UserDefined.After);
5335     break;
5336 
5337   case ImplicitConversionSequence::StandardConversion:
5338     dropPointerConversion(ICS.Standard);
5339     break;
5340   }
5341 
5342   return ICS;
5343 }
5344 
5345 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5346 /// conversion of the expression From to an Objective-C pointer type.
5347 /// Returns a valid but null ExprResult if no conversion sequence exists.
5348 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5349   if (checkPlaceholderForOverload(*this, From))
5350     return ExprError();
5351 
5352   QualType Ty = Context.getObjCIdType();
5353   ImplicitConversionSequence ICS =
5354     TryContextuallyConvertToObjCPointer(*this, From);
5355   if (!ICS.isBad())
5356     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5357   return ExprResult();
5358 }
5359 
5360 /// Determine whether the provided type is an integral type, or an enumeration
5361 /// type of a permitted flavor.
5362 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5363   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5364                                  : T->isIntegralOrUnscopedEnumerationType();
5365 }
5366 
5367 static ExprResult
5368 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5369                             Sema::ContextualImplicitConverter &Converter,
5370                             QualType T, UnresolvedSetImpl &ViableConversions) {
5371 
5372   if (Converter.Suppress)
5373     return ExprError();
5374 
5375   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5376   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5377     CXXConversionDecl *Conv =
5378         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5379     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5380     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5381   }
5382   return From;
5383 }
5384 
5385 static bool
5386 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5387                            Sema::ContextualImplicitConverter &Converter,
5388                            QualType T, bool HadMultipleCandidates,
5389                            UnresolvedSetImpl &ExplicitConversions) {
5390   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5391     DeclAccessPair Found = ExplicitConversions[0];
5392     CXXConversionDecl *Conversion =
5393         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5394 
5395     // The user probably meant to invoke the given explicit
5396     // conversion; use it.
5397     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5398     std::string TypeStr;
5399     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5400 
5401     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5402         << FixItHint::CreateInsertion(From->getLocStart(),
5403                                       "static_cast<" + TypeStr + ">(")
5404         << FixItHint::CreateInsertion(
5405                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5406     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5407 
5408     // If we aren't in a SFINAE context, build a call to the
5409     // explicit conversion function.
5410     if (SemaRef.isSFINAEContext())
5411       return true;
5412 
5413     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5414     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5415                                                        HadMultipleCandidates);
5416     if (Result.isInvalid())
5417       return true;
5418     // Record usage of conversion in an implicit cast.
5419     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5420                                     CK_UserDefinedConversion, Result.get(),
5421                                     nullptr, Result.get()->getValueKind());
5422   }
5423   return false;
5424 }
5425 
5426 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5427                              Sema::ContextualImplicitConverter &Converter,
5428                              QualType T, bool HadMultipleCandidates,
5429                              DeclAccessPair &Found) {
5430   CXXConversionDecl *Conversion =
5431       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5432   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5433 
5434   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5435   if (!Converter.SuppressConversion) {
5436     if (SemaRef.isSFINAEContext())
5437       return true;
5438 
5439     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5440         << From->getSourceRange();
5441   }
5442 
5443   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5444                                                      HadMultipleCandidates);
5445   if (Result.isInvalid())
5446     return true;
5447   // Record usage of conversion in an implicit cast.
5448   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5449                                   CK_UserDefinedConversion, Result.get(),
5450                                   nullptr, Result.get()->getValueKind());
5451   return false;
5452 }
5453 
5454 static ExprResult finishContextualImplicitConversion(
5455     Sema &SemaRef, SourceLocation Loc, Expr *From,
5456     Sema::ContextualImplicitConverter &Converter) {
5457   if (!Converter.match(From->getType()) && !Converter.Suppress)
5458     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5459         << From->getSourceRange();
5460 
5461   return SemaRef.DefaultLvalueConversion(From);
5462 }
5463 
5464 static void
5465 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5466                                   UnresolvedSetImpl &ViableConversions,
5467                                   OverloadCandidateSet &CandidateSet) {
5468   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5469     DeclAccessPair FoundDecl = ViableConversions[I];
5470     NamedDecl *D = FoundDecl.getDecl();
5471     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5472     if (isa<UsingShadowDecl>(D))
5473       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5474 
5475     CXXConversionDecl *Conv;
5476     FunctionTemplateDecl *ConvTemplate;
5477     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5478       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5479     else
5480       Conv = cast<CXXConversionDecl>(D);
5481 
5482     if (ConvTemplate)
5483       SemaRef.AddTemplateConversionCandidate(
5484         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5485         /*AllowObjCConversionOnExplicit=*/false);
5486     else
5487       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5488                                      ToType, CandidateSet,
5489                                      /*AllowObjCConversionOnExplicit=*/false);
5490   }
5491 }
5492 
5493 /// \brief Attempt to convert the given expression to a type which is accepted
5494 /// by the given converter.
5495 ///
5496 /// This routine will attempt to convert an expression of class type to a
5497 /// type accepted by the specified converter. In C++11 and before, the class
5498 /// must have a single non-explicit conversion function converting to a matching
5499 /// type. In C++1y, there can be multiple such conversion functions, but only
5500 /// one target type.
5501 ///
5502 /// \param Loc The source location of the construct that requires the
5503 /// conversion.
5504 ///
5505 /// \param From The expression we're converting from.
5506 ///
5507 /// \param Converter Used to control and diagnose the conversion process.
5508 ///
5509 /// \returns The expression, converted to an integral or enumeration type if
5510 /// successful.
5511 ExprResult Sema::PerformContextualImplicitConversion(
5512     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5513   // We can't perform any more checking for type-dependent expressions.
5514   if (From->isTypeDependent())
5515     return From;
5516 
5517   // Process placeholders immediately.
5518   if (From->hasPlaceholderType()) {
5519     ExprResult result = CheckPlaceholderExpr(From);
5520     if (result.isInvalid())
5521       return result;
5522     From = result.get();
5523   }
5524 
5525   // If the expression already has a matching type, we're golden.
5526   QualType T = From->getType();
5527   if (Converter.match(T))
5528     return DefaultLvalueConversion(From);
5529 
5530   // FIXME: Check for missing '()' if T is a function type?
5531 
5532   // We can only perform contextual implicit conversions on objects of class
5533   // type.
5534   const RecordType *RecordTy = T->getAs<RecordType>();
5535   if (!RecordTy || !getLangOpts().CPlusPlus) {
5536     if (!Converter.Suppress)
5537       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5538     return From;
5539   }
5540 
5541   // We must have a complete class type.
5542   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5543     ContextualImplicitConverter &Converter;
5544     Expr *From;
5545 
5546     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5547         : Converter(Converter), From(From) {}
5548 
5549     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5550       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5551     }
5552   } IncompleteDiagnoser(Converter, From);
5553 
5554   if (Converter.Suppress ? !isCompleteType(Loc, T)
5555                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5556     return From;
5557 
5558   // Look for a conversion to an integral or enumeration type.
5559   UnresolvedSet<4>
5560       ViableConversions; // These are *potentially* viable in C++1y.
5561   UnresolvedSet<4> ExplicitConversions;
5562   const auto &Conversions =
5563       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5564 
5565   bool HadMultipleCandidates =
5566       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5567 
5568   // To check that there is only one target type, in C++1y:
5569   QualType ToType;
5570   bool HasUniqueTargetType = true;
5571 
5572   // Collect explicit or viable (potentially in C++1y) conversions.
5573   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5574     NamedDecl *D = (*I)->getUnderlyingDecl();
5575     CXXConversionDecl *Conversion;
5576     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5577     if (ConvTemplate) {
5578       if (getLangOpts().CPlusPlus14)
5579         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5580       else
5581         continue; // C++11 does not consider conversion operator templates(?).
5582     } else
5583       Conversion = cast<CXXConversionDecl>(D);
5584 
5585     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5586            "Conversion operator templates are considered potentially "
5587            "viable in C++1y");
5588 
5589     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5590     if (Converter.match(CurToType) || ConvTemplate) {
5591 
5592       if (Conversion->isExplicit()) {
5593         // FIXME: For C++1y, do we need this restriction?
5594         // cf. diagnoseNoViableConversion()
5595         if (!ConvTemplate)
5596           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5597       } else {
5598         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5599           if (ToType.isNull())
5600             ToType = CurToType.getUnqualifiedType();
5601           else if (HasUniqueTargetType &&
5602                    (CurToType.getUnqualifiedType() != ToType))
5603             HasUniqueTargetType = false;
5604         }
5605         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5606       }
5607     }
5608   }
5609 
5610   if (getLangOpts().CPlusPlus14) {
5611     // C++1y [conv]p6:
5612     // ... An expression e of class type E appearing in such a context
5613     // is said to be contextually implicitly converted to a specified
5614     // type T and is well-formed if and only if e can be implicitly
5615     // converted to a type T that is determined as follows: E is searched
5616     // for conversion functions whose return type is cv T or reference to
5617     // cv T such that T is allowed by the context. There shall be
5618     // exactly one such T.
5619 
5620     // If no unique T is found:
5621     if (ToType.isNull()) {
5622       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5623                                      HadMultipleCandidates,
5624                                      ExplicitConversions))
5625         return ExprError();
5626       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5627     }
5628 
5629     // If more than one unique Ts are found:
5630     if (!HasUniqueTargetType)
5631       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5632                                          ViableConversions);
5633 
5634     // If one unique T is found:
5635     // First, build a candidate set from the previously recorded
5636     // potentially viable conversions.
5637     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5638     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5639                                       CandidateSet);
5640 
5641     // Then, perform overload resolution over the candidate set.
5642     OverloadCandidateSet::iterator Best;
5643     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5644     case OR_Success: {
5645       // Apply this conversion.
5646       DeclAccessPair Found =
5647           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5648       if (recordConversion(*this, Loc, From, Converter, T,
5649                            HadMultipleCandidates, Found))
5650         return ExprError();
5651       break;
5652     }
5653     case OR_Ambiguous:
5654       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5655                                          ViableConversions);
5656     case OR_No_Viable_Function:
5657       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5658                                      HadMultipleCandidates,
5659                                      ExplicitConversions))
5660         return ExprError();
5661     // fall through 'OR_Deleted' case.
5662     case OR_Deleted:
5663       // We'll complain below about a non-integral condition type.
5664       break;
5665     }
5666   } else {
5667     switch (ViableConversions.size()) {
5668     case 0: {
5669       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5670                                      HadMultipleCandidates,
5671                                      ExplicitConversions))
5672         return ExprError();
5673 
5674       // We'll complain below about a non-integral condition type.
5675       break;
5676     }
5677     case 1: {
5678       // Apply this conversion.
5679       DeclAccessPair Found = ViableConversions[0];
5680       if (recordConversion(*this, Loc, From, Converter, T,
5681                            HadMultipleCandidates, Found))
5682         return ExprError();
5683       break;
5684     }
5685     default:
5686       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5687                                          ViableConversions);
5688     }
5689   }
5690 
5691   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5692 }
5693 
5694 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5695 /// an acceptable non-member overloaded operator for a call whose
5696 /// arguments have types T1 (and, if non-empty, T2). This routine
5697 /// implements the check in C++ [over.match.oper]p3b2 concerning
5698 /// enumeration types.
5699 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5700                                                    FunctionDecl *Fn,
5701                                                    ArrayRef<Expr *> Args) {
5702   QualType T1 = Args[0]->getType();
5703   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5704 
5705   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5706     return true;
5707 
5708   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5709     return true;
5710 
5711   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5712   if (Proto->getNumParams() < 1)
5713     return false;
5714 
5715   if (T1->isEnumeralType()) {
5716     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5717     if (Context.hasSameUnqualifiedType(T1, ArgType))
5718       return true;
5719   }
5720 
5721   if (Proto->getNumParams() < 2)
5722     return false;
5723 
5724   if (!T2.isNull() && T2->isEnumeralType()) {
5725     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5726     if (Context.hasSameUnqualifiedType(T2, ArgType))
5727       return true;
5728   }
5729 
5730   return false;
5731 }
5732 
5733 /// AddOverloadCandidate - Adds the given function to the set of
5734 /// candidate functions, using the given function call arguments.  If
5735 /// @p SuppressUserConversions, then don't allow user-defined
5736 /// conversions via constructors or conversion operators.
5737 ///
5738 /// \param PartialOverloading true if we are performing "partial" overloading
5739 /// based on an incomplete set of function arguments. This feature is used by
5740 /// code completion.
5741 void
5742 Sema::AddOverloadCandidate(FunctionDecl *Function,
5743                            DeclAccessPair FoundDecl,
5744                            ArrayRef<Expr *> Args,
5745                            OverloadCandidateSet &CandidateSet,
5746                            bool SuppressUserConversions,
5747                            bool PartialOverloading,
5748                            bool AllowExplicit) {
5749   const FunctionProtoType *Proto
5750     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5751   assert(Proto && "Functions without a prototype cannot be overloaded");
5752   assert(!Function->getDescribedFunctionTemplate() &&
5753          "Use AddTemplateOverloadCandidate for function templates");
5754 
5755   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5756     if (!isa<CXXConstructorDecl>(Method)) {
5757       // If we get here, it's because we're calling a member function
5758       // that is named without a member access expression (e.g.,
5759       // "this->f") that was either written explicitly or created
5760       // implicitly. This can happen with a qualified call to a member
5761       // function, e.g., X::f(). We use an empty type for the implied
5762       // object argument (C++ [over.call.func]p3), and the acting context
5763       // is irrelevant.
5764       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5765                          QualType(), Expr::Classification::makeSimpleLValue(),
5766                          Args, CandidateSet, SuppressUserConversions,
5767                          PartialOverloading);
5768       return;
5769     }
5770     // We treat a constructor like a non-member function, since its object
5771     // argument doesn't participate in overload resolution.
5772   }
5773 
5774   if (!CandidateSet.isNewCandidate(Function))
5775     return;
5776 
5777   // C++ [over.match.oper]p3:
5778   //   if no operand has a class type, only those non-member functions in the
5779   //   lookup set that have a first parameter of type T1 or "reference to
5780   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5781   //   is a right operand) a second parameter of type T2 or "reference to
5782   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5783   //   candidate functions.
5784   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5785       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5786     return;
5787 
5788   // C++11 [class.copy]p11: [DR1402]
5789   //   A defaulted move constructor that is defined as deleted is ignored by
5790   //   overload resolution.
5791   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5792   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5793       Constructor->isMoveConstructor())
5794     return;
5795 
5796   // Overload resolution is always an unevaluated context.
5797   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5798 
5799   // Add this candidate
5800   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5801   Candidate.FoundDecl = FoundDecl;
5802   Candidate.Function = Function;
5803   Candidate.Viable = true;
5804   Candidate.IsSurrogate = false;
5805   Candidate.IgnoreObjectArgument = false;
5806   Candidate.ExplicitCallArguments = Args.size();
5807 
5808   if (Constructor) {
5809     // C++ [class.copy]p3:
5810     //   A member function template is never instantiated to perform the copy
5811     //   of a class object to an object of its class type.
5812     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5813     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5814         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5815          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5816                        ClassType))) {
5817       Candidate.Viable = false;
5818       Candidate.FailureKind = ovl_fail_illegal_constructor;
5819       return;
5820     }
5821   }
5822 
5823   unsigned NumParams = Proto->getNumParams();
5824 
5825   // (C++ 13.3.2p2): A candidate function having fewer than m
5826   // parameters is viable only if it has an ellipsis in its parameter
5827   // list (8.3.5).
5828   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5829       !Proto->isVariadic()) {
5830     Candidate.Viable = false;
5831     Candidate.FailureKind = ovl_fail_too_many_arguments;
5832     return;
5833   }
5834 
5835   // (C++ 13.3.2p2): A candidate function having more than m parameters
5836   // is viable only if the (m+1)st parameter has a default argument
5837   // (8.3.6). For the purposes of overload resolution, the
5838   // parameter list is truncated on the right, so that there are
5839   // exactly m parameters.
5840   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5841   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5842     // Not enough arguments.
5843     Candidate.Viable = false;
5844     Candidate.FailureKind = ovl_fail_too_few_arguments;
5845     return;
5846   }
5847 
5848   // (CUDA B.1): Check for invalid calls between targets.
5849   if (getLangOpts().CUDA)
5850     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5851       // Skip the check for callers that are implicit members, because in this
5852       // case we may not yet know what the member's target is; the target is
5853       // inferred for the member automatically, based on the bases and fields of
5854       // the class.
5855       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5856         Candidate.Viable = false;
5857         Candidate.FailureKind = ovl_fail_bad_target;
5858         return;
5859       }
5860 
5861   // Determine the implicit conversion sequences for each of the
5862   // arguments.
5863   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5864     if (ArgIdx < NumParams) {
5865       // (C++ 13.3.2p3): for F to be a viable function, there shall
5866       // exist for each argument an implicit conversion sequence
5867       // (13.3.3.1) that converts that argument to the corresponding
5868       // parameter of F.
5869       QualType ParamType = Proto->getParamType(ArgIdx);
5870       Candidate.Conversions[ArgIdx]
5871         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5872                                 SuppressUserConversions,
5873                                 /*InOverloadResolution=*/true,
5874                                 /*AllowObjCWritebackConversion=*/
5875                                   getLangOpts().ObjCAutoRefCount,
5876                                 AllowExplicit);
5877       if (Candidate.Conversions[ArgIdx].isBad()) {
5878         Candidate.Viable = false;
5879         Candidate.FailureKind = ovl_fail_bad_conversion;
5880         return;
5881       }
5882     } else {
5883       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5884       // argument for which there is no corresponding parameter is
5885       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5886       Candidate.Conversions[ArgIdx].setEllipsis();
5887     }
5888   }
5889 
5890   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5891     Candidate.Viable = false;
5892     Candidate.FailureKind = ovl_fail_enable_if;
5893     Candidate.DeductionFailure.Data = FailedAttr;
5894     return;
5895   }
5896 }
5897 
5898 ObjCMethodDecl *
5899 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5900                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5901   if (Methods.size() <= 1)
5902     return nullptr;
5903 
5904   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5905     bool Match = true;
5906     ObjCMethodDecl *Method = Methods[b];
5907     unsigned NumNamedArgs = Sel.getNumArgs();
5908     // Method might have more arguments than selector indicates. This is due
5909     // to addition of c-style arguments in method.
5910     if (Method->param_size() > NumNamedArgs)
5911       NumNamedArgs = Method->param_size();
5912     if (Args.size() < NumNamedArgs)
5913       continue;
5914 
5915     for (unsigned i = 0; i < NumNamedArgs; i++) {
5916       // We can't do any type-checking on a type-dependent argument.
5917       if (Args[i]->isTypeDependent()) {
5918         Match = false;
5919         break;
5920       }
5921 
5922       ParmVarDecl *param = Method->parameters()[i];
5923       Expr *argExpr = Args[i];
5924       assert(argExpr && "SelectBestMethod(): missing expression");
5925 
5926       // Strip the unbridged-cast placeholder expression off unless it's
5927       // a consumed argument.
5928       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5929           !param->hasAttr<CFConsumedAttr>())
5930         argExpr = stripARCUnbridgedCast(argExpr);
5931 
5932       // If the parameter is __unknown_anytype, move on to the next method.
5933       if (param->getType() == Context.UnknownAnyTy) {
5934         Match = false;
5935         break;
5936       }
5937 
5938       ImplicitConversionSequence ConversionState
5939         = TryCopyInitialization(*this, argExpr, param->getType(),
5940                                 /*SuppressUserConversions*/false,
5941                                 /*InOverloadResolution=*/true,
5942                                 /*AllowObjCWritebackConversion=*/
5943                                 getLangOpts().ObjCAutoRefCount,
5944                                 /*AllowExplicit*/false);
5945       // This function looks for a reasonably-exact match, so we consider
5946       // incompatible pointer conversions to be a failure here.
5947       if (ConversionState.isBad() ||
5948           (ConversionState.isStandard() &&
5949            ConversionState.Standard.Second ==
5950                ICK_Incompatible_Pointer_Conversion)) {
5951         Match = false;
5952         break;
5953       }
5954     }
5955     // Promote additional arguments to variadic methods.
5956     if (Match && Method->isVariadic()) {
5957       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5958         if (Args[i]->isTypeDependent()) {
5959           Match = false;
5960           break;
5961         }
5962         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5963                                                           nullptr);
5964         if (Arg.isInvalid()) {
5965           Match = false;
5966           break;
5967         }
5968       }
5969     } else {
5970       // Check for extra arguments to non-variadic methods.
5971       if (Args.size() != NumNamedArgs)
5972         Match = false;
5973       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5974         // Special case when selectors have no argument. In this case, select
5975         // one with the most general result type of 'id'.
5976         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5977           QualType ReturnT = Methods[b]->getReturnType();
5978           if (ReturnT->isObjCIdType())
5979             return Methods[b];
5980         }
5981       }
5982     }
5983 
5984     if (Match)
5985       return Method;
5986   }
5987   return nullptr;
5988 }
5989 
5990 // specific_attr_iterator iterates over enable_if attributes in reverse, and
5991 // enable_if is order-sensitive. As a result, we need to reverse things
5992 // sometimes. Size of 4 elements is arbitrary.
5993 static SmallVector<EnableIfAttr *, 4>
5994 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5995   SmallVector<EnableIfAttr *, 4> Result;
5996   if (!Function->hasAttrs())
5997     return Result;
5998 
5999   const auto &FuncAttrs = Function->getAttrs();
6000   for (Attr *Attr : FuncAttrs)
6001     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6002       Result.push_back(EnableIf);
6003 
6004   std::reverse(Result.begin(), Result.end());
6005   return Result;
6006 }
6007 
6008 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6009                                   bool MissingImplicitThis) {
6010   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6011   if (EnableIfAttrs.empty())
6012     return nullptr;
6013 
6014   SFINAETrap Trap(*this);
6015   SmallVector<Expr *, 16> ConvertedArgs;
6016   bool InitializationFailed = false;
6017 
6018   // Ignore any variadic arguments. Converting them is pointless, since the
6019   // user can't refer to them in the enable_if condition.
6020   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6021 
6022   // Convert the arguments.
6023   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6024     ExprResult R;
6025     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
6026         !cast<CXXMethodDecl>(Function)->isStatic() &&
6027         !isa<CXXConstructorDecl>(Function)) {
6028       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6029       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6030                                               Method, Method);
6031     } else {
6032       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6033                                         Context, Function->getParamDecl(I)),
6034                                     SourceLocation(), Args[I]);
6035     }
6036 
6037     if (R.isInvalid()) {
6038       InitializationFailed = true;
6039       break;
6040     }
6041 
6042     ConvertedArgs.push_back(R.get());
6043   }
6044 
6045   if (InitializationFailed || Trap.hasErrorOccurred())
6046     return EnableIfAttrs[0];
6047 
6048   // Push default arguments if needed.
6049   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6050     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6051       ParmVarDecl *P = Function->getParamDecl(i);
6052       ExprResult R = PerformCopyInitialization(
6053           InitializedEntity::InitializeParameter(Context,
6054                                                  Function->getParamDecl(i)),
6055           SourceLocation(),
6056           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6057                                            : P->getDefaultArg());
6058       if (R.isInvalid()) {
6059         InitializationFailed = true;
6060         break;
6061       }
6062       ConvertedArgs.push_back(R.get());
6063     }
6064 
6065     if (InitializationFailed || Trap.hasErrorOccurred())
6066       return EnableIfAttrs[0];
6067   }
6068 
6069   for (auto *EIA : EnableIfAttrs) {
6070     APValue Result;
6071     // FIXME: This doesn't consider value-dependent cases, because doing so is
6072     // very difficult. Ideally, we should handle them more gracefully.
6073     if (!EIA->getCond()->EvaluateWithSubstitution(
6074             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6075       return EIA;
6076 
6077     if (!Result.isInt() || !Result.getInt().getBoolValue())
6078       return EIA;
6079   }
6080   return nullptr;
6081 }
6082 
6083 /// \brief Add all of the function declarations in the given function set to
6084 /// the overload candidate set.
6085 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6086                                  ArrayRef<Expr *> Args,
6087                                  OverloadCandidateSet& CandidateSet,
6088                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6089                                  bool SuppressUserConversions,
6090                                  bool PartialOverloading) {
6091   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6092     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6093     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6094       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6095         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6096                            cast<CXXMethodDecl>(FD)->getParent(),
6097                            Args[0]->getType(), Args[0]->Classify(Context),
6098                            Args.slice(1), CandidateSet,
6099                            SuppressUserConversions, PartialOverloading);
6100       else
6101         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6102                              SuppressUserConversions, PartialOverloading);
6103     } else {
6104       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6105       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6106           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6107         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6108                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6109                                    ExplicitTemplateArgs,
6110                                    Args[0]->getType(),
6111                                    Args[0]->Classify(Context), Args.slice(1),
6112                                    CandidateSet, SuppressUserConversions,
6113                                    PartialOverloading);
6114       else
6115         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6116                                      ExplicitTemplateArgs, Args,
6117                                      CandidateSet, SuppressUserConversions,
6118                                      PartialOverloading);
6119     }
6120   }
6121 }
6122 
6123 /// AddMethodCandidate - Adds a named decl (which is some kind of
6124 /// method) as a method candidate to the given overload set.
6125 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6126                               QualType ObjectType,
6127                               Expr::Classification ObjectClassification,
6128                               ArrayRef<Expr *> Args,
6129                               OverloadCandidateSet& CandidateSet,
6130                               bool SuppressUserConversions) {
6131   NamedDecl *Decl = FoundDecl.getDecl();
6132   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6133 
6134   if (isa<UsingShadowDecl>(Decl))
6135     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6136 
6137   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6138     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6139            "Expected a member function template");
6140     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6141                                /*ExplicitArgs*/ nullptr,
6142                                ObjectType, ObjectClassification,
6143                                Args, CandidateSet,
6144                                SuppressUserConversions);
6145   } else {
6146     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6147                        ObjectType, ObjectClassification,
6148                        Args,
6149                        CandidateSet, SuppressUserConversions);
6150   }
6151 }
6152 
6153 /// AddMethodCandidate - Adds the given C++ member function to the set
6154 /// of candidate functions, using the given function call arguments
6155 /// and the object argument (@c Object). For example, in a call
6156 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6157 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6158 /// allow user-defined conversions via constructors or conversion
6159 /// operators.
6160 void
6161 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6162                          CXXRecordDecl *ActingContext, QualType ObjectType,
6163                          Expr::Classification ObjectClassification,
6164                          ArrayRef<Expr *> Args,
6165                          OverloadCandidateSet &CandidateSet,
6166                          bool SuppressUserConversions,
6167                          bool PartialOverloading) {
6168   const FunctionProtoType *Proto
6169     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6170   assert(Proto && "Methods without a prototype cannot be overloaded");
6171   assert(!isa<CXXConstructorDecl>(Method) &&
6172          "Use AddOverloadCandidate for constructors");
6173 
6174   if (!CandidateSet.isNewCandidate(Method))
6175     return;
6176 
6177   // C++11 [class.copy]p23: [DR1402]
6178   //   A defaulted move assignment operator that is defined as deleted is
6179   //   ignored by overload resolution.
6180   if (Method->isDefaulted() && Method->isDeleted() &&
6181       Method->isMoveAssignmentOperator())
6182     return;
6183 
6184   // Overload resolution is always an unevaluated context.
6185   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6186 
6187   // Add this candidate
6188   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6189   Candidate.FoundDecl = FoundDecl;
6190   Candidate.Function = Method;
6191   Candidate.IsSurrogate = false;
6192   Candidate.IgnoreObjectArgument = false;
6193   Candidate.ExplicitCallArguments = Args.size();
6194 
6195   unsigned NumParams = Proto->getNumParams();
6196 
6197   // (C++ 13.3.2p2): A candidate function having fewer than m
6198   // parameters is viable only if it has an ellipsis in its parameter
6199   // list (8.3.5).
6200   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6201       !Proto->isVariadic()) {
6202     Candidate.Viable = false;
6203     Candidate.FailureKind = ovl_fail_too_many_arguments;
6204     return;
6205   }
6206 
6207   // (C++ 13.3.2p2): A candidate function having more than m parameters
6208   // is viable only if the (m+1)st parameter has a default argument
6209   // (8.3.6). For the purposes of overload resolution, the
6210   // parameter list is truncated on the right, so that there are
6211   // exactly m parameters.
6212   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6213   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6214     // Not enough arguments.
6215     Candidate.Viable = false;
6216     Candidate.FailureKind = ovl_fail_too_few_arguments;
6217     return;
6218   }
6219 
6220   Candidate.Viable = true;
6221 
6222   if (Method->isStatic() || ObjectType.isNull())
6223     // The implicit object argument is ignored.
6224     Candidate.IgnoreObjectArgument = true;
6225   else {
6226     // Determine the implicit conversion sequence for the object
6227     // parameter.
6228     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6229         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6230         Method, ActingContext);
6231     if (Candidate.Conversions[0].isBad()) {
6232       Candidate.Viable = false;
6233       Candidate.FailureKind = ovl_fail_bad_conversion;
6234       return;
6235     }
6236   }
6237 
6238   // (CUDA B.1): Check for invalid calls between targets.
6239   if (getLangOpts().CUDA)
6240     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6241       if (!IsAllowedCUDACall(Caller, Method)) {
6242         Candidate.Viable = false;
6243         Candidate.FailureKind = ovl_fail_bad_target;
6244         return;
6245       }
6246 
6247   // Determine the implicit conversion sequences for each of the
6248   // arguments.
6249   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6250     if (ArgIdx < NumParams) {
6251       // (C++ 13.3.2p3): for F to be a viable function, there shall
6252       // exist for each argument an implicit conversion sequence
6253       // (13.3.3.1) that converts that argument to the corresponding
6254       // parameter of F.
6255       QualType ParamType = Proto->getParamType(ArgIdx);
6256       Candidate.Conversions[ArgIdx + 1]
6257         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6258                                 SuppressUserConversions,
6259                                 /*InOverloadResolution=*/true,
6260                                 /*AllowObjCWritebackConversion=*/
6261                                   getLangOpts().ObjCAutoRefCount);
6262       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6263         Candidate.Viable = false;
6264         Candidate.FailureKind = ovl_fail_bad_conversion;
6265         return;
6266       }
6267     } else {
6268       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6269       // argument for which there is no corresponding parameter is
6270       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6271       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6272     }
6273   }
6274 
6275   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6276     Candidate.Viable = false;
6277     Candidate.FailureKind = ovl_fail_enable_if;
6278     Candidate.DeductionFailure.Data = FailedAttr;
6279     return;
6280   }
6281 }
6282 
6283 /// \brief Add a C++ member function template as a candidate to the candidate
6284 /// set, using template argument deduction to produce an appropriate member
6285 /// function template specialization.
6286 void
6287 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6288                                  DeclAccessPair FoundDecl,
6289                                  CXXRecordDecl *ActingContext,
6290                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6291                                  QualType ObjectType,
6292                                  Expr::Classification ObjectClassification,
6293                                  ArrayRef<Expr *> Args,
6294                                  OverloadCandidateSet& CandidateSet,
6295                                  bool SuppressUserConversions,
6296                                  bool PartialOverloading) {
6297   if (!CandidateSet.isNewCandidate(MethodTmpl))
6298     return;
6299 
6300   // C++ [over.match.funcs]p7:
6301   //   In each case where a candidate is a function template, candidate
6302   //   function template specializations are generated using template argument
6303   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6304   //   candidate functions in the usual way.113) A given name can refer to one
6305   //   or more function templates and also to a set of overloaded non-template
6306   //   functions. In such a case, the candidate functions generated from each
6307   //   function template are combined with the set of non-template candidate
6308   //   functions.
6309   TemplateDeductionInfo Info(CandidateSet.getLocation());
6310   FunctionDecl *Specialization = nullptr;
6311   if (TemplateDeductionResult Result
6312       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6313                                 Specialization, Info, PartialOverloading)) {
6314     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6315     Candidate.FoundDecl = FoundDecl;
6316     Candidate.Function = MethodTmpl->getTemplatedDecl();
6317     Candidate.Viable = false;
6318     Candidate.FailureKind = ovl_fail_bad_deduction;
6319     Candidate.IsSurrogate = false;
6320     Candidate.IgnoreObjectArgument = false;
6321     Candidate.ExplicitCallArguments = Args.size();
6322     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6323                                                           Info);
6324     return;
6325   }
6326 
6327   // Add the function template specialization produced by template argument
6328   // deduction as a candidate.
6329   assert(Specialization && "Missing member function template specialization?");
6330   assert(isa<CXXMethodDecl>(Specialization) &&
6331          "Specialization is not a member function?");
6332   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6333                      ActingContext, ObjectType, ObjectClassification, Args,
6334                      CandidateSet, SuppressUserConversions, PartialOverloading);
6335 }
6336 
6337 /// \brief Add a C++ function template specialization as a candidate
6338 /// in the candidate set, using template argument deduction to produce
6339 /// an appropriate function template specialization.
6340 void
6341 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6342                                    DeclAccessPair FoundDecl,
6343                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6344                                    ArrayRef<Expr *> Args,
6345                                    OverloadCandidateSet& CandidateSet,
6346                                    bool SuppressUserConversions,
6347                                    bool PartialOverloading) {
6348   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6349     return;
6350 
6351   // C++ [over.match.funcs]p7:
6352   //   In each case where a candidate is a function template, candidate
6353   //   function template specializations are generated using template argument
6354   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6355   //   candidate functions in the usual way.113) A given name can refer to one
6356   //   or more function templates and also to a set of overloaded non-template
6357   //   functions. In such a case, the candidate functions generated from each
6358   //   function template are combined with the set of non-template candidate
6359   //   functions.
6360   TemplateDeductionInfo Info(CandidateSet.getLocation());
6361   FunctionDecl *Specialization = nullptr;
6362   if (TemplateDeductionResult Result
6363         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6364                                   Specialization, Info, PartialOverloading)) {
6365     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6366     Candidate.FoundDecl = FoundDecl;
6367     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6368     Candidate.Viable = false;
6369     Candidate.FailureKind = ovl_fail_bad_deduction;
6370     Candidate.IsSurrogate = false;
6371     Candidate.IgnoreObjectArgument = false;
6372     Candidate.ExplicitCallArguments = Args.size();
6373     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6374                                                           Info);
6375     return;
6376   }
6377 
6378   // Add the function template specialization produced by template argument
6379   // deduction as a candidate.
6380   assert(Specialization && "Missing function template specialization?");
6381   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6382                        SuppressUserConversions, PartialOverloading);
6383 }
6384 
6385 /// Determine whether this is an allowable conversion from the result
6386 /// of an explicit conversion operator to the expected type, per C++
6387 /// [over.match.conv]p1 and [over.match.ref]p1.
6388 ///
6389 /// \param ConvType The return type of the conversion function.
6390 ///
6391 /// \param ToType The type we are converting to.
6392 ///
6393 /// \param AllowObjCPointerConversion Allow a conversion from one
6394 /// Objective-C pointer to another.
6395 ///
6396 /// \returns true if the conversion is allowable, false otherwise.
6397 static bool isAllowableExplicitConversion(Sema &S,
6398                                           QualType ConvType, QualType ToType,
6399                                           bool AllowObjCPointerConversion) {
6400   QualType ToNonRefType = ToType.getNonReferenceType();
6401 
6402   // Easy case: the types are the same.
6403   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6404     return true;
6405 
6406   // Allow qualification conversions.
6407   bool ObjCLifetimeConversion;
6408   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6409                                   ObjCLifetimeConversion))
6410     return true;
6411 
6412   // If we're not allowed to consider Objective-C pointer conversions,
6413   // we're done.
6414   if (!AllowObjCPointerConversion)
6415     return false;
6416 
6417   // Is this an Objective-C pointer conversion?
6418   bool IncompatibleObjC = false;
6419   QualType ConvertedType;
6420   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6421                                    IncompatibleObjC);
6422 }
6423 
6424 /// AddConversionCandidate - Add a C++ conversion function as a
6425 /// candidate in the candidate set (C++ [over.match.conv],
6426 /// C++ [over.match.copy]). From is the expression we're converting from,
6427 /// and ToType is the type that we're eventually trying to convert to
6428 /// (which may or may not be the same type as the type that the
6429 /// conversion function produces).
6430 void
6431 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6432                              DeclAccessPair FoundDecl,
6433                              CXXRecordDecl *ActingContext,
6434                              Expr *From, QualType ToType,
6435                              OverloadCandidateSet& CandidateSet,
6436                              bool AllowObjCConversionOnExplicit) {
6437   assert(!Conversion->getDescribedFunctionTemplate() &&
6438          "Conversion function templates use AddTemplateConversionCandidate");
6439   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6440   if (!CandidateSet.isNewCandidate(Conversion))
6441     return;
6442 
6443   // If the conversion function has an undeduced return type, trigger its
6444   // deduction now.
6445   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6446     if (DeduceReturnType(Conversion, From->getExprLoc()))
6447       return;
6448     ConvType = Conversion->getConversionType().getNonReferenceType();
6449   }
6450 
6451   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6452   // operator is only a candidate if its return type is the target type or
6453   // can be converted to the target type with a qualification conversion.
6454   if (Conversion->isExplicit() &&
6455       !isAllowableExplicitConversion(*this, ConvType, ToType,
6456                                      AllowObjCConversionOnExplicit))
6457     return;
6458 
6459   // Overload resolution is always an unevaluated context.
6460   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6461 
6462   // Add this candidate
6463   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6464   Candidate.FoundDecl = FoundDecl;
6465   Candidate.Function = Conversion;
6466   Candidate.IsSurrogate = false;
6467   Candidate.IgnoreObjectArgument = false;
6468   Candidate.FinalConversion.setAsIdentityConversion();
6469   Candidate.FinalConversion.setFromType(ConvType);
6470   Candidate.FinalConversion.setAllToTypes(ToType);
6471   Candidate.Viable = true;
6472   Candidate.ExplicitCallArguments = 1;
6473 
6474   // C++ [over.match.funcs]p4:
6475   //   For conversion functions, the function is considered to be a member of
6476   //   the class of the implicit implied object argument for the purpose of
6477   //   defining the type of the implicit object parameter.
6478   //
6479   // Determine the implicit conversion sequence for the implicit
6480   // object parameter.
6481   QualType ImplicitParamType = From->getType();
6482   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6483     ImplicitParamType = FromPtrType->getPointeeType();
6484   CXXRecordDecl *ConversionContext
6485     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6486 
6487   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6488       *this, CandidateSet.getLocation(), From->getType(),
6489       From->Classify(Context), Conversion, ConversionContext);
6490 
6491   if (Candidate.Conversions[0].isBad()) {
6492     Candidate.Viable = false;
6493     Candidate.FailureKind = ovl_fail_bad_conversion;
6494     return;
6495   }
6496 
6497   // We won't go through a user-defined type conversion function to convert a
6498   // derived to base as such conversions are given Conversion Rank. They only
6499   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6500   QualType FromCanon
6501     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6502   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6503   if (FromCanon == ToCanon ||
6504       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6505     Candidate.Viable = false;
6506     Candidate.FailureKind = ovl_fail_trivial_conversion;
6507     return;
6508   }
6509 
6510   // To determine what the conversion from the result of calling the
6511   // conversion function to the type we're eventually trying to
6512   // convert to (ToType), we need to synthesize a call to the
6513   // conversion function and attempt copy initialization from it. This
6514   // makes sure that we get the right semantics with respect to
6515   // lvalues/rvalues and the type. Fortunately, we can allocate this
6516   // call on the stack and we don't need its arguments to be
6517   // well-formed.
6518   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6519                             VK_LValue, From->getLocStart());
6520   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6521                                 Context.getPointerType(Conversion->getType()),
6522                                 CK_FunctionToPointerDecay,
6523                                 &ConversionRef, VK_RValue);
6524 
6525   QualType ConversionType = Conversion->getConversionType();
6526   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6527     Candidate.Viable = false;
6528     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6529     return;
6530   }
6531 
6532   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6533 
6534   // Note that it is safe to allocate CallExpr on the stack here because
6535   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6536   // allocator).
6537   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6538   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6539                 From->getLocStart());
6540   ImplicitConversionSequence ICS =
6541     TryCopyInitialization(*this, &Call, ToType,
6542                           /*SuppressUserConversions=*/true,
6543                           /*InOverloadResolution=*/false,
6544                           /*AllowObjCWritebackConversion=*/false);
6545 
6546   switch (ICS.getKind()) {
6547   case ImplicitConversionSequence::StandardConversion:
6548     Candidate.FinalConversion = ICS.Standard;
6549 
6550     // C++ [over.ics.user]p3:
6551     //   If the user-defined conversion is specified by a specialization of a
6552     //   conversion function template, the second standard conversion sequence
6553     //   shall have exact match rank.
6554     if (Conversion->getPrimaryTemplate() &&
6555         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6556       Candidate.Viable = false;
6557       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6558       return;
6559     }
6560 
6561     // C++0x [dcl.init.ref]p5:
6562     //    In the second case, if the reference is an rvalue reference and
6563     //    the second standard conversion sequence of the user-defined
6564     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6565     //    program is ill-formed.
6566     if (ToType->isRValueReferenceType() &&
6567         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6568       Candidate.Viable = false;
6569       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6570       return;
6571     }
6572     break;
6573 
6574   case ImplicitConversionSequence::BadConversion:
6575     Candidate.Viable = false;
6576     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6577     return;
6578 
6579   default:
6580     llvm_unreachable(
6581            "Can only end up with a standard conversion sequence or failure");
6582   }
6583 
6584   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6585     Candidate.Viable = false;
6586     Candidate.FailureKind = ovl_fail_enable_if;
6587     Candidate.DeductionFailure.Data = FailedAttr;
6588     return;
6589   }
6590 }
6591 
6592 /// \brief Adds a conversion function template specialization
6593 /// candidate to the overload set, using template argument deduction
6594 /// to deduce the template arguments of the conversion function
6595 /// template from the type that we are converting to (C++
6596 /// [temp.deduct.conv]).
6597 void
6598 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6599                                      DeclAccessPair FoundDecl,
6600                                      CXXRecordDecl *ActingDC,
6601                                      Expr *From, QualType ToType,
6602                                      OverloadCandidateSet &CandidateSet,
6603                                      bool AllowObjCConversionOnExplicit) {
6604   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6605          "Only conversion function templates permitted here");
6606 
6607   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6608     return;
6609 
6610   TemplateDeductionInfo Info(CandidateSet.getLocation());
6611   CXXConversionDecl *Specialization = nullptr;
6612   if (TemplateDeductionResult Result
6613         = DeduceTemplateArguments(FunctionTemplate, ToType,
6614                                   Specialization, Info)) {
6615     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6616     Candidate.FoundDecl = FoundDecl;
6617     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6618     Candidate.Viable = false;
6619     Candidate.FailureKind = ovl_fail_bad_deduction;
6620     Candidate.IsSurrogate = false;
6621     Candidate.IgnoreObjectArgument = false;
6622     Candidate.ExplicitCallArguments = 1;
6623     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6624                                                           Info);
6625     return;
6626   }
6627 
6628   // Add the conversion function template specialization produced by
6629   // template argument deduction as a candidate.
6630   assert(Specialization && "Missing function template specialization?");
6631   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6632                          CandidateSet, AllowObjCConversionOnExplicit);
6633 }
6634 
6635 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6636 /// converts the given @c Object to a function pointer via the
6637 /// conversion function @c Conversion, and then attempts to call it
6638 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6639 /// the type of function that we'll eventually be calling.
6640 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6641                                  DeclAccessPair FoundDecl,
6642                                  CXXRecordDecl *ActingContext,
6643                                  const FunctionProtoType *Proto,
6644                                  Expr *Object,
6645                                  ArrayRef<Expr *> Args,
6646                                  OverloadCandidateSet& CandidateSet) {
6647   if (!CandidateSet.isNewCandidate(Conversion))
6648     return;
6649 
6650   // Overload resolution is always an unevaluated context.
6651   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6652 
6653   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6654   Candidate.FoundDecl = FoundDecl;
6655   Candidate.Function = nullptr;
6656   Candidate.Surrogate = Conversion;
6657   Candidate.Viable = true;
6658   Candidate.IsSurrogate = true;
6659   Candidate.IgnoreObjectArgument = false;
6660   Candidate.ExplicitCallArguments = Args.size();
6661 
6662   // Determine the implicit conversion sequence for the implicit
6663   // object parameter.
6664   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6665       *this, CandidateSet.getLocation(), Object->getType(),
6666       Object->Classify(Context), Conversion, ActingContext);
6667   if (ObjectInit.isBad()) {
6668     Candidate.Viable = false;
6669     Candidate.FailureKind = ovl_fail_bad_conversion;
6670     Candidate.Conversions[0] = ObjectInit;
6671     return;
6672   }
6673 
6674   // The first conversion is actually a user-defined conversion whose
6675   // first conversion is ObjectInit's standard conversion (which is
6676   // effectively a reference binding). Record it as such.
6677   Candidate.Conversions[0].setUserDefined();
6678   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6679   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6680   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6681   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6682   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6683   Candidate.Conversions[0].UserDefined.After
6684     = Candidate.Conversions[0].UserDefined.Before;
6685   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6686 
6687   // Find the
6688   unsigned NumParams = Proto->getNumParams();
6689 
6690   // (C++ 13.3.2p2): A candidate function having fewer than m
6691   // parameters is viable only if it has an ellipsis in its parameter
6692   // list (8.3.5).
6693   if (Args.size() > NumParams && !Proto->isVariadic()) {
6694     Candidate.Viable = false;
6695     Candidate.FailureKind = ovl_fail_too_many_arguments;
6696     return;
6697   }
6698 
6699   // Function types don't have any default arguments, so just check if
6700   // we have enough arguments.
6701   if (Args.size() < NumParams) {
6702     // Not enough arguments.
6703     Candidate.Viable = false;
6704     Candidate.FailureKind = ovl_fail_too_few_arguments;
6705     return;
6706   }
6707 
6708   // Determine the implicit conversion sequences for each of the
6709   // arguments.
6710   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6711     if (ArgIdx < NumParams) {
6712       // (C++ 13.3.2p3): for F to be a viable function, there shall
6713       // exist for each argument an implicit conversion sequence
6714       // (13.3.3.1) that converts that argument to the corresponding
6715       // parameter of F.
6716       QualType ParamType = Proto->getParamType(ArgIdx);
6717       Candidate.Conversions[ArgIdx + 1]
6718         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6719                                 /*SuppressUserConversions=*/false,
6720                                 /*InOverloadResolution=*/false,
6721                                 /*AllowObjCWritebackConversion=*/
6722                                   getLangOpts().ObjCAutoRefCount);
6723       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6724         Candidate.Viable = false;
6725         Candidate.FailureKind = ovl_fail_bad_conversion;
6726         return;
6727       }
6728     } else {
6729       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6730       // argument for which there is no corresponding parameter is
6731       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6732       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6733     }
6734   }
6735 
6736   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6737     Candidate.Viable = false;
6738     Candidate.FailureKind = ovl_fail_enable_if;
6739     Candidate.DeductionFailure.Data = FailedAttr;
6740     return;
6741   }
6742 }
6743 
6744 /// \brief Add overload candidates for overloaded operators that are
6745 /// member functions.
6746 ///
6747 /// Add the overloaded operator candidates that are member functions
6748 /// for the operator Op that was used in an operator expression such
6749 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6750 /// CandidateSet will store the added overload candidates. (C++
6751 /// [over.match.oper]).
6752 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6753                                        SourceLocation OpLoc,
6754                                        ArrayRef<Expr *> Args,
6755                                        OverloadCandidateSet& CandidateSet,
6756                                        SourceRange OpRange) {
6757   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6758 
6759   // C++ [over.match.oper]p3:
6760   //   For a unary operator @ with an operand of a type whose
6761   //   cv-unqualified version is T1, and for a binary operator @ with
6762   //   a left operand of a type whose cv-unqualified version is T1 and
6763   //   a right operand of a type whose cv-unqualified version is T2,
6764   //   three sets of candidate functions, designated member
6765   //   candidates, non-member candidates and built-in candidates, are
6766   //   constructed as follows:
6767   QualType T1 = Args[0]->getType();
6768 
6769   //     -- If T1 is a complete class type or a class currently being
6770   //        defined, the set of member candidates is the result of the
6771   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6772   //        the set of member candidates is empty.
6773   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6774     // Complete the type if it can be completed.
6775     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6776       return;
6777     // If the type is neither complete nor being defined, bail out now.
6778     if (!T1Rec->getDecl()->getDefinition())
6779       return;
6780 
6781     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6782     LookupQualifiedName(Operators, T1Rec->getDecl());
6783     Operators.suppressDiagnostics();
6784 
6785     for (LookupResult::iterator Oper = Operators.begin(),
6786                              OperEnd = Operators.end();
6787          Oper != OperEnd;
6788          ++Oper)
6789       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6790                          Args[0]->Classify(Context),
6791                          Args.slice(1),
6792                          CandidateSet,
6793                          /* SuppressUserConversions = */ false);
6794   }
6795 }
6796 
6797 /// AddBuiltinCandidate - Add a candidate for a built-in
6798 /// operator. ResultTy and ParamTys are the result and parameter types
6799 /// of the built-in candidate, respectively. Args and NumArgs are the
6800 /// arguments being passed to the candidate. IsAssignmentOperator
6801 /// should be true when this built-in candidate is an assignment
6802 /// operator. NumContextualBoolArguments is the number of arguments
6803 /// (at the beginning of the argument list) that will be contextually
6804 /// converted to bool.
6805 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6806                                ArrayRef<Expr *> Args,
6807                                OverloadCandidateSet& CandidateSet,
6808                                bool IsAssignmentOperator,
6809                                unsigned NumContextualBoolArguments) {
6810   // Overload resolution is always an unevaluated context.
6811   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6812 
6813   // Add this candidate
6814   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6815   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6816   Candidate.Function = nullptr;
6817   Candidate.IsSurrogate = false;
6818   Candidate.IgnoreObjectArgument = false;
6819   Candidate.BuiltinTypes.ResultTy = ResultTy;
6820   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6821     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6822 
6823   // Determine the implicit conversion sequences for each of the
6824   // arguments.
6825   Candidate.Viable = true;
6826   Candidate.ExplicitCallArguments = Args.size();
6827   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6828     // C++ [over.match.oper]p4:
6829     //   For the built-in assignment operators, conversions of the
6830     //   left operand are restricted as follows:
6831     //     -- no temporaries are introduced to hold the left operand, and
6832     //     -- no user-defined conversions are applied to the left
6833     //        operand to achieve a type match with the left-most
6834     //        parameter of a built-in candidate.
6835     //
6836     // We block these conversions by turning off user-defined
6837     // conversions, since that is the only way that initialization of
6838     // a reference to a non-class type can occur from something that
6839     // is not of the same type.
6840     if (ArgIdx < NumContextualBoolArguments) {
6841       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6842              "Contextual conversion to bool requires bool type");
6843       Candidate.Conversions[ArgIdx]
6844         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6845     } else {
6846       Candidate.Conversions[ArgIdx]
6847         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6848                                 ArgIdx == 0 && IsAssignmentOperator,
6849                                 /*InOverloadResolution=*/false,
6850                                 /*AllowObjCWritebackConversion=*/
6851                                   getLangOpts().ObjCAutoRefCount);
6852     }
6853     if (Candidate.Conversions[ArgIdx].isBad()) {
6854       Candidate.Viable = false;
6855       Candidate.FailureKind = ovl_fail_bad_conversion;
6856       break;
6857     }
6858   }
6859 }
6860 
6861 namespace {
6862 
6863 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6864 /// candidate operator functions for built-in operators (C++
6865 /// [over.built]). The types are separated into pointer types and
6866 /// enumeration types.
6867 class BuiltinCandidateTypeSet  {
6868   /// TypeSet - A set of types.
6869   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6870                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6871 
6872   /// PointerTypes - The set of pointer types that will be used in the
6873   /// built-in candidates.
6874   TypeSet PointerTypes;
6875 
6876   /// MemberPointerTypes - The set of member pointer types that will be
6877   /// used in the built-in candidates.
6878   TypeSet MemberPointerTypes;
6879 
6880   /// EnumerationTypes - The set of enumeration types that will be
6881   /// used in the built-in candidates.
6882   TypeSet EnumerationTypes;
6883 
6884   /// \brief The set of vector types that will be used in the built-in
6885   /// candidates.
6886   TypeSet VectorTypes;
6887 
6888   /// \brief A flag indicating non-record types are viable candidates
6889   bool HasNonRecordTypes;
6890 
6891   /// \brief A flag indicating whether either arithmetic or enumeration types
6892   /// were present in the candidate set.
6893   bool HasArithmeticOrEnumeralTypes;
6894 
6895   /// \brief A flag indicating whether the nullptr type was present in the
6896   /// candidate set.
6897   bool HasNullPtrType;
6898 
6899   /// Sema - The semantic analysis instance where we are building the
6900   /// candidate type set.
6901   Sema &SemaRef;
6902 
6903   /// Context - The AST context in which we will build the type sets.
6904   ASTContext &Context;
6905 
6906   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6907                                                const Qualifiers &VisibleQuals);
6908   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6909 
6910 public:
6911   /// iterator - Iterates through the types that are part of the set.
6912   typedef TypeSet::iterator iterator;
6913 
6914   BuiltinCandidateTypeSet(Sema &SemaRef)
6915     : HasNonRecordTypes(false),
6916       HasArithmeticOrEnumeralTypes(false),
6917       HasNullPtrType(false),
6918       SemaRef(SemaRef),
6919       Context(SemaRef.Context) { }
6920 
6921   void AddTypesConvertedFrom(QualType Ty,
6922                              SourceLocation Loc,
6923                              bool AllowUserConversions,
6924                              bool AllowExplicitConversions,
6925                              const Qualifiers &VisibleTypeConversionsQuals);
6926 
6927   /// pointer_begin - First pointer type found;
6928   iterator pointer_begin() { return PointerTypes.begin(); }
6929 
6930   /// pointer_end - Past the last pointer type found;
6931   iterator pointer_end() { return PointerTypes.end(); }
6932 
6933   /// member_pointer_begin - First member pointer type found;
6934   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6935 
6936   /// member_pointer_end - Past the last member pointer type found;
6937   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6938 
6939   /// enumeration_begin - First enumeration type found;
6940   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6941 
6942   /// enumeration_end - Past the last enumeration type found;
6943   iterator enumeration_end() { return EnumerationTypes.end(); }
6944 
6945   iterator vector_begin() { return VectorTypes.begin(); }
6946   iterator vector_end() { return VectorTypes.end(); }
6947 
6948   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6949   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6950   bool hasNullPtrType() const { return HasNullPtrType; }
6951 };
6952 
6953 } // end anonymous namespace
6954 
6955 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6956 /// the set of pointer types along with any more-qualified variants of
6957 /// that type. For example, if @p Ty is "int const *", this routine
6958 /// will add "int const *", "int const volatile *", "int const
6959 /// restrict *", and "int const volatile restrict *" to the set of
6960 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6961 /// false otherwise.
6962 ///
6963 /// FIXME: what to do about extended qualifiers?
6964 bool
6965 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6966                                              const Qualifiers &VisibleQuals) {
6967 
6968   // Insert this type.
6969   if (!PointerTypes.insert(Ty))
6970     return false;
6971 
6972   QualType PointeeTy;
6973   const PointerType *PointerTy = Ty->getAs<PointerType>();
6974   bool buildObjCPtr = false;
6975   if (!PointerTy) {
6976     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6977     PointeeTy = PTy->getPointeeType();
6978     buildObjCPtr = true;
6979   } else {
6980     PointeeTy = PointerTy->getPointeeType();
6981   }
6982 
6983   // Don't add qualified variants of arrays. For one, they're not allowed
6984   // (the qualifier would sink to the element type), and for another, the
6985   // only overload situation where it matters is subscript or pointer +- int,
6986   // and those shouldn't have qualifier variants anyway.
6987   if (PointeeTy->isArrayType())
6988     return true;
6989 
6990   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6991   bool hasVolatile = VisibleQuals.hasVolatile();
6992   bool hasRestrict = VisibleQuals.hasRestrict();
6993 
6994   // Iterate through all strict supersets of BaseCVR.
6995   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6996     if ((CVR | BaseCVR) != CVR) continue;
6997     // Skip over volatile if no volatile found anywhere in the types.
6998     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6999 
7000     // Skip over restrict if no restrict found anywhere in the types, or if
7001     // the type cannot be restrict-qualified.
7002     if ((CVR & Qualifiers::Restrict) &&
7003         (!hasRestrict ||
7004          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7005       continue;
7006 
7007     // Build qualified pointee type.
7008     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7009 
7010     // Build qualified pointer type.
7011     QualType QPointerTy;
7012     if (!buildObjCPtr)
7013       QPointerTy = Context.getPointerType(QPointeeTy);
7014     else
7015       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7016 
7017     // Insert qualified pointer type.
7018     PointerTypes.insert(QPointerTy);
7019   }
7020 
7021   return true;
7022 }
7023 
7024 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7025 /// to the set of pointer types along with any more-qualified variants of
7026 /// that type. For example, if @p Ty is "int const *", this routine
7027 /// will add "int const *", "int const volatile *", "int const
7028 /// restrict *", and "int const volatile restrict *" to the set of
7029 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7030 /// false otherwise.
7031 ///
7032 /// FIXME: what to do about extended qualifiers?
7033 bool
7034 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7035     QualType Ty) {
7036   // Insert this type.
7037   if (!MemberPointerTypes.insert(Ty))
7038     return false;
7039 
7040   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7041   assert(PointerTy && "type was not a member pointer type!");
7042 
7043   QualType PointeeTy = PointerTy->getPointeeType();
7044   // Don't add qualified variants of arrays. For one, they're not allowed
7045   // (the qualifier would sink to the element type), and for another, the
7046   // only overload situation where it matters is subscript or pointer +- int,
7047   // and those shouldn't have qualifier variants anyway.
7048   if (PointeeTy->isArrayType())
7049     return true;
7050   const Type *ClassTy = PointerTy->getClass();
7051 
7052   // Iterate through all strict supersets of the pointee type's CVR
7053   // qualifiers.
7054   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7055   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7056     if ((CVR | BaseCVR) != CVR) continue;
7057 
7058     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7059     MemberPointerTypes.insert(
7060       Context.getMemberPointerType(QPointeeTy, ClassTy));
7061   }
7062 
7063   return true;
7064 }
7065 
7066 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7067 /// Ty can be implicit converted to the given set of @p Types. We're
7068 /// primarily interested in pointer types and enumeration types. We also
7069 /// take member pointer types, for the conditional operator.
7070 /// AllowUserConversions is true if we should look at the conversion
7071 /// functions of a class type, and AllowExplicitConversions if we
7072 /// should also include the explicit conversion functions of a class
7073 /// type.
7074 void
7075 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7076                                                SourceLocation Loc,
7077                                                bool AllowUserConversions,
7078                                                bool AllowExplicitConversions,
7079                                                const Qualifiers &VisibleQuals) {
7080   // Only deal with canonical types.
7081   Ty = Context.getCanonicalType(Ty);
7082 
7083   // Look through reference types; they aren't part of the type of an
7084   // expression for the purposes of conversions.
7085   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7086     Ty = RefTy->getPointeeType();
7087 
7088   // If we're dealing with an array type, decay to the pointer.
7089   if (Ty->isArrayType())
7090     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7091 
7092   // Otherwise, we don't care about qualifiers on the type.
7093   Ty = Ty.getLocalUnqualifiedType();
7094 
7095   // Flag if we ever add a non-record type.
7096   const RecordType *TyRec = Ty->getAs<RecordType>();
7097   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7098 
7099   // Flag if we encounter an arithmetic type.
7100   HasArithmeticOrEnumeralTypes =
7101     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7102 
7103   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7104     PointerTypes.insert(Ty);
7105   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7106     // Insert our type, and its more-qualified variants, into the set
7107     // of types.
7108     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7109       return;
7110   } else if (Ty->isMemberPointerType()) {
7111     // Member pointers are far easier, since the pointee can't be converted.
7112     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7113       return;
7114   } else if (Ty->isEnumeralType()) {
7115     HasArithmeticOrEnumeralTypes = true;
7116     EnumerationTypes.insert(Ty);
7117   } else if (Ty->isVectorType()) {
7118     // We treat vector types as arithmetic types in many contexts as an
7119     // extension.
7120     HasArithmeticOrEnumeralTypes = true;
7121     VectorTypes.insert(Ty);
7122   } else if (Ty->isNullPtrType()) {
7123     HasNullPtrType = true;
7124   } else if (AllowUserConversions && TyRec) {
7125     // No conversion functions in incomplete types.
7126     if (!SemaRef.isCompleteType(Loc, Ty))
7127       return;
7128 
7129     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7130     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7131       if (isa<UsingShadowDecl>(D))
7132         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7133 
7134       // Skip conversion function templates; they don't tell us anything
7135       // about which builtin types we can convert to.
7136       if (isa<FunctionTemplateDecl>(D))
7137         continue;
7138 
7139       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7140       if (AllowExplicitConversions || !Conv->isExplicit()) {
7141         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7142                               VisibleQuals);
7143       }
7144     }
7145   }
7146 }
7147 
7148 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7149 /// the volatile- and non-volatile-qualified assignment operators for the
7150 /// given type to the candidate set.
7151 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7152                                                    QualType T,
7153                                                    ArrayRef<Expr *> Args,
7154                                     OverloadCandidateSet &CandidateSet) {
7155   QualType ParamTypes[2];
7156 
7157   // T& operator=(T&, T)
7158   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7159   ParamTypes[1] = T;
7160   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7161                         /*IsAssignmentOperator=*/true);
7162 
7163   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7164     // volatile T& operator=(volatile T&, T)
7165     ParamTypes[0]
7166       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7167     ParamTypes[1] = T;
7168     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7169                           /*IsAssignmentOperator=*/true);
7170   }
7171 }
7172 
7173 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7174 /// if any, found in visible type conversion functions found in ArgExpr's type.
7175 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7176     Qualifiers VRQuals;
7177     const RecordType *TyRec;
7178     if (const MemberPointerType *RHSMPType =
7179         ArgExpr->getType()->getAs<MemberPointerType>())
7180       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7181     else
7182       TyRec = ArgExpr->getType()->getAs<RecordType>();
7183     if (!TyRec) {
7184       // Just to be safe, assume the worst case.
7185       VRQuals.addVolatile();
7186       VRQuals.addRestrict();
7187       return VRQuals;
7188     }
7189 
7190     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7191     if (!ClassDecl->hasDefinition())
7192       return VRQuals;
7193 
7194     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7195       if (isa<UsingShadowDecl>(D))
7196         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7197       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7198         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7199         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7200           CanTy = ResTypeRef->getPointeeType();
7201         // Need to go down the pointer/mempointer chain and add qualifiers
7202         // as see them.
7203         bool done = false;
7204         while (!done) {
7205           if (CanTy.isRestrictQualified())
7206             VRQuals.addRestrict();
7207           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7208             CanTy = ResTypePtr->getPointeeType();
7209           else if (const MemberPointerType *ResTypeMPtr =
7210                 CanTy->getAs<MemberPointerType>())
7211             CanTy = ResTypeMPtr->getPointeeType();
7212           else
7213             done = true;
7214           if (CanTy.isVolatileQualified())
7215             VRQuals.addVolatile();
7216           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7217             return VRQuals;
7218         }
7219       }
7220     }
7221     return VRQuals;
7222 }
7223 
7224 namespace {
7225 
7226 /// \brief Helper class to manage the addition of builtin operator overload
7227 /// candidates. It provides shared state and utility methods used throughout
7228 /// the process, as well as a helper method to add each group of builtin
7229 /// operator overloads from the standard to a candidate set.
7230 class BuiltinOperatorOverloadBuilder {
7231   // Common instance state available to all overload candidate addition methods.
7232   Sema &S;
7233   ArrayRef<Expr *> Args;
7234   Qualifiers VisibleTypeConversionsQuals;
7235   bool HasArithmeticOrEnumeralCandidateType;
7236   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7237   OverloadCandidateSet &CandidateSet;
7238 
7239   // Define some constants used to index and iterate over the arithemetic types
7240   // provided via the getArithmeticType() method below.
7241   // The "promoted arithmetic types" are the arithmetic
7242   // types are that preserved by promotion (C++ [over.built]p2).
7243   static const unsigned FirstIntegralType = 4;
7244   static const unsigned LastIntegralType = 21;
7245   static const unsigned FirstPromotedIntegralType = 4,
7246                         LastPromotedIntegralType = 12;
7247   static const unsigned FirstPromotedArithmeticType = 0,
7248                         LastPromotedArithmeticType = 12;
7249   static const unsigned NumArithmeticTypes = 21;
7250 
7251   /// \brief Get the canonical type for a given arithmetic type index.
7252   CanQualType getArithmeticType(unsigned index) {
7253     assert(index < NumArithmeticTypes);
7254     static CanQualType ASTContext::* const
7255       ArithmeticTypes[NumArithmeticTypes] = {
7256       // Start of promoted types.
7257       &ASTContext::FloatTy,
7258       &ASTContext::DoubleTy,
7259       &ASTContext::LongDoubleTy,
7260       &ASTContext::Float128Ty,
7261 
7262       // Start of integral types.
7263       &ASTContext::IntTy,
7264       &ASTContext::LongTy,
7265       &ASTContext::LongLongTy,
7266       &ASTContext::Int128Ty,
7267       &ASTContext::UnsignedIntTy,
7268       &ASTContext::UnsignedLongTy,
7269       &ASTContext::UnsignedLongLongTy,
7270       &ASTContext::UnsignedInt128Ty,
7271       // End of promoted types.
7272 
7273       &ASTContext::BoolTy,
7274       &ASTContext::CharTy,
7275       &ASTContext::WCharTy,
7276       &ASTContext::Char16Ty,
7277       &ASTContext::Char32Ty,
7278       &ASTContext::SignedCharTy,
7279       &ASTContext::ShortTy,
7280       &ASTContext::UnsignedCharTy,
7281       &ASTContext::UnsignedShortTy,
7282       // End of integral types.
7283       // FIXME: What about complex? What about half?
7284     };
7285     return S.Context.*ArithmeticTypes[index];
7286   }
7287 
7288   /// \brief Gets the canonical type resulting from the usual arithemetic
7289   /// converions for the given arithmetic types.
7290   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7291     // Accelerator table for performing the usual arithmetic conversions.
7292     // The rules are basically:
7293     //   - if either is floating-point, use the wider floating-point
7294     //   - if same signedness, use the higher rank
7295     //   - if same size, use unsigned of the higher rank
7296     //   - use the larger type
7297     // These rules, together with the axiom that higher ranks are
7298     // never smaller, are sufficient to precompute all of these results
7299     // *except* when dealing with signed types of higher rank.
7300     // (we could precompute SLL x UI for all known platforms, but it's
7301     // better not to make any assumptions).
7302     // We assume that int128 has a higher rank than long long on all platforms.
7303     enum PromotedType : int8_t {
7304             Dep=-1,
7305             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7306     };
7307     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7308                                         [LastPromotedArithmeticType] = {
7309 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7310 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7311 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7312 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7313 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7314 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7315 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7316 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7317 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7318 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7319 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7320     };
7321 
7322     assert(L < LastPromotedArithmeticType);
7323     assert(R < LastPromotedArithmeticType);
7324     int Idx = ConversionsTable[L][R];
7325 
7326     // Fast path: the table gives us a concrete answer.
7327     if (Idx != Dep) return getArithmeticType(Idx);
7328 
7329     // Slow path: we need to compare widths.
7330     // An invariant is that the signed type has higher rank.
7331     CanQualType LT = getArithmeticType(L),
7332                 RT = getArithmeticType(R);
7333     unsigned LW = S.Context.getIntWidth(LT),
7334              RW = S.Context.getIntWidth(RT);
7335 
7336     // If they're different widths, use the signed type.
7337     if (LW > RW) return LT;
7338     else if (LW < RW) return RT;
7339 
7340     // Otherwise, use the unsigned type of the signed type's rank.
7341     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7342     assert(L == SLL || R == SLL);
7343     return S.Context.UnsignedLongLongTy;
7344   }
7345 
7346   /// \brief Helper method to factor out the common pattern of adding overloads
7347   /// for '++' and '--' builtin operators.
7348   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7349                                            bool HasVolatile,
7350                                            bool HasRestrict) {
7351     QualType ParamTypes[2] = {
7352       S.Context.getLValueReferenceType(CandidateTy),
7353       S.Context.IntTy
7354     };
7355 
7356     // Non-volatile version.
7357     if (Args.size() == 1)
7358       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7359     else
7360       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7361 
7362     // Use a heuristic to reduce number of builtin candidates in the set:
7363     // add volatile version only if there are conversions to a volatile type.
7364     if (HasVolatile) {
7365       ParamTypes[0] =
7366         S.Context.getLValueReferenceType(
7367           S.Context.getVolatileType(CandidateTy));
7368       if (Args.size() == 1)
7369         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7370       else
7371         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7372     }
7373 
7374     // Add restrict version only if there are conversions to a restrict type
7375     // and our candidate type is a non-restrict-qualified pointer.
7376     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7377         !CandidateTy.isRestrictQualified()) {
7378       ParamTypes[0]
7379         = S.Context.getLValueReferenceType(
7380             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7381       if (Args.size() == 1)
7382         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7383       else
7384         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7385 
7386       if (HasVolatile) {
7387         ParamTypes[0]
7388           = S.Context.getLValueReferenceType(
7389               S.Context.getCVRQualifiedType(CandidateTy,
7390                                             (Qualifiers::Volatile |
7391                                              Qualifiers::Restrict)));
7392         if (Args.size() == 1)
7393           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7394         else
7395           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7396       }
7397     }
7398 
7399   }
7400 
7401 public:
7402   BuiltinOperatorOverloadBuilder(
7403     Sema &S, ArrayRef<Expr *> Args,
7404     Qualifiers VisibleTypeConversionsQuals,
7405     bool HasArithmeticOrEnumeralCandidateType,
7406     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7407     OverloadCandidateSet &CandidateSet)
7408     : S(S), Args(Args),
7409       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7410       HasArithmeticOrEnumeralCandidateType(
7411         HasArithmeticOrEnumeralCandidateType),
7412       CandidateTypes(CandidateTypes),
7413       CandidateSet(CandidateSet) {
7414     // Validate some of our static helper constants in debug builds.
7415     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7416            "Invalid first promoted integral type");
7417     assert(getArithmeticType(LastPromotedIntegralType - 1)
7418              == S.Context.UnsignedInt128Ty &&
7419            "Invalid last promoted integral type");
7420     assert(getArithmeticType(FirstPromotedArithmeticType)
7421              == S.Context.FloatTy &&
7422            "Invalid first promoted arithmetic type");
7423     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7424              == S.Context.UnsignedInt128Ty &&
7425            "Invalid last promoted arithmetic type");
7426   }
7427 
7428   // C++ [over.built]p3:
7429   //
7430   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7431   //   is either volatile or empty, there exist candidate operator
7432   //   functions of the form
7433   //
7434   //       VQ T&      operator++(VQ T&);
7435   //       T          operator++(VQ T&, int);
7436   //
7437   // C++ [over.built]p4:
7438   //
7439   //   For every pair (T, VQ), where T is an arithmetic type other
7440   //   than bool, and VQ is either volatile or empty, there exist
7441   //   candidate operator functions of the form
7442   //
7443   //       VQ T&      operator--(VQ T&);
7444   //       T          operator--(VQ T&, int);
7445   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7446     if (!HasArithmeticOrEnumeralCandidateType)
7447       return;
7448 
7449     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7450          Arith < NumArithmeticTypes; ++Arith) {
7451       addPlusPlusMinusMinusStyleOverloads(
7452         getArithmeticType(Arith),
7453         VisibleTypeConversionsQuals.hasVolatile(),
7454         VisibleTypeConversionsQuals.hasRestrict());
7455     }
7456   }
7457 
7458   // C++ [over.built]p5:
7459   //
7460   //   For every pair (T, VQ), where T is a cv-qualified or
7461   //   cv-unqualified object type, and VQ is either volatile or
7462   //   empty, there exist candidate operator functions of the form
7463   //
7464   //       T*VQ&      operator++(T*VQ&);
7465   //       T*VQ&      operator--(T*VQ&);
7466   //       T*         operator++(T*VQ&, int);
7467   //       T*         operator--(T*VQ&, int);
7468   void addPlusPlusMinusMinusPointerOverloads() {
7469     for (BuiltinCandidateTypeSet::iterator
7470               Ptr = CandidateTypes[0].pointer_begin(),
7471            PtrEnd = CandidateTypes[0].pointer_end();
7472          Ptr != PtrEnd; ++Ptr) {
7473       // Skip pointer types that aren't pointers to object types.
7474       if (!(*Ptr)->getPointeeType()->isObjectType())
7475         continue;
7476 
7477       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7478         (!(*Ptr).isVolatileQualified() &&
7479          VisibleTypeConversionsQuals.hasVolatile()),
7480         (!(*Ptr).isRestrictQualified() &&
7481          VisibleTypeConversionsQuals.hasRestrict()));
7482     }
7483   }
7484 
7485   // C++ [over.built]p6:
7486   //   For every cv-qualified or cv-unqualified object type T, there
7487   //   exist candidate operator functions of the form
7488   //
7489   //       T&         operator*(T*);
7490   //
7491   // C++ [over.built]p7:
7492   //   For every function type T that does not have cv-qualifiers or a
7493   //   ref-qualifier, there exist candidate operator functions of the form
7494   //       T&         operator*(T*);
7495   void addUnaryStarPointerOverloads() {
7496     for (BuiltinCandidateTypeSet::iterator
7497               Ptr = CandidateTypes[0].pointer_begin(),
7498            PtrEnd = CandidateTypes[0].pointer_end();
7499          Ptr != PtrEnd; ++Ptr) {
7500       QualType ParamTy = *Ptr;
7501       QualType PointeeTy = ParamTy->getPointeeType();
7502       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7503         continue;
7504 
7505       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7506         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7507           continue;
7508 
7509       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7510                             &ParamTy, Args, CandidateSet);
7511     }
7512   }
7513 
7514   // C++ [over.built]p9:
7515   //  For every promoted arithmetic type T, there exist candidate
7516   //  operator functions of the form
7517   //
7518   //       T         operator+(T);
7519   //       T         operator-(T);
7520   void addUnaryPlusOrMinusArithmeticOverloads() {
7521     if (!HasArithmeticOrEnumeralCandidateType)
7522       return;
7523 
7524     for (unsigned Arith = FirstPromotedArithmeticType;
7525          Arith < LastPromotedArithmeticType; ++Arith) {
7526       QualType ArithTy = getArithmeticType(Arith);
7527       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7528     }
7529 
7530     // Extension: We also add these operators for vector types.
7531     for (BuiltinCandidateTypeSet::iterator
7532               Vec = CandidateTypes[0].vector_begin(),
7533            VecEnd = CandidateTypes[0].vector_end();
7534          Vec != VecEnd; ++Vec) {
7535       QualType VecTy = *Vec;
7536       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7537     }
7538   }
7539 
7540   // C++ [over.built]p8:
7541   //   For every type T, there exist candidate operator functions of
7542   //   the form
7543   //
7544   //       T*         operator+(T*);
7545   void addUnaryPlusPointerOverloads() {
7546     for (BuiltinCandidateTypeSet::iterator
7547               Ptr = CandidateTypes[0].pointer_begin(),
7548            PtrEnd = CandidateTypes[0].pointer_end();
7549          Ptr != PtrEnd; ++Ptr) {
7550       QualType ParamTy = *Ptr;
7551       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7552     }
7553   }
7554 
7555   // C++ [over.built]p10:
7556   //   For every promoted integral type T, there exist candidate
7557   //   operator functions of the form
7558   //
7559   //        T         operator~(T);
7560   void addUnaryTildePromotedIntegralOverloads() {
7561     if (!HasArithmeticOrEnumeralCandidateType)
7562       return;
7563 
7564     for (unsigned Int = FirstPromotedIntegralType;
7565          Int < LastPromotedIntegralType; ++Int) {
7566       QualType IntTy = getArithmeticType(Int);
7567       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7568     }
7569 
7570     // Extension: We also add this operator for vector types.
7571     for (BuiltinCandidateTypeSet::iterator
7572               Vec = CandidateTypes[0].vector_begin(),
7573            VecEnd = CandidateTypes[0].vector_end();
7574          Vec != VecEnd; ++Vec) {
7575       QualType VecTy = *Vec;
7576       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7577     }
7578   }
7579 
7580   // C++ [over.match.oper]p16:
7581   //   For every pointer to member type T, there exist candidate operator
7582   //   functions of the form
7583   //
7584   //        bool operator==(T,T);
7585   //        bool operator!=(T,T);
7586   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7587     /// Set of (canonical) types that we've already handled.
7588     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7589 
7590     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7591       for (BuiltinCandidateTypeSet::iterator
7592                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7593              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7594            MemPtr != MemPtrEnd;
7595            ++MemPtr) {
7596         // Don't add the same builtin candidate twice.
7597         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7598           continue;
7599 
7600         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7601         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7602       }
7603     }
7604   }
7605 
7606   // C++ [over.built]p15:
7607   //
7608   //   For every T, where T is an enumeration type, a pointer type, or
7609   //   std::nullptr_t, there exist candidate operator functions of the form
7610   //
7611   //        bool       operator<(T, T);
7612   //        bool       operator>(T, T);
7613   //        bool       operator<=(T, T);
7614   //        bool       operator>=(T, T);
7615   //        bool       operator==(T, T);
7616   //        bool       operator!=(T, T);
7617   void addRelationalPointerOrEnumeralOverloads() {
7618     // C++ [over.match.oper]p3:
7619     //   [...]the built-in candidates include all of the candidate operator
7620     //   functions defined in 13.6 that, compared to the given operator, [...]
7621     //   do not have the same parameter-type-list as any non-template non-member
7622     //   candidate.
7623     //
7624     // Note that in practice, this only affects enumeration types because there
7625     // aren't any built-in candidates of record type, and a user-defined operator
7626     // must have an operand of record or enumeration type. Also, the only other
7627     // overloaded operator with enumeration arguments, operator=,
7628     // cannot be overloaded for enumeration types, so this is the only place
7629     // where we must suppress candidates like this.
7630     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7631       UserDefinedBinaryOperators;
7632 
7633     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7634       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7635           CandidateTypes[ArgIdx].enumeration_end()) {
7636         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7637                                          CEnd = CandidateSet.end();
7638              C != CEnd; ++C) {
7639           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7640             continue;
7641 
7642           if (C->Function->isFunctionTemplateSpecialization())
7643             continue;
7644 
7645           QualType FirstParamType =
7646             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7647           QualType SecondParamType =
7648             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7649 
7650           // Skip if either parameter isn't of enumeral type.
7651           if (!FirstParamType->isEnumeralType() ||
7652               !SecondParamType->isEnumeralType())
7653             continue;
7654 
7655           // Add this operator to the set of known user-defined operators.
7656           UserDefinedBinaryOperators.insert(
7657             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7658                            S.Context.getCanonicalType(SecondParamType)));
7659         }
7660       }
7661     }
7662 
7663     /// Set of (canonical) types that we've already handled.
7664     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7665 
7666     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7667       for (BuiltinCandidateTypeSet::iterator
7668                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7669              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7670            Ptr != PtrEnd; ++Ptr) {
7671         // Don't add the same builtin candidate twice.
7672         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7673           continue;
7674 
7675         QualType ParamTypes[2] = { *Ptr, *Ptr };
7676         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7677       }
7678       for (BuiltinCandidateTypeSet::iterator
7679                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7680              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7681            Enum != EnumEnd; ++Enum) {
7682         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7683 
7684         // Don't add the same builtin candidate twice, or if a user defined
7685         // candidate exists.
7686         if (!AddedTypes.insert(CanonType).second ||
7687             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7688                                                             CanonType)))
7689           continue;
7690 
7691         QualType ParamTypes[2] = { *Enum, *Enum };
7692         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7693       }
7694 
7695       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7696         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7697         if (AddedTypes.insert(NullPtrTy).second &&
7698             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7699                                                              NullPtrTy))) {
7700           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7701           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7702                                 CandidateSet);
7703         }
7704       }
7705     }
7706   }
7707 
7708   // C++ [over.built]p13:
7709   //
7710   //   For every cv-qualified or cv-unqualified object type T
7711   //   there exist candidate operator functions of the form
7712   //
7713   //      T*         operator+(T*, ptrdiff_t);
7714   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7715   //      T*         operator-(T*, ptrdiff_t);
7716   //      T*         operator+(ptrdiff_t, T*);
7717   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7718   //
7719   // C++ [over.built]p14:
7720   //
7721   //   For every T, where T is a pointer to object type, there
7722   //   exist candidate operator functions of the form
7723   //
7724   //      ptrdiff_t  operator-(T, T);
7725   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7726     /// Set of (canonical) types that we've already handled.
7727     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7728 
7729     for (int Arg = 0; Arg < 2; ++Arg) {
7730       QualType AsymmetricParamTypes[2] = {
7731         S.Context.getPointerDiffType(),
7732         S.Context.getPointerDiffType(),
7733       };
7734       for (BuiltinCandidateTypeSet::iterator
7735                 Ptr = CandidateTypes[Arg].pointer_begin(),
7736              PtrEnd = CandidateTypes[Arg].pointer_end();
7737            Ptr != PtrEnd; ++Ptr) {
7738         QualType PointeeTy = (*Ptr)->getPointeeType();
7739         if (!PointeeTy->isObjectType())
7740           continue;
7741 
7742         AsymmetricParamTypes[Arg] = *Ptr;
7743         if (Arg == 0 || Op == OO_Plus) {
7744           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7745           // T* operator+(ptrdiff_t, T*);
7746           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7747         }
7748         if (Op == OO_Minus) {
7749           // ptrdiff_t operator-(T, T);
7750           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7751             continue;
7752 
7753           QualType ParamTypes[2] = { *Ptr, *Ptr };
7754           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7755                                 Args, CandidateSet);
7756         }
7757       }
7758     }
7759   }
7760 
7761   // C++ [over.built]p12:
7762   //
7763   //   For every pair of promoted arithmetic types L and R, there
7764   //   exist candidate operator functions of the form
7765   //
7766   //        LR         operator*(L, R);
7767   //        LR         operator/(L, R);
7768   //        LR         operator+(L, R);
7769   //        LR         operator-(L, R);
7770   //        bool       operator<(L, R);
7771   //        bool       operator>(L, R);
7772   //        bool       operator<=(L, R);
7773   //        bool       operator>=(L, R);
7774   //        bool       operator==(L, R);
7775   //        bool       operator!=(L, R);
7776   //
7777   //   where LR is the result of the usual arithmetic conversions
7778   //   between types L and R.
7779   //
7780   // C++ [over.built]p24:
7781   //
7782   //   For every pair of promoted arithmetic types L and R, there exist
7783   //   candidate operator functions of the form
7784   //
7785   //        LR       operator?(bool, L, R);
7786   //
7787   //   where LR is the result of the usual arithmetic conversions
7788   //   between types L and R.
7789   // Our candidates ignore the first parameter.
7790   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7791     if (!HasArithmeticOrEnumeralCandidateType)
7792       return;
7793 
7794     for (unsigned Left = FirstPromotedArithmeticType;
7795          Left < LastPromotedArithmeticType; ++Left) {
7796       for (unsigned Right = FirstPromotedArithmeticType;
7797            Right < LastPromotedArithmeticType; ++Right) {
7798         QualType LandR[2] = { getArithmeticType(Left),
7799                               getArithmeticType(Right) };
7800         QualType Result =
7801           isComparison ? S.Context.BoolTy
7802                        : getUsualArithmeticConversions(Left, Right);
7803         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7804       }
7805     }
7806 
7807     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7808     // conditional operator for vector types.
7809     for (BuiltinCandidateTypeSet::iterator
7810               Vec1 = CandidateTypes[0].vector_begin(),
7811            Vec1End = CandidateTypes[0].vector_end();
7812          Vec1 != Vec1End; ++Vec1) {
7813       for (BuiltinCandidateTypeSet::iterator
7814                 Vec2 = CandidateTypes[1].vector_begin(),
7815              Vec2End = CandidateTypes[1].vector_end();
7816            Vec2 != Vec2End; ++Vec2) {
7817         QualType LandR[2] = { *Vec1, *Vec2 };
7818         QualType Result = S.Context.BoolTy;
7819         if (!isComparison) {
7820           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7821             Result = *Vec1;
7822           else
7823             Result = *Vec2;
7824         }
7825 
7826         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7827       }
7828     }
7829   }
7830 
7831   // C++ [over.built]p17:
7832   //
7833   //   For every pair of promoted integral types L and R, there
7834   //   exist candidate operator functions of the form
7835   //
7836   //      LR         operator%(L, R);
7837   //      LR         operator&(L, R);
7838   //      LR         operator^(L, R);
7839   //      LR         operator|(L, R);
7840   //      L          operator<<(L, R);
7841   //      L          operator>>(L, R);
7842   //
7843   //   where LR is the result of the usual arithmetic conversions
7844   //   between types L and R.
7845   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7846     if (!HasArithmeticOrEnumeralCandidateType)
7847       return;
7848 
7849     for (unsigned Left = FirstPromotedIntegralType;
7850          Left < LastPromotedIntegralType; ++Left) {
7851       for (unsigned Right = FirstPromotedIntegralType;
7852            Right < LastPromotedIntegralType; ++Right) {
7853         QualType LandR[2] = { getArithmeticType(Left),
7854                               getArithmeticType(Right) };
7855         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7856             ? LandR[0]
7857             : getUsualArithmeticConversions(Left, Right);
7858         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7859       }
7860     }
7861   }
7862 
7863   // C++ [over.built]p20:
7864   //
7865   //   For every pair (T, VQ), where T is an enumeration or
7866   //   pointer to member type and VQ is either volatile or
7867   //   empty, there exist candidate operator functions of the form
7868   //
7869   //        VQ T&      operator=(VQ T&, T);
7870   void addAssignmentMemberPointerOrEnumeralOverloads() {
7871     /// Set of (canonical) types that we've already handled.
7872     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7873 
7874     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7875       for (BuiltinCandidateTypeSet::iterator
7876                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7877              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7878            Enum != EnumEnd; ++Enum) {
7879         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7880           continue;
7881 
7882         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7883       }
7884 
7885       for (BuiltinCandidateTypeSet::iterator
7886                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7887              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7888            MemPtr != MemPtrEnd; ++MemPtr) {
7889         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7890           continue;
7891 
7892         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7893       }
7894     }
7895   }
7896 
7897   // C++ [over.built]p19:
7898   //
7899   //   For every pair (T, VQ), where T is any type and VQ is either
7900   //   volatile or empty, there exist candidate operator functions
7901   //   of the form
7902   //
7903   //        T*VQ&      operator=(T*VQ&, T*);
7904   //
7905   // C++ [over.built]p21:
7906   //
7907   //   For every pair (T, VQ), where T is a cv-qualified or
7908   //   cv-unqualified object type and VQ is either volatile or
7909   //   empty, there exist candidate operator functions of the form
7910   //
7911   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7912   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7913   void addAssignmentPointerOverloads(bool isEqualOp) {
7914     /// Set of (canonical) types that we've already handled.
7915     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7916 
7917     for (BuiltinCandidateTypeSet::iterator
7918               Ptr = CandidateTypes[0].pointer_begin(),
7919            PtrEnd = CandidateTypes[0].pointer_end();
7920          Ptr != PtrEnd; ++Ptr) {
7921       // If this is operator=, keep track of the builtin candidates we added.
7922       if (isEqualOp)
7923         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7924       else if (!(*Ptr)->getPointeeType()->isObjectType())
7925         continue;
7926 
7927       // non-volatile version
7928       QualType ParamTypes[2] = {
7929         S.Context.getLValueReferenceType(*Ptr),
7930         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7931       };
7932       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7933                             /*IsAssigmentOperator=*/ isEqualOp);
7934 
7935       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7936                           VisibleTypeConversionsQuals.hasVolatile();
7937       if (NeedVolatile) {
7938         // volatile version
7939         ParamTypes[0] =
7940           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7941         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7942                               /*IsAssigmentOperator=*/isEqualOp);
7943       }
7944 
7945       if (!(*Ptr).isRestrictQualified() &&
7946           VisibleTypeConversionsQuals.hasRestrict()) {
7947         // restrict version
7948         ParamTypes[0]
7949           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7950         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7951                               /*IsAssigmentOperator=*/isEqualOp);
7952 
7953         if (NeedVolatile) {
7954           // volatile restrict version
7955           ParamTypes[0]
7956             = S.Context.getLValueReferenceType(
7957                 S.Context.getCVRQualifiedType(*Ptr,
7958                                               (Qualifiers::Volatile |
7959                                                Qualifiers::Restrict)));
7960           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7961                                 /*IsAssigmentOperator=*/isEqualOp);
7962         }
7963       }
7964     }
7965 
7966     if (isEqualOp) {
7967       for (BuiltinCandidateTypeSet::iterator
7968                 Ptr = CandidateTypes[1].pointer_begin(),
7969              PtrEnd = CandidateTypes[1].pointer_end();
7970            Ptr != PtrEnd; ++Ptr) {
7971         // Make sure we don't add the same candidate twice.
7972         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7973           continue;
7974 
7975         QualType ParamTypes[2] = {
7976           S.Context.getLValueReferenceType(*Ptr),
7977           *Ptr,
7978         };
7979 
7980         // non-volatile version
7981         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7982                               /*IsAssigmentOperator=*/true);
7983 
7984         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7985                            VisibleTypeConversionsQuals.hasVolatile();
7986         if (NeedVolatile) {
7987           // volatile version
7988           ParamTypes[0] =
7989             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7990           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7991                                 /*IsAssigmentOperator=*/true);
7992         }
7993 
7994         if (!(*Ptr).isRestrictQualified() &&
7995             VisibleTypeConversionsQuals.hasRestrict()) {
7996           // restrict version
7997           ParamTypes[0]
7998             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7999           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8000                                 /*IsAssigmentOperator=*/true);
8001 
8002           if (NeedVolatile) {
8003             // volatile restrict version
8004             ParamTypes[0]
8005               = S.Context.getLValueReferenceType(
8006                   S.Context.getCVRQualifiedType(*Ptr,
8007                                                 (Qualifiers::Volatile |
8008                                                  Qualifiers::Restrict)));
8009             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8010                                   /*IsAssigmentOperator=*/true);
8011           }
8012         }
8013       }
8014     }
8015   }
8016 
8017   // C++ [over.built]p18:
8018   //
8019   //   For every triple (L, VQ, R), where L is an arithmetic type,
8020   //   VQ is either volatile or empty, and R is a promoted
8021   //   arithmetic type, there exist candidate operator functions of
8022   //   the form
8023   //
8024   //        VQ L&      operator=(VQ L&, R);
8025   //        VQ L&      operator*=(VQ L&, R);
8026   //        VQ L&      operator/=(VQ L&, R);
8027   //        VQ L&      operator+=(VQ L&, R);
8028   //        VQ L&      operator-=(VQ L&, R);
8029   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8030     if (!HasArithmeticOrEnumeralCandidateType)
8031       return;
8032 
8033     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8034       for (unsigned Right = FirstPromotedArithmeticType;
8035            Right < LastPromotedArithmeticType; ++Right) {
8036         QualType ParamTypes[2];
8037         ParamTypes[1] = getArithmeticType(Right);
8038 
8039         // Add this built-in operator as a candidate (VQ is empty).
8040         ParamTypes[0] =
8041           S.Context.getLValueReferenceType(getArithmeticType(Left));
8042         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8043                               /*IsAssigmentOperator=*/isEqualOp);
8044 
8045         // Add this built-in operator as a candidate (VQ is 'volatile').
8046         if (VisibleTypeConversionsQuals.hasVolatile()) {
8047           ParamTypes[0] =
8048             S.Context.getVolatileType(getArithmeticType(Left));
8049           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8050           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8051                                 /*IsAssigmentOperator=*/isEqualOp);
8052         }
8053       }
8054     }
8055 
8056     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8057     for (BuiltinCandidateTypeSet::iterator
8058               Vec1 = CandidateTypes[0].vector_begin(),
8059            Vec1End = CandidateTypes[0].vector_end();
8060          Vec1 != Vec1End; ++Vec1) {
8061       for (BuiltinCandidateTypeSet::iterator
8062                 Vec2 = CandidateTypes[1].vector_begin(),
8063              Vec2End = CandidateTypes[1].vector_end();
8064            Vec2 != Vec2End; ++Vec2) {
8065         QualType ParamTypes[2];
8066         ParamTypes[1] = *Vec2;
8067         // Add this built-in operator as a candidate (VQ is empty).
8068         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8069         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8070                               /*IsAssigmentOperator=*/isEqualOp);
8071 
8072         // Add this built-in operator as a candidate (VQ is 'volatile').
8073         if (VisibleTypeConversionsQuals.hasVolatile()) {
8074           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8075           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8076           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8077                                 /*IsAssigmentOperator=*/isEqualOp);
8078         }
8079       }
8080     }
8081   }
8082 
8083   // C++ [over.built]p22:
8084   //
8085   //   For every triple (L, VQ, R), where L is an integral type, VQ
8086   //   is either volatile or empty, and R is a promoted integral
8087   //   type, there exist candidate operator functions of the form
8088   //
8089   //        VQ L&       operator%=(VQ L&, R);
8090   //        VQ L&       operator<<=(VQ L&, R);
8091   //        VQ L&       operator>>=(VQ L&, R);
8092   //        VQ L&       operator&=(VQ L&, R);
8093   //        VQ L&       operator^=(VQ L&, R);
8094   //        VQ L&       operator|=(VQ L&, R);
8095   void addAssignmentIntegralOverloads() {
8096     if (!HasArithmeticOrEnumeralCandidateType)
8097       return;
8098 
8099     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8100       for (unsigned Right = FirstPromotedIntegralType;
8101            Right < LastPromotedIntegralType; ++Right) {
8102         QualType ParamTypes[2];
8103         ParamTypes[1] = getArithmeticType(Right);
8104 
8105         // Add this built-in operator as a candidate (VQ is empty).
8106         ParamTypes[0] =
8107           S.Context.getLValueReferenceType(getArithmeticType(Left));
8108         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8109         if (VisibleTypeConversionsQuals.hasVolatile()) {
8110           // Add this built-in operator as a candidate (VQ is 'volatile').
8111           ParamTypes[0] = getArithmeticType(Left);
8112           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8113           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8114           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8115         }
8116       }
8117     }
8118   }
8119 
8120   // C++ [over.operator]p23:
8121   //
8122   //   There also exist candidate operator functions of the form
8123   //
8124   //        bool        operator!(bool);
8125   //        bool        operator&&(bool, bool);
8126   //        bool        operator||(bool, bool);
8127   void addExclaimOverload() {
8128     QualType ParamTy = S.Context.BoolTy;
8129     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8130                           /*IsAssignmentOperator=*/false,
8131                           /*NumContextualBoolArguments=*/1);
8132   }
8133   void addAmpAmpOrPipePipeOverload() {
8134     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8135     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8136                           /*IsAssignmentOperator=*/false,
8137                           /*NumContextualBoolArguments=*/2);
8138   }
8139 
8140   // C++ [over.built]p13:
8141   //
8142   //   For every cv-qualified or cv-unqualified object type T there
8143   //   exist candidate operator functions of the form
8144   //
8145   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8146   //        T&         operator[](T*, ptrdiff_t);
8147   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8148   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8149   //        T&         operator[](ptrdiff_t, T*);
8150   void addSubscriptOverloads() {
8151     for (BuiltinCandidateTypeSet::iterator
8152               Ptr = CandidateTypes[0].pointer_begin(),
8153            PtrEnd = CandidateTypes[0].pointer_end();
8154          Ptr != PtrEnd; ++Ptr) {
8155       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8156       QualType PointeeType = (*Ptr)->getPointeeType();
8157       if (!PointeeType->isObjectType())
8158         continue;
8159 
8160       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8161 
8162       // T& operator[](T*, ptrdiff_t)
8163       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8164     }
8165 
8166     for (BuiltinCandidateTypeSet::iterator
8167               Ptr = CandidateTypes[1].pointer_begin(),
8168            PtrEnd = CandidateTypes[1].pointer_end();
8169          Ptr != PtrEnd; ++Ptr) {
8170       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8171       QualType PointeeType = (*Ptr)->getPointeeType();
8172       if (!PointeeType->isObjectType())
8173         continue;
8174 
8175       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8176 
8177       // T& operator[](ptrdiff_t, T*)
8178       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8179     }
8180   }
8181 
8182   // C++ [over.built]p11:
8183   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8184   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8185   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8186   //    there exist candidate operator functions of the form
8187   //
8188   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8189   //
8190   //    where CV12 is the union of CV1 and CV2.
8191   void addArrowStarOverloads() {
8192     for (BuiltinCandidateTypeSet::iterator
8193              Ptr = CandidateTypes[0].pointer_begin(),
8194            PtrEnd = CandidateTypes[0].pointer_end();
8195          Ptr != PtrEnd; ++Ptr) {
8196       QualType C1Ty = (*Ptr);
8197       QualType C1;
8198       QualifierCollector Q1;
8199       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8200       if (!isa<RecordType>(C1))
8201         continue;
8202       // heuristic to reduce number of builtin candidates in the set.
8203       // Add volatile/restrict version only if there are conversions to a
8204       // volatile/restrict type.
8205       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8206         continue;
8207       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8208         continue;
8209       for (BuiltinCandidateTypeSet::iterator
8210                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8211              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8212            MemPtr != MemPtrEnd; ++MemPtr) {
8213         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8214         QualType C2 = QualType(mptr->getClass(), 0);
8215         C2 = C2.getUnqualifiedType();
8216         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8217           break;
8218         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8219         // build CV12 T&
8220         QualType T = mptr->getPointeeType();
8221         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8222             T.isVolatileQualified())
8223           continue;
8224         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8225             T.isRestrictQualified())
8226           continue;
8227         T = Q1.apply(S.Context, T);
8228         QualType ResultTy = S.Context.getLValueReferenceType(T);
8229         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8230       }
8231     }
8232   }
8233 
8234   // Note that we don't consider the first argument, since it has been
8235   // contextually converted to bool long ago. The candidates below are
8236   // therefore added as binary.
8237   //
8238   // C++ [over.built]p25:
8239   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8240   //   enumeration type, there exist candidate operator functions of the form
8241   //
8242   //        T        operator?(bool, T, T);
8243   //
8244   void addConditionalOperatorOverloads() {
8245     /// Set of (canonical) types that we've already handled.
8246     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8247 
8248     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8249       for (BuiltinCandidateTypeSet::iterator
8250                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8251              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8252            Ptr != PtrEnd; ++Ptr) {
8253         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8254           continue;
8255 
8256         QualType ParamTypes[2] = { *Ptr, *Ptr };
8257         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8258       }
8259 
8260       for (BuiltinCandidateTypeSet::iterator
8261                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8262              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8263            MemPtr != MemPtrEnd; ++MemPtr) {
8264         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8265           continue;
8266 
8267         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8268         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8269       }
8270 
8271       if (S.getLangOpts().CPlusPlus11) {
8272         for (BuiltinCandidateTypeSet::iterator
8273                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8274                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8275              Enum != EnumEnd; ++Enum) {
8276           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8277             continue;
8278 
8279           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8280             continue;
8281 
8282           QualType ParamTypes[2] = { *Enum, *Enum };
8283           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8284         }
8285       }
8286     }
8287   }
8288 };
8289 
8290 } // end anonymous namespace
8291 
8292 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8293 /// operator overloads to the candidate set (C++ [over.built]), based
8294 /// on the operator @p Op and the arguments given. For example, if the
8295 /// operator is a binary '+', this routine might add "int
8296 /// operator+(int, int)" to cover integer addition.
8297 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8298                                         SourceLocation OpLoc,
8299                                         ArrayRef<Expr *> Args,
8300                                         OverloadCandidateSet &CandidateSet) {
8301   // Find all of the types that the arguments can convert to, but only
8302   // if the operator we're looking at has built-in operator candidates
8303   // that make use of these types. Also record whether we encounter non-record
8304   // candidate types or either arithmetic or enumeral candidate types.
8305   Qualifiers VisibleTypeConversionsQuals;
8306   VisibleTypeConversionsQuals.addConst();
8307   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8308     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8309 
8310   bool HasNonRecordCandidateType = false;
8311   bool HasArithmeticOrEnumeralCandidateType = false;
8312   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8313   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8314     CandidateTypes.emplace_back(*this);
8315     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8316                                                  OpLoc,
8317                                                  true,
8318                                                  (Op == OO_Exclaim ||
8319                                                   Op == OO_AmpAmp ||
8320                                                   Op == OO_PipePipe),
8321                                                  VisibleTypeConversionsQuals);
8322     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8323         CandidateTypes[ArgIdx].hasNonRecordTypes();
8324     HasArithmeticOrEnumeralCandidateType =
8325         HasArithmeticOrEnumeralCandidateType ||
8326         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8327   }
8328 
8329   // Exit early when no non-record types have been added to the candidate set
8330   // for any of the arguments to the operator.
8331   //
8332   // We can't exit early for !, ||, or &&, since there we have always have
8333   // 'bool' overloads.
8334   if (!HasNonRecordCandidateType &&
8335       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8336     return;
8337 
8338   // Setup an object to manage the common state for building overloads.
8339   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8340                                            VisibleTypeConversionsQuals,
8341                                            HasArithmeticOrEnumeralCandidateType,
8342                                            CandidateTypes, CandidateSet);
8343 
8344   // Dispatch over the operation to add in only those overloads which apply.
8345   switch (Op) {
8346   case OO_None:
8347   case NUM_OVERLOADED_OPERATORS:
8348     llvm_unreachable("Expected an overloaded operator");
8349 
8350   case OO_New:
8351   case OO_Delete:
8352   case OO_Array_New:
8353   case OO_Array_Delete:
8354   case OO_Call:
8355     llvm_unreachable(
8356                     "Special operators don't use AddBuiltinOperatorCandidates");
8357 
8358   case OO_Comma:
8359   case OO_Arrow:
8360   case OO_Coawait:
8361     // C++ [over.match.oper]p3:
8362     //   -- For the operator ',', the unary operator '&', the
8363     //      operator '->', or the operator 'co_await', the
8364     //      built-in candidates set is empty.
8365     break;
8366 
8367   case OO_Plus: // '+' is either unary or binary
8368     if (Args.size() == 1)
8369       OpBuilder.addUnaryPlusPointerOverloads();
8370     // Fall through.
8371 
8372   case OO_Minus: // '-' is either unary or binary
8373     if (Args.size() == 1) {
8374       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8375     } else {
8376       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8377       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8378     }
8379     break;
8380 
8381   case OO_Star: // '*' is either unary or binary
8382     if (Args.size() == 1)
8383       OpBuilder.addUnaryStarPointerOverloads();
8384     else
8385       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8386     break;
8387 
8388   case OO_Slash:
8389     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8390     break;
8391 
8392   case OO_PlusPlus:
8393   case OO_MinusMinus:
8394     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8395     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8396     break;
8397 
8398   case OO_EqualEqual:
8399   case OO_ExclaimEqual:
8400     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8401     // Fall through.
8402 
8403   case OO_Less:
8404   case OO_Greater:
8405   case OO_LessEqual:
8406   case OO_GreaterEqual:
8407     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8408     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8409     break;
8410 
8411   case OO_Percent:
8412   case OO_Caret:
8413   case OO_Pipe:
8414   case OO_LessLess:
8415   case OO_GreaterGreater:
8416     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8417     break;
8418 
8419   case OO_Amp: // '&' is either unary or binary
8420     if (Args.size() == 1)
8421       // C++ [over.match.oper]p3:
8422       //   -- For the operator ',', the unary operator '&', or the
8423       //      operator '->', the built-in candidates set is empty.
8424       break;
8425 
8426     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8427     break;
8428 
8429   case OO_Tilde:
8430     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8431     break;
8432 
8433   case OO_Equal:
8434     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8435     // Fall through.
8436 
8437   case OO_PlusEqual:
8438   case OO_MinusEqual:
8439     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8440     // Fall through.
8441 
8442   case OO_StarEqual:
8443   case OO_SlashEqual:
8444     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8445     break;
8446 
8447   case OO_PercentEqual:
8448   case OO_LessLessEqual:
8449   case OO_GreaterGreaterEqual:
8450   case OO_AmpEqual:
8451   case OO_CaretEqual:
8452   case OO_PipeEqual:
8453     OpBuilder.addAssignmentIntegralOverloads();
8454     break;
8455 
8456   case OO_Exclaim:
8457     OpBuilder.addExclaimOverload();
8458     break;
8459 
8460   case OO_AmpAmp:
8461   case OO_PipePipe:
8462     OpBuilder.addAmpAmpOrPipePipeOverload();
8463     break;
8464 
8465   case OO_Subscript:
8466     OpBuilder.addSubscriptOverloads();
8467     break;
8468 
8469   case OO_ArrowStar:
8470     OpBuilder.addArrowStarOverloads();
8471     break;
8472 
8473   case OO_Conditional:
8474     OpBuilder.addConditionalOperatorOverloads();
8475     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8476     break;
8477   }
8478 }
8479 
8480 /// \brief Add function candidates found via argument-dependent lookup
8481 /// to the set of overloading candidates.
8482 ///
8483 /// This routine performs argument-dependent name lookup based on the
8484 /// given function name (which may also be an operator name) and adds
8485 /// all of the overload candidates found by ADL to the overload
8486 /// candidate set (C++ [basic.lookup.argdep]).
8487 void
8488 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8489                                            SourceLocation Loc,
8490                                            ArrayRef<Expr *> Args,
8491                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8492                                            OverloadCandidateSet& CandidateSet,
8493                                            bool PartialOverloading) {
8494   ADLResult Fns;
8495 
8496   // FIXME: This approach for uniquing ADL results (and removing
8497   // redundant candidates from the set) relies on pointer-equality,
8498   // which means we need to key off the canonical decl.  However,
8499   // always going back to the canonical decl might not get us the
8500   // right set of default arguments.  What default arguments are
8501   // we supposed to consider on ADL candidates, anyway?
8502 
8503   // FIXME: Pass in the explicit template arguments?
8504   ArgumentDependentLookup(Name, Loc, Args, Fns);
8505 
8506   // Erase all of the candidates we already knew about.
8507   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8508                                    CandEnd = CandidateSet.end();
8509        Cand != CandEnd; ++Cand)
8510     if (Cand->Function) {
8511       Fns.erase(Cand->Function);
8512       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8513         Fns.erase(FunTmpl);
8514     }
8515 
8516   // For each of the ADL candidates we found, add it to the overload
8517   // set.
8518   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8519     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8520     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8521       if (ExplicitTemplateArgs)
8522         continue;
8523 
8524       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8525                            PartialOverloading);
8526     } else
8527       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8528                                    FoundDecl, ExplicitTemplateArgs,
8529                                    Args, CandidateSet, PartialOverloading);
8530   }
8531 }
8532 
8533 namespace {
8534 enum class Comparison { Equal, Better, Worse };
8535 }
8536 
8537 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8538 /// overload resolution.
8539 ///
8540 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8541 /// Cand1's first N enable_if attributes have precisely the same conditions as
8542 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8543 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8544 ///
8545 /// Note that you can have a pair of candidates such that Cand1's enable_if
8546 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8547 /// worse than Cand1's.
8548 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8549                                        const FunctionDecl *Cand2) {
8550   // Common case: One (or both) decls don't have enable_if attrs.
8551   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8552   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8553   if (!Cand1Attr || !Cand2Attr) {
8554     if (Cand1Attr == Cand2Attr)
8555       return Comparison::Equal;
8556     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8557   }
8558 
8559   // FIXME: The next several lines are just
8560   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8561   // instead of reverse order which is how they're stored in the AST.
8562   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8563   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8564 
8565   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8566   // has fewer enable_if attributes than Cand2.
8567   if (Cand1Attrs.size() < Cand2Attrs.size())
8568     return Comparison::Worse;
8569 
8570   auto Cand1I = Cand1Attrs.begin();
8571   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8572   for (auto &Cand2A : Cand2Attrs) {
8573     Cand1ID.clear();
8574     Cand2ID.clear();
8575 
8576     auto &Cand1A = *Cand1I++;
8577     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8578     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8579     if (Cand1ID != Cand2ID)
8580       return Comparison::Worse;
8581   }
8582 
8583   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8584 }
8585 
8586 /// isBetterOverloadCandidate - Determines whether the first overload
8587 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8588 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8589                                       const OverloadCandidate &Cand2,
8590                                       SourceLocation Loc,
8591                                       bool UserDefinedConversion) {
8592   // Define viable functions to be better candidates than non-viable
8593   // functions.
8594   if (!Cand2.Viable)
8595     return Cand1.Viable;
8596   else if (!Cand1.Viable)
8597     return false;
8598 
8599   // C++ [over.match.best]p1:
8600   //
8601   //   -- if F is a static member function, ICS1(F) is defined such
8602   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8603   //      any function G, and, symmetrically, ICS1(G) is neither
8604   //      better nor worse than ICS1(F).
8605   unsigned StartArg = 0;
8606   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8607     StartArg = 1;
8608 
8609   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8610     // We don't allow incompatible pointer conversions in C++.
8611     if (!S.getLangOpts().CPlusPlus)
8612       return ICS.isStandard() &&
8613              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8614 
8615     // The only ill-formed conversion we allow in C++ is the string literal to
8616     // char* conversion, which is only considered ill-formed after C++11.
8617     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8618            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8619   };
8620 
8621   // Define functions that don't require ill-formed conversions for a given
8622   // argument to be better candidates than functions that do.
8623   unsigned NumArgs = Cand1.NumConversions;
8624   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8625   bool HasBetterConversion = false;
8626   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8627     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8628     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8629     if (Cand1Bad != Cand2Bad) {
8630       if (Cand1Bad)
8631         return false;
8632       HasBetterConversion = true;
8633     }
8634   }
8635 
8636   if (HasBetterConversion)
8637     return true;
8638 
8639   // C++ [over.match.best]p1:
8640   //   A viable function F1 is defined to be a better function than another
8641   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8642   //   conversion sequence than ICSi(F2), and then...
8643   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8644     switch (CompareImplicitConversionSequences(S, Loc,
8645                                                Cand1.Conversions[ArgIdx],
8646                                                Cand2.Conversions[ArgIdx])) {
8647     case ImplicitConversionSequence::Better:
8648       // Cand1 has a better conversion sequence.
8649       HasBetterConversion = true;
8650       break;
8651 
8652     case ImplicitConversionSequence::Worse:
8653       // Cand1 can't be better than Cand2.
8654       return false;
8655 
8656     case ImplicitConversionSequence::Indistinguishable:
8657       // Do nothing.
8658       break;
8659     }
8660   }
8661 
8662   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8663   //       ICSj(F2), or, if not that,
8664   if (HasBetterConversion)
8665     return true;
8666 
8667   //   -- the context is an initialization by user-defined conversion
8668   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8669   //      from the return type of F1 to the destination type (i.e.,
8670   //      the type of the entity being initialized) is a better
8671   //      conversion sequence than the standard conversion sequence
8672   //      from the return type of F2 to the destination type.
8673   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8674       isa<CXXConversionDecl>(Cand1.Function) &&
8675       isa<CXXConversionDecl>(Cand2.Function)) {
8676     // First check whether we prefer one of the conversion functions over the
8677     // other. This only distinguishes the results in non-standard, extension
8678     // cases such as the conversion from a lambda closure type to a function
8679     // pointer or block.
8680     ImplicitConversionSequence::CompareKind Result =
8681         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8682     if (Result == ImplicitConversionSequence::Indistinguishable)
8683       Result = CompareStandardConversionSequences(S, Loc,
8684                                                   Cand1.FinalConversion,
8685                                                   Cand2.FinalConversion);
8686 
8687     if (Result != ImplicitConversionSequence::Indistinguishable)
8688       return Result == ImplicitConversionSequence::Better;
8689 
8690     // FIXME: Compare kind of reference binding if conversion functions
8691     // convert to a reference type used in direct reference binding, per
8692     // C++14 [over.match.best]p1 section 2 bullet 3.
8693   }
8694 
8695   //    -- F1 is a non-template function and F2 is a function template
8696   //       specialization, or, if not that,
8697   bool Cand1IsSpecialization = Cand1.Function &&
8698                                Cand1.Function->getPrimaryTemplate();
8699   bool Cand2IsSpecialization = Cand2.Function &&
8700                                Cand2.Function->getPrimaryTemplate();
8701   if (Cand1IsSpecialization != Cand2IsSpecialization)
8702     return Cand2IsSpecialization;
8703 
8704   //   -- F1 and F2 are function template specializations, and the function
8705   //      template for F1 is more specialized than the template for F2
8706   //      according to the partial ordering rules described in 14.5.5.2, or,
8707   //      if not that,
8708   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8709     if (FunctionTemplateDecl *BetterTemplate
8710           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8711                                          Cand2.Function->getPrimaryTemplate(),
8712                                          Loc,
8713                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8714                                                              : TPOC_Call,
8715                                          Cand1.ExplicitCallArguments,
8716                                          Cand2.ExplicitCallArguments))
8717       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8718   }
8719 
8720   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8721   // A derived-class constructor beats an (inherited) base class constructor.
8722   bool Cand1IsInherited =
8723       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8724   bool Cand2IsInherited =
8725       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8726   if (Cand1IsInherited != Cand2IsInherited)
8727     return Cand2IsInherited;
8728   else if (Cand1IsInherited) {
8729     assert(Cand2IsInherited);
8730     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8731     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8732     if (Cand1Class->isDerivedFrom(Cand2Class))
8733       return true;
8734     if (Cand2Class->isDerivedFrom(Cand1Class))
8735       return false;
8736     // Inherited from sibling base classes: still ambiguous.
8737   }
8738 
8739   // Check for enable_if value-based overload resolution.
8740   if (Cand1.Function && Cand2.Function) {
8741     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8742     if (Cmp != Comparison::Equal)
8743       return Cmp == Comparison::Better;
8744   }
8745 
8746   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8747     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8748     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8749            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8750   }
8751 
8752   bool HasPS1 = Cand1.Function != nullptr &&
8753                 functionHasPassObjectSizeParams(Cand1.Function);
8754   bool HasPS2 = Cand2.Function != nullptr &&
8755                 functionHasPassObjectSizeParams(Cand2.Function);
8756   return HasPS1 != HasPS2 && HasPS1;
8757 }
8758 
8759 /// Determine whether two declarations are "equivalent" for the purposes of
8760 /// name lookup and overload resolution. This applies when the same internal/no
8761 /// linkage entity is defined by two modules (probably by textually including
8762 /// the same header). In such a case, we don't consider the declarations to
8763 /// declare the same entity, but we also don't want lookups with both
8764 /// declarations visible to be ambiguous in some cases (this happens when using
8765 /// a modularized libstdc++).
8766 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8767                                                   const NamedDecl *B) {
8768   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8769   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8770   if (!VA || !VB)
8771     return false;
8772 
8773   // The declarations must be declaring the same name as an internal linkage
8774   // entity in different modules.
8775   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8776           VB->getDeclContext()->getRedeclContext()) ||
8777       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8778           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8779       VA->isExternallyVisible() || VB->isExternallyVisible())
8780     return false;
8781 
8782   // Check that the declarations appear to be equivalent.
8783   //
8784   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8785   // For constants and functions, we should check the initializer or body is
8786   // the same. For non-constant variables, we shouldn't allow it at all.
8787   if (Context.hasSameType(VA->getType(), VB->getType()))
8788     return true;
8789 
8790   // Enum constants within unnamed enumerations will have different types, but
8791   // may still be similar enough to be interchangeable for our purposes.
8792   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8793     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8794       // Only handle anonymous enums. If the enumerations were named and
8795       // equivalent, they would have been merged to the same type.
8796       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8797       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8798       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8799           !Context.hasSameType(EnumA->getIntegerType(),
8800                                EnumB->getIntegerType()))
8801         return false;
8802       // Allow this only if the value is the same for both enumerators.
8803       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8804     }
8805   }
8806 
8807   // Nothing else is sufficiently similar.
8808   return false;
8809 }
8810 
8811 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8812     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8813   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8814 
8815   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8816   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8817       << !M << (M ? M->getFullModuleName() : "");
8818 
8819   for (auto *E : Equiv) {
8820     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8821     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8822         << !M << (M ? M->getFullModuleName() : "");
8823   }
8824 }
8825 
8826 /// \brief Computes the best viable function (C++ 13.3.3)
8827 /// within an overload candidate set.
8828 ///
8829 /// \param Loc The location of the function name (or operator symbol) for
8830 /// which overload resolution occurs.
8831 ///
8832 /// \param Best If overload resolution was successful or found a deleted
8833 /// function, \p Best points to the candidate function found.
8834 ///
8835 /// \returns The result of overload resolution.
8836 OverloadingResult
8837 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8838                                          iterator &Best,
8839                                          bool UserDefinedConversion) {
8840   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8841   std::transform(begin(), end(), std::back_inserter(Candidates),
8842                  [](OverloadCandidate &Cand) { return &Cand; });
8843 
8844   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8845   // are accepted by both clang and NVCC. However, during a particular
8846   // compilation mode only one call variant is viable. We need to
8847   // exclude non-viable overload candidates from consideration based
8848   // only on their host/device attributes. Specifically, if one
8849   // candidate call is WrongSide and the other is SameSide, we ignore
8850   // the WrongSide candidate.
8851   if (S.getLangOpts().CUDA) {
8852     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8853     bool ContainsSameSideCandidate =
8854         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8855           return Cand->Function &&
8856                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8857                      Sema::CFP_SameSide;
8858         });
8859     if (ContainsSameSideCandidate) {
8860       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8861         return Cand->Function &&
8862                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8863                    Sema::CFP_WrongSide;
8864       };
8865       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8866                                       IsWrongSideCandidate),
8867                        Candidates.end());
8868     }
8869   }
8870 
8871   // Find the best viable function.
8872   Best = end();
8873   for (auto *Cand : Candidates)
8874     if (Cand->Viable)
8875       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8876                                                      UserDefinedConversion))
8877         Best = Cand;
8878 
8879   // If we didn't find any viable functions, abort.
8880   if (Best == end())
8881     return OR_No_Viable_Function;
8882 
8883   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8884 
8885   // Make sure that this function is better than every other viable
8886   // function. If not, we have an ambiguity.
8887   for (auto *Cand : Candidates) {
8888     if (Cand->Viable &&
8889         Cand != Best &&
8890         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8891                                    UserDefinedConversion)) {
8892       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8893                                                    Cand->Function)) {
8894         EquivalentCands.push_back(Cand->Function);
8895         continue;
8896       }
8897 
8898       Best = end();
8899       return OR_Ambiguous;
8900     }
8901   }
8902 
8903   // Best is the best viable function.
8904   if (Best->Function &&
8905       (Best->Function->isDeleted() ||
8906        S.isFunctionConsideredUnavailable(Best->Function)))
8907     return OR_Deleted;
8908 
8909   if (!EquivalentCands.empty())
8910     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8911                                                     EquivalentCands);
8912 
8913   return OR_Success;
8914 }
8915 
8916 namespace {
8917 
8918 enum OverloadCandidateKind {
8919   oc_function,
8920   oc_method,
8921   oc_constructor,
8922   oc_function_template,
8923   oc_method_template,
8924   oc_constructor_template,
8925   oc_implicit_default_constructor,
8926   oc_implicit_copy_constructor,
8927   oc_implicit_move_constructor,
8928   oc_implicit_copy_assignment,
8929   oc_implicit_move_assignment,
8930   oc_inherited_constructor,
8931   oc_inherited_constructor_template
8932 };
8933 
8934 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8935                                                 NamedDecl *Found,
8936                                                 FunctionDecl *Fn,
8937                                                 std::string &Description) {
8938   bool isTemplate = false;
8939 
8940   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8941     isTemplate = true;
8942     Description = S.getTemplateArgumentBindingsText(
8943       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8944   }
8945 
8946   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8947     if (!Ctor->isImplicit()) {
8948       if (isa<ConstructorUsingShadowDecl>(Found))
8949         return isTemplate ? oc_inherited_constructor_template
8950                           : oc_inherited_constructor;
8951       else
8952         return isTemplate ? oc_constructor_template : oc_constructor;
8953     }
8954 
8955     if (Ctor->isDefaultConstructor())
8956       return oc_implicit_default_constructor;
8957 
8958     if (Ctor->isMoveConstructor())
8959       return oc_implicit_move_constructor;
8960 
8961     assert(Ctor->isCopyConstructor() &&
8962            "unexpected sort of implicit constructor");
8963     return oc_implicit_copy_constructor;
8964   }
8965 
8966   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8967     // This actually gets spelled 'candidate function' for now, but
8968     // it doesn't hurt to split it out.
8969     if (!Meth->isImplicit())
8970       return isTemplate ? oc_method_template : oc_method;
8971 
8972     if (Meth->isMoveAssignmentOperator())
8973       return oc_implicit_move_assignment;
8974 
8975     if (Meth->isCopyAssignmentOperator())
8976       return oc_implicit_copy_assignment;
8977 
8978     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8979     return oc_method;
8980   }
8981 
8982   return isTemplate ? oc_function_template : oc_function;
8983 }
8984 
8985 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8986   // FIXME: It'd be nice to only emit a note once per using-decl per overload
8987   // set.
8988   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8989     S.Diag(FoundDecl->getLocation(),
8990            diag::note_ovl_candidate_inherited_constructor)
8991       << Shadow->getNominatedBaseClass();
8992 }
8993 
8994 } // end anonymous namespace
8995 
8996 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8997                                     const FunctionDecl *FD) {
8998   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8999     bool AlwaysTrue;
9000     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9001       return false;
9002     if (!AlwaysTrue)
9003       return false;
9004   }
9005   return true;
9006 }
9007 
9008 /// \brief Returns true if we can take the address of the function.
9009 ///
9010 /// \param Complain - If true, we'll emit a diagnostic
9011 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9012 ///   we in overload resolution?
9013 /// \param Loc - The location of the statement we're complaining about. Ignored
9014 ///   if we're not complaining, or if we're in overload resolution.
9015 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9016                                               bool Complain,
9017                                               bool InOverloadResolution,
9018                                               SourceLocation Loc) {
9019   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9020     if (Complain) {
9021       if (InOverloadResolution)
9022         S.Diag(FD->getLocStart(),
9023                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9024       else
9025         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9026     }
9027     return false;
9028   }
9029 
9030   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9031     return P->hasAttr<PassObjectSizeAttr>();
9032   });
9033   if (I == FD->param_end())
9034     return true;
9035 
9036   if (Complain) {
9037     // Add one to ParamNo because it's user-facing
9038     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9039     if (InOverloadResolution)
9040       S.Diag(FD->getLocation(),
9041              diag::note_ovl_candidate_has_pass_object_size_params)
9042           << ParamNo;
9043     else
9044       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9045           << FD << ParamNo;
9046   }
9047   return false;
9048 }
9049 
9050 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9051                                                const FunctionDecl *FD) {
9052   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9053                                            /*InOverloadResolution=*/true,
9054                                            /*Loc=*/SourceLocation());
9055 }
9056 
9057 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9058                                              bool Complain,
9059                                              SourceLocation Loc) {
9060   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9061                                              /*InOverloadResolution=*/false,
9062                                              Loc);
9063 }
9064 
9065 // Notes the location of an overload candidate.
9066 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9067                                  QualType DestType, bool TakingAddress) {
9068   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9069     return;
9070 
9071   std::string FnDesc;
9072   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9073   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9074                              << (unsigned) K << FnDesc;
9075 
9076   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9077   Diag(Fn->getLocation(), PD);
9078   MaybeEmitInheritedConstructorNote(*this, Found);
9079 }
9080 
9081 // Notes the location of all overload candidates designated through
9082 // OverloadedExpr
9083 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9084                                      bool TakingAddress) {
9085   assert(OverloadedExpr->getType() == Context.OverloadTy);
9086 
9087   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9088   OverloadExpr *OvlExpr = Ovl.Expression;
9089 
9090   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9091                             IEnd = OvlExpr->decls_end();
9092        I != IEnd; ++I) {
9093     if (FunctionTemplateDecl *FunTmpl =
9094                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9095       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9096                             TakingAddress);
9097     } else if (FunctionDecl *Fun
9098                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9099       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9100     }
9101   }
9102 }
9103 
9104 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9105 /// "lead" diagnostic; it will be given two arguments, the source and
9106 /// target types of the conversion.
9107 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9108                                  Sema &S,
9109                                  SourceLocation CaretLoc,
9110                                  const PartialDiagnostic &PDiag) const {
9111   S.Diag(CaretLoc, PDiag)
9112     << Ambiguous.getFromType() << Ambiguous.getToType();
9113   // FIXME: The note limiting machinery is borrowed from
9114   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9115   // refactoring here.
9116   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9117   unsigned CandsShown = 0;
9118   AmbiguousConversionSequence::const_iterator I, E;
9119   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9120     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9121       break;
9122     ++CandsShown;
9123     S.NoteOverloadCandidate(I->first, I->second);
9124   }
9125   if (I != E)
9126     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9127 }
9128 
9129 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9130                                   unsigned I, bool TakingCandidateAddress) {
9131   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9132   assert(Conv.isBad());
9133   assert(Cand->Function && "for now, candidate must be a function");
9134   FunctionDecl *Fn = Cand->Function;
9135 
9136   // There's a conversion slot for the object argument if this is a
9137   // non-constructor method.  Note that 'I' corresponds the
9138   // conversion-slot index.
9139   bool isObjectArgument = false;
9140   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9141     if (I == 0)
9142       isObjectArgument = true;
9143     else
9144       I--;
9145   }
9146 
9147   std::string FnDesc;
9148   OverloadCandidateKind FnKind =
9149       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9150 
9151   Expr *FromExpr = Conv.Bad.FromExpr;
9152   QualType FromTy = Conv.Bad.getFromType();
9153   QualType ToTy = Conv.Bad.getToType();
9154 
9155   if (FromTy == S.Context.OverloadTy) {
9156     assert(FromExpr && "overload set argument came from implicit argument?");
9157     Expr *E = FromExpr->IgnoreParens();
9158     if (isa<UnaryOperator>(E))
9159       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9160     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9161 
9162     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9163       << (unsigned) FnKind << FnDesc
9164       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9165       << ToTy << Name << I+1;
9166     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9167     return;
9168   }
9169 
9170   // Do some hand-waving analysis to see if the non-viability is due
9171   // to a qualifier mismatch.
9172   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9173   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9174   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9175     CToTy = RT->getPointeeType();
9176   else {
9177     // TODO: detect and diagnose the full richness of const mismatches.
9178     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9179       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9180         CFromTy = FromPT->getPointeeType();
9181         CToTy = ToPT->getPointeeType();
9182       }
9183   }
9184 
9185   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9186       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9187     Qualifiers FromQs = CFromTy.getQualifiers();
9188     Qualifiers ToQs = CToTy.getQualifiers();
9189 
9190     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9191       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9192         << (unsigned) FnKind << FnDesc
9193         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9194         << FromTy
9195         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9196         << (unsigned) isObjectArgument << I+1;
9197       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9198       return;
9199     }
9200 
9201     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9202       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9203         << (unsigned) FnKind << FnDesc
9204         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9205         << FromTy
9206         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9207         << (unsigned) isObjectArgument << I+1;
9208       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9209       return;
9210     }
9211 
9212     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9213       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9214       << (unsigned) FnKind << FnDesc
9215       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9216       << FromTy
9217       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9218       << (unsigned) isObjectArgument << I+1;
9219       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9220       return;
9221     }
9222 
9223     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9224       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9225         << (unsigned) FnKind << FnDesc
9226         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9227         << FromTy << FromQs.hasUnaligned() << I+1;
9228       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9229       return;
9230     }
9231 
9232     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9233     assert(CVR && "unexpected qualifiers mismatch");
9234 
9235     if (isObjectArgument) {
9236       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9237         << (unsigned) FnKind << FnDesc
9238         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9239         << FromTy << (CVR - 1);
9240     } else {
9241       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9242         << (unsigned) FnKind << FnDesc
9243         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9244         << FromTy << (CVR - 1) << I+1;
9245     }
9246     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9247     return;
9248   }
9249 
9250   // Special diagnostic for failure to convert an initializer list, since
9251   // telling the user that it has type void is not useful.
9252   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9253     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9254       << (unsigned) FnKind << FnDesc
9255       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9256       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9257     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9258     return;
9259   }
9260 
9261   // Diagnose references or pointers to incomplete types differently,
9262   // since it's far from impossible that the incompleteness triggered
9263   // the failure.
9264   QualType TempFromTy = FromTy.getNonReferenceType();
9265   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9266     TempFromTy = PTy->getPointeeType();
9267   if (TempFromTy->isIncompleteType()) {
9268     // Emit the generic diagnostic and, optionally, add the hints to it.
9269     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9270       << (unsigned) FnKind << FnDesc
9271       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9272       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9273       << (unsigned) (Cand->Fix.Kind);
9274 
9275     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9276     return;
9277   }
9278 
9279   // Diagnose base -> derived pointer conversions.
9280   unsigned BaseToDerivedConversion = 0;
9281   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9282     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9283       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9284                                                FromPtrTy->getPointeeType()) &&
9285           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9286           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9287           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9288                           FromPtrTy->getPointeeType()))
9289         BaseToDerivedConversion = 1;
9290     }
9291   } else if (const ObjCObjectPointerType *FromPtrTy
9292                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9293     if (const ObjCObjectPointerType *ToPtrTy
9294                                         = ToTy->getAs<ObjCObjectPointerType>())
9295       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9296         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9297           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9298                                                 FromPtrTy->getPointeeType()) &&
9299               FromIface->isSuperClassOf(ToIface))
9300             BaseToDerivedConversion = 2;
9301   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9302     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9303         !FromTy->isIncompleteType() &&
9304         !ToRefTy->getPointeeType()->isIncompleteType() &&
9305         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9306       BaseToDerivedConversion = 3;
9307     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9308                ToTy.getNonReferenceType().getCanonicalType() ==
9309                FromTy.getNonReferenceType().getCanonicalType()) {
9310       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9311         << (unsigned) FnKind << FnDesc
9312         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9313         << (unsigned) isObjectArgument << I + 1;
9314       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9315       return;
9316     }
9317   }
9318 
9319   if (BaseToDerivedConversion) {
9320     S.Diag(Fn->getLocation(),
9321            diag::note_ovl_candidate_bad_base_to_derived_conv)
9322       << (unsigned) FnKind << FnDesc
9323       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9324       << (BaseToDerivedConversion - 1)
9325       << FromTy << ToTy << I+1;
9326     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9327     return;
9328   }
9329 
9330   if (isa<ObjCObjectPointerType>(CFromTy) &&
9331       isa<PointerType>(CToTy)) {
9332       Qualifiers FromQs = CFromTy.getQualifiers();
9333       Qualifiers ToQs = CToTy.getQualifiers();
9334       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9335         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9336         << (unsigned) FnKind << FnDesc
9337         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9338         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9339         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9340         return;
9341       }
9342   }
9343 
9344   if (TakingCandidateAddress &&
9345       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9346     return;
9347 
9348   // Emit the generic diagnostic and, optionally, add the hints to it.
9349   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9350   FDiag << (unsigned) FnKind << FnDesc
9351     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9352     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9353     << (unsigned) (Cand->Fix.Kind);
9354 
9355   // If we can fix the conversion, suggest the FixIts.
9356   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9357        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9358     FDiag << *HI;
9359   S.Diag(Fn->getLocation(), FDiag);
9360 
9361   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9362 }
9363 
9364 /// Additional arity mismatch diagnosis specific to a function overload
9365 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9366 /// over a candidate in any candidate set.
9367 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9368                                unsigned NumArgs) {
9369   FunctionDecl *Fn = Cand->Function;
9370   unsigned MinParams = Fn->getMinRequiredArguments();
9371 
9372   // With invalid overloaded operators, it's possible that we think we
9373   // have an arity mismatch when in fact it looks like we have the
9374   // right number of arguments, because only overloaded operators have
9375   // the weird behavior of overloading member and non-member functions.
9376   // Just don't report anything.
9377   if (Fn->isInvalidDecl() &&
9378       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9379     return true;
9380 
9381   if (NumArgs < MinParams) {
9382     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9383            (Cand->FailureKind == ovl_fail_bad_deduction &&
9384             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9385   } else {
9386     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9387            (Cand->FailureKind == ovl_fail_bad_deduction &&
9388             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9389   }
9390 
9391   return false;
9392 }
9393 
9394 /// General arity mismatch diagnosis over a candidate in a candidate set.
9395 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9396                                   unsigned NumFormalArgs) {
9397   assert(isa<FunctionDecl>(D) &&
9398       "The templated declaration should at least be a function"
9399       " when diagnosing bad template argument deduction due to too many"
9400       " or too few arguments");
9401 
9402   FunctionDecl *Fn = cast<FunctionDecl>(D);
9403 
9404   // TODO: treat calls to a missing default constructor as a special case
9405   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9406   unsigned MinParams = Fn->getMinRequiredArguments();
9407 
9408   // at least / at most / exactly
9409   unsigned mode, modeCount;
9410   if (NumFormalArgs < MinParams) {
9411     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9412         FnTy->isTemplateVariadic())
9413       mode = 0; // "at least"
9414     else
9415       mode = 2; // "exactly"
9416     modeCount = MinParams;
9417   } else {
9418     if (MinParams != FnTy->getNumParams())
9419       mode = 1; // "at most"
9420     else
9421       mode = 2; // "exactly"
9422     modeCount = FnTy->getNumParams();
9423   }
9424 
9425   std::string Description;
9426   OverloadCandidateKind FnKind =
9427       ClassifyOverloadCandidate(S, Found, Fn, Description);
9428 
9429   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9430     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9431       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9432       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9433   else
9434     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9435       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9436       << mode << modeCount << NumFormalArgs;
9437   MaybeEmitInheritedConstructorNote(S, Found);
9438 }
9439 
9440 /// Arity mismatch diagnosis specific to a function overload candidate.
9441 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9442                                   unsigned NumFormalArgs) {
9443   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9444     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9445 }
9446 
9447 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9448   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9449     return TD;
9450   llvm_unreachable("Unsupported: Getting the described template declaration"
9451                    " for bad deduction diagnosis");
9452 }
9453 
9454 /// Diagnose a failed template-argument deduction.
9455 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9456                                  DeductionFailureInfo &DeductionFailure,
9457                                  unsigned NumArgs,
9458                                  bool TakingCandidateAddress) {
9459   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9460   NamedDecl *ParamD;
9461   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9462   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9463   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9464   switch (DeductionFailure.Result) {
9465   case Sema::TDK_Success:
9466     llvm_unreachable("TDK_success while diagnosing bad deduction");
9467 
9468   case Sema::TDK_Incomplete: {
9469     assert(ParamD && "no parameter found for incomplete deduction result");
9470     S.Diag(Templated->getLocation(),
9471            diag::note_ovl_candidate_incomplete_deduction)
9472         << ParamD->getDeclName();
9473     MaybeEmitInheritedConstructorNote(S, Found);
9474     return;
9475   }
9476 
9477   case Sema::TDK_Underqualified: {
9478     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9479     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9480 
9481     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9482 
9483     // Param will have been canonicalized, but it should just be a
9484     // qualified version of ParamD, so move the qualifiers to that.
9485     QualifierCollector Qs;
9486     Qs.strip(Param);
9487     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9488     assert(S.Context.hasSameType(Param, NonCanonParam));
9489 
9490     // Arg has also been canonicalized, but there's nothing we can do
9491     // about that.  It also doesn't matter as much, because it won't
9492     // have any template parameters in it (because deduction isn't
9493     // done on dependent types).
9494     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9495 
9496     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9497         << ParamD->getDeclName() << Arg << NonCanonParam;
9498     MaybeEmitInheritedConstructorNote(S, Found);
9499     return;
9500   }
9501 
9502   case Sema::TDK_Inconsistent: {
9503     assert(ParamD && "no parameter found for inconsistent deduction result");
9504     int which = 0;
9505     if (isa<TemplateTypeParmDecl>(ParamD))
9506       which = 0;
9507     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9508       which = 1;
9509     else {
9510       which = 2;
9511     }
9512 
9513     S.Diag(Templated->getLocation(),
9514            diag::note_ovl_candidate_inconsistent_deduction)
9515         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9516         << *DeductionFailure.getSecondArg();
9517     MaybeEmitInheritedConstructorNote(S, Found);
9518     return;
9519   }
9520 
9521   case Sema::TDK_InvalidExplicitArguments:
9522     assert(ParamD && "no parameter found for invalid explicit arguments");
9523     if (ParamD->getDeclName())
9524       S.Diag(Templated->getLocation(),
9525              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9526           << ParamD->getDeclName();
9527     else {
9528       int index = 0;
9529       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9530         index = TTP->getIndex();
9531       else if (NonTypeTemplateParmDecl *NTTP
9532                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9533         index = NTTP->getIndex();
9534       else
9535         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9536       S.Diag(Templated->getLocation(),
9537              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9538           << (index + 1);
9539     }
9540     MaybeEmitInheritedConstructorNote(S, Found);
9541     return;
9542 
9543   case Sema::TDK_TooManyArguments:
9544   case Sema::TDK_TooFewArguments:
9545     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9546     return;
9547 
9548   case Sema::TDK_InstantiationDepth:
9549     S.Diag(Templated->getLocation(),
9550            diag::note_ovl_candidate_instantiation_depth);
9551     MaybeEmitInheritedConstructorNote(S, Found);
9552     return;
9553 
9554   case Sema::TDK_SubstitutionFailure: {
9555     // Format the template argument list into the argument string.
9556     SmallString<128> TemplateArgString;
9557     if (TemplateArgumentList *Args =
9558             DeductionFailure.getTemplateArgumentList()) {
9559       TemplateArgString = " ";
9560       TemplateArgString += S.getTemplateArgumentBindingsText(
9561           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9562     }
9563 
9564     // If this candidate was disabled by enable_if, say so.
9565     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9566     if (PDiag && PDiag->second.getDiagID() ==
9567           diag::err_typename_nested_not_found_enable_if) {
9568       // FIXME: Use the source range of the condition, and the fully-qualified
9569       //        name of the enable_if template. These are both present in PDiag.
9570       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9571         << "'enable_if'" << TemplateArgString;
9572       return;
9573     }
9574 
9575     // Format the SFINAE diagnostic into the argument string.
9576     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9577     //        formatted message in another diagnostic.
9578     SmallString<128> SFINAEArgString;
9579     SourceRange R;
9580     if (PDiag) {
9581       SFINAEArgString = ": ";
9582       R = SourceRange(PDiag->first, PDiag->first);
9583       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9584     }
9585 
9586     S.Diag(Templated->getLocation(),
9587            diag::note_ovl_candidate_substitution_failure)
9588         << TemplateArgString << SFINAEArgString << R;
9589     MaybeEmitInheritedConstructorNote(S, Found);
9590     return;
9591   }
9592 
9593   case Sema::TDK_FailedOverloadResolution: {
9594     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9595     S.Diag(Templated->getLocation(),
9596            diag::note_ovl_candidate_failed_overload_resolution)
9597         << R.Expression->getName();
9598     return;
9599   }
9600 
9601   case Sema::TDK_DeducedMismatch: {
9602     // Format the template argument list into the argument string.
9603     SmallString<128> TemplateArgString;
9604     if (TemplateArgumentList *Args =
9605             DeductionFailure.getTemplateArgumentList()) {
9606       TemplateArgString = " ";
9607       TemplateArgString += S.getTemplateArgumentBindingsText(
9608           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9609     }
9610 
9611     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9612         << (*DeductionFailure.getCallArgIndex() + 1)
9613         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9614         << TemplateArgString;
9615     break;
9616   }
9617 
9618   case Sema::TDK_NonDeducedMismatch: {
9619     // FIXME: Provide a source location to indicate what we couldn't match.
9620     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9621     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9622     if (FirstTA.getKind() == TemplateArgument::Template &&
9623         SecondTA.getKind() == TemplateArgument::Template) {
9624       TemplateName FirstTN = FirstTA.getAsTemplate();
9625       TemplateName SecondTN = SecondTA.getAsTemplate();
9626       if (FirstTN.getKind() == TemplateName::Template &&
9627           SecondTN.getKind() == TemplateName::Template) {
9628         if (FirstTN.getAsTemplateDecl()->getName() ==
9629             SecondTN.getAsTemplateDecl()->getName()) {
9630           // FIXME: This fixes a bad diagnostic where both templates are named
9631           // the same.  This particular case is a bit difficult since:
9632           // 1) It is passed as a string to the diagnostic printer.
9633           // 2) The diagnostic printer only attempts to find a better
9634           //    name for types, not decls.
9635           // Ideally, this should folded into the diagnostic printer.
9636           S.Diag(Templated->getLocation(),
9637                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9638               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9639           return;
9640         }
9641       }
9642     }
9643 
9644     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9645         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9646       return;
9647 
9648     // FIXME: For generic lambda parameters, check if the function is a lambda
9649     // call operator, and if so, emit a prettier and more informative
9650     // diagnostic that mentions 'auto' and lambda in addition to
9651     // (or instead of?) the canonical template type parameters.
9652     S.Diag(Templated->getLocation(),
9653            diag::note_ovl_candidate_non_deduced_mismatch)
9654         << FirstTA << SecondTA;
9655     return;
9656   }
9657   // TODO: diagnose these individually, then kill off
9658   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9659   case Sema::TDK_MiscellaneousDeductionFailure:
9660     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9661     MaybeEmitInheritedConstructorNote(S, Found);
9662     return;
9663   }
9664 }
9665 
9666 /// Diagnose a failed template-argument deduction, for function calls.
9667 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9668                                  unsigned NumArgs,
9669                                  bool TakingCandidateAddress) {
9670   unsigned TDK = Cand->DeductionFailure.Result;
9671   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9672     if (CheckArityMismatch(S, Cand, NumArgs))
9673       return;
9674   }
9675   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9676                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9677 }
9678 
9679 /// CUDA: diagnose an invalid call across targets.
9680 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9681   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9682   FunctionDecl *Callee = Cand->Function;
9683 
9684   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9685                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9686 
9687   std::string FnDesc;
9688   OverloadCandidateKind FnKind =
9689       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9690 
9691   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9692       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9693 
9694   // This could be an implicit constructor for which we could not infer the
9695   // target due to a collsion. Diagnose that case.
9696   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9697   if (Meth != nullptr && Meth->isImplicit()) {
9698     CXXRecordDecl *ParentClass = Meth->getParent();
9699     Sema::CXXSpecialMember CSM;
9700 
9701     switch (FnKind) {
9702     default:
9703       return;
9704     case oc_implicit_default_constructor:
9705       CSM = Sema::CXXDefaultConstructor;
9706       break;
9707     case oc_implicit_copy_constructor:
9708       CSM = Sema::CXXCopyConstructor;
9709       break;
9710     case oc_implicit_move_constructor:
9711       CSM = Sema::CXXMoveConstructor;
9712       break;
9713     case oc_implicit_copy_assignment:
9714       CSM = Sema::CXXCopyAssignment;
9715       break;
9716     case oc_implicit_move_assignment:
9717       CSM = Sema::CXXMoveAssignment;
9718       break;
9719     };
9720 
9721     bool ConstRHS = false;
9722     if (Meth->getNumParams()) {
9723       if (const ReferenceType *RT =
9724               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9725         ConstRHS = RT->getPointeeType().isConstQualified();
9726       }
9727     }
9728 
9729     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9730                                               /* ConstRHS */ ConstRHS,
9731                                               /* Diagnose */ true);
9732   }
9733 }
9734 
9735 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9736   FunctionDecl *Callee = Cand->Function;
9737   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9738 
9739   S.Diag(Callee->getLocation(),
9740          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9741       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9742 }
9743 
9744 /// Generates a 'note' diagnostic for an overload candidate.  We've
9745 /// already generated a primary error at the call site.
9746 ///
9747 /// It really does need to be a single diagnostic with its caret
9748 /// pointed at the candidate declaration.  Yes, this creates some
9749 /// major challenges of technical writing.  Yes, this makes pointing
9750 /// out problems with specific arguments quite awkward.  It's still
9751 /// better than generating twenty screens of text for every failed
9752 /// overload.
9753 ///
9754 /// It would be great to be able to express per-candidate problems
9755 /// more richly for those diagnostic clients that cared, but we'd
9756 /// still have to be just as careful with the default diagnostics.
9757 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9758                                   unsigned NumArgs,
9759                                   bool TakingCandidateAddress) {
9760   FunctionDecl *Fn = Cand->Function;
9761 
9762   // Note deleted candidates, but only if they're viable.
9763   if (Cand->Viable && (Fn->isDeleted() ||
9764       S.isFunctionConsideredUnavailable(Fn))) {
9765     std::string FnDesc;
9766     OverloadCandidateKind FnKind =
9767         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9768 
9769     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9770       << FnKind << FnDesc
9771       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9772     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9773     return;
9774   }
9775 
9776   // We don't really have anything else to say about viable candidates.
9777   if (Cand->Viable) {
9778     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9779     return;
9780   }
9781 
9782   switch (Cand->FailureKind) {
9783   case ovl_fail_too_many_arguments:
9784   case ovl_fail_too_few_arguments:
9785     return DiagnoseArityMismatch(S, Cand, NumArgs);
9786 
9787   case ovl_fail_bad_deduction:
9788     return DiagnoseBadDeduction(S, Cand, NumArgs,
9789                                 TakingCandidateAddress);
9790 
9791   case ovl_fail_illegal_constructor: {
9792     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9793       << (Fn->getPrimaryTemplate() ? 1 : 0);
9794     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9795     return;
9796   }
9797 
9798   case ovl_fail_trivial_conversion:
9799   case ovl_fail_bad_final_conversion:
9800   case ovl_fail_final_conversion_not_exact:
9801     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9802 
9803   case ovl_fail_bad_conversion: {
9804     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9805     for (unsigned N = Cand->NumConversions; I != N; ++I)
9806       if (Cand->Conversions[I].isBad())
9807         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9808 
9809     // FIXME: this currently happens when we're called from SemaInit
9810     // when user-conversion overload fails.  Figure out how to handle
9811     // those conditions and diagnose them well.
9812     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9813   }
9814 
9815   case ovl_fail_bad_target:
9816     return DiagnoseBadTarget(S, Cand);
9817 
9818   case ovl_fail_enable_if:
9819     return DiagnoseFailedEnableIfAttr(S, Cand);
9820 
9821   case ovl_fail_addr_not_available: {
9822     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9823     (void)Available;
9824     assert(!Available);
9825     break;
9826   }
9827   }
9828 }
9829 
9830 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9831   // Desugar the type of the surrogate down to a function type,
9832   // retaining as many typedefs as possible while still showing
9833   // the function type (and, therefore, its parameter types).
9834   QualType FnType = Cand->Surrogate->getConversionType();
9835   bool isLValueReference = false;
9836   bool isRValueReference = false;
9837   bool isPointer = false;
9838   if (const LValueReferenceType *FnTypeRef =
9839         FnType->getAs<LValueReferenceType>()) {
9840     FnType = FnTypeRef->getPointeeType();
9841     isLValueReference = true;
9842   } else if (const RValueReferenceType *FnTypeRef =
9843                FnType->getAs<RValueReferenceType>()) {
9844     FnType = FnTypeRef->getPointeeType();
9845     isRValueReference = true;
9846   }
9847   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9848     FnType = FnTypePtr->getPointeeType();
9849     isPointer = true;
9850   }
9851   // Desugar down to a function type.
9852   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9853   // Reconstruct the pointer/reference as appropriate.
9854   if (isPointer) FnType = S.Context.getPointerType(FnType);
9855   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9856   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9857 
9858   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9859     << FnType;
9860 }
9861 
9862 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9863                                          SourceLocation OpLoc,
9864                                          OverloadCandidate *Cand) {
9865   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9866   std::string TypeStr("operator");
9867   TypeStr += Opc;
9868   TypeStr += "(";
9869   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9870   if (Cand->NumConversions == 1) {
9871     TypeStr += ")";
9872     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9873   } else {
9874     TypeStr += ", ";
9875     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9876     TypeStr += ")";
9877     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9878   }
9879 }
9880 
9881 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9882                                          OverloadCandidate *Cand) {
9883   unsigned NoOperands = Cand->NumConversions;
9884   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9885     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9886     if (ICS.isBad()) break; // all meaningless after first invalid
9887     if (!ICS.isAmbiguous()) continue;
9888 
9889     ICS.DiagnoseAmbiguousConversion(
9890         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9891   }
9892 }
9893 
9894 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9895   if (Cand->Function)
9896     return Cand->Function->getLocation();
9897   if (Cand->IsSurrogate)
9898     return Cand->Surrogate->getLocation();
9899   return SourceLocation();
9900 }
9901 
9902 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9903   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9904   case Sema::TDK_Success:
9905     llvm_unreachable("TDK_success while diagnosing bad deduction");
9906 
9907   case Sema::TDK_Invalid:
9908   case Sema::TDK_Incomplete:
9909     return 1;
9910 
9911   case Sema::TDK_Underqualified:
9912   case Sema::TDK_Inconsistent:
9913     return 2;
9914 
9915   case Sema::TDK_SubstitutionFailure:
9916   case Sema::TDK_DeducedMismatch:
9917   case Sema::TDK_NonDeducedMismatch:
9918   case Sema::TDK_MiscellaneousDeductionFailure:
9919     return 3;
9920 
9921   case Sema::TDK_InstantiationDepth:
9922   case Sema::TDK_FailedOverloadResolution:
9923     return 4;
9924 
9925   case Sema::TDK_InvalidExplicitArguments:
9926     return 5;
9927 
9928   case Sema::TDK_TooManyArguments:
9929   case Sema::TDK_TooFewArguments:
9930     return 6;
9931   }
9932   llvm_unreachable("Unhandled deduction result");
9933 }
9934 
9935 namespace {
9936 struct CompareOverloadCandidatesForDisplay {
9937   Sema &S;
9938   SourceLocation Loc;
9939   size_t NumArgs;
9940 
9941   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9942       : S(S), NumArgs(nArgs) {}
9943 
9944   bool operator()(const OverloadCandidate *L,
9945                   const OverloadCandidate *R) {
9946     // Fast-path this check.
9947     if (L == R) return false;
9948 
9949     // Order first by viability.
9950     if (L->Viable) {
9951       if (!R->Viable) return true;
9952 
9953       // TODO: introduce a tri-valued comparison for overload
9954       // candidates.  Would be more worthwhile if we had a sort
9955       // that could exploit it.
9956       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9957       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9958     } else if (R->Viable)
9959       return false;
9960 
9961     assert(L->Viable == R->Viable);
9962 
9963     // Criteria by which we can sort non-viable candidates:
9964     if (!L->Viable) {
9965       // 1. Arity mismatches come after other candidates.
9966       if (L->FailureKind == ovl_fail_too_many_arguments ||
9967           L->FailureKind == ovl_fail_too_few_arguments) {
9968         if (R->FailureKind == ovl_fail_too_many_arguments ||
9969             R->FailureKind == ovl_fail_too_few_arguments) {
9970           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9971           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9972           if (LDist == RDist) {
9973             if (L->FailureKind == R->FailureKind)
9974               // Sort non-surrogates before surrogates.
9975               return !L->IsSurrogate && R->IsSurrogate;
9976             // Sort candidates requiring fewer parameters than there were
9977             // arguments given after candidates requiring more parameters
9978             // than there were arguments given.
9979             return L->FailureKind == ovl_fail_too_many_arguments;
9980           }
9981           return LDist < RDist;
9982         }
9983         return false;
9984       }
9985       if (R->FailureKind == ovl_fail_too_many_arguments ||
9986           R->FailureKind == ovl_fail_too_few_arguments)
9987         return true;
9988 
9989       // 2. Bad conversions come first and are ordered by the number
9990       // of bad conversions and quality of good conversions.
9991       if (L->FailureKind == ovl_fail_bad_conversion) {
9992         if (R->FailureKind != ovl_fail_bad_conversion)
9993           return true;
9994 
9995         // The conversion that can be fixed with a smaller number of changes,
9996         // comes first.
9997         unsigned numLFixes = L->Fix.NumConversionsFixed;
9998         unsigned numRFixes = R->Fix.NumConversionsFixed;
9999         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10000         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10001         if (numLFixes != numRFixes) {
10002           return numLFixes < numRFixes;
10003         }
10004 
10005         // If there's any ordering between the defined conversions...
10006         // FIXME: this might not be transitive.
10007         assert(L->NumConversions == R->NumConversions);
10008 
10009         int leftBetter = 0;
10010         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10011         for (unsigned E = L->NumConversions; I != E; ++I) {
10012           switch (CompareImplicitConversionSequences(S, Loc,
10013                                                      L->Conversions[I],
10014                                                      R->Conversions[I])) {
10015           case ImplicitConversionSequence::Better:
10016             leftBetter++;
10017             break;
10018 
10019           case ImplicitConversionSequence::Worse:
10020             leftBetter--;
10021             break;
10022 
10023           case ImplicitConversionSequence::Indistinguishable:
10024             break;
10025           }
10026         }
10027         if (leftBetter > 0) return true;
10028         if (leftBetter < 0) return false;
10029 
10030       } else if (R->FailureKind == ovl_fail_bad_conversion)
10031         return false;
10032 
10033       if (L->FailureKind == ovl_fail_bad_deduction) {
10034         if (R->FailureKind != ovl_fail_bad_deduction)
10035           return true;
10036 
10037         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10038           return RankDeductionFailure(L->DeductionFailure)
10039                < RankDeductionFailure(R->DeductionFailure);
10040       } else if (R->FailureKind == ovl_fail_bad_deduction)
10041         return false;
10042 
10043       // TODO: others?
10044     }
10045 
10046     // Sort everything else by location.
10047     SourceLocation LLoc = GetLocationForCandidate(L);
10048     SourceLocation RLoc = GetLocationForCandidate(R);
10049 
10050     // Put candidates without locations (e.g. builtins) at the end.
10051     if (LLoc.isInvalid()) return false;
10052     if (RLoc.isInvalid()) return true;
10053 
10054     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10055   }
10056 };
10057 }
10058 
10059 /// CompleteNonViableCandidate - Normally, overload resolution only
10060 /// computes up to the first. Produces the FixIt set if possible.
10061 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10062                                        ArrayRef<Expr *> Args) {
10063   assert(!Cand->Viable);
10064 
10065   // Don't do anything on failures other than bad conversion.
10066   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10067 
10068   // We only want the FixIts if all the arguments can be corrected.
10069   bool Unfixable = false;
10070   // Use a implicit copy initialization to check conversion fixes.
10071   Cand->Fix.setConversionChecker(TryCopyInitialization);
10072 
10073   // Skip forward to the first bad conversion.
10074   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10075   unsigned ConvCount = Cand->NumConversions;
10076   while (true) {
10077     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10078     ConvIdx++;
10079     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10080       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10081       break;
10082     }
10083   }
10084 
10085   if (ConvIdx == ConvCount)
10086     return;
10087 
10088   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10089          "remaining conversion is initialized?");
10090 
10091   // FIXME: this should probably be preserved from the overload
10092   // operation somehow.
10093   bool SuppressUserConversions = false;
10094 
10095   const FunctionProtoType* Proto;
10096   unsigned ArgIdx = ConvIdx;
10097 
10098   if (Cand->IsSurrogate) {
10099     QualType ConvType
10100       = Cand->Surrogate->getConversionType().getNonReferenceType();
10101     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10102       ConvType = ConvPtrType->getPointeeType();
10103     Proto = ConvType->getAs<FunctionProtoType>();
10104     ArgIdx--;
10105   } else if (Cand->Function) {
10106     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10107     if (isa<CXXMethodDecl>(Cand->Function) &&
10108         !isa<CXXConstructorDecl>(Cand->Function))
10109       ArgIdx--;
10110   } else {
10111     // Builtin binary operator with a bad first conversion.
10112     assert(ConvCount <= 3);
10113     for (; ConvIdx != ConvCount; ++ConvIdx)
10114       Cand->Conversions[ConvIdx]
10115         = TryCopyInitialization(S, Args[ConvIdx],
10116                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10117                                 SuppressUserConversions,
10118                                 /*InOverloadResolution*/ true,
10119                                 /*AllowObjCWritebackConversion=*/
10120                                   S.getLangOpts().ObjCAutoRefCount);
10121     return;
10122   }
10123 
10124   // Fill in the rest of the conversions.
10125   unsigned NumParams = Proto->getNumParams();
10126   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10127     if (ArgIdx < NumParams) {
10128       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10129           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10130           /*InOverloadResolution=*/true,
10131           /*AllowObjCWritebackConversion=*/
10132           S.getLangOpts().ObjCAutoRefCount);
10133       // Store the FixIt in the candidate if it exists.
10134       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10135         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10136     }
10137     else
10138       Cand->Conversions[ConvIdx].setEllipsis();
10139   }
10140 }
10141 
10142 /// PrintOverloadCandidates - When overload resolution fails, prints
10143 /// diagnostic messages containing the candidates in the candidate
10144 /// set.
10145 void OverloadCandidateSet::NoteCandidates(
10146     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10147     StringRef Opc, SourceLocation OpLoc,
10148     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10149   // Sort the candidates by viability and position.  Sorting directly would
10150   // be prohibitive, so we make a set of pointers and sort those.
10151   SmallVector<OverloadCandidate*, 32> Cands;
10152   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10153   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10154     if (!Filter(*Cand))
10155       continue;
10156     if (Cand->Viable)
10157       Cands.push_back(Cand);
10158     else if (OCD == OCD_AllCandidates) {
10159       CompleteNonViableCandidate(S, Cand, Args);
10160       if (Cand->Function || Cand->IsSurrogate)
10161         Cands.push_back(Cand);
10162       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10163       // want to list every possible builtin candidate.
10164     }
10165   }
10166 
10167   std::sort(Cands.begin(), Cands.end(),
10168             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10169 
10170   bool ReportedAmbiguousConversions = false;
10171 
10172   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10173   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10174   unsigned CandsShown = 0;
10175   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10176     OverloadCandidate *Cand = *I;
10177 
10178     // Set an arbitrary limit on the number of candidate functions we'll spam
10179     // the user with.  FIXME: This limit should depend on details of the
10180     // candidate list.
10181     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10182       break;
10183     }
10184     ++CandsShown;
10185 
10186     if (Cand->Function)
10187       NoteFunctionCandidate(S, Cand, Args.size(),
10188                             /*TakingCandidateAddress=*/false);
10189     else if (Cand->IsSurrogate)
10190       NoteSurrogateCandidate(S, Cand);
10191     else {
10192       assert(Cand->Viable &&
10193              "Non-viable built-in candidates are not added to Cands.");
10194       // Generally we only see ambiguities including viable builtin
10195       // operators if overload resolution got screwed up by an
10196       // ambiguous user-defined conversion.
10197       //
10198       // FIXME: It's quite possible for different conversions to see
10199       // different ambiguities, though.
10200       if (!ReportedAmbiguousConversions) {
10201         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10202         ReportedAmbiguousConversions = true;
10203       }
10204 
10205       // If this is a viable builtin, print it.
10206       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10207     }
10208   }
10209 
10210   if (I != E)
10211     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10212 }
10213 
10214 static SourceLocation
10215 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10216   return Cand->Specialization ? Cand->Specialization->getLocation()
10217                               : SourceLocation();
10218 }
10219 
10220 namespace {
10221 struct CompareTemplateSpecCandidatesForDisplay {
10222   Sema &S;
10223   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10224 
10225   bool operator()(const TemplateSpecCandidate *L,
10226                   const TemplateSpecCandidate *R) {
10227     // Fast-path this check.
10228     if (L == R)
10229       return false;
10230 
10231     // Assuming that both candidates are not matches...
10232 
10233     // Sort by the ranking of deduction failures.
10234     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10235       return RankDeductionFailure(L->DeductionFailure) <
10236              RankDeductionFailure(R->DeductionFailure);
10237 
10238     // Sort everything else by location.
10239     SourceLocation LLoc = GetLocationForCandidate(L);
10240     SourceLocation RLoc = GetLocationForCandidate(R);
10241 
10242     // Put candidates without locations (e.g. builtins) at the end.
10243     if (LLoc.isInvalid())
10244       return false;
10245     if (RLoc.isInvalid())
10246       return true;
10247 
10248     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10249   }
10250 };
10251 }
10252 
10253 /// Diagnose a template argument deduction failure.
10254 /// We are treating these failures as overload failures due to bad
10255 /// deductions.
10256 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10257                                                  bool ForTakingAddress) {
10258   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10259                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10260 }
10261 
10262 void TemplateSpecCandidateSet::destroyCandidates() {
10263   for (iterator i = begin(), e = end(); i != e; ++i) {
10264     i->DeductionFailure.Destroy();
10265   }
10266 }
10267 
10268 void TemplateSpecCandidateSet::clear() {
10269   destroyCandidates();
10270   Candidates.clear();
10271 }
10272 
10273 /// NoteCandidates - When no template specialization match is found, prints
10274 /// diagnostic messages containing the non-matching specializations that form
10275 /// the candidate set.
10276 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10277 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10278 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10279   // Sort the candidates by position (assuming no candidate is a match).
10280   // Sorting directly would be prohibitive, so we make a set of pointers
10281   // and sort those.
10282   SmallVector<TemplateSpecCandidate *, 32> Cands;
10283   Cands.reserve(size());
10284   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10285     if (Cand->Specialization)
10286       Cands.push_back(Cand);
10287     // Otherwise, this is a non-matching builtin candidate.  We do not,
10288     // in general, want to list every possible builtin candidate.
10289   }
10290 
10291   std::sort(Cands.begin(), Cands.end(),
10292             CompareTemplateSpecCandidatesForDisplay(S));
10293 
10294   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10295   // for generalization purposes (?).
10296   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10297 
10298   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10299   unsigned CandsShown = 0;
10300   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10301     TemplateSpecCandidate *Cand = *I;
10302 
10303     // Set an arbitrary limit on the number of candidates we'll spam
10304     // the user with.  FIXME: This limit should depend on details of the
10305     // candidate list.
10306     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10307       break;
10308     ++CandsShown;
10309 
10310     assert(Cand->Specialization &&
10311            "Non-matching built-in candidates are not added to Cands.");
10312     Cand->NoteDeductionFailure(S, ForTakingAddress);
10313   }
10314 
10315   if (I != E)
10316     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10317 }
10318 
10319 // [PossiblyAFunctionType]  -->   [Return]
10320 // NonFunctionType --> NonFunctionType
10321 // R (A) --> R(A)
10322 // R (*)(A) --> R (A)
10323 // R (&)(A) --> R (A)
10324 // R (S::*)(A) --> R (A)
10325 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10326   QualType Ret = PossiblyAFunctionType;
10327   if (const PointerType *ToTypePtr =
10328     PossiblyAFunctionType->getAs<PointerType>())
10329     Ret = ToTypePtr->getPointeeType();
10330   else if (const ReferenceType *ToTypeRef =
10331     PossiblyAFunctionType->getAs<ReferenceType>())
10332     Ret = ToTypeRef->getPointeeType();
10333   else if (const MemberPointerType *MemTypePtr =
10334     PossiblyAFunctionType->getAs<MemberPointerType>())
10335     Ret = MemTypePtr->getPointeeType();
10336   Ret =
10337     Context.getCanonicalType(Ret).getUnqualifiedType();
10338   return Ret;
10339 }
10340 
10341 namespace {
10342 // A helper class to help with address of function resolution
10343 // - allows us to avoid passing around all those ugly parameters
10344 class AddressOfFunctionResolver {
10345   Sema& S;
10346   Expr* SourceExpr;
10347   const QualType& TargetType;
10348   QualType TargetFunctionType; // Extracted function type from target type
10349 
10350   bool Complain;
10351   //DeclAccessPair& ResultFunctionAccessPair;
10352   ASTContext& Context;
10353 
10354   bool TargetTypeIsNonStaticMemberFunction;
10355   bool FoundNonTemplateFunction;
10356   bool StaticMemberFunctionFromBoundPointer;
10357   bool HasComplained;
10358 
10359   OverloadExpr::FindResult OvlExprInfo;
10360   OverloadExpr *OvlExpr;
10361   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10362   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10363   TemplateSpecCandidateSet FailedCandidates;
10364 
10365 public:
10366   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10367                             const QualType &TargetType, bool Complain)
10368       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10369         Complain(Complain), Context(S.getASTContext()),
10370         TargetTypeIsNonStaticMemberFunction(
10371             !!TargetType->getAs<MemberPointerType>()),
10372         FoundNonTemplateFunction(false),
10373         StaticMemberFunctionFromBoundPointer(false),
10374         HasComplained(false),
10375         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10376         OvlExpr(OvlExprInfo.Expression),
10377         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10378     ExtractUnqualifiedFunctionTypeFromTargetType();
10379 
10380     if (TargetFunctionType->isFunctionType()) {
10381       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10382         if (!UME->isImplicitAccess() &&
10383             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10384           StaticMemberFunctionFromBoundPointer = true;
10385     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10386       DeclAccessPair dap;
10387       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10388               OvlExpr, false, &dap)) {
10389         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10390           if (!Method->isStatic()) {
10391             // If the target type is a non-function type and the function found
10392             // is a non-static member function, pretend as if that was the
10393             // target, it's the only possible type to end up with.
10394             TargetTypeIsNonStaticMemberFunction = true;
10395 
10396             // And skip adding the function if its not in the proper form.
10397             // We'll diagnose this due to an empty set of functions.
10398             if (!OvlExprInfo.HasFormOfMemberPointer)
10399               return;
10400           }
10401 
10402         Matches.push_back(std::make_pair(dap, Fn));
10403       }
10404       return;
10405     }
10406 
10407     if (OvlExpr->hasExplicitTemplateArgs())
10408       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10409 
10410     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10411       // C++ [over.over]p4:
10412       //   If more than one function is selected, [...]
10413       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10414         if (FoundNonTemplateFunction)
10415           EliminateAllTemplateMatches();
10416         else
10417           EliminateAllExceptMostSpecializedTemplate();
10418       }
10419     }
10420 
10421     if (S.getLangOpts().CUDA && Matches.size() > 1)
10422       EliminateSuboptimalCudaMatches();
10423   }
10424 
10425   bool hasComplained() const { return HasComplained; }
10426 
10427 private:
10428   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10429     QualType Discard;
10430     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10431            S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10432   }
10433 
10434   /// \return true if A is considered a better overload candidate for the
10435   /// desired type than B.
10436   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10437     // If A doesn't have exactly the correct type, we don't want to classify it
10438     // as "better" than anything else. This way, the user is required to
10439     // disambiguate for us if there are multiple candidates and no exact match.
10440     return candidateHasExactlyCorrectType(A) &&
10441            (!candidateHasExactlyCorrectType(B) ||
10442             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10443   }
10444 
10445   /// \return true if we were able to eliminate all but one overload candidate,
10446   /// false otherwise.
10447   bool eliminiateSuboptimalOverloadCandidates() {
10448     // Same algorithm as overload resolution -- one pass to pick the "best",
10449     // another pass to be sure that nothing is better than the best.
10450     auto Best = Matches.begin();
10451     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10452       if (isBetterCandidate(I->second, Best->second))
10453         Best = I;
10454 
10455     const FunctionDecl *BestFn = Best->second;
10456     auto IsBestOrInferiorToBest = [this, BestFn](
10457         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10458       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10459     };
10460 
10461     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10462     // option, so we can potentially give the user a better error
10463     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10464       return false;
10465     Matches[0] = *Best;
10466     Matches.resize(1);
10467     return true;
10468   }
10469 
10470   bool isTargetTypeAFunction() const {
10471     return TargetFunctionType->isFunctionType();
10472   }
10473 
10474   // [ToType]     [Return]
10475 
10476   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10477   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10478   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10479   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10480     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10481   }
10482 
10483   // return true if any matching specializations were found
10484   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10485                                    const DeclAccessPair& CurAccessFunPair) {
10486     if (CXXMethodDecl *Method
10487               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10488       // Skip non-static function templates when converting to pointer, and
10489       // static when converting to member pointer.
10490       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10491         return false;
10492     }
10493     else if (TargetTypeIsNonStaticMemberFunction)
10494       return false;
10495 
10496     // C++ [over.over]p2:
10497     //   If the name is a function template, template argument deduction is
10498     //   done (14.8.2.2), and if the argument deduction succeeds, the
10499     //   resulting template argument list is used to generate a single
10500     //   function template specialization, which is added to the set of
10501     //   overloaded functions considered.
10502     FunctionDecl *Specialization = nullptr;
10503     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10504     if (Sema::TemplateDeductionResult Result
10505           = S.DeduceTemplateArguments(FunctionTemplate,
10506                                       &OvlExplicitTemplateArgs,
10507                                       TargetFunctionType, Specialization,
10508                                       Info, /*InOverloadResolution=*/true)) {
10509       // Make a note of the failed deduction for diagnostics.
10510       FailedCandidates.addCandidate()
10511           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10512                MakeDeductionFailureInfo(Context, Result, Info));
10513       return false;
10514     }
10515 
10516     // Template argument deduction ensures that we have an exact match or
10517     // compatible pointer-to-function arguments that would be adjusted by ICS.
10518     // This function template specicalization works.
10519     assert(S.isSameOrCompatibleFunctionType(
10520               Context.getCanonicalType(Specialization->getType()),
10521               Context.getCanonicalType(TargetFunctionType)));
10522 
10523     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10524       return false;
10525 
10526     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10527     return true;
10528   }
10529 
10530   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10531                                       const DeclAccessPair& CurAccessFunPair) {
10532     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10533       // Skip non-static functions when converting to pointer, and static
10534       // when converting to member pointer.
10535       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10536         return false;
10537     }
10538     else if (TargetTypeIsNonStaticMemberFunction)
10539       return false;
10540 
10541     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10542       if (S.getLangOpts().CUDA)
10543         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10544           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10545             return false;
10546 
10547       // If any candidate has a placeholder return type, trigger its deduction
10548       // now.
10549       if (S.getLangOpts().CPlusPlus14 &&
10550           FunDecl->getReturnType()->isUndeducedType() &&
10551           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10552         HasComplained |= Complain;
10553         return false;
10554       }
10555 
10556       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10557         return false;
10558 
10559       // If we're in C, we need to support types that aren't exactly identical.
10560       if (!S.getLangOpts().CPlusPlus ||
10561           candidateHasExactlyCorrectType(FunDecl)) {
10562         Matches.push_back(std::make_pair(
10563             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10564         FoundNonTemplateFunction = true;
10565         return true;
10566       }
10567     }
10568 
10569     return false;
10570   }
10571 
10572   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10573     bool Ret = false;
10574 
10575     // If the overload expression doesn't have the form of a pointer to
10576     // member, don't try to convert it to a pointer-to-member type.
10577     if (IsInvalidFormOfPointerToMemberFunction())
10578       return false;
10579 
10580     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10581                                E = OvlExpr->decls_end();
10582          I != E; ++I) {
10583       // Look through any using declarations to find the underlying function.
10584       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10585 
10586       // C++ [over.over]p3:
10587       //   Non-member functions and static member functions match
10588       //   targets of type "pointer-to-function" or "reference-to-function."
10589       //   Nonstatic member functions match targets of
10590       //   type "pointer-to-member-function."
10591       // Note that according to DR 247, the containing class does not matter.
10592       if (FunctionTemplateDecl *FunctionTemplate
10593                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10594         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10595           Ret = true;
10596       }
10597       // If we have explicit template arguments supplied, skip non-templates.
10598       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10599                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10600         Ret = true;
10601     }
10602     assert(Ret || Matches.empty());
10603     return Ret;
10604   }
10605 
10606   void EliminateAllExceptMostSpecializedTemplate() {
10607     //   [...] and any given function template specialization F1 is
10608     //   eliminated if the set contains a second function template
10609     //   specialization whose function template is more specialized
10610     //   than the function template of F1 according to the partial
10611     //   ordering rules of 14.5.5.2.
10612 
10613     // The algorithm specified above is quadratic. We instead use a
10614     // two-pass algorithm (similar to the one used to identify the
10615     // best viable function in an overload set) that identifies the
10616     // best function template (if it exists).
10617 
10618     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10619     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10620       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10621 
10622     // TODO: It looks like FailedCandidates does not serve much purpose
10623     // here, since the no_viable diagnostic has index 0.
10624     UnresolvedSetIterator Result = S.getMostSpecialized(
10625         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10626         SourceExpr->getLocStart(), S.PDiag(),
10627         S.PDiag(diag::err_addr_ovl_ambiguous)
10628           << Matches[0].second->getDeclName(),
10629         S.PDiag(diag::note_ovl_candidate)
10630           << (unsigned)oc_function_template,
10631         Complain, TargetFunctionType);
10632 
10633     if (Result != MatchesCopy.end()) {
10634       // Make it the first and only element
10635       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10636       Matches[0].second = cast<FunctionDecl>(*Result);
10637       Matches.resize(1);
10638     } else
10639       HasComplained |= Complain;
10640   }
10641 
10642   void EliminateAllTemplateMatches() {
10643     //   [...] any function template specializations in the set are
10644     //   eliminated if the set also contains a non-template function, [...]
10645     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10646       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10647         ++I;
10648       else {
10649         Matches[I] = Matches[--N];
10650         Matches.resize(N);
10651       }
10652     }
10653   }
10654 
10655   void EliminateSuboptimalCudaMatches() {
10656     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10657   }
10658 
10659 public:
10660   void ComplainNoMatchesFound() const {
10661     assert(Matches.empty());
10662     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10663         << OvlExpr->getName() << TargetFunctionType
10664         << OvlExpr->getSourceRange();
10665     if (FailedCandidates.empty())
10666       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10667                                   /*TakingAddress=*/true);
10668     else {
10669       // We have some deduction failure messages. Use them to diagnose
10670       // the function templates, and diagnose the non-template candidates
10671       // normally.
10672       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10673                                  IEnd = OvlExpr->decls_end();
10674            I != IEnd; ++I)
10675         if (FunctionDecl *Fun =
10676                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10677           if (!functionHasPassObjectSizeParams(Fun))
10678             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10679                                     /*TakingAddress=*/true);
10680       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10681     }
10682   }
10683 
10684   bool IsInvalidFormOfPointerToMemberFunction() const {
10685     return TargetTypeIsNonStaticMemberFunction &&
10686       !OvlExprInfo.HasFormOfMemberPointer;
10687   }
10688 
10689   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10690       // TODO: Should we condition this on whether any functions might
10691       // have matched, or is it more appropriate to do that in callers?
10692       // TODO: a fixit wouldn't hurt.
10693       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10694         << TargetType << OvlExpr->getSourceRange();
10695   }
10696 
10697   bool IsStaticMemberFunctionFromBoundPointer() const {
10698     return StaticMemberFunctionFromBoundPointer;
10699   }
10700 
10701   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10702     S.Diag(OvlExpr->getLocStart(),
10703            diag::err_invalid_form_pointer_member_function)
10704       << OvlExpr->getSourceRange();
10705   }
10706 
10707   void ComplainOfInvalidConversion() const {
10708     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10709       << OvlExpr->getName() << TargetType;
10710   }
10711 
10712   void ComplainMultipleMatchesFound() const {
10713     assert(Matches.size() > 1);
10714     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10715       << OvlExpr->getName()
10716       << OvlExpr->getSourceRange();
10717     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10718                                 /*TakingAddress=*/true);
10719   }
10720 
10721   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10722 
10723   int getNumMatches() const { return Matches.size(); }
10724 
10725   FunctionDecl* getMatchingFunctionDecl() const {
10726     if (Matches.size() != 1) return nullptr;
10727     return Matches[0].second;
10728   }
10729 
10730   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10731     if (Matches.size() != 1) return nullptr;
10732     return &Matches[0].first;
10733   }
10734 };
10735 }
10736 
10737 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10738 /// an overloaded function (C++ [over.over]), where @p From is an
10739 /// expression with overloaded function type and @p ToType is the type
10740 /// we're trying to resolve to. For example:
10741 ///
10742 /// @code
10743 /// int f(double);
10744 /// int f(int);
10745 ///
10746 /// int (*pfd)(double) = f; // selects f(double)
10747 /// @endcode
10748 ///
10749 /// This routine returns the resulting FunctionDecl if it could be
10750 /// resolved, and NULL otherwise. When @p Complain is true, this
10751 /// routine will emit diagnostics if there is an error.
10752 FunctionDecl *
10753 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10754                                          QualType TargetType,
10755                                          bool Complain,
10756                                          DeclAccessPair &FoundResult,
10757                                          bool *pHadMultipleCandidates) {
10758   assert(AddressOfExpr->getType() == Context.OverloadTy);
10759 
10760   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10761                                      Complain);
10762   int NumMatches = Resolver.getNumMatches();
10763   FunctionDecl *Fn = nullptr;
10764   bool ShouldComplain = Complain && !Resolver.hasComplained();
10765   if (NumMatches == 0 && ShouldComplain) {
10766     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10767       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10768     else
10769       Resolver.ComplainNoMatchesFound();
10770   }
10771   else if (NumMatches > 1 && ShouldComplain)
10772     Resolver.ComplainMultipleMatchesFound();
10773   else if (NumMatches == 1) {
10774     Fn = Resolver.getMatchingFunctionDecl();
10775     assert(Fn);
10776     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10777     if (Complain) {
10778       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10779         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10780       else
10781         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10782     }
10783   }
10784 
10785   if (pHadMultipleCandidates)
10786     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10787   return Fn;
10788 }
10789 
10790 /// \brief Given an expression that refers to an overloaded function, try to
10791 /// resolve that function to a single function that can have its address taken.
10792 /// This will modify `Pair` iff it returns non-null.
10793 ///
10794 /// This routine can only realistically succeed if all but one candidates in the
10795 /// overload set for SrcExpr cannot have their addresses taken.
10796 FunctionDecl *
10797 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10798                                                   DeclAccessPair &Pair) {
10799   OverloadExpr::FindResult R = OverloadExpr::find(E);
10800   OverloadExpr *Ovl = R.Expression;
10801   FunctionDecl *Result = nullptr;
10802   DeclAccessPair DAP;
10803   // Don't use the AddressOfResolver because we're specifically looking for
10804   // cases where we have one overload candidate that lacks
10805   // enable_if/pass_object_size/...
10806   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10807     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10808     if (!FD)
10809       return nullptr;
10810 
10811     if (!checkAddressOfFunctionIsAvailable(FD))
10812       continue;
10813 
10814     // We have more than one result; quit.
10815     if (Result)
10816       return nullptr;
10817     DAP = I.getPair();
10818     Result = FD;
10819   }
10820 
10821   if (Result)
10822     Pair = DAP;
10823   return Result;
10824 }
10825 
10826 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10827 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10828 /// will perform access checks, diagnose the use of the resultant decl, and, if
10829 /// necessary, perform a function-to-pointer decay.
10830 ///
10831 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10832 /// Otherwise, returns true. This may emit diagnostics and return true.
10833 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10834     ExprResult &SrcExpr) {
10835   Expr *E = SrcExpr.get();
10836   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10837 
10838   DeclAccessPair DAP;
10839   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10840   if (!Found)
10841     return false;
10842 
10843   // Emitting multiple diagnostics for a function that is both inaccessible and
10844   // unavailable is consistent with our behavior elsewhere. So, always check
10845   // for both.
10846   DiagnoseUseOfDecl(Found, E->getExprLoc());
10847   CheckAddressOfMemberAccess(E, DAP);
10848   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10849   if (Fixed->getType()->isFunctionType())
10850     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10851   else
10852     SrcExpr = Fixed;
10853   return true;
10854 }
10855 
10856 /// \brief Given an expression that refers to an overloaded function, try to
10857 /// resolve that overloaded function expression down to a single function.
10858 ///
10859 /// This routine can only resolve template-ids that refer to a single function
10860 /// template, where that template-id refers to a single template whose template
10861 /// arguments are either provided by the template-id or have defaults,
10862 /// as described in C++0x [temp.arg.explicit]p3.
10863 ///
10864 /// If no template-ids are found, no diagnostics are emitted and NULL is
10865 /// returned.
10866 FunctionDecl *
10867 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10868                                                   bool Complain,
10869                                                   DeclAccessPair *FoundResult) {
10870   // C++ [over.over]p1:
10871   //   [...] [Note: any redundant set of parentheses surrounding the
10872   //   overloaded function name is ignored (5.1). ]
10873   // C++ [over.over]p1:
10874   //   [...] The overloaded function name can be preceded by the &
10875   //   operator.
10876 
10877   // If we didn't actually find any template-ids, we're done.
10878   if (!ovl->hasExplicitTemplateArgs())
10879     return nullptr;
10880 
10881   TemplateArgumentListInfo ExplicitTemplateArgs;
10882   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10883   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10884 
10885   // Look through all of the overloaded functions, searching for one
10886   // whose type matches exactly.
10887   FunctionDecl *Matched = nullptr;
10888   for (UnresolvedSetIterator I = ovl->decls_begin(),
10889          E = ovl->decls_end(); I != E; ++I) {
10890     // C++0x [temp.arg.explicit]p3:
10891     //   [...] In contexts where deduction is done and fails, or in contexts
10892     //   where deduction is not done, if a template argument list is
10893     //   specified and it, along with any default template arguments,
10894     //   identifies a single function template specialization, then the
10895     //   template-id is an lvalue for the function template specialization.
10896     FunctionTemplateDecl *FunctionTemplate
10897       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10898 
10899     // C++ [over.over]p2:
10900     //   If the name is a function template, template argument deduction is
10901     //   done (14.8.2.2), and if the argument deduction succeeds, the
10902     //   resulting template argument list is used to generate a single
10903     //   function template specialization, which is added to the set of
10904     //   overloaded functions considered.
10905     FunctionDecl *Specialization = nullptr;
10906     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10907     if (TemplateDeductionResult Result
10908           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10909                                     Specialization, Info,
10910                                     /*InOverloadResolution=*/true)) {
10911       // Make a note of the failed deduction for diagnostics.
10912       // TODO: Actually use the failed-deduction info?
10913       FailedCandidates.addCandidate()
10914           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10915                MakeDeductionFailureInfo(Context, Result, Info));
10916       continue;
10917     }
10918 
10919     assert(Specialization && "no specialization and no error?");
10920 
10921     // Multiple matches; we can't resolve to a single declaration.
10922     if (Matched) {
10923       if (Complain) {
10924         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10925           << ovl->getName();
10926         NoteAllOverloadCandidates(ovl);
10927       }
10928       return nullptr;
10929     }
10930 
10931     Matched = Specialization;
10932     if (FoundResult) *FoundResult = I.getPair();
10933   }
10934 
10935   if (Matched && getLangOpts().CPlusPlus14 &&
10936       Matched->getReturnType()->isUndeducedType() &&
10937       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10938     return nullptr;
10939 
10940   return Matched;
10941 }
10942 
10943 
10944 
10945 
10946 // Resolve and fix an overloaded expression that can be resolved
10947 // because it identifies a single function template specialization.
10948 //
10949 // Last three arguments should only be supplied if Complain = true
10950 //
10951 // Return true if it was logically possible to so resolve the
10952 // expression, regardless of whether or not it succeeded.  Always
10953 // returns true if 'complain' is set.
10954 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10955                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10956                       bool complain, SourceRange OpRangeForComplaining,
10957                                            QualType DestTypeForComplaining,
10958                                             unsigned DiagIDForComplaining) {
10959   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10960 
10961   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10962 
10963   DeclAccessPair found;
10964   ExprResult SingleFunctionExpression;
10965   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10966                            ovl.Expression, /*complain*/ false, &found)) {
10967     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10968       SrcExpr = ExprError();
10969       return true;
10970     }
10971 
10972     // It is only correct to resolve to an instance method if we're
10973     // resolving a form that's permitted to be a pointer to member.
10974     // Otherwise we'll end up making a bound member expression, which
10975     // is illegal in all the contexts we resolve like this.
10976     if (!ovl.HasFormOfMemberPointer &&
10977         isa<CXXMethodDecl>(fn) &&
10978         cast<CXXMethodDecl>(fn)->isInstance()) {
10979       if (!complain) return false;
10980 
10981       Diag(ovl.Expression->getExprLoc(),
10982            diag::err_bound_member_function)
10983         << 0 << ovl.Expression->getSourceRange();
10984 
10985       // TODO: I believe we only end up here if there's a mix of
10986       // static and non-static candidates (otherwise the expression
10987       // would have 'bound member' type, not 'overload' type).
10988       // Ideally we would note which candidate was chosen and why
10989       // the static candidates were rejected.
10990       SrcExpr = ExprError();
10991       return true;
10992     }
10993 
10994     // Fix the expression to refer to 'fn'.
10995     SingleFunctionExpression =
10996         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10997 
10998     // If desired, do function-to-pointer decay.
10999     if (doFunctionPointerConverion) {
11000       SingleFunctionExpression =
11001         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11002       if (SingleFunctionExpression.isInvalid()) {
11003         SrcExpr = ExprError();
11004         return true;
11005       }
11006     }
11007   }
11008 
11009   if (!SingleFunctionExpression.isUsable()) {
11010     if (complain) {
11011       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11012         << ovl.Expression->getName()
11013         << DestTypeForComplaining
11014         << OpRangeForComplaining
11015         << ovl.Expression->getQualifierLoc().getSourceRange();
11016       NoteAllOverloadCandidates(SrcExpr.get());
11017 
11018       SrcExpr = ExprError();
11019       return true;
11020     }
11021 
11022     return false;
11023   }
11024 
11025   SrcExpr = SingleFunctionExpression;
11026   return true;
11027 }
11028 
11029 /// \brief Add a single candidate to the overload set.
11030 static void AddOverloadedCallCandidate(Sema &S,
11031                                        DeclAccessPair FoundDecl,
11032                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11033                                        ArrayRef<Expr *> Args,
11034                                        OverloadCandidateSet &CandidateSet,
11035                                        bool PartialOverloading,
11036                                        bool KnownValid) {
11037   NamedDecl *Callee = FoundDecl.getDecl();
11038   if (isa<UsingShadowDecl>(Callee))
11039     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11040 
11041   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11042     if (ExplicitTemplateArgs) {
11043       assert(!KnownValid && "Explicit template arguments?");
11044       return;
11045     }
11046     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11047                            /*SuppressUsedConversions=*/false,
11048                            PartialOverloading);
11049     return;
11050   }
11051 
11052   if (FunctionTemplateDecl *FuncTemplate
11053       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11054     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11055                                    ExplicitTemplateArgs, Args, CandidateSet,
11056                                    /*SuppressUsedConversions=*/false,
11057                                    PartialOverloading);
11058     return;
11059   }
11060 
11061   assert(!KnownValid && "unhandled case in overloaded call candidate");
11062 }
11063 
11064 /// \brief Add the overload candidates named by callee and/or found by argument
11065 /// dependent lookup to the given overload set.
11066 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11067                                        ArrayRef<Expr *> Args,
11068                                        OverloadCandidateSet &CandidateSet,
11069                                        bool PartialOverloading) {
11070 
11071 #ifndef NDEBUG
11072   // Verify that ArgumentDependentLookup is consistent with the rules
11073   // in C++0x [basic.lookup.argdep]p3:
11074   //
11075   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11076   //   and let Y be the lookup set produced by argument dependent
11077   //   lookup (defined as follows). If X contains
11078   //
11079   //     -- a declaration of a class member, or
11080   //
11081   //     -- a block-scope function declaration that is not a
11082   //        using-declaration, or
11083   //
11084   //     -- a declaration that is neither a function or a function
11085   //        template
11086   //
11087   //   then Y is empty.
11088 
11089   if (ULE->requiresADL()) {
11090     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11091            E = ULE->decls_end(); I != E; ++I) {
11092       assert(!(*I)->getDeclContext()->isRecord());
11093       assert(isa<UsingShadowDecl>(*I) ||
11094              !(*I)->getDeclContext()->isFunctionOrMethod());
11095       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11096     }
11097   }
11098 #endif
11099 
11100   // It would be nice to avoid this copy.
11101   TemplateArgumentListInfo TABuffer;
11102   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11103   if (ULE->hasExplicitTemplateArgs()) {
11104     ULE->copyTemplateArgumentsInto(TABuffer);
11105     ExplicitTemplateArgs = &TABuffer;
11106   }
11107 
11108   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11109          E = ULE->decls_end(); I != E; ++I)
11110     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11111                                CandidateSet, PartialOverloading,
11112                                /*KnownValid*/ true);
11113 
11114   if (ULE->requiresADL())
11115     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11116                                          Args, ExplicitTemplateArgs,
11117                                          CandidateSet, PartialOverloading);
11118 }
11119 
11120 /// Determine whether a declaration with the specified name could be moved into
11121 /// a different namespace.
11122 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11123   switch (Name.getCXXOverloadedOperator()) {
11124   case OO_New: case OO_Array_New:
11125   case OO_Delete: case OO_Array_Delete:
11126     return false;
11127 
11128   default:
11129     return true;
11130   }
11131 }
11132 
11133 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11134 /// template, where the non-dependent name was declared after the template
11135 /// was defined. This is common in code written for a compilers which do not
11136 /// correctly implement two-stage name lookup.
11137 ///
11138 /// Returns true if a viable candidate was found and a diagnostic was issued.
11139 static bool
11140 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11141                        const CXXScopeSpec &SS, LookupResult &R,
11142                        OverloadCandidateSet::CandidateSetKind CSK,
11143                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11144                        ArrayRef<Expr *> Args,
11145                        bool *DoDiagnoseEmptyLookup = nullptr) {
11146   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11147     return false;
11148 
11149   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11150     if (DC->isTransparentContext())
11151       continue;
11152 
11153     SemaRef.LookupQualifiedName(R, DC);
11154 
11155     if (!R.empty()) {
11156       R.suppressDiagnostics();
11157 
11158       if (isa<CXXRecordDecl>(DC)) {
11159         // Don't diagnose names we find in classes; we get much better
11160         // diagnostics for these from DiagnoseEmptyLookup.
11161         R.clear();
11162         if (DoDiagnoseEmptyLookup)
11163           *DoDiagnoseEmptyLookup = true;
11164         return false;
11165       }
11166 
11167       OverloadCandidateSet Candidates(FnLoc, CSK);
11168       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11169         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11170                                    ExplicitTemplateArgs, Args,
11171                                    Candidates, false, /*KnownValid*/ false);
11172 
11173       OverloadCandidateSet::iterator Best;
11174       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11175         // No viable functions. Don't bother the user with notes for functions
11176         // which don't work and shouldn't be found anyway.
11177         R.clear();
11178         return false;
11179       }
11180 
11181       // Find the namespaces where ADL would have looked, and suggest
11182       // declaring the function there instead.
11183       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11184       Sema::AssociatedClassSet AssociatedClasses;
11185       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11186                                                  AssociatedNamespaces,
11187                                                  AssociatedClasses);
11188       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11189       if (canBeDeclaredInNamespace(R.getLookupName())) {
11190         DeclContext *Std = SemaRef.getStdNamespace();
11191         for (Sema::AssociatedNamespaceSet::iterator
11192                it = AssociatedNamespaces.begin(),
11193                end = AssociatedNamespaces.end(); it != end; ++it) {
11194           // Never suggest declaring a function within namespace 'std'.
11195           if (Std && Std->Encloses(*it))
11196             continue;
11197 
11198           // Never suggest declaring a function within a namespace with a
11199           // reserved name, like __gnu_cxx.
11200           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11201           if (NS &&
11202               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11203             continue;
11204 
11205           SuggestedNamespaces.insert(*it);
11206         }
11207       }
11208 
11209       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11210         << R.getLookupName();
11211       if (SuggestedNamespaces.empty()) {
11212         SemaRef.Diag(Best->Function->getLocation(),
11213                      diag::note_not_found_by_two_phase_lookup)
11214           << R.getLookupName() << 0;
11215       } else if (SuggestedNamespaces.size() == 1) {
11216         SemaRef.Diag(Best->Function->getLocation(),
11217                      diag::note_not_found_by_two_phase_lookup)
11218           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11219       } else {
11220         // FIXME: It would be useful to list the associated namespaces here,
11221         // but the diagnostics infrastructure doesn't provide a way to produce
11222         // a localized representation of a list of items.
11223         SemaRef.Diag(Best->Function->getLocation(),
11224                      diag::note_not_found_by_two_phase_lookup)
11225           << R.getLookupName() << 2;
11226       }
11227 
11228       // Try to recover by calling this function.
11229       return true;
11230     }
11231 
11232     R.clear();
11233   }
11234 
11235   return false;
11236 }
11237 
11238 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11239 /// template, where the non-dependent operator was declared after the template
11240 /// was defined.
11241 ///
11242 /// Returns true if a viable candidate was found and a diagnostic was issued.
11243 static bool
11244 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11245                                SourceLocation OpLoc,
11246                                ArrayRef<Expr *> Args) {
11247   DeclarationName OpName =
11248     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11249   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11250   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11251                                 OverloadCandidateSet::CSK_Operator,
11252                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11253 }
11254 
11255 namespace {
11256 class BuildRecoveryCallExprRAII {
11257   Sema &SemaRef;
11258 public:
11259   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11260     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11261     SemaRef.IsBuildingRecoveryCallExpr = true;
11262   }
11263 
11264   ~BuildRecoveryCallExprRAII() {
11265     SemaRef.IsBuildingRecoveryCallExpr = false;
11266   }
11267 };
11268 
11269 }
11270 
11271 static std::unique_ptr<CorrectionCandidateCallback>
11272 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11273               bool HasTemplateArgs, bool AllowTypoCorrection) {
11274   if (!AllowTypoCorrection)
11275     return llvm::make_unique<NoTypoCorrectionCCC>();
11276   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11277                                                   HasTemplateArgs, ME);
11278 }
11279 
11280 /// Attempts to recover from a call where no functions were found.
11281 ///
11282 /// Returns true if new candidates were found.
11283 static ExprResult
11284 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11285                       UnresolvedLookupExpr *ULE,
11286                       SourceLocation LParenLoc,
11287                       MutableArrayRef<Expr *> Args,
11288                       SourceLocation RParenLoc,
11289                       bool EmptyLookup, bool AllowTypoCorrection) {
11290   // Do not try to recover if it is already building a recovery call.
11291   // This stops infinite loops for template instantiations like
11292   //
11293   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11294   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11295   //
11296   if (SemaRef.IsBuildingRecoveryCallExpr)
11297     return ExprError();
11298   BuildRecoveryCallExprRAII RCE(SemaRef);
11299 
11300   CXXScopeSpec SS;
11301   SS.Adopt(ULE->getQualifierLoc());
11302   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11303 
11304   TemplateArgumentListInfo TABuffer;
11305   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11306   if (ULE->hasExplicitTemplateArgs()) {
11307     ULE->copyTemplateArgumentsInto(TABuffer);
11308     ExplicitTemplateArgs = &TABuffer;
11309   }
11310 
11311   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11312                  Sema::LookupOrdinaryName);
11313   bool DoDiagnoseEmptyLookup = EmptyLookup;
11314   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11315                               OverloadCandidateSet::CSK_Normal,
11316                               ExplicitTemplateArgs, Args,
11317                               &DoDiagnoseEmptyLookup) &&
11318     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11319         S, SS, R,
11320         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11321                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11322         ExplicitTemplateArgs, Args)))
11323     return ExprError();
11324 
11325   assert(!R.empty() && "lookup results empty despite recovery");
11326 
11327   // Build an implicit member call if appropriate.  Just drop the
11328   // casts and such from the call, we don't really care.
11329   ExprResult NewFn = ExprError();
11330   if ((*R.begin())->isCXXClassMember())
11331     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11332                                                     ExplicitTemplateArgs, S);
11333   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11334     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11335                                         ExplicitTemplateArgs);
11336   else
11337     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11338 
11339   if (NewFn.isInvalid())
11340     return ExprError();
11341 
11342   // This shouldn't cause an infinite loop because we're giving it
11343   // an expression with viable lookup results, which should never
11344   // end up here.
11345   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11346                                MultiExprArg(Args.data(), Args.size()),
11347                                RParenLoc);
11348 }
11349 
11350 /// \brief Constructs and populates an OverloadedCandidateSet from
11351 /// the given function.
11352 /// \returns true when an the ExprResult output parameter has been set.
11353 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11354                                   UnresolvedLookupExpr *ULE,
11355                                   MultiExprArg Args,
11356                                   SourceLocation RParenLoc,
11357                                   OverloadCandidateSet *CandidateSet,
11358                                   ExprResult *Result) {
11359 #ifndef NDEBUG
11360   if (ULE->requiresADL()) {
11361     // To do ADL, we must have found an unqualified name.
11362     assert(!ULE->getQualifier() && "qualified name with ADL");
11363 
11364     // We don't perform ADL for implicit declarations of builtins.
11365     // Verify that this was correctly set up.
11366     FunctionDecl *F;
11367     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11368         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11369         F->getBuiltinID() && F->isImplicit())
11370       llvm_unreachable("performing ADL for builtin");
11371 
11372     // We don't perform ADL in C.
11373     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11374   }
11375 #endif
11376 
11377   UnbridgedCastsSet UnbridgedCasts;
11378   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11379     *Result = ExprError();
11380     return true;
11381   }
11382 
11383   // Add the functions denoted by the callee to the set of candidate
11384   // functions, including those from argument-dependent lookup.
11385   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11386 
11387   if (getLangOpts().MSVCCompat &&
11388       CurContext->isDependentContext() && !isSFINAEContext() &&
11389       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11390 
11391     OverloadCandidateSet::iterator Best;
11392     if (CandidateSet->empty() ||
11393         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11394             OR_No_Viable_Function) {
11395       // In Microsoft mode, if we are inside a template class member function then
11396       // create a type dependent CallExpr. The goal is to postpone name lookup
11397       // to instantiation time to be able to search into type dependent base
11398       // classes.
11399       CallExpr *CE = new (Context) CallExpr(
11400           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11401       CE->setTypeDependent(true);
11402       CE->setValueDependent(true);
11403       CE->setInstantiationDependent(true);
11404       *Result = CE;
11405       return true;
11406     }
11407   }
11408 
11409   if (CandidateSet->empty())
11410     return false;
11411 
11412   UnbridgedCasts.restore();
11413   return false;
11414 }
11415 
11416 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11417 /// the completed call expression. If overload resolution fails, emits
11418 /// diagnostics and returns ExprError()
11419 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11420                                            UnresolvedLookupExpr *ULE,
11421                                            SourceLocation LParenLoc,
11422                                            MultiExprArg Args,
11423                                            SourceLocation RParenLoc,
11424                                            Expr *ExecConfig,
11425                                            OverloadCandidateSet *CandidateSet,
11426                                            OverloadCandidateSet::iterator *Best,
11427                                            OverloadingResult OverloadResult,
11428                                            bool AllowTypoCorrection) {
11429   if (CandidateSet->empty())
11430     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11431                                  RParenLoc, /*EmptyLookup=*/true,
11432                                  AllowTypoCorrection);
11433 
11434   switch (OverloadResult) {
11435   case OR_Success: {
11436     FunctionDecl *FDecl = (*Best)->Function;
11437     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11438     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11439       return ExprError();
11440     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11441     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11442                                          ExecConfig);
11443   }
11444 
11445   case OR_No_Viable_Function: {
11446     // Try to recover by looking for viable functions which the user might
11447     // have meant to call.
11448     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11449                                                 Args, RParenLoc,
11450                                                 /*EmptyLookup=*/false,
11451                                                 AllowTypoCorrection);
11452     if (!Recovery.isInvalid())
11453       return Recovery;
11454 
11455     // If the user passes in a function that we can't take the address of, we
11456     // generally end up emitting really bad error messages. Here, we attempt to
11457     // emit better ones.
11458     for (const Expr *Arg : Args) {
11459       if (!Arg->getType()->isFunctionType())
11460         continue;
11461       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11462         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11463         if (FD &&
11464             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11465                                                        Arg->getExprLoc()))
11466           return ExprError();
11467       }
11468     }
11469 
11470     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11471         << ULE->getName() << Fn->getSourceRange();
11472     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11473     break;
11474   }
11475 
11476   case OR_Ambiguous:
11477     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11478       << ULE->getName() << Fn->getSourceRange();
11479     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11480     break;
11481 
11482   case OR_Deleted: {
11483     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11484       << (*Best)->Function->isDeleted()
11485       << ULE->getName()
11486       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11487       << Fn->getSourceRange();
11488     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11489 
11490     // We emitted an error for the unvailable/deleted function call but keep
11491     // the call in the AST.
11492     FunctionDecl *FDecl = (*Best)->Function;
11493     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11494     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11495                                          ExecConfig);
11496   }
11497   }
11498 
11499   // Overload resolution failed.
11500   return ExprError();
11501 }
11502 
11503 static void markUnaddressableCandidatesUnviable(Sema &S,
11504                                                 OverloadCandidateSet &CS) {
11505   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11506     if (I->Viable &&
11507         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11508       I->Viable = false;
11509       I->FailureKind = ovl_fail_addr_not_available;
11510     }
11511   }
11512 }
11513 
11514 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11515 /// (which eventually refers to the declaration Func) and the call
11516 /// arguments Args/NumArgs, attempt to resolve the function call down
11517 /// to a specific function. If overload resolution succeeds, returns
11518 /// the call expression produced by overload resolution.
11519 /// Otherwise, emits diagnostics and returns ExprError.
11520 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11521                                          UnresolvedLookupExpr *ULE,
11522                                          SourceLocation LParenLoc,
11523                                          MultiExprArg Args,
11524                                          SourceLocation RParenLoc,
11525                                          Expr *ExecConfig,
11526                                          bool AllowTypoCorrection,
11527                                          bool CalleesAddressIsTaken) {
11528   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11529                                     OverloadCandidateSet::CSK_Normal);
11530   ExprResult result;
11531 
11532   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11533                              &result))
11534     return result;
11535 
11536   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11537   // functions that aren't addressible are considered unviable.
11538   if (CalleesAddressIsTaken)
11539     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11540 
11541   OverloadCandidateSet::iterator Best;
11542   OverloadingResult OverloadResult =
11543       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11544 
11545   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11546                                   RParenLoc, ExecConfig, &CandidateSet,
11547                                   &Best, OverloadResult,
11548                                   AllowTypoCorrection);
11549 }
11550 
11551 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11552   return Functions.size() > 1 ||
11553     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11554 }
11555 
11556 /// \brief Create a unary operation that may resolve to an overloaded
11557 /// operator.
11558 ///
11559 /// \param OpLoc The location of the operator itself (e.g., '*').
11560 ///
11561 /// \param Opc The UnaryOperatorKind that describes this operator.
11562 ///
11563 /// \param Fns The set of non-member functions that will be
11564 /// considered by overload resolution. The caller needs to build this
11565 /// set based on the context using, e.g.,
11566 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11567 /// set should not contain any member functions; those will be added
11568 /// by CreateOverloadedUnaryOp().
11569 ///
11570 /// \param Input The input argument.
11571 ExprResult
11572 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11573                               const UnresolvedSetImpl &Fns,
11574                               Expr *Input) {
11575   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11576   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11577   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11578   // TODO: provide better source location info.
11579   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11580 
11581   if (checkPlaceholderForOverload(*this, Input))
11582     return ExprError();
11583 
11584   Expr *Args[2] = { Input, nullptr };
11585   unsigned NumArgs = 1;
11586 
11587   // For post-increment and post-decrement, add the implicit '0' as
11588   // the second argument, so that we know this is a post-increment or
11589   // post-decrement.
11590   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11591     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11592     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11593                                      SourceLocation());
11594     NumArgs = 2;
11595   }
11596 
11597   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11598 
11599   if (Input->isTypeDependent()) {
11600     if (Fns.empty())
11601       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11602                                          VK_RValue, OK_Ordinary, OpLoc);
11603 
11604     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11605     UnresolvedLookupExpr *Fn
11606       = UnresolvedLookupExpr::Create(Context, NamingClass,
11607                                      NestedNameSpecifierLoc(), OpNameInfo,
11608                                      /*ADL*/ true, IsOverloaded(Fns),
11609                                      Fns.begin(), Fns.end());
11610     return new (Context)
11611         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11612                             VK_RValue, OpLoc, false);
11613   }
11614 
11615   // Build an empty overload set.
11616   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11617 
11618   // Add the candidates from the given function set.
11619   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11620 
11621   // Add operator candidates that are member functions.
11622   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11623 
11624   // Add candidates from ADL.
11625   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11626                                        /*ExplicitTemplateArgs*/nullptr,
11627                                        CandidateSet);
11628 
11629   // Add builtin operator candidates.
11630   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11631 
11632   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11633 
11634   // Perform overload resolution.
11635   OverloadCandidateSet::iterator Best;
11636   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11637   case OR_Success: {
11638     // We found a built-in operator or an overloaded operator.
11639     FunctionDecl *FnDecl = Best->Function;
11640 
11641     if (FnDecl) {
11642       // We matched an overloaded operator. Build a call to that
11643       // operator.
11644 
11645       // Convert the arguments.
11646       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11647         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11648 
11649         ExprResult InputRes =
11650           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11651                                               Best->FoundDecl, Method);
11652         if (InputRes.isInvalid())
11653           return ExprError();
11654         Input = InputRes.get();
11655       } else {
11656         // Convert the arguments.
11657         ExprResult InputInit
11658           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11659                                                       Context,
11660                                                       FnDecl->getParamDecl(0)),
11661                                       SourceLocation(),
11662                                       Input);
11663         if (InputInit.isInvalid())
11664           return ExprError();
11665         Input = InputInit.get();
11666       }
11667 
11668       // Build the actual expression node.
11669       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11670                                                 HadMultipleCandidates, OpLoc);
11671       if (FnExpr.isInvalid())
11672         return ExprError();
11673 
11674       // Determine the result type.
11675       QualType ResultTy = FnDecl->getReturnType();
11676       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11677       ResultTy = ResultTy.getNonLValueExprType(Context);
11678 
11679       Args[0] = Input;
11680       CallExpr *TheCall =
11681         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11682                                           ResultTy, VK, OpLoc, false);
11683 
11684       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11685         return ExprError();
11686 
11687       return MaybeBindToTemporary(TheCall);
11688     } else {
11689       // We matched a built-in operator. Convert the arguments, then
11690       // break out so that we will build the appropriate built-in
11691       // operator node.
11692       ExprResult InputRes =
11693         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11694                                   Best->Conversions[0], AA_Passing);
11695       if (InputRes.isInvalid())
11696         return ExprError();
11697       Input = InputRes.get();
11698       break;
11699     }
11700   }
11701 
11702   case OR_No_Viable_Function:
11703     // This is an erroneous use of an operator which can be overloaded by
11704     // a non-member function. Check for non-member operators which were
11705     // defined too late to be candidates.
11706     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11707       // FIXME: Recover by calling the found function.
11708       return ExprError();
11709 
11710     // No viable function; fall through to handling this as a
11711     // built-in operator, which will produce an error message for us.
11712     break;
11713 
11714   case OR_Ambiguous:
11715     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11716         << UnaryOperator::getOpcodeStr(Opc)
11717         << Input->getType()
11718         << Input->getSourceRange();
11719     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11720                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11721     return ExprError();
11722 
11723   case OR_Deleted:
11724     Diag(OpLoc, diag::err_ovl_deleted_oper)
11725       << Best->Function->isDeleted()
11726       << UnaryOperator::getOpcodeStr(Opc)
11727       << getDeletedOrUnavailableSuffix(Best->Function)
11728       << Input->getSourceRange();
11729     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11730                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11731     return ExprError();
11732   }
11733 
11734   // Either we found no viable overloaded operator or we matched a
11735   // built-in operator. In either case, fall through to trying to
11736   // build a built-in operation.
11737   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11738 }
11739 
11740 /// \brief Create a binary operation that may resolve to an overloaded
11741 /// operator.
11742 ///
11743 /// \param OpLoc The location of the operator itself (e.g., '+').
11744 ///
11745 /// \param Opc The BinaryOperatorKind that describes this operator.
11746 ///
11747 /// \param Fns The set of non-member functions that will be
11748 /// considered by overload resolution. The caller needs to build this
11749 /// set based on the context using, e.g.,
11750 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11751 /// set should not contain any member functions; those will be added
11752 /// by CreateOverloadedBinOp().
11753 ///
11754 /// \param LHS Left-hand argument.
11755 /// \param RHS Right-hand argument.
11756 ExprResult
11757 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11758                             BinaryOperatorKind Opc,
11759                             const UnresolvedSetImpl &Fns,
11760                             Expr *LHS, Expr *RHS) {
11761   Expr *Args[2] = { LHS, RHS };
11762   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11763 
11764   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11765   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11766 
11767   // If either side is type-dependent, create an appropriate dependent
11768   // expression.
11769   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11770     if (Fns.empty()) {
11771       // If there are no functions to store, just build a dependent
11772       // BinaryOperator or CompoundAssignment.
11773       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11774         return new (Context) BinaryOperator(
11775             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11776             OpLoc, FPFeatures.fp_contract);
11777 
11778       return new (Context) CompoundAssignOperator(
11779           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11780           Context.DependentTy, Context.DependentTy, OpLoc,
11781           FPFeatures.fp_contract);
11782     }
11783 
11784     // FIXME: save results of ADL from here?
11785     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11786     // TODO: provide better source location info in DNLoc component.
11787     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11788     UnresolvedLookupExpr *Fn
11789       = UnresolvedLookupExpr::Create(Context, NamingClass,
11790                                      NestedNameSpecifierLoc(), OpNameInfo,
11791                                      /*ADL*/ true, IsOverloaded(Fns),
11792                                      Fns.begin(), Fns.end());
11793     return new (Context)
11794         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11795                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11796   }
11797 
11798   // Always do placeholder-like conversions on the RHS.
11799   if (checkPlaceholderForOverload(*this, Args[1]))
11800     return ExprError();
11801 
11802   // Do placeholder-like conversion on the LHS; note that we should
11803   // not get here with a PseudoObject LHS.
11804   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11805   if (checkPlaceholderForOverload(*this, Args[0]))
11806     return ExprError();
11807 
11808   // If this is the assignment operator, we only perform overload resolution
11809   // if the left-hand side is a class or enumeration type. This is actually
11810   // a hack. The standard requires that we do overload resolution between the
11811   // various built-in candidates, but as DR507 points out, this can lead to
11812   // problems. So we do it this way, which pretty much follows what GCC does.
11813   // Note that we go the traditional code path for compound assignment forms.
11814   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11815     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11816 
11817   // If this is the .* operator, which is not overloadable, just
11818   // create a built-in binary operator.
11819   if (Opc == BO_PtrMemD)
11820     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11821 
11822   // Build an empty overload set.
11823   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11824 
11825   // Add the candidates from the given function set.
11826   AddFunctionCandidates(Fns, Args, CandidateSet);
11827 
11828   // Add operator candidates that are member functions.
11829   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11830 
11831   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11832   // performed for an assignment operator (nor for operator[] nor operator->,
11833   // which don't get here).
11834   if (Opc != BO_Assign)
11835     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11836                                          /*ExplicitTemplateArgs*/ nullptr,
11837                                          CandidateSet);
11838 
11839   // Add builtin operator candidates.
11840   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11841 
11842   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11843 
11844   // Perform overload resolution.
11845   OverloadCandidateSet::iterator Best;
11846   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11847     case OR_Success: {
11848       // We found a built-in operator or an overloaded operator.
11849       FunctionDecl *FnDecl = Best->Function;
11850 
11851       if (FnDecl) {
11852         // We matched an overloaded operator. Build a call to that
11853         // operator.
11854 
11855         // Convert the arguments.
11856         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11857           // Best->Access is only meaningful for class members.
11858           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11859 
11860           ExprResult Arg1 =
11861             PerformCopyInitialization(
11862               InitializedEntity::InitializeParameter(Context,
11863                                                      FnDecl->getParamDecl(0)),
11864               SourceLocation(), Args[1]);
11865           if (Arg1.isInvalid())
11866             return ExprError();
11867 
11868           ExprResult Arg0 =
11869             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11870                                                 Best->FoundDecl, Method);
11871           if (Arg0.isInvalid())
11872             return ExprError();
11873           Args[0] = Arg0.getAs<Expr>();
11874           Args[1] = RHS = Arg1.getAs<Expr>();
11875         } else {
11876           // Convert the arguments.
11877           ExprResult Arg0 = PerformCopyInitialization(
11878             InitializedEntity::InitializeParameter(Context,
11879                                                    FnDecl->getParamDecl(0)),
11880             SourceLocation(), Args[0]);
11881           if (Arg0.isInvalid())
11882             return ExprError();
11883 
11884           ExprResult Arg1 =
11885             PerformCopyInitialization(
11886               InitializedEntity::InitializeParameter(Context,
11887                                                      FnDecl->getParamDecl(1)),
11888               SourceLocation(), Args[1]);
11889           if (Arg1.isInvalid())
11890             return ExprError();
11891           Args[0] = LHS = Arg0.getAs<Expr>();
11892           Args[1] = RHS = Arg1.getAs<Expr>();
11893         }
11894 
11895         // Build the actual expression node.
11896         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11897                                                   Best->FoundDecl,
11898                                                   HadMultipleCandidates, OpLoc);
11899         if (FnExpr.isInvalid())
11900           return ExprError();
11901 
11902         // Determine the result type.
11903         QualType ResultTy = FnDecl->getReturnType();
11904         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11905         ResultTy = ResultTy.getNonLValueExprType(Context);
11906 
11907         CXXOperatorCallExpr *TheCall =
11908           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11909                                             Args, ResultTy, VK, OpLoc,
11910                                             FPFeatures.fp_contract);
11911 
11912         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11913                                 FnDecl))
11914           return ExprError();
11915 
11916         ArrayRef<const Expr *> ArgsArray(Args, 2);
11917         // Cut off the implicit 'this'.
11918         if (isa<CXXMethodDecl>(FnDecl))
11919           ArgsArray = ArgsArray.slice(1);
11920 
11921         // Check for a self move.
11922         if (Op == OO_Equal)
11923           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11924 
11925         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11926                   TheCall->getSourceRange(), VariadicDoesNotApply);
11927 
11928         return MaybeBindToTemporary(TheCall);
11929       } else {
11930         // We matched a built-in operator. Convert the arguments, then
11931         // break out so that we will build the appropriate built-in
11932         // operator node.
11933         ExprResult ArgsRes0 =
11934           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11935                                     Best->Conversions[0], AA_Passing);
11936         if (ArgsRes0.isInvalid())
11937           return ExprError();
11938         Args[0] = ArgsRes0.get();
11939 
11940         ExprResult ArgsRes1 =
11941           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11942                                     Best->Conversions[1], AA_Passing);
11943         if (ArgsRes1.isInvalid())
11944           return ExprError();
11945         Args[1] = ArgsRes1.get();
11946         break;
11947       }
11948     }
11949 
11950     case OR_No_Viable_Function: {
11951       // C++ [over.match.oper]p9:
11952       //   If the operator is the operator , [...] and there are no
11953       //   viable functions, then the operator is assumed to be the
11954       //   built-in operator and interpreted according to clause 5.
11955       if (Opc == BO_Comma)
11956         break;
11957 
11958       // For class as left operand for assignment or compound assigment
11959       // operator do not fall through to handling in built-in, but report that
11960       // no overloaded assignment operator found
11961       ExprResult Result = ExprError();
11962       if (Args[0]->getType()->isRecordType() &&
11963           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11964         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11965              << BinaryOperator::getOpcodeStr(Opc)
11966              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11967         if (Args[0]->getType()->isIncompleteType()) {
11968           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11969             << Args[0]->getType()
11970             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11971         }
11972       } else {
11973         // This is an erroneous use of an operator which can be overloaded by
11974         // a non-member function. Check for non-member operators which were
11975         // defined too late to be candidates.
11976         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11977           // FIXME: Recover by calling the found function.
11978           return ExprError();
11979 
11980         // No viable function; try to create a built-in operation, which will
11981         // produce an error. Then, show the non-viable candidates.
11982         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11983       }
11984       assert(Result.isInvalid() &&
11985              "C++ binary operator overloading is missing candidates!");
11986       if (Result.isInvalid())
11987         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11988                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11989       return Result;
11990     }
11991 
11992     case OR_Ambiguous:
11993       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11994           << BinaryOperator::getOpcodeStr(Opc)
11995           << Args[0]->getType() << Args[1]->getType()
11996           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11997       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11998                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11999       return ExprError();
12000 
12001     case OR_Deleted:
12002       if (isImplicitlyDeleted(Best->Function)) {
12003         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12004         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12005           << Context.getRecordType(Method->getParent())
12006           << getSpecialMember(Method);
12007 
12008         // The user probably meant to call this special member. Just
12009         // explain why it's deleted.
12010         NoteDeletedFunction(Method);
12011         return ExprError();
12012       } else {
12013         Diag(OpLoc, diag::err_ovl_deleted_oper)
12014           << Best->Function->isDeleted()
12015           << BinaryOperator::getOpcodeStr(Opc)
12016           << getDeletedOrUnavailableSuffix(Best->Function)
12017           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12018       }
12019       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12020                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12021       return ExprError();
12022   }
12023 
12024   // We matched a built-in operator; build it.
12025   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12026 }
12027 
12028 ExprResult
12029 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12030                                          SourceLocation RLoc,
12031                                          Expr *Base, Expr *Idx) {
12032   Expr *Args[2] = { Base, Idx };
12033   DeclarationName OpName =
12034       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12035 
12036   // If either side is type-dependent, create an appropriate dependent
12037   // expression.
12038   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12039 
12040     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12041     // CHECKME: no 'operator' keyword?
12042     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12043     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12044     UnresolvedLookupExpr *Fn
12045       = UnresolvedLookupExpr::Create(Context, NamingClass,
12046                                      NestedNameSpecifierLoc(), OpNameInfo,
12047                                      /*ADL*/ true, /*Overloaded*/ false,
12048                                      UnresolvedSetIterator(),
12049                                      UnresolvedSetIterator());
12050     // Can't add any actual overloads yet
12051 
12052     return new (Context)
12053         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12054                             Context.DependentTy, VK_RValue, RLoc, false);
12055   }
12056 
12057   // Handle placeholders on both operands.
12058   if (checkPlaceholderForOverload(*this, Args[0]))
12059     return ExprError();
12060   if (checkPlaceholderForOverload(*this, Args[1]))
12061     return ExprError();
12062 
12063   // Build an empty overload set.
12064   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12065 
12066   // Subscript can only be overloaded as a member function.
12067 
12068   // Add operator candidates that are member functions.
12069   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12070 
12071   // Add builtin operator candidates.
12072   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12073 
12074   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12075 
12076   // Perform overload resolution.
12077   OverloadCandidateSet::iterator Best;
12078   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12079     case OR_Success: {
12080       // We found a built-in operator or an overloaded operator.
12081       FunctionDecl *FnDecl = Best->Function;
12082 
12083       if (FnDecl) {
12084         // We matched an overloaded operator. Build a call to that
12085         // operator.
12086 
12087         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12088 
12089         // Convert the arguments.
12090         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12091         ExprResult Arg0 =
12092           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12093                                               Best->FoundDecl, Method);
12094         if (Arg0.isInvalid())
12095           return ExprError();
12096         Args[0] = Arg0.get();
12097 
12098         // Convert the arguments.
12099         ExprResult InputInit
12100           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12101                                                       Context,
12102                                                       FnDecl->getParamDecl(0)),
12103                                       SourceLocation(),
12104                                       Args[1]);
12105         if (InputInit.isInvalid())
12106           return ExprError();
12107 
12108         Args[1] = InputInit.getAs<Expr>();
12109 
12110         // Build the actual expression node.
12111         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12112         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12113         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12114                                                   Best->FoundDecl,
12115                                                   HadMultipleCandidates,
12116                                                   OpLocInfo.getLoc(),
12117                                                   OpLocInfo.getInfo());
12118         if (FnExpr.isInvalid())
12119           return ExprError();
12120 
12121         // Determine the result type
12122         QualType ResultTy = FnDecl->getReturnType();
12123         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12124         ResultTy = ResultTy.getNonLValueExprType(Context);
12125 
12126         CXXOperatorCallExpr *TheCall =
12127           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12128                                             FnExpr.get(), Args,
12129                                             ResultTy, VK, RLoc,
12130                                             false);
12131 
12132         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12133           return ExprError();
12134 
12135         return MaybeBindToTemporary(TheCall);
12136       } else {
12137         // We matched a built-in operator. Convert the arguments, then
12138         // break out so that we will build the appropriate built-in
12139         // operator node.
12140         ExprResult ArgsRes0 =
12141           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12142                                     Best->Conversions[0], AA_Passing);
12143         if (ArgsRes0.isInvalid())
12144           return ExprError();
12145         Args[0] = ArgsRes0.get();
12146 
12147         ExprResult ArgsRes1 =
12148           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12149                                     Best->Conversions[1], AA_Passing);
12150         if (ArgsRes1.isInvalid())
12151           return ExprError();
12152         Args[1] = ArgsRes1.get();
12153 
12154         break;
12155       }
12156     }
12157 
12158     case OR_No_Viable_Function: {
12159       if (CandidateSet.empty())
12160         Diag(LLoc, diag::err_ovl_no_oper)
12161           << Args[0]->getType() << /*subscript*/ 0
12162           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12163       else
12164         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12165           << Args[0]->getType()
12166           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12167       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12168                                   "[]", LLoc);
12169       return ExprError();
12170     }
12171 
12172     case OR_Ambiguous:
12173       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12174           << "[]"
12175           << Args[0]->getType() << Args[1]->getType()
12176           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12177       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12178                                   "[]", LLoc);
12179       return ExprError();
12180 
12181     case OR_Deleted:
12182       Diag(LLoc, diag::err_ovl_deleted_oper)
12183         << Best->Function->isDeleted() << "[]"
12184         << getDeletedOrUnavailableSuffix(Best->Function)
12185         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12186       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12187                                   "[]", LLoc);
12188       return ExprError();
12189     }
12190 
12191   // We matched a built-in operator; build it.
12192   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12193 }
12194 
12195 /// BuildCallToMemberFunction - Build a call to a member
12196 /// function. MemExpr is the expression that refers to the member
12197 /// function (and includes the object parameter), Args/NumArgs are the
12198 /// arguments to the function call (not including the object
12199 /// parameter). The caller needs to validate that the member
12200 /// expression refers to a non-static member function or an overloaded
12201 /// member function.
12202 ExprResult
12203 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12204                                 SourceLocation LParenLoc,
12205                                 MultiExprArg Args,
12206                                 SourceLocation RParenLoc) {
12207   assert(MemExprE->getType() == Context.BoundMemberTy ||
12208          MemExprE->getType() == Context.OverloadTy);
12209 
12210   // Dig out the member expression. This holds both the object
12211   // argument and the member function we're referring to.
12212   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12213 
12214   // Determine whether this is a call to a pointer-to-member function.
12215   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12216     assert(op->getType() == Context.BoundMemberTy);
12217     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12218 
12219     QualType fnType =
12220       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12221 
12222     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12223     QualType resultType = proto->getCallResultType(Context);
12224     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12225 
12226     // Check that the object type isn't more qualified than the
12227     // member function we're calling.
12228     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12229 
12230     QualType objectType = op->getLHS()->getType();
12231     if (op->getOpcode() == BO_PtrMemI)
12232       objectType = objectType->castAs<PointerType>()->getPointeeType();
12233     Qualifiers objectQuals = objectType.getQualifiers();
12234 
12235     Qualifiers difference = objectQuals - funcQuals;
12236     difference.removeObjCGCAttr();
12237     difference.removeAddressSpace();
12238     if (difference) {
12239       std::string qualsString = difference.getAsString();
12240       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12241         << fnType.getUnqualifiedType()
12242         << qualsString
12243         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12244     }
12245 
12246     CXXMemberCallExpr *call
12247       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12248                                         resultType, valueKind, RParenLoc);
12249 
12250     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12251                             call, nullptr))
12252       return ExprError();
12253 
12254     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12255       return ExprError();
12256 
12257     if (CheckOtherCall(call, proto))
12258       return ExprError();
12259 
12260     return MaybeBindToTemporary(call);
12261   }
12262 
12263   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12264     return new (Context)
12265         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12266 
12267   UnbridgedCastsSet UnbridgedCasts;
12268   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12269     return ExprError();
12270 
12271   MemberExpr *MemExpr;
12272   CXXMethodDecl *Method = nullptr;
12273   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12274   NestedNameSpecifier *Qualifier = nullptr;
12275   if (isa<MemberExpr>(NakedMemExpr)) {
12276     MemExpr = cast<MemberExpr>(NakedMemExpr);
12277     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12278     FoundDecl = MemExpr->getFoundDecl();
12279     Qualifier = MemExpr->getQualifier();
12280     UnbridgedCasts.restore();
12281   } else {
12282     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12283     Qualifier = UnresExpr->getQualifier();
12284 
12285     QualType ObjectType = UnresExpr->getBaseType();
12286     Expr::Classification ObjectClassification
12287       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12288                             : UnresExpr->getBase()->Classify(Context);
12289 
12290     // Add overload candidates
12291     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12292                                       OverloadCandidateSet::CSK_Normal);
12293 
12294     // FIXME: avoid copy.
12295     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12296     if (UnresExpr->hasExplicitTemplateArgs()) {
12297       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12298       TemplateArgs = &TemplateArgsBuffer;
12299     }
12300 
12301     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12302            E = UnresExpr->decls_end(); I != E; ++I) {
12303 
12304       NamedDecl *Func = *I;
12305       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12306       if (isa<UsingShadowDecl>(Func))
12307         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12308 
12309 
12310       // Microsoft supports direct constructor calls.
12311       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12312         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12313                              Args, CandidateSet);
12314       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12315         // If explicit template arguments were provided, we can't call a
12316         // non-template member function.
12317         if (TemplateArgs)
12318           continue;
12319 
12320         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12321                            ObjectClassification, Args, CandidateSet,
12322                            /*SuppressUserConversions=*/false);
12323       } else {
12324         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12325                                    I.getPair(), ActingDC, TemplateArgs,
12326                                    ObjectType,  ObjectClassification,
12327                                    Args, CandidateSet,
12328                                    /*SuppressUsedConversions=*/false);
12329       }
12330     }
12331 
12332     DeclarationName DeclName = UnresExpr->getMemberName();
12333 
12334     UnbridgedCasts.restore();
12335 
12336     OverloadCandidateSet::iterator Best;
12337     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12338                                             Best)) {
12339     case OR_Success:
12340       Method = cast<CXXMethodDecl>(Best->Function);
12341       FoundDecl = Best->FoundDecl;
12342       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12343       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12344         return ExprError();
12345       // If FoundDecl is different from Method (such as if one is a template
12346       // and the other a specialization), make sure DiagnoseUseOfDecl is
12347       // called on both.
12348       // FIXME: This would be more comprehensively addressed by modifying
12349       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12350       // being used.
12351       if (Method != FoundDecl.getDecl() &&
12352                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12353         return ExprError();
12354       break;
12355 
12356     case OR_No_Viable_Function:
12357       Diag(UnresExpr->getMemberLoc(),
12358            diag::err_ovl_no_viable_member_function_in_call)
12359         << DeclName << MemExprE->getSourceRange();
12360       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12361       // FIXME: Leaking incoming expressions!
12362       return ExprError();
12363 
12364     case OR_Ambiguous:
12365       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12366         << DeclName << MemExprE->getSourceRange();
12367       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12368       // FIXME: Leaking incoming expressions!
12369       return ExprError();
12370 
12371     case OR_Deleted:
12372       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12373         << Best->Function->isDeleted()
12374         << DeclName
12375         << getDeletedOrUnavailableSuffix(Best->Function)
12376         << MemExprE->getSourceRange();
12377       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12378       // FIXME: Leaking incoming expressions!
12379       return ExprError();
12380     }
12381 
12382     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12383 
12384     // If overload resolution picked a static member, build a
12385     // non-member call based on that function.
12386     if (Method->isStatic()) {
12387       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12388                                    RParenLoc);
12389     }
12390 
12391     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12392   }
12393 
12394   QualType ResultType = Method->getReturnType();
12395   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12396   ResultType = ResultType.getNonLValueExprType(Context);
12397 
12398   assert(Method && "Member call to something that isn't a method?");
12399   CXXMemberCallExpr *TheCall =
12400     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12401                                     ResultType, VK, RParenLoc);
12402 
12403   // Check for a valid return type.
12404   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12405                           TheCall, Method))
12406     return ExprError();
12407 
12408   // Convert the object argument (for a non-static member function call).
12409   // We only need to do this if there was actually an overload; otherwise
12410   // it was done at lookup.
12411   if (!Method->isStatic()) {
12412     ExprResult ObjectArg =
12413       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12414                                           FoundDecl, Method);
12415     if (ObjectArg.isInvalid())
12416       return ExprError();
12417     MemExpr->setBase(ObjectArg.get());
12418   }
12419 
12420   // Convert the rest of the arguments
12421   const FunctionProtoType *Proto =
12422     Method->getType()->getAs<FunctionProtoType>();
12423   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12424                               RParenLoc))
12425     return ExprError();
12426 
12427   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12428 
12429   if (CheckFunctionCall(Method, TheCall, Proto))
12430     return ExprError();
12431 
12432   // In the case the method to call was not selected by the overloading
12433   // resolution process, we still need to handle the enable_if attribute. Do
12434   // that here, so it will not hide previous -- and more relevant -- errors
12435   if (isa<MemberExpr>(NakedMemExpr)) {
12436     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12437       Diag(MemExprE->getLocStart(),
12438            diag::err_ovl_no_viable_member_function_in_call)
12439           << Method << Method->getSourceRange();
12440       Diag(Method->getLocation(),
12441            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12442           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12443       return ExprError();
12444     }
12445   }
12446 
12447   if ((isa<CXXConstructorDecl>(CurContext) ||
12448        isa<CXXDestructorDecl>(CurContext)) &&
12449       TheCall->getMethodDecl()->isPure()) {
12450     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12451 
12452     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12453         MemExpr->performsVirtualDispatch(getLangOpts())) {
12454       Diag(MemExpr->getLocStart(),
12455            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12456         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12457         << MD->getParent()->getDeclName();
12458 
12459       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12460       if (getLangOpts().AppleKext)
12461         Diag(MemExpr->getLocStart(),
12462              diag::note_pure_qualified_call_kext)
12463              << MD->getParent()->getDeclName()
12464              << MD->getDeclName();
12465     }
12466   }
12467 
12468   if (CXXDestructorDecl *DD =
12469           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12470     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12471     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12472     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12473                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12474                          MemExpr->getMemberLoc());
12475   }
12476 
12477   return MaybeBindToTemporary(TheCall);
12478 }
12479 
12480 /// BuildCallToObjectOfClassType - Build a call to an object of class
12481 /// type (C++ [over.call.object]), which can end up invoking an
12482 /// overloaded function call operator (@c operator()) or performing a
12483 /// user-defined conversion on the object argument.
12484 ExprResult
12485 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12486                                    SourceLocation LParenLoc,
12487                                    MultiExprArg Args,
12488                                    SourceLocation RParenLoc) {
12489   if (checkPlaceholderForOverload(*this, Obj))
12490     return ExprError();
12491   ExprResult Object = Obj;
12492 
12493   UnbridgedCastsSet UnbridgedCasts;
12494   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12495     return ExprError();
12496 
12497   assert(Object.get()->getType()->isRecordType() &&
12498          "Requires object type argument");
12499   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12500 
12501   // C++ [over.call.object]p1:
12502   //  If the primary-expression E in the function call syntax
12503   //  evaluates to a class object of type "cv T", then the set of
12504   //  candidate functions includes at least the function call
12505   //  operators of T. The function call operators of T are obtained by
12506   //  ordinary lookup of the name operator() in the context of
12507   //  (E).operator().
12508   OverloadCandidateSet CandidateSet(LParenLoc,
12509                                     OverloadCandidateSet::CSK_Operator);
12510   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12511 
12512   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12513                           diag::err_incomplete_object_call, Object.get()))
12514     return true;
12515 
12516   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12517   LookupQualifiedName(R, Record->getDecl());
12518   R.suppressDiagnostics();
12519 
12520   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12521        Oper != OperEnd; ++Oper) {
12522     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12523                        Object.get()->Classify(Context),
12524                        Args, CandidateSet,
12525                        /*SuppressUserConversions=*/ false);
12526   }
12527 
12528   // C++ [over.call.object]p2:
12529   //   In addition, for each (non-explicit in C++0x) conversion function
12530   //   declared in T of the form
12531   //
12532   //        operator conversion-type-id () cv-qualifier;
12533   //
12534   //   where cv-qualifier is the same cv-qualification as, or a
12535   //   greater cv-qualification than, cv, and where conversion-type-id
12536   //   denotes the type "pointer to function of (P1,...,Pn) returning
12537   //   R", or the type "reference to pointer to function of
12538   //   (P1,...,Pn) returning R", or the type "reference to function
12539   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12540   //   is also considered as a candidate function. Similarly,
12541   //   surrogate call functions are added to the set of candidate
12542   //   functions for each conversion function declared in an
12543   //   accessible base class provided the function is not hidden
12544   //   within T by another intervening declaration.
12545   const auto &Conversions =
12546       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12547   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12548     NamedDecl *D = *I;
12549     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12550     if (isa<UsingShadowDecl>(D))
12551       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12552 
12553     // Skip over templated conversion functions; they aren't
12554     // surrogates.
12555     if (isa<FunctionTemplateDecl>(D))
12556       continue;
12557 
12558     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12559     if (!Conv->isExplicit()) {
12560       // Strip the reference type (if any) and then the pointer type (if
12561       // any) to get down to what might be a function type.
12562       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12563       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12564         ConvType = ConvPtrType->getPointeeType();
12565 
12566       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12567       {
12568         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12569                               Object.get(), Args, CandidateSet);
12570       }
12571     }
12572   }
12573 
12574   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12575 
12576   // Perform overload resolution.
12577   OverloadCandidateSet::iterator Best;
12578   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12579                              Best)) {
12580   case OR_Success:
12581     // Overload resolution succeeded; we'll build the appropriate call
12582     // below.
12583     break;
12584 
12585   case OR_No_Viable_Function:
12586     if (CandidateSet.empty())
12587       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12588         << Object.get()->getType() << /*call*/ 1
12589         << Object.get()->getSourceRange();
12590     else
12591       Diag(Object.get()->getLocStart(),
12592            diag::err_ovl_no_viable_object_call)
12593         << Object.get()->getType() << Object.get()->getSourceRange();
12594     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12595     break;
12596 
12597   case OR_Ambiguous:
12598     Diag(Object.get()->getLocStart(),
12599          diag::err_ovl_ambiguous_object_call)
12600       << Object.get()->getType() << Object.get()->getSourceRange();
12601     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12602     break;
12603 
12604   case OR_Deleted:
12605     Diag(Object.get()->getLocStart(),
12606          diag::err_ovl_deleted_object_call)
12607       << Best->Function->isDeleted()
12608       << Object.get()->getType()
12609       << getDeletedOrUnavailableSuffix(Best->Function)
12610       << Object.get()->getSourceRange();
12611     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12612     break;
12613   }
12614 
12615   if (Best == CandidateSet.end())
12616     return true;
12617 
12618   UnbridgedCasts.restore();
12619 
12620   if (Best->Function == nullptr) {
12621     // Since there is no function declaration, this is one of the
12622     // surrogate candidates. Dig out the conversion function.
12623     CXXConversionDecl *Conv
12624       = cast<CXXConversionDecl>(
12625                          Best->Conversions[0].UserDefined.ConversionFunction);
12626 
12627     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12628                               Best->FoundDecl);
12629     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12630       return ExprError();
12631     assert(Conv == Best->FoundDecl.getDecl() &&
12632              "Found Decl & conversion-to-functionptr should be same, right?!");
12633     // We selected one of the surrogate functions that converts the
12634     // object parameter to a function pointer. Perform the conversion
12635     // on the object argument, then let ActOnCallExpr finish the job.
12636 
12637     // Create an implicit member expr to refer to the conversion operator.
12638     // and then call it.
12639     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12640                                              Conv, HadMultipleCandidates);
12641     if (Call.isInvalid())
12642       return ExprError();
12643     // Record usage of conversion in an implicit cast.
12644     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12645                                     CK_UserDefinedConversion, Call.get(),
12646                                     nullptr, VK_RValue);
12647 
12648     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12649   }
12650 
12651   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12652 
12653   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12654   // that calls this method, using Object for the implicit object
12655   // parameter and passing along the remaining arguments.
12656   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12657 
12658   // An error diagnostic has already been printed when parsing the declaration.
12659   if (Method->isInvalidDecl())
12660     return ExprError();
12661 
12662   const FunctionProtoType *Proto =
12663     Method->getType()->getAs<FunctionProtoType>();
12664 
12665   unsigned NumParams = Proto->getNumParams();
12666 
12667   DeclarationNameInfo OpLocInfo(
12668                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12669   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12670   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12671                                            HadMultipleCandidates,
12672                                            OpLocInfo.getLoc(),
12673                                            OpLocInfo.getInfo());
12674   if (NewFn.isInvalid())
12675     return true;
12676 
12677   // Build the full argument list for the method call (the implicit object
12678   // parameter is placed at the beginning of the list).
12679   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12680   MethodArgs[0] = Object.get();
12681   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12682 
12683   // Once we've built TheCall, all of the expressions are properly
12684   // owned.
12685   QualType ResultTy = Method->getReturnType();
12686   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12687   ResultTy = ResultTy.getNonLValueExprType(Context);
12688 
12689   CXXOperatorCallExpr *TheCall = new (Context)
12690       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12691                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12692                           ResultTy, VK, RParenLoc, false);
12693   MethodArgs.reset();
12694 
12695   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12696     return true;
12697 
12698   // We may have default arguments. If so, we need to allocate more
12699   // slots in the call for them.
12700   if (Args.size() < NumParams)
12701     TheCall->setNumArgs(Context, NumParams + 1);
12702 
12703   bool IsError = false;
12704 
12705   // Initialize the implicit object parameter.
12706   ExprResult ObjRes =
12707     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12708                                         Best->FoundDecl, Method);
12709   if (ObjRes.isInvalid())
12710     IsError = true;
12711   else
12712     Object = ObjRes;
12713   TheCall->setArg(0, Object.get());
12714 
12715   // Check the argument types.
12716   for (unsigned i = 0; i != NumParams; i++) {
12717     Expr *Arg;
12718     if (i < Args.size()) {
12719       Arg = Args[i];
12720 
12721       // Pass the argument.
12722 
12723       ExprResult InputInit
12724         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12725                                                     Context,
12726                                                     Method->getParamDecl(i)),
12727                                     SourceLocation(), Arg);
12728 
12729       IsError |= InputInit.isInvalid();
12730       Arg = InputInit.getAs<Expr>();
12731     } else {
12732       ExprResult DefArg
12733         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12734       if (DefArg.isInvalid()) {
12735         IsError = true;
12736         break;
12737       }
12738 
12739       Arg = DefArg.getAs<Expr>();
12740     }
12741 
12742     TheCall->setArg(i + 1, Arg);
12743   }
12744 
12745   // If this is a variadic call, handle args passed through "...".
12746   if (Proto->isVariadic()) {
12747     // Promote the arguments (C99 6.5.2.2p7).
12748     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12749       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12750                                                         nullptr);
12751       IsError |= Arg.isInvalid();
12752       TheCall->setArg(i + 1, Arg.get());
12753     }
12754   }
12755 
12756   if (IsError) return true;
12757 
12758   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12759 
12760   if (CheckFunctionCall(Method, TheCall, Proto))
12761     return true;
12762 
12763   return MaybeBindToTemporary(TheCall);
12764 }
12765 
12766 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12767 ///  (if one exists), where @c Base is an expression of class type and
12768 /// @c Member is the name of the member we're trying to find.
12769 ExprResult
12770 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12771                                bool *NoArrowOperatorFound) {
12772   assert(Base->getType()->isRecordType() &&
12773          "left-hand side must have class type");
12774 
12775   if (checkPlaceholderForOverload(*this, Base))
12776     return ExprError();
12777 
12778   SourceLocation Loc = Base->getExprLoc();
12779 
12780   // C++ [over.ref]p1:
12781   //
12782   //   [...] An expression x->m is interpreted as (x.operator->())->m
12783   //   for a class object x of type T if T::operator->() exists and if
12784   //   the operator is selected as the best match function by the
12785   //   overload resolution mechanism (13.3).
12786   DeclarationName OpName =
12787     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12788   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12789   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12790 
12791   if (RequireCompleteType(Loc, Base->getType(),
12792                           diag::err_typecheck_incomplete_tag, Base))
12793     return ExprError();
12794 
12795   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12796   LookupQualifiedName(R, BaseRecord->getDecl());
12797   R.suppressDiagnostics();
12798 
12799   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12800        Oper != OperEnd; ++Oper) {
12801     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12802                        None, CandidateSet, /*SuppressUserConversions=*/false);
12803   }
12804 
12805   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12806 
12807   // Perform overload resolution.
12808   OverloadCandidateSet::iterator Best;
12809   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12810   case OR_Success:
12811     // Overload resolution succeeded; we'll build the call below.
12812     break;
12813 
12814   case OR_No_Viable_Function:
12815     if (CandidateSet.empty()) {
12816       QualType BaseType = Base->getType();
12817       if (NoArrowOperatorFound) {
12818         // Report this specific error to the caller instead of emitting a
12819         // diagnostic, as requested.
12820         *NoArrowOperatorFound = true;
12821         return ExprError();
12822       }
12823       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12824         << BaseType << Base->getSourceRange();
12825       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12826         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12827           << FixItHint::CreateReplacement(OpLoc, ".");
12828       }
12829     } else
12830       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12831         << "operator->" << Base->getSourceRange();
12832     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12833     return ExprError();
12834 
12835   case OR_Ambiguous:
12836     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12837       << "->" << Base->getType() << Base->getSourceRange();
12838     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12839     return ExprError();
12840 
12841   case OR_Deleted:
12842     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12843       << Best->Function->isDeleted()
12844       << "->"
12845       << getDeletedOrUnavailableSuffix(Best->Function)
12846       << Base->getSourceRange();
12847     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12848     return ExprError();
12849   }
12850 
12851   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12852 
12853   // Convert the object parameter.
12854   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12855   ExprResult BaseResult =
12856     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12857                                         Best->FoundDecl, Method);
12858   if (BaseResult.isInvalid())
12859     return ExprError();
12860   Base = BaseResult.get();
12861 
12862   // Build the operator call.
12863   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12864                                             HadMultipleCandidates, OpLoc);
12865   if (FnExpr.isInvalid())
12866     return ExprError();
12867 
12868   QualType ResultTy = Method->getReturnType();
12869   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12870   ResultTy = ResultTy.getNonLValueExprType(Context);
12871   CXXOperatorCallExpr *TheCall =
12872     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12873                                       Base, ResultTy, VK, OpLoc, false);
12874 
12875   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12876           return ExprError();
12877 
12878   return MaybeBindToTemporary(TheCall);
12879 }
12880 
12881 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12882 /// a literal operator described by the provided lookup results.
12883 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12884                                           DeclarationNameInfo &SuffixInfo,
12885                                           ArrayRef<Expr*> Args,
12886                                           SourceLocation LitEndLoc,
12887                                        TemplateArgumentListInfo *TemplateArgs) {
12888   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12889 
12890   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12891                                     OverloadCandidateSet::CSK_Normal);
12892   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12893                         /*SuppressUserConversions=*/true);
12894 
12895   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12896 
12897   // Perform overload resolution. This will usually be trivial, but might need
12898   // to perform substitutions for a literal operator template.
12899   OverloadCandidateSet::iterator Best;
12900   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12901   case OR_Success:
12902   case OR_Deleted:
12903     break;
12904 
12905   case OR_No_Viable_Function:
12906     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12907       << R.getLookupName();
12908     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12909     return ExprError();
12910 
12911   case OR_Ambiguous:
12912     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12913     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12914     return ExprError();
12915   }
12916 
12917   FunctionDecl *FD = Best->Function;
12918   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12919                                         HadMultipleCandidates,
12920                                         SuffixInfo.getLoc(),
12921                                         SuffixInfo.getInfo());
12922   if (Fn.isInvalid())
12923     return true;
12924 
12925   // Check the argument types. This should almost always be a no-op, except
12926   // that array-to-pointer decay is applied to string literals.
12927   Expr *ConvArgs[2];
12928   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12929     ExprResult InputInit = PerformCopyInitialization(
12930       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12931       SourceLocation(), Args[ArgIdx]);
12932     if (InputInit.isInvalid())
12933       return true;
12934     ConvArgs[ArgIdx] = InputInit.get();
12935   }
12936 
12937   QualType ResultTy = FD->getReturnType();
12938   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12939   ResultTy = ResultTy.getNonLValueExprType(Context);
12940 
12941   UserDefinedLiteral *UDL =
12942     new (Context) UserDefinedLiteral(Context, Fn.get(),
12943                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12944                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12945 
12946   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12947     return ExprError();
12948 
12949   if (CheckFunctionCall(FD, UDL, nullptr))
12950     return ExprError();
12951 
12952   return MaybeBindToTemporary(UDL);
12953 }
12954 
12955 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12956 /// given LookupResult is non-empty, it is assumed to describe a member which
12957 /// will be invoked. Otherwise, the function will be found via argument
12958 /// dependent lookup.
12959 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12960 /// otherwise CallExpr is set to ExprError() and some non-success value
12961 /// is returned.
12962 Sema::ForRangeStatus
12963 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12964                                 SourceLocation RangeLoc,
12965                                 const DeclarationNameInfo &NameInfo,
12966                                 LookupResult &MemberLookup,
12967                                 OverloadCandidateSet *CandidateSet,
12968                                 Expr *Range, ExprResult *CallExpr) {
12969   Scope *S = nullptr;
12970 
12971   CandidateSet->clear();
12972   if (!MemberLookup.empty()) {
12973     ExprResult MemberRef =
12974         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12975                                  /*IsPtr=*/false, CXXScopeSpec(),
12976                                  /*TemplateKWLoc=*/SourceLocation(),
12977                                  /*FirstQualifierInScope=*/nullptr,
12978                                  MemberLookup,
12979                                  /*TemplateArgs=*/nullptr, S);
12980     if (MemberRef.isInvalid()) {
12981       *CallExpr = ExprError();
12982       return FRS_DiagnosticIssued;
12983     }
12984     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12985     if (CallExpr->isInvalid()) {
12986       *CallExpr = ExprError();
12987       return FRS_DiagnosticIssued;
12988     }
12989   } else {
12990     UnresolvedSet<0> FoundNames;
12991     UnresolvedLookupExpr *Fn =
12992       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12993                                    NestedNameSpecifierLoc(), NameInfo,
12994                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12995                                    FoundNames.begin(), FoundNames.end());
12996 
12997     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12998                                                     CandidateSet, CallExpr);
12999     if (CandidateSet->empty() || CandidateSetError) {
13000       *CallExpr = ExprError();
13001       return FRS_NoViableFunction;
13002     }
13003     OverloadCandidateSet::iterator Best;
13004     OverloadingResult OverloadResult =
13005         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13006 
13007     if (OverloadResult == OR_No_Viable_Function) {
13008       *CallExpr = ExprError();
13009       return FRS_NoViableFunction;
13010     }
13011     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13012                                          Loc, nullptr, CandidateSet, &Best,
13013                                          OverloadResult,
13014                                          /*AllowTypoCorrection=*/false);
13015     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13016       *CallExpr = ExprError();
13017       return FRS_DiagnosticIssued;
13018     }
13019   }
13020   return FRS_Success;
13021 }
13022 
13023 
13024 /// FixOverloadedFunctionReference - E is an expression that refers to
13025 /// a C++ overloaded function (possibly with some parentheses and
13026 /// perhaps a '&' around it). We have resolved the overloaded function
13027 /// to the function declaration Fn, so patch up the expression E to
13028 /// refer (possibly indirectly) to Fn. Returns the new expr.
13029 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13030                                            FunctionDecl *Fn) {
13031   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13032     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13033                                                    Found, Fn);
13034     if (SubExpr == PE->getSubExpr())
13035       return PE;
13036 
13037     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13038   }
13039 
13040   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13041     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13042                                                    Found, Fn);
13043     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13044                                SubExpr->getType()) &&
13045            "Implicit cast type cannot be determined from overload");
13046     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13047     if (SubExpr == ICE->getSubExpr())
13048       return ICE;
13049 
13050     return ImplicitCastExpr::Create(Context, ICE->getType(),
13051                                     ICE->getCastKind(),
13052                                     SubExpr, nullptr,
13053                                     ICE->getValueKind());
13054   }
13055 
13056   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13057     if (!GSE->isResultDependent()) {
13058       Expr *SubExpr =
13059           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13060       if (SubExpr == GSE->getResultExpr())
13061         return GSE;
13062 
13063       // Replace the resulting type information before rebuilding the generic
13064       // selection expression.
13065       ArrayRef<Expr *> A = GSE->getAssocExprs();
13066       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13067       unsigned ResultIdx = GSE->getResultIndex();
13068       AssocExprs[ResultIdx] = SubExpr;
13069 
13070       return new (Context) GenericSelectionExpr(
13071           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13072           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13073           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13074           ResultIdx);
13075     }
13076     // Rather than fall through to the unreachable, return the original generic
13077     // selection expression.
13078     return GSE;
13079   }
13080 
13081   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13082     assert(UnOp->getOpcode() == UO_AddrOf &&
13083            "Can only take the address of an overloaded function");
13084     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13085       if (Method->isStatic()) {
13086         // Do nothing: static member functions aren't any different
13087         // from non-member functions.
13088       } else {
13089         // Fix the subexpression, which really has to be an
13090         // UnresolvedLookupExpr holding an overloaded member function
13091         // or template.
13092         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13093                                                        Found, Fn);
13094         if (SubExpr == UnOp->getSubExpr())
13095           return UnOp;
13096 
13097         assert(isa<DeclRefExpr>(SubExpr)
13098                && "fixed to something other than a decl ref");
13099         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13100                && "fixed to a member ref with no nested name qualifier");
13101 
13102         // We have taken the address of a pointer to member
13103         // function. Perform the computation here so that we get the
13104         // appropriate pointer to member type.
13105         QualType ClassType
13106           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13107         QualType MemPtrType
13108           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13109         // Under the MS ABI, lock down the inheritance model now.
13110         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13111           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13112 
13113         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13114                                            VK_RValue, OK_Ordinary,
13115                                            UnOp->getOperatorLoc());
13116       }
13117     }
13118     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13119                                                    Found, Fn);
13120     if (SubExpr == UnOp->getSubExpr())
13121       return UnOp;
13122 
13123     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13124                                      Context.getPointerType(SubExpr->getType()),
13125                                        VK_RValue, OK_Ordinary,
13126                                        UnOp->getOperatorLoc());
13127   }
13128 
13129   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13130     // FIXME: avoid copy.
13131     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13132     if (ULE->hasExplicitTemplateArgs()) {
13133       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13134       TemplateArgs = &TemplateArgsBuffer;
13135     }
13136 
13137     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13138                                            ULE->getQualifierLoc(),
13139                                            ULE->getTemplateKeywordLoc(),
13140                                            Fn,
13141                                            /*enclosing*/ false, // FIXME?
13142                                            ULE->getNameLoc(),
13143                                            Fn->getType(),
13144                                            VK_LValue,
13145                                            Found.getDecl(),
13146                                            TemplateArgs);
13147     MarkDeclRefReferenced(DRE);
13148     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13149     return DRE;
13150   }
13151 
13152   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13153     // FIXME: avoid copy.
13154     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13155     if (MemExpr->hasExplicitTemplateArgs()) {
13156       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13157       TemplateArgs = &TemplateArgsBuffer;
13158     }
13159 
13160     Expr *Base;
13161 
13162     // If we're filling in a static method where we used to have an
13163     // implicit member access, rewrite to a simple decl ref.
13164     if (MemExpr->isImplicitAccess()) {
13165       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13166         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13167                                                MemExpr->getQualifierLoc(),
13168                                                MemExpr->getTemplateKeywordLoc(),
13169                                                Fn,
13170                                                /*enclosing*/ false,
13171                                                MemExpr->getMemberLoc(),
13172                                                Fn->getType(),
13173                                                VK_LValue,
13174                                                Found.getDecl(),
13175                                                TemplateArgs);
13176         MarkDeclRefReferenced(DRE);
13177         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13178         return DRE;
13179       } else {
13180         SourceLocation Loc = MemExpr->getMemberLoc();
13181         if (MemExpr->getQualifier())
13182           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13183         CheckCXXThisCapture(Loc);
13184         Base = new (Context) CXXThisExpr(Loc,
13185                                          MemExpr->getBaseType(),
13186                                          /*isImplicit=*/true);
13187       }
13188     } else
13189       Base = MemExpr->getBase();
13190 
13191     ExprValueKind valueKind;
13192     QualType type;
13193     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13194       valueKind = VK_LValue;
13195       type = Fn->getType();
13196     } else {
13197       valueKind = VK_RValue;
13198       type = Context.BoundMemberTy;
13199     }
13200 
13201     MemberExpr *ME = MemberExpr::Create(
13202         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13203         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13204         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13205         OK_Ordinary);
13206     ME->setHadMultipleCandidates(true);
13207     MarkMemberReferenced(ME);
13208     return ME;
13209   }
13210 
13211   llvm_unreachable("Invalid reference to overloaded function");
13212 }
13213 
13214 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13215                                                 DeclAccessPair Found,
13216                                                 FunctionDecl *Fn) {
13217   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13218 }
13219