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     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1133                        OldTarget = IdentifyCUDATarget(Old);
1134     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1135       return false;
1136 
1137     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1138 
1139     // Don't allow mixing of HD with other kinds. This guarantees that
1140     // we have only one viable function with this signature on any
1141     // side of CUDA compilation .
1142     // __global__ functions can't be overloaded based on attribute
1143     // difference because, like HD, they also exist on both sides.
1144     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1145         (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1146       return false;
1147 
1148     // Allow overloading of functions with same signature, but
1149     // different CUDA target attributes.
1150     return NewTarget != OldTarget;
1151   }
1152 
1153   // The signatures match; this is not an overload.
1154   return false;
1155 }
1156 
1157 /// \brief Checks availability of the function depending on the current
1158 /// function context. Inside an unavailable function, unavailability is ignored.
1159 ///
1160 /// \returns true if \arg FD is unavailable and current context is inside
1161 /// an available function, false otherwise.
1162 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1163   if (!FD->isUnavailable())
1164     return false;
1165 
1166   // Walk up the context of the caller.
1167   Decl *C = cast<Decl>(CurContext);
1168   do {
1169     if (C->isUnavailable())
1170       return false;
1171   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1172   return true;
1173 }
1174 
1175 /// \brief Tries a user-defined conversion from From to ToType.
1176 ///
1177 /// Produces an implicit conversion sequence for when a standard conversion
1178 /// is not an option. See TryImplicitConversion for more information.
1179 static ImplicitConversionSequence
1180 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1181                          bool SuppressUserConversions,
1182                          bool AllowExplicit,
1183                          bool InOverloadResolution,
1184                          bool CStyle,
1185                          bool AllowObjCWritebackConversion,
1186                          bool AllowObjCConversionOnExplicit) {
1187   ImplicitConversionSequence ICS;
1188 
1189   if (SuppressUserConversions) {
1190     // We're not in the case above, so there is no conversion that
1191     // we can perform.
1192     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193     return ICS;
1194   }
1195 
1196   // Attempt user-defined conversion.
1197   OverloadCandidateSet Conversions(From->getExprLoc(),
1198                                    OverloadCandidateSet::CSK_Normal);
1199   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1200                                   Conversions, AllowExplicit,
1201                                   AllowObjCConversionOnExplicit)) {
1202   case OR_Success:
1203   case OR_Deleted:
1204     ICS.setUserDefined();
1205     // C++ [over.ics.user]p4:
1206     //   A conversion of an expression of class type to the same class
1207     //   type is given Exact Match rank, and a conversion of an
1208     //   expression of class type to a base class of that type is
1209     //   given Conversion rank, in spite of the fact that a copy
1210     //   constructor (i.e., a user-defined conversion function) is
1211     //   called for those cases.
1212     if (CXXConstructorDecl *Constructor
1213           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1214       QualType FromCanon
1215         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1216       QualType ToCanon
1217         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1218       if (Constructor->isCopyConstructor() &&
1219           (FromCanon == ToCanon ||
1220            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1221         // Turn this into a "standard" conversion sequence, so that it
1222         // gets ranked with standard conversion sequences.
1223         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1224         ICS.setStandard();
1225         ICS.Standard.setAsIdentityConversion();
1226         ICS.Standard.setFromType(From->getType());
1227         ICS.Standard.setAllToTypes(ToType);
1228         ICS.Standard.CopyConstructor = Constructor;
1229         ICS.Standard.FoundCopyConstructor = Found;
1230         if (ToCanon != FromCanon)
1231           ICS.Standard.Second = ICK_Derived_To_Base;
1232       }
1233     }
1234     break;
1235 
1236   case OR_Ambiguous:
1237     ICS.setAmbiguous();
1238     ICS.Ambiguous.setFromType(From->getType());
1239     ICS.Ambiguous.setToType(ToType);
1240     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1241          Cand != Conversions.end(); ++Cand)
1242       if (Cand->Viable)
1243         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1244     break;
1245 
1246     // Fall through.
1247   case OR_No_Viable_Function:
1248     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1249     break;
1250   }
1251 
1252   return ICS;
1253 }
1254 
1255 /// TryImplicitConversion - Attempt to perform an implicit conversion
1256 /// from the given expression (Expr) to the given type (ToType). This
1257 /// function returns an implicit conversion sequence that can be used
1258 /// to perform the initialization. Given
1259 ///
1260 ///   void f(float f);
1261 ///   void g(int i) { f(i); }
1262 ///
1263 /// this routine would produce an implicit conversion sequence to
1264 /// describe the initialization of f from i, which will be a standard
1265 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1266 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1267 //
1268 /// Note that this routine only determines how the conversion can be
1269 /// performed; it does not actually perform the conversion. As such,
1270 /// it will not produce any diagnostics if no conversion is available,
1271 /// but will instead return an implicit conversion sequence of kind
1272 /// "BadConversion".
1273 ///
1274 /// If @p SuppressUserConversions, then user-defined conversions are
1275 /// not permitted.
1276 /// If @p AllowExplicit, then explicit user-defined conversions are
1277 /// permitted.
1278 ///
1279 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1280 /// writeback conversion, which allows __autoreleasing id* parameters to
1281 /// be initialized with __strong id* or __weak id* arguments.
1282 static ImplicitConversionSequence
1283 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1284                       bool SuppressUserConversions,
1285                       bool AllowExplicit,
1286                       bool InOverloadResolution,
1287                       bool CStyle,
1288                       bool AllowObjCWritebackConversion,
1289                       bool AllowObjCConversionOnExplicit) {
1290   ImplicitConversionSequence ICS;
1291   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1292                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1293     ICS.setStandard();
1294     return ICS;
1295   }
1296 
1297   if (!S.getLangOpts().CPlusPlus) {
1298     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1299     return ICS;
1300   }
1301 
1302   // C++ [over.ics.user]p4:
1303   //   A conversion of an expression of class type to the same class
1304   //   type is given Exact Match rank, and a conversion of an
1305   //   expression of class type to a base class of that type is
1306   //   given Conversion rank, in spite of the fact that a copy/move
1307   //   constructor (i.e., a user-defined conversion function) is
1308   //   called for those cases.
1309   QualType FromType = From->getType();
1310   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1311       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1312        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1313     ICS.setStandard();
1314     ICS.Standard.setAsIdentityConversion();
1315     ICS.Standard.setFromType(FromType);
1316     ICS.Standard.setAllToTypes(ToType);
1317 
1318     // We don't actually check at this point whether there is a valid
1319     // copy/move constructor, since overloading just assumes that it
1320     // exists. When we actually perform initialization, we'll find the
1321     // appropriate constructor to copy the returned object, if needed.
1322     ICS.Standard.CopyConstructor = nullptr;
1323 
1324     // Determine whether this is considered a derived-to-base conversion.
1325     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1326       ICS.Standard.Second = ICK_Derived_To_Base;
1327 
1328     return ICS;
1329   }
1330 
1331   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1332                                   AllowExplicit, InOverloadResolution, CStyle,
1333                                   AllowObjCWritebackConversion,
1334                                   AllowObjCConversionOnExplicit);
1335 }
1336 
1337 ImplicitConversionSequence
1338 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1339                             bool SuppressUserConversions,
1340                             bool AllowExplicit,
1341                             bool InOverloadResolution,
1342                             bool CStyle,
1343                             bool AllowObjCWritebackConversion) {
1344   return ::TryImplicitConversion(*this, From, ToType,
1345                                  SuppressUserConversions, AllowExplicit,
1346                                  InOverloadResolution, CStyle,
1347                                  AllowObjCWritebackConversion,
1348                                  /*AllowObjCConversionOnExplicit=*/false);
1349 }
1350 
1351 /// PerformImplicitConversion - Perform an implicit conversion of the
1352 /// expression From to the type ToType. Returns the
1353 /// converted expression. Flavor is the kind of conversion we're
1354 /// performing, used in the error message. If @p AllowExplicit,
1355 /// explicit user-defined conversions are permitted.
1356 ExprResult
1357 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1358                                 AssignmentAction Action, bool AllowExplicit) {
1359   ImplicitConversionSequence ICS;
1360   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1361 }
1362 
1363 ExprResult
1364 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1365                                 AssignmentAction Action, bool AllowExplicit,
1366                                 ImplicitConversionSequence& ICS) {
1367   if (checkPlaceholderForOverload(*this, From))
1368     return ExprError();
1369 
1370   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1371   bool AllowObjCWritebackConversion
1372     = getLangOpts().ObjCAutoRefCount &&
1373       (Action == AA_Passing || Action == AA_Sending);
1374   if (getLangOpts().ObjC1)
1375     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1376                                       ToType, From->getType(), From);
1377   ICS = ::TryImplicitConversion(*this, From, ToType,
1378                                 /*SuppressUserConversions=*/false,
1379                                 AllowExplicit,
1380                                 /*InOverloadResolution=*/false,
1381                                 /*CStyle=*/false,
1382                                 AllowObjCWritebackConversion,
1383                                 /*AllowObjCConversionOnExplicit=*/false);
1384   return PerformImplicitConversion(From, ToType, ICS, Action);
1385 }
1386 
1387 /// \brief Determine whether the conversion from FromType to ToType is a valid
1388 /// conversion that strips "noreturn" off the nested function type.
1389 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1390                                 QualType &ResultTy) {
1391   if (Context.hasSameUnqualifiedType(FromType, ToType))
1392     return false;
1393 
1394   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1395   // where F adds one of the following at most once:
1396   //   - a pointer
1397   //   - a member pointer
1398   //   - a block pointer
1399   CanQualType CanTo = Context.getCanonicalType(ToType);
1400   CanQualType CanFrom = Context.getCanonicalType(FromType);
1401   Type::TypeClass TyClass = CanTo->getTypeClass();
1402   if (TyClass != CanFrom->getTypeClass()) return false;
1403   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1404     if (TyClass == Type::Pointer) {
1405       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1406       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1407     } else if (TyClass == Type::BlockPointer) {
1408       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1409       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1410     } else if (TyClass == Type::MemberPointer) {
1411       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1412       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1413     } else {
1414       return false;
1415     }
1416 
1417     TyClass = CanTo->getTypeClass();
1418     if (TyClass != CanFrom->getTypeClass()) return false;
1419     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1420       return false;
1421   }
1422 
1423   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1424   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1425   if (!EInfo.getNoReturn()) return false;
1426 
1427   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1428   assert(QualType(FromFn, 0).isCanonical());
1429   if (QualType(FromFn, 0) != CanTo) return false;
1430 
1431   ResultTy = ToType;
1432   return true;
1433 }
1434 
1435 /// \brief Determine whether the conversion from FromType to ToType is a valid
1436 /// vector conversion.
1437 ///
1438 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1439 /// conversion.
1440 static bool IsVectorConversion(Sema &S, QualType FromType,
1441                                QualType ToType, ImplicitConversionKind &ICK) {
1442   // We need at least one of these types to be a vector type to have a vector
1443   // conversion.
1444   if (!ToType->isVectorType() && !FromType->isVectorType())
1445     return false;
1446 
1447   // Identical types require no conversions.
1448   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1449     return false;
1450 
1451   // There are no conversions between extended vector types, only identity.
1452   if (ToType->isExtVectorType()) {
1453     // There are no conversions between extended vector types other than the
1454     // identity conversion.
1455     if (FromType->isExtVectorType())
1456       return false;
1457 
1458     // Vector splat from any arithmetic type to a vector.
1459     if (FromType->isArithmeticType()) {
1460       ICK = ICK_Vector_Splat;
1461       return true;
1462     }
1463   }
1464 
1465   // We can perform the conversion between vector types in the following cases:
1466   // 1)vector types are equivalent AltiVec and GCC vector types
1467   // 2)lax vector conversions are permitted and the vector types are of the
1468   //   same size
1469   if (ToType->isVectorType() && FromType->isVectorType()) {
1470     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1471         S.isLaxVectorConversion(FromType, ToType)) {
1472       ICK = ICK_Vector_Conversion;
1473       return true;
1474     }
1475   }
1476 
1477   return false;
1478 }
1479 
1480 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1481                                 bool InOverloadResolution,
1482                                 StandardConversionSequence &SCS,
1483                                 bool CStyle);
1484 
1485 /// IsStandardConversion - Determines whether there is a standard
1486 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1487 /// expression From to the type ToType. Standard conversion sequences
1488 /// only consider non-class types; for conversions that involve class
1489 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1490 /// contain the standard conversion sequence required to perform this
1491 /// conversion and this routine will return true. Otherwise, this
1492 /// routine will return false and the value of SCS is unspecified.
1493 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1494                                  bool InOverloadResolution,
1495                                  StandardConversionSequence &SCS,
1496                                  bool CStyle,
1497                                  bool AllowObjCWritebackConversion) {
1498   QualType FromType = From->getType();
1499 
1500   // Standard conversions (C++ [conv])
1501   SCS.setAsIdentityConversion();
1502   SCS.IncompatibleObjC = false;
1503   SCS.setFromType(FromType);
1504   SCS.CopyConstructor = nullptr;
1505 
1506   // There are no standard conversions for class types in C++, so
1507   // abort early. When overloading in C, however, we do permit them.
1508   if (S.getLangOpts().CPlusPlus &&
1509       (FromType->isRecordType() || ToType->isRecordType()))
1510     return false;
1511 
1512   // The first conversion can be an lvalue-to-rvalue conversion,
1513   // array-to-pointer conversion, or function-to-pointer conversion
1514   // (C++ 4p1).
1515 
1516   if (FromType == S.Context.OverloadTy) {
1517     DeclAccessPair AccessPair;
1518     if (FunctionDecl *Fn
1519           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1520                                                  AccessPair)) {
1521       // We were able to resolve the address of the overloaded function,
1522       // so we can convert to the type of that function.
1523       FromType = Fn->getType();
1524       SCS.setFromType(FromType);
1525 
1526       // we can sometimes resolve &foo<int> regardless of ToType, so check
1527       // if the type matches (identity) or we are converting to bool
1528       if (!S.Context.hasSameUnqualifiedType(
1529                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1530         QualType resultTy;
1531         // if the function type matches except for [[noreturn]], it's ok
1532         if (!S.IsNoReturnConversion(FromType,
1533               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1534           // otherwise, only a boolean conversion is standard
1535           if (!ToType->isBooleanType())
1536             return false;
1537       }
1538 
1539       // Check if the "from" expression is taking the address of an overloaded
1540       // function and recompute the FromType accordingly. Take advantage of the
1541       // fact that non-static member functions *must* have such an address-of
1542       // expression.
1543       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1544       if (Method && !Method->isStatic()) {
1545         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1546                "Non-unary operator on non-static member address");
1547         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1548                == UO_AddrOf &&
1549                "Non-address-of operator on non-static member address");
1550         const Type *ClassType
1551           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1552         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1553       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1554         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1555                UO_AddrOf &&
1556                "Non-address-of operator for overloaded function expression");
1557         FromType = S.Context.getPointerType(FromType);
1558       }
1559 
1560       // Check that we've computed the proper type after overload resolution.
1561       assert(S.Context.hasSameType(
1562         FromType,
1563         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1564     } else {
1565       return false;
1566     }
1567   }
1568   // Lvalue-to-rvalue conversion (C++11 4.1):
1569   //   A glvalue (3.10) of a non-function, non-array type T can
1570   //   be converted to a prvalue.
1571   bool argIsLValue = From->isGLValue();
1572   if (argIsLValue &&
1573       !FromType->isFunctionType() && !FromType->isArrayType() &&
1574       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1575     SCS.First = ICK_Lvalue_To_Rvalue;
1576 
1577     // C11 6.3.2.1p2:
1578     //   ... if the lvalue has atomic type, the value has the non-atomic version
1579     //   of the type of the lvalue ...
1580     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1581       FromType = Atomic->getValueType();
1582 
1583     // If T is a non-class type, the type of the rvalue is the
1584     // cv-unqualified version of T. Otherwise, the type of the rvalue
1585     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1586     // just strip the qualifiers because they don't matter.
1587     FromType = FromType.getUnqualifiedType();
1588   } else if (FromType->isArrayType()) {
1589     // Array-to-pointer conversion (C++ 4.2)
1590     SCS.First = ICK_Array_To_Pointer;
1591 
1592     // An lvalue or rvalue of type "array of N T" or "array of unknown
1593     // bound of T" can be converted to an rvalue of type "pointer to
1594     // T" (C++ 4.2p1).
1595     FromType = S.Context.getArrayDecayedType(FromType);
1596 
1597     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1598       // This conversion is deprecated in C++03 (D.4)
1599       SCS.DeprecatedStringLiteralToCharPtr = true;
1600 
1601       // For the purpose of ranking in overload resolution
1602       // (13.3.3.1.1), this conversion is considered an
1603       // array-to-pointer conversion followed by a qualification
1604       // conversion (4.4). (C++ 4.2p2)
1605       SCS.Second = ICK_Identity;
1606       SCS.Third = ICK_Qualification;
1607       SCS.QualificationIncludesObjCLifetime = false;
1608       SCS.setAllToTypes(FromType);
1609       return true;
1610     }
1611   } else if (FromType->isFunctionType() && argIsLValue) {
1612     // Function-to-pointer conversion (C++ 4.3).
1613     SCS.First = ICK_Function_To_Pointer;
1614 
1615     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1616       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1617         if (!S.checkAddressOfFunctionIsAvailable(FD))
1618           return false;
1619 
1620     // An lvalue of function type T can be converted to an rvalue of
1621     // type "pointer to T." The result is a pointer to the
1622     // function. (C++ 4.3p1).
1623     FromType = S.Context.getPointerType(FromType);
1624   } else {
1625     // We don't require any conversions for the first step.
1626     SCS.First = ICK_Identity;
1627   }
1628   SCS.setToType(0, FromType);
1629 
1630   // The second conversion can be an integral promotion, floating
1631   // point promotion, integral conversion, floating point conversion,
1632   // floating-integral conversion, pointer conversion,
1633   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1634   // For overloading in C, this can also be a "compatible-type"
1635   // conversion.
1636   bool IncompatibleObjC = false;
1637   ImplicitConversionKind SecondICK = ICK_Identity;
1638   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1639     // The unqualified versions of the types are the same: there's no
1640     // conversion to do.
1641     SCS.Second = ICK_Identity;
1642   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1643     // Integral promotion (C++ 4.5).
1644     SCS.Second = ICK_Integral_Promotion;
1645     FromType = ToType.getUnqualifiedType();
1646   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1647     // Floating point promotion (C++ 4.6).
1648     SCS.Second = ICK_Floating_Promotion;
1649     FromType = ToType.getUnqualifiedType();
1650   } else if (S.IsComplexPromotion(FromType, ToType)) {
1651     // Complex promotion (Clang extension)
1652     SCS.Second = ICK_Complex_Promotion;
1653     FromType = ToType.getUnqualifiedType();
1654   } else if (ToType->isBooleanType() &&
1655              (FromType->isArithmeticType() ||
1656               FromType->isAnyPointerType() ||
1657               FromType->isBlockPointerType() ||
1658               FromType->isMemberPointerType() ||
1659               FromType->isNullPtrType())) {
1660     // Boolean conversions (C++ 4.12).
1661     SCS.Second = ICK_Boolean_Conversion;
1662     FromType = S.Context.BoolTy;
1663   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1664              ToType->isIntegralType(S.Context)) {
1665     // Integral conversions (C++ 4.7).
1666     SCS.Second = ICK_Integral_Conversion;
1667     FromType = ToType.getUnqualifiedType();
1668   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1669     // Complex conversions (C99 6.3.1.6)
1670     SCS.Second = ICK_Complex_Conversion;
1671     FromType = ToType.getUnqualifiedType();
1672   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1673              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1674     // Complex-real conversions (C99 6.3.1.7)
1675     SCS.Second = ICK_Complex_Real;
1676     FromType = ToType.getUnqualifiedType();
1677   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1678     // FIXME: disable conversions between long double and __float128 if
1679     // their representation is different until there is back end support
1680     // We of course allow this conversion if long double is really double.
1681     if (&S.Context.getFloatTypeSemantics(FromType) !=
1682         &S.Context.getFloatTypeSemantics(ToType)) {
1683       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1684                                     ToType == S.Context.LongDoubleTy) ||
1685                                    (FromType == S.Context.LongDoubleTy &&
1686                                     ToType == S.Context.Float128Ty));
1687       if (Float128AndLongDouble &&
1688           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1689            &llvm::APFloat::IEEEdouble))
1690         return false;
1691     }
1692     // Floating point conversions (C++ 4.8).
1693     SCS.Second = ICK_Floating_Conversion;
1694     FromType = ToType.getUnqualifiedType();
1695   } else if ((FromType->isRealFloatingType() &&
1696               ToType->isIntegralType(S.Context)) ||
1697              (FromType->isIntegralOrUnscopedEnumerationType() &&
1698               ToType->isRealFloatingType())) {
1699     // Floating-integral conversions (C++ 4.9).
1700     SCS.Second = ICK_Floating_Integral;
1701     FromType = ToType.getUnqualifiedType();
1702   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1703     SCS.Second = ICK_Block_Pointer_Conversion;
1704   } else if (AllowObjCWritebackConversion &&
1705              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1706     SCS.Second = ICK_Writeback_Conversion;
1707   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1708                                    FromType, IncompatibleObjC)) {
1709     // Pointer conversions (C++ 4.10).
1710     SCS.Second = ICK_Pointer_Conversion;
1711     SCS.IncompatibleObjC = IncompatibleObjC;
1712     FromType = FromType.getUnqualifiedType();
1713   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1714                                          InOverloadResolution, FromType)) {
1715     // Pointer to member conversions (4.11).
1716     SCS.Second = ICK_Pointer_Member;
1717   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1718     SCS.Second = SecondICK;
1719     FromType = ToType.getUnqualifiedType();
1720   } else if (!S.getLangOpts().CPlusPlus &&
1721              S.Context.typesAreCompatible(ToType, FromType)) {
1722     // Compatible conversions (Clang extension for C function overloading)
1723     SCS.Second = ICK_Compatible_Conversion;
1724     FromType = ToType.getUnqualifiedType();
1725   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1726     // Treat a conversion that strips "noreturn" as an identity conversion.
1727     SCS.Second = ICK_NoReturn_Adjustment;
1728   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1729                                              InOverloadResolution,
1730                                              SCS, CStyle)) {
1731     SCS.Second = ICK_TransparentUnionConversion;
1732     FromType = ToType;
1733   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1734                                  CStyle)) {
1735     // tryAtomicConversion has updated the standard conversion sequence
1736     // appropriately.
1737     return true;
1738   } else if (ToType->isEventT() &&
1739              From->isIntegerConstantExpr(S.getASTContext()) &&
1740              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1741     SCS.Second = ICK_Zero_Event_Conversion;
1742     FromType = ToType;
1743   } else {
1744     // No second conversion required.
1745     SCS.Second = ICK_Identity;
1746   }
1747   SCS.setToType(1, FromType);
1748 
1749   QualType CanonFrom;
1750   QualType CanonTo;
1751   // The third conversion can be a qualification conversion (C++ 4p1).
1752   bool ObjCLifetimeConversion;
1753   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1754                                   ObjCLifetimeConversion)) {
1755     SCS.Third = ICK_Qualification;
1756     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1757     FromType = ToType;
1758     CanonFrom = S.Context.getCanonicalType(FromType);
1759     CanonTo = S.Context.getCanonicalType(ToType);
1760   } else {
1761     // No conversion required
1762     SCS.Third = ICK_Identity;
1763 
1764     // C++ [over.best.ics]p6:
1765     //   [...] Any difference in top-level cv-qualification is
1766     //   subsumed by the initialization itself and does not constitute
1767     //   a conversion. [...]
1768     CanonFrom = S.Context.getCanonicalType(FromType);
1769     CanonTo = S.Context.getCanonicalType(ToType);
1770     if (CanonFrom.getLocalUnqualifiedType()
1771                                        == CanonTo.getLocalUnqualifiedType() &&
1772         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1773       FromType = ToType;
1774       CanonFrom = CanonTo;
1775     }
1776   }
1777   SCS.setToType(2, FromType);
1778 
1779   if (CanonFrom == CanonTo)
1780     return true;
1781 
1782   // If we have not converted the argument type to the parameter type,
1783   // this is a bad conversion sequence, unless we're resolving an overload in C.
1784   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1785     return false;
1786 
1787   ExprResult ER = ExprResult{From};
1788   Sema::AssignConvertType Conv =
1789       S.CheckSingleAssignmentConstraints(ToType, ER,
1790                                          /*Diagnose=*/false,
1791                                          /*DiagnoseCFAudited=*/false,
1792                                          /*ConvertRHS=*/false);
1793   ImplicitConversionKind SecondConv;
1794   switch (Conv) {
1795   case Sema::Compatible:
1796     SecondConv = ICK_C_Only_Conversion;
1797     break;
1798   // For our purposes, discarding qualifiers is just as bad as using an
1799   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1800   // qualifiers, as well.
1801   case Sema::CompatiblePointerDiscardsQualifiers:
1802   case Sema::IncompatiblePointer:
1803   case Sema::IncompatiblePointerSign:
1804     SecondConv = ICK_Incompatible_Pointer_Conversion;
1805     break;
1806   default:
1807     return false;
1808   }
1809 
1810   // First can only be an lvalue conversion, so we pretend that this was the
1811   // second conversion. First should already be valid from earlier in the
1812   // function.
1813   SCS.Second = SecondConv;
1814   SCS.setToType(1, ToType);
1815 
1816   // Third is Identity, because Second should rank us worse than any other
1817   // conversion. This could also be ICK_Qualification, but it's simpler to just
1818   // lump everything in with the second conversion, and we don't gain anything
1819   // from making this ICK_Qualification.
1820   SCS.Third = ICK_Identity;
1821   SCS.setToType(2, ToType);
1822   return true;
1823 }
1824 
1825 static bool
1826 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1827                                      QualType &ToType,
1828                                      bool InOverloadResolution,
1829                                      StandardConversionSequence &SCS,
1830                                      bool CStyle) {
1831 
1832   const RecordType *UT = ToType->getAsUnionType();
1833   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1834     return false;
1835   // The field to initialize within the transparent union.
1836   RecordDecl *UD = UT->getDecl();
1837   // It's compatible if the expression matches any of the fields.
1838   for (const auto *it : UD->fields()) {
1839     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1840                              CStyle, /*ObjCWritebackConversion=*/false)) {
1841       ToType = it->getType();
1842       return true;
1843     }
1844   }
1845   return false;
1846 }
1847 
1848 /// IsIntegralPromotion - Determines whether the conversion from the
1849 /// expression From (whose potentially-adjusted type is FromType) to
1850 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1851 /// sets PromotedType to the promoted type.
1852 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1853   const BuiltinType *To = ToType->getAs<BuiltinType>();
1854   // All integers are built-in.
1855   if (!To) {
1856     return false;
1857   }
1858 
1859   // An rvalue of type char, signed char, unsigned char, short int, or
1860   // unsigned short int can be converted to an rvalue of type int if
1861   // int can represent all the values of the source type; otherwise,
1862   // the source rvalue can be converted to an rvalue of type unsigned
1863   // int (C++ 4.5p1).
1864   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1865       !FromType->isEnumeralType()) {
1866     if (// We can promote any signed, promotable integer type to an int
1867         (FromType->isSignedIntegerType() ||
1868          // We can promote any unsigned integer type whose size is
1869          // less than int to an int.
1870          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1871       return To->getKind() == BuiltinType::Int;
1872     }
1873 
1874     return To->getKind() == BuiltinType::UInt;
1875   }
1876 
1877   // C++11 [conv.prom]p3:
1878   //   A prvalue of an unscoped enumeration type whose underlying type is not
1879   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1880   //   following types that can represent all the values of the enumeration
1881   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1882   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1883   //   long long int. If none of the types in that list can represent all the
1884   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1885   //   type can be converted to an rvalue a prvalue of the extended integer type
1886   //   with lowest integer conversion rank (4.13) greater than the rank of long
1887   //   long in which all the values of the enumeration can be represented. If
1888   //   there are two such extended types, the signed one is chosen.
1889   // C++11 [conv.prom]p4:
1890   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1891   //   can be converted to a prvalue of its underlying type. Moreover, if
1892   //   integral promotion can be applied to its underlying type, a prvalue of an
1893   //   unscoped enumeration type whose underlying type is fixed can also be
1894   //   converted to a prvalue of the promoted underlying type.
1895   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1896     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1897     // provided for a scoped enumeration.
1898     if (FromEnumType->getDecl()->isScoped())
1899       return false;
1900 
1901     // We can perform an integral promotion to the underlying type of the enum,
1902     // even if that's not the promoted type. Note that the check for promoting
1903     // the underlying type is based on the type alone, and does not consider
1904     // the bitfield-ness of the actual source expression.
1905     if (FromEnumType->getDecl()->isFixed()) {
1906       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1907       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1908              IsIntegralPromotion(nullptr, Underlying, ToType);
1909     }
1910 
1911     // We have already pre-calculated the promotion type, so this is trivial.
1912     if (ToType->isIntegerType() &&
1913         isCompleteType(From->getLocStart(), FromType))
1914       return Context.hasSameUnqualifiedType(
1915           ToType, FromEnumType->getDecl()->getPromotionType());
1916   }
1917 
1918   // C++0x [conv.prom]p2:
1919   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1920   //   to an rvalue a prvalue of the first of the following types that can
1921   //   represent all the values of its underlying type: int, unsigned int,
1922   //   long int, unsigned long int, long long int, or unsigned long long int.
1923   //   If none of the types in that list can represent all the values of its
1924   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1925   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1926   //   type.
1927   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1928       ToType->isIntegerType()) {
1929     // Determine whether the type we're converting from is signed or
1930     // unsigned.
1931     bool FromIsSigned = FromType->isSignedIntegerType();
1932     uint64_t FromSize = Context.getTypeSize(FromType);
1933 
1934     // The types we'll try to promote to, in the appropriate
1935     // order. Try each of these types.
1936     QualType PromoteTypes[6] = {
1937       Context.IntTy, Context.UnsignedIntTy,
1938       Context.LongTy, Context.UnsignedLongTy ,
1939       Context.LongLongTy, Context.UnsignedLongLongTy
1940     };
1941     for (int Idx = 0; Idx < 6; ++Idx) {
1942       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1943       if (FromSize < ToSize ||
1944           (FromSize == ToSize &&
1945            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1946         // We found the type that we can promote to. If this is the
1947         // type we wanted, we have a promotion. Otherwise, no
1948         // promotion.
1949         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1950       }
1951     }
1952   }
1953 
1954   // An rvalue for an integral bit-field (9.6) can be converted to an
1955   // rvalue of type int if int can represent all the values of the
1956   // bit-field; otherwise, it can be converted to unsigned int if
1957   // unsigned int can represent all the values of the bit-field. If
1958   // the bit-field is larger yet, no integral promotion applies to
1959   // it. If the bit-field has an enumerated type, it is treated as any
1960   // other value of that type for promotion purposes (C++ 4.5p3).
1961   // FIXME: We should delay checking of bit-fields until we actually perform the
1962   // conversion.
1963   if (From) {
1964     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1965       llvm::APSInt BitWidth;
1966       if (FromType->isIntegralType(Context) &&
1967           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1968         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1969         ToSize = Context.getTypeSize(ToType);
1970 
1971         // Are we promoting to an int from a bitfield that fits in an int?
1972         if (BitWidth < ToSize ||
1973             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1974           return To->getKind() == BuiltinType::Int;
1975         }
1976 
1977         // Are we promoting to an unsigned int from an unsigned bitfield
1978         // that fits into an unsigned int?
1979         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1980           return To->getKind() == BuiltinType::UInt;
1981         }
1982 
1983         return false;
1984       }
1985     }
1986   }
1987 
1988   // An rvalue of type bool can be converted to an rvalue of type int,
1989   // with false becoming zero and true becoming one (C++ 4.5p4).
1990   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1991     return true;
1992   }
1993 
1994   return false;
1995 }
1996 
1997 /// IsFloatingPointPromotion - Determines whether the conversion from
1998 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1999 /// returns true and sets PromotedType to the promoted type.
2000 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2001   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2002     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2003       /// An rvalue of type float can be converted to an rvalue of type
2004       /// double. (C++ 4.6p1).
2005       if (FromBuiltin->getKind() == BuiltinType::Float &&
2006           ToBuiltin->getKind() == BuiltinType::Double)
2007         return true;
2008 
2009       // C99 6.3.1.5p1:
2010       //   When a float is promoted to double or long double, or a
2011       //   double is promoted to long double [...].
2012       if (!getLangOpts().CPlusPlus &&
2013           (FromBuiltin->getKind() == BuiltinType::Float ||
2014            FromBuiltin->getKind() == BuiltinType::Double) &&
2015           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2016            ToBuiltin->getKind() == BuiltinType::Float128))
2017         return true;
2018 
2019       // Half can be promoted to float.
2020       if (!getLangOpts().NativeHalfType &&
2021            FromBuiltin->getKind() == BuiltinType::Half &&
2022           ToBuiltin->getKind() == BuiltinType::Float)
2023         return true;
2024     }
2025 
2026   return false;
2027 }
2028 
2029 /// \brief Determine if a conversion is a complex promotion.
2030 ///
2031 /// A complex promotion is defined as a complex -> complex conversion
2032 /// where the conversion between the underlying real types is a
2033 /// floating-point or integral promotion.
2034 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2035   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2036   if (!FromComplex)
2037     return false;
2038 
2039   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2040   if (!ToComplex)
2041     return false;
2042 
2043   return IsFloatingPointPromotion(FromComplex->getElementType(),
2044                                   ToComplex->getElementType()) ||
2045     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2046                         ToComplex->getElementType());
2047 }
2048 
2049 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2050 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2051 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2052 /// if non-empty, will be a pointer to ToType that may or may not have
2053 /// the right set of qualifiers on its pointee.
2054 ///
2055 static QualType
2056 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2057                                    QualType ToPointee, QualType ToType,
2058                                    ASTContext &Context,
2059                                    bool StripObjCLifetime = false) {
2060   assert((FromPtr->getTypeClass() == Type::Pointer ||
2061           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2062          "Invalid similarly-qualified pointer type");
2063 
2064   /// Conversions to 'id' subsume cv-qualifier conversions.
2065   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2066     return ToType.getUnqualifiedType();
2067 
2068   QualType CanonFromPointee
2069     = Context.getCanonicalType(FromPtr->getPointeeType());
2070   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2071   Qualifiers Quals = CanonFromPointee.getQualifiers();
2072 
2073   if (StripObjCLifetime)
2074     Quals.removeObjCLifetime();
2075 
2076   // Exact qualifier match -> return the pointer type we're converting to.
2077   if (CanonToPointee.getLocalQualifiers() == Quals) {
2078     // ToType is exactly what we need. Return it.
2079     if (!ToType.isNull())
2080       return ToType.getUnqualifiedType();
2081 
2082     // Build a pointer to ToPointee. It has the right qualifiers
2083     // already.
2084     if (isa<ObjCObjectPointerType>(ToType))
2085       return Context.getObjCObjectPointerType(ToPointee);
2086     return Context.getPointerType(ToPointee);
2087   }
2088 
2089   // Just build a canonical type that has the right qualifiers.
2090   QualType QualifiedCanonToPointee
2091     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2092 
2093   if (isa<ObjCObjectPointerType>(ToType))
2094     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2095   return Context.getPointerType(QualifiedCanonToPointee);
2096 }
2097 
2098 static bool isNullPointerConstantForConversion(Expr *Expr,
2099                                                bool InOverloadResolution,
2100                                                ASTContext &Context) {
2101   // Handle value-dependent integral null pointer constants correctly.
2102   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2103   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2104       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2105     return !InOverloadResolution;
2106 
2107   return Expr->isNullPointerConstant(Context,
2108                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2109                                         : Expr::NPC_ValueDependentIsNull);
2110 }
2111 
2112 /// IsPointerConversion - Determines whether the conversion of the
2113 /// expression From, which has the (possibly adjusted) type FromType,
2114 /// can be converted to the type ToType via a pointer conversion (C++
2115 /// 4.10). If so, returns true and places the converted type (that
2116 /// might differ from ToType in its cv-qualifiers at some level) into
2117 /// ConvertedType.
2118 ///
2119 /// This routine also supports conversions to and from block pointers
2120 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2121 /// pointers to interfaces. FIXME: Once we've determined the
2122 /// appropriate overloading rules for Objective-C, we may want to
2123 /// split the Objective-C checks into a different routine; however,
2124 /// GCC seems to consider all of these conversions to be pointer
2125 /// conversions, so for now they live here. IncompatibleObjC will be
2126 /// set if the conversion is an allowed Objective-C conversion that
2127 /// should result in a warning.
2128 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2129                                bool InOverloadResolution,
2130                                QualType& ConvertedType,
2131                                bool &IncompatibleObjC) {
2132   IncompatibleObjC = false;
2133   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2134                               IncompatibleObjC))
2135     return true;
2136 
2137   // Conversion from a null pointer constant to any Objective-C pointer type.
2138   if (ToType->isObjCObjectPointerType() &&
2139       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2140     ConvertedType = ToType;
2141     return true;
2142   }
2143 
2144   // Blocks: Block pointers can be converted to void*.
2145   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2146       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2147     ConvertedType = ToType;
2148     return true;
2149   }
2150   // Blocks: A null pointer constant can be converted to a block
2151   // pointer type.
2152   if (ToType->isBlockPointerType() &&
2153       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2154     ConvertedType = ToType;
2155     return true;
2156   }
2157 
2158   // If the left-hand-side is nullptr_t, the right side can be a null
2159   // pointer constant.
2160   if (ToType->isNullPtrType() &&
2161       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2162     ConvertedType = ToType;
2163     return true;
2164   }
2165 
2166   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2167   if (!ToTypePtr)
2168     return false;
2169 
2170   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2171   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2172     ConvertedType = ToType;
2173     return true;
2174   }
2175 
2176   // Beyond this point, both types need to be pointers
2177   // , including objective-c pointers.
2178   QualType ToPointeeType = ToTypePtr->getPointeeType();
2179   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2180       !getLangOpts().ObjCAutoRefCount) {
2181     ConvertedType = BuildSimilarlyQualifiedPointerType(
2182                                       FromType->getAs<ObjCObjectPointerType>(),
2183                                                        ToPointeeType,
2184                                                        ToType, Context);
2185     return true;
2186   }
2187   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2188   if (!FromTypePtr)
2189     return false;
2190 
2191   QualType FromPointeeType = FromTypePtr->getPointeeType();
2192 
2193   // If the unqualified pointee types are the same, this can't be a
2194   // pointer conversion, so don't do all of the work below.
2195   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2196     return false;
2197 
2198   // An rvalue of type "pointer to cv T," where T is an object type,
2199   // can be converted to an rvalue of type "pointer to cv void" (C++
2200   // 4.10p2).
2201   if (FromPointeeType->isIncompleteOrObjectType() &&
2202       ToPointeeType->isVoidType()) {
2203     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2204                                                        ToPointeeType,
2205                                                        ToType, Context,
2206                                                    /*StripObjCLifetime=*/true);
2207     return true;
2208   }
2209 
2210   // MSVC allows implicit function to void* type conversion.
2211   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2212       ToPointeeType->isVoidType()) {
2213     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2214                                                        ToPointeeType,
2215                                                        ToType, Context);
2216     return true;
2217   }
2218 
2219   // When we're overloading in C, we allow a special kind of pointer
2220   // conversion for compatible-but-not-identical pointee types.
2221   if (!getLangOpts().CPlusPlus &&
2222       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2223     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2224                                                        ToPointeeType,
2225                                                        ToType, Context);
2226     return true;
2227   }
2228 
2229   // C++ [conv.ptr]p3:
2230   //
2231   //   An rvalue of type "pointer to cv D," where D is a class type,
2232   //   can be converted to an rvalue of type "pointer to cv B," where
2233   //   B is a base class (clause 10) of D. If B is an inaccessible
2234   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2235   //   necessitates this conversion is ill-formed. The result of the
2236   //   conversion is a pointer to the base class sub-object of the
2237   //   derived class object. The null pointer value is converted to
2238   //   the null pointer value of the destination type.
2239   //
2240   // Note that we do not check for ambiguity or inaccessibility
2241   // here. That is handled by CheckPointerConversion.
2242   if (getLangOpts().CPlusPlus &&
2243       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2244       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2245       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2246     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2247                                                        ToPointeeType,
2248                                                        ToType, Context);
2249     return true;
2250   }
2251 
2252   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2253       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2254     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2255                                                        ToPointeeType,
2256                                                        ToType, Context);
2257     return true;
2258   }
2259 
2260   return false;
2261 }
2262 
2263 /// \brief Adopt the given qualifiers for the given type.
2264 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2265   Qualifiers TQs = T.getQualifiers();
2266 
2267   // Check whether qualifiers already match.
2268   if (TQs == Qs)
2269     return T;
2270 
2271   if (Qs.compatiblyIncludes(TQs))
2272     return Context.getQualifiedType(T, Qs);
2273 
2274   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2275 }
2276 
2277 /// isObjCPointerConversion - Determines whether this is an
2278 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2279 /// with the same arguments and return values.
2280 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2281                                    QualType& ConvertedType,
2282                                    bool &IncompatibleObjC) {
2283   if (!getLangOpts().ObjC1)
2284     return false;
2285 
2286   // The set of qualifiers on the type we're converting from.
2287   Qualifiers FromQualifiers = FromType.getQualifiers();
2288 
2289   // First, we handle all conversions on ObjC object pointer types.
2290   const ObjCObjectPointerType* ToObjCPtr =
2291     ToType->getAs<ObjCObjectPointerType>();
2292   const ObjCObjectPointerType *FromObjCPtr =
2293     FromType->getAs<ObjCObjectPointerType>();
2294 
2295   if (ToObjCPtr && FromObjCPtr) {
2296     // If the pointee types are the same (ignoring qualifications),
2297     // then this is not a pointer conversion.
2298     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2299                                        FromObjCPtr->getPointeeType()))
2300       return false;
2301 
2302     // Conversion between Objective-C pointers.
2303     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2304       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2305       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2306       if (getLangOpts().CPlusPlus && LHS && RHS &&
2307           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2308                                                 FromObjCPtr->getPointeeType()))
2309         return false;
2310       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2311                                                    ToObjCPtr->getPointeeType(),
2312                                                          ToType, Context);
2313       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2314       return true;
2315     }
2316 
2317     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2318       // Okay: this is some kind of implicit downcast of Objective-C
2319       // interfaces, which is permitted. However, we're going to
2320       // complain about it.
2321       IncompatibleObjC = true;
2322       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2323                                                    ToObjCPtr->getPointeeType(),
2324                                                          ToType, Context);
2325       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2326       return true;
2327     }
2328   }
2329   // Beyond this point, both types need to be C pointers or block pointers.
2330   QualType ToPointeeType;
2331   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2332     ToPointeeType = ToCPtr->getPointeeType();
2333   else if (const BlockPointerType *ToBlockPtr =
2334             ToType->getAs<BlockPointerType>()) {
2335     // Objective C++: We're able to convert from a pointer to any object
2336     // to a block pointer type.
2337     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2338       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2339       return true;
2340     }
2341     ToPointeeType = ToBlockPtr->getPointeeType();
2342   }
2343   else if (FromType->getAs<BlockPointerType>() &&
2344            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2345     // Objective C++: We're able to convert from a block pointer type to a
2346     // pointer to any object.
2347     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2348     return true;
2349   }
2350   else
2351     return false;
2352 
2353   QualType FromPointeeType;
2354   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2355     FromPointeeType = FromCPtr->getPointeeType();
2356   else if (const BlockPointerType *FromBlockPtr =
2357            FromType->getAs<BlockPointerType>())
2358     FromPointeeType = FromBlockPtr->getPointeeType();
2359   else
2360     return false;
2361 
2362   // If we have pointers to pointers, recursively check whether this
2363   // is an Objective-C conversion.
2364   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2365       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2366                               IncompatibleObjC)) {
2367     // We always complain about this conversion.
2368     IncompatibleObjC = true;
2369     ConvertedType = Context.getPointerType(ConvertedType);
2370     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2371     return true;
2372   }
2373   // Allow conversion of pointee being objective-c pointer to another one;
2374   // as in I* to id.
2375   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2376       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2377       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2378                               IncompatibleObjC)) {
2379 
2380     ConvertedType = Context.getPointerType(ConvertedType);
2381     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2382     return true;
2383   }
2384 
2385   // If we have pointers to functions or blocks, check whether the only
2386   // differences in the argument and result types are in Objective-C
2387   // pointer conversions. If so, we permit the conversion (but
2388   // complain about it).
2389   const FunctionProtoType *FromFunctionType
2390     = FromPointeeType->getAs<FunctionProtoType>();
2391   const FunctionProtoType *ToFunctionType
2392     = ToPointeeType->getAs<FunctionProtoType>();
2393   if (FromFunctionType && ToFunctionType) {
2394     // If the function types are exactly the same, this isn't an
2395     // Objective-C pointer conversion.
2396     if (Context.getCanonicalType(FromPointeeType)
2397           == Context.getCanonicalType(ToPointeeType))
2398       return false;
2399 
2400     // Perform the quick checks that will tell us whether these
2401     // function types are obviously different.
2402     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2403         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2404         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2405       return false;
2406 
2407     bool HasObjCConversion = false;
2408     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2409         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2410       // Okay, the types match exactly. Nothing to do.
2411     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2412                                        ToFunctionType->getReturnType(),
2413                                        ConvertedType, IncompatibleObjC)) {
2414       // Okay, we have an Objective-C pointer conversion.
2415       HasObjCConversion = true;
2416     } else {
2417       // Function types are too different. Abort.
2418       return false;
2419     }
2420 
2421     // Check argument types.
2422     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2423          ArgIdx != NumArgs; ++ArgIdx) {
2424       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2425       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2426       if (Context.getCanonicalType(FromArgType)
2427             == Context.getCanonicalType(ToArgType)) {
2428         // Okay, the types match exactly. Nothing to do.
2429       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2430                                          ConvertedType, IncompatibleObjC)) {
2431         // Okay, we have an Objective-C pointer conversion.
2432         HasObjCConversion = true;
2433       } else {
2434         // Argument types are too different. Abort.
2435         return false;
2436       }
2437     }
2438 
2439     if (HasObjCConversion) {
2440       // We had an Objective-C conversion. Allow this pointer
2441       // conversion, but complain about it.
2442       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2443       IncompatibleObjC = true;
2444       return true;
2445     }
2446   }
2447 
2448   return false;
2449 }
2450 
2451 /// \brief Determine whether this is an Objective-C writeback conversion,
2452 /// used for parameter passing when performing automatic reference counting.
2453 ///
2454 /// \param FromType The type we're converting form.
2455 ///
2456 /// \param ToType The type we're converting to.
2457 ///
2458 /// \param ConvertedType The type that will be produced after applying
2459 /// this conversion.
2460 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2461                                      QualType &ConvertedType) {
2462   if (!getLangOpts().ObjCAutoRefCount ||
2463       Context.hasSameUnqualifiedType(FromType, ToType))
2464     return false;
2465 
2466   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2467   QualType ToPointee;
2468   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2469     ToPointee = ToPointer->getPointeeType();
2470   else
2471     return false;
2472 
2473   Qualifiers ToQuals = ToPointee.getQualifiers();
2474   if (!ToPointee->isObjCLifetimeType() ||
2475       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2476       !ToQuals.withoutObjCLifetime().empty())
2477     return false;
2478 
2479   // Argument must be a pointer to __strong to __weak.
2480   QualType FromPointee;
2481   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2482     FromPointee = FromPointer->getPointeeType();
2483   else
2484     return false;
2485 
2486   Qualifiers FromQuals = FromPointee.getQualifiers();
2487   if (!FromPointee->isObjCLifetimeType() ||
2488       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2489        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2490     return false;
2491 
2492   // Make sure that we have compatible qualifiers.
2493   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2494   if (!ToQuals.compatiblyIncludes(FromQuals))
2495     return false;
2496 
2497   // Remove qualifiers from the pointee type we're converting from; they
2498   // aren't used in the compatibility check belong, and we'll be adding back
2499   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2500   FromPointee = FromPointee.getUnqualifiedType();
2501 
2502   // The unqualified form of the pointee types must be compatible.
2503   ToPointee = ToPointee.getUnqualifiedType();
2504   bool IncompatibleObjC;
2505   if (Context.typesAreCompatible(FromPointee, ToPointee))
2506     FromPointee = ToPointee;
2507   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2508                                     IncompatibleObjC))
2509     return false;
2510 
2511   /// \brief Construct the type we're converting to, which is a pointer to
2512   /// __autoreleasing pointee.
2513   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2514   ConvertedType = Context.getPointerType(FromPointee);
2515   return true;
2516 }
2517 
2518 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2519                                     QualType& ConvertedType) {
2520   QualType ToPointeeType;
2521   if (const BlockPointerType *ToBlockPtr =
2522         ToType->getAs<BlockPointerType>())
2523     ToPointeeType = ToBlockPtr->getPointeeType();
2524   else
2525     return false;
2526 
2527   QualType FromPointeeType;
2528   if (const BlockPointerType *FromBlockPtr =
2529       FromType->getAs<BlockPointerType>())
2530     FromPointeeType = FromBlockPtr->getPointeeType();
2531   else
2532     return false;
2533   // We have pointer to blocks, check whether the only
2534   // differences in the argument and result types are in Objective-C
2535   // pointer conversions. If so, we permit the conversion.
2536 
2537   const FunctionProtoType *FromFunctionType
2538     = FromPointeeType->getAs<FunctionProtoType>();
2539   const FunctionProtoType *ToFunctionType
2540     = ToPointeeType->getAs<FunctionProtoType>();
2541 
2542   if (!FromFunctionType || !ToFunctionType)
2543     return false;
2544 
2545   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2546     return true;
2547 
2548   // Perform the quick checks that will tell us whether these
2549   // function types are obviously different.
2550   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2551       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2552     return false;
2553 
2554   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2555   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2556   if (FromEInfo != ToEInfo)
2557     return false;
2558 
2559   bool IncompatibleObjC = false;
2560   if (Context.hasSameType(FromFunctionType->getReturnType(),
2561                           ToFunctionType->getReturnType())) {
2562     // Okay, the types match exactly. Nothing to do.
2563   } else {
2564     QualType RHS = FromFunctionType->getReturnType();
2565     QualType LHS = ToFunctionType->getReturnType();
2566     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2567         !RHS.hasQualifiers() && LHS.hasQualifiers())
2568        LHS = LHS.getUnqualifiedType();
2569 
2570      if (Context.hasSameType(RHS,LHS)) {
2571        // OK exact match.
2572      } else if (isObjCPointerConversion(RHS, LHS,
2573                                         ConvertedType, IncompatibleObjC)) {
2574      if (IncompatibleObjC)
2575        return false;
2576      // Okay, we have an Objective-C pointer conversion.
2577      }
2578      else
2579        return false;
2580    }
2581 
2582    // Check argument types.
2583    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2584         ArgIdx != NumArgs; ++ArgIdx) {
2585      IncompatibleObjC = false;
2586      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2587      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2588      if (Context.hasSameType(FromArgType, ToArgType)) {
2589        // Okay, the types match exactly. Nothing to do.
2590      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2591                                         ConvertedType, IncompatibleObjC)) {
2592        if (IncompatibleObjC)
2593          return false;
2594        // Okay, we have an Objective-C pointer conversion.
2595      } else
2596        // Argument types are too different. Abort.
2597        return false;
2598    }
2599    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2600                                                         ToFunctionType))
2601      return false;
2602 
2603    ConvertedType = ToType;
2604    return true;
2605 }
2606 
2607 enum {
2608   ft_default,
2609   ft_different_class,
2610   ft_parameter_arity,
2611   ft_parameter_mismatch,
2612   ft_return_type,
2613   ft_qualifer_mismatch
2614 };
2615 
2616 /// Attempts to get the FunctionProtoType from a Type. Handles
2617 /// MemberFunctionPointers properly.
2618 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2619   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2620     return FPT;
2621 
2622   if (auto *MPT = FromType->getAs<MemberPointerType>())
2623     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2624 
2625   return nullptr;
2626 }
2627 
2628 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2629 /// function types.  Catches different number of parameter, mismatch in
2630 /// parameter types, and different return types.
2631 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2632                                       QualType FromType, QualType ToType) {
2633   // If either type is not valid, include no extra info.
2634   if (FromType.isNull() || ToType.isNull()) {
2635     PDiag << ft_default;
2636     return;
2637   }
2638 
2639   // Get the function type from the pointers.
2640   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2641     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2642                             *ToMember = ToType->getAs<MemberPointerType>();
2643     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2644       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2645             << QualType(FromMember->getClass(), 0);
2646       return;
2647     }
2648     FromType = FromMember->getPointeeType();
2649     ToType = ToMember->getPointeeType();
2650   }
2651 
2652   if (FromType->isPointerType())
2653     FromType = FromType->getPointeeType();
2654   if (ToType->isPointerType())
2655     ToType = ToType->getPointeeType();
2656 
2657   // Remove references.
2658   FromType = FromType.getNonReferenceType();
2659   ToType = ToType.getNonReferenceType();
2660 
2661   // Don't print extra info for non-specialized template functions.
2662   if (FromType->isInstantiationDependentType() &&
2663       !FromType->getAs<TemplateSpecializationType>()) {
2664     PDiag << ft_default;
2665     return;
2666   }
2667 
2668   // No extra info for same types.
2669   if (Context.hasSameType(FromType, ToType)) {
2670     PDiag << ft_default;
2671     return;
2672   }
2673 
2674   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2675                           *ToFunction = tryGetFunctionProtoType(ToType);
2676 
2677   // Both types need to be function types.
2678   if (!FromFunction || !ToFunction) {
2679     PDiag << ft_default;
2680     return;
2681   }
2682 
2683   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2684     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2685           << FromFunction->getNumParams();
2686     return;
2687   }
2688 
2689   // Handle different parameter types.
2690   unsigned ArgPos;
2691   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2692     PDiag << ft_parameter_mismatch << ArgPos + 1
2693           << ToFunction->getParamType(ArgPos)
2694           << FromFunction->getParamType(ArgPos);
2695     return;
2696   }
2697 
2698   // Handle different return type.
2699   if (!Context.hasSameType(FromFunction->getReturnType(),
2700                            ToFunction->getReturnType())) {
2701     PDiag << ft_return_type << ToFunction->getReturnType()
2702           << FromFunction->getReturnType();
2703     return;
2704   }
2705 
2706   unsigned FromQuals = FromFunction->getTypeQuals(),
2707            ToQuals = ToFunction->getTypeQuals();
2708   if (FromQuals != ToQuals) {
2709     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2710     return;
2711   }
2712 
2713   // Unable to find a difference, so add no extra info.
2714   PDiag << ft_default;
2715 }
2716 
2717 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2718 /// for equality of their argument types. Caller has already checked that
2719 /// they have same number of arguments.  If the parameters are different,
2720 /// ArgPos will have the parameter index of the first different parameter.
2721 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2722                                       const FunctionProtoType *NewType,
2723                                       unsigned *ArgPos) {
2724   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2725                                               N = NewType->param_type_begin(),
2726                                               E = OldType->param_type_end();
2727        O && (O != E); ++O, ++N) {
2728     if (!Context.hasSameType(O->getUnqualifiedType(),
2729                              N->getUnqualifiedType())) {
2730       if (ArgPos)
2731         *ArgPos = O - OldType->param_type_begin();
2732       return false;
2733     }
2734   }
2735   return true;
2736 }
2737 
2738 /// CheckPointerConversion - Check the pointer conversion from the
2739 /// expression From to the type ToType. This routine checks for
2740 /// ambiguous or inaccessible derived-to-base pointer
2741 /// conversions for which IsPointerConversion has already returned
2742 /// true. It returns true and produces a diagnostic if there was an
2743 /// error, or returns false otherwise.
2744 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2745                                   CastKind &Kind,
2746                                   CXXCastPath& BasePath,
2747                                   bool IgnoreBaseAccess,
2748                                   bool Diagnose) {
2749   QualType FromType = From->getType();
2750   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2751 
2752   Kind = CK_BitCast;
2753 
2754   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2755       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2756           Expr::NPCK_ZeroExpression) {
2757     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2758       DiagRuntimeBehavior(From->getExprLoc(), From,
2759                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2760                             << ToType << From->getSourceRange());
2761     else if (!isUnevaluatedContext())
2762       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2763         << ToType << From->getSourceRange();
2764   }
2765   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2766     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2767       QualType FromPointeeType = FromPtrType->getPointeeType(),
2768                ToPointeeType   = ToPtrType->getPointeeType();
2769 
2770       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2771           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2772         // We must have a derived-to-base conversion. Check an
2773         // ambiguous or inaccessible conversion.
2774         unsigned InaccessibleID = 0;
2775         unsigned AmbigiousID = 0;
2776         if (Diagnose) {
2777           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2778           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2779         }
2780         if (CheckDerivedToBaseConversion(
2781                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2782                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2783                 &BasePath, IgnoreBaseAccess))
2784           return true;
2785 
2786         // The conversion was successful.
2787         Kind = CK_DerivedToBase;
2788       }
2789 
2790       if (Diagnose && !IsCStyleOrFunctionalCast &&
2791           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2792         assert(getLangOpts().MSVCCompat &&
2793                "this should only be possible with MSVCCompat!");
2794         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2795             << From->getSourceRange();
2796       }
2797     }
2798   } else if (const ObjCObjectPointerType *ToPtrType =
2799                ToType->getAs<ObjCObjectPointerType>()) {
2800     if (const ObjCObjectPointerType *FromPtrType =
2801           FromType->getAs<ObjCObjectPointerType>()) {
2802       // Objective-C++ conversions are always okay.
2803       // FIXME: We should have a different class of conversions for the
2804       // Objective-C++ implicit conversions.
2805       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2806         return false;
2807     } else if (FromType->isBlockPointerType()) {
2808       Kind = CK_BlockPointerToObjCPointerCast;
2809     } else {
2810       Kind = CK_CPointerToObjCPointerCast;
2811     }
2812   } else if (ToType->isBlockPointerType()) {
2813     if (!FromType->isBlockPointerType())
2814       Kind = CK_AnyPointerToBlockPointerCast;
2815   }
2816 
2817   // We shouldn't fall into this case unless it's valid for other
2818   // reasons.
2819   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2820     Kind = CK_NullToPointer;
2821 
2822   return false;
2823 }
2824 
2825 /// IsMemberPointerConversion - Determines whether the conversion of the
2826 /// expression From, which has the (possibly adjusted) type FromType, can be
2827 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2828 /// If so, returns true and places the converted type (that might differ from
2829 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2830 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2831                                      QualType ToType,
2832                                      bool InOverloadResolution,
2833                                      QualType &ConvertedType) {
2834   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2835   if (!ToTypePtr)
2836     return false;
2837 
2838   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2839   if (From->isNullPointerConstant(Context,
2840                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2841                                         : Expr::NPC_ValueDependentIsNull)) {
2842     ConvertedType = ToType;
2843     return true;
2844   }
2845 
2846   // Otherwise, both types have to be member pointers.
2847   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2848   if (!FromTypePtr)
2849     return false;
2850 
2851   // A pointer to member of B can be converted to a pointer to member of D,
2852   // where D is derived from B (C++ 4.11p2).
2853   QualType FromClass(FromTypePtr->getClass(), 0);
2854   QualType ToClass(ToTypePtr->getClass(), 0);
2855 
2856   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2857       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2858     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2859                                                  ToClass.getTypePtr());
2860     return true;
2861   }
2862 
2863   return false;
2864 }
2865 
2866 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2867 /// expression From to the type ToType. This routine checks for ambiguous or
2868 /// virtual or inaccessible base-to-derived member pointer conversions
2869 /// for which IsMemberPointerConversion has already returned true. It returns
2870 /// true and produces a diagnostic if there was an error, or returns false
2871 /// otherwise.
2872 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2873                                         CastKind &Kind,
2874                                         CXXCastPath &BasePath,
2875                                         bool IgnoreBaseAccess) {
2876   QualType FromType = From->getType();
2877   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2878   if (!FromPtrType) {
2879     // This must be a null pointer to member pointer conversion
2880     assert(From->isNullPointerConstant(Context,
2881                                        Expr::NPC_ValueDependentIsNull) &&
2882            "Expr must be null pointer constant!");
2883     Kind = CK_NullToMemberPointer;
2884     return false;
2885   }
2886 
2887   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2888   assert(ToPtrType && "No member pointer cast has a target type "
2889                       "that is not a member pointer.");
2890 
2891   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2892   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2893 
2894   // FIXME: What about dependent types?
2895   assert(FromClass->isRecordType() && "Pointer into non-class.");
2896   assert(ToClass->isRecordType() && "Pointer into non-class.");
2897 
2898   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2899                      /*DetectVirtual=*/true);
2900   bool DerivationOkay =
2901       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2902   assert(DerivationOkay &&
2903          "Should not have been called if derivation isn't OK.");
2904   (void)DerivationOkay;
2905 
2906   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2907                                   getUnqualifiedType())) {
2908     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2909     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2910       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2911     return true;
2912   }
2913 
2914   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2915     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2916       << FromClass << ToClass << QualType(VBase, 0)
2917       << From->getSourceRange();
2918     return true;
2919   }
2920 
2921   if (!IgnoreBaseAccess)
2922     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2923                          Paths.front(),
2924                          diag::err_downcast_from_inaccessible_base);
2925 
2926   // Must be a base to derived member conversion.
2927   BuildBasePathArray(Paths, BasePath);
2928   Kind = CK_BaseToDerivedMemberPointer;
2929   return false;
2930 }
2931 
2932 /// Determine whether the lifetime conversion between the two given
2933 /// qualifiers sets is nontrivial.
2934 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2935                                                Qualifiers ToQuals) {
2936   // Converting anything to const __unsafe_unretained is trivial.
2937   if (ToQuals.hasConst() &&
2938       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2939     return false;
2940 
2941   return true;
2942 }
2943 
2944 /// IsQualificationConversion - Determines whether the conversion from
2945 /// an rvalue of type FromType to ToType is a qualification conversion
2946 /// (C++ 4.4).
2947 ///
2948 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2949 /// when the qualification conversion involves a change in the Objective-C
2950 /// object lifetime.
2951 bool
2952 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2953                                 bool CStyle, bool &ObjCLifetimeConversion) {
2954   FromType = Context.getCanonicalType(FromType);
2955   ToType = Context.getCanonicalType(ToType);
2956   ObjCLifetimeConversion = false;
2957 
2958   // If FromType and ToType are the same type, this is not a
2959   // qualification conversion.
2960   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2961     return false;
2962 
2963   // (C++ 4.4p4):
2964   //   A conversion can add cv-qualifiers at levels other than the first
2965   //   in multi-level pointers, subject to the following rules: [...]
2966   bool PreviousToQualsIncludeConst = true;
2967   bool UnwrappedAnyPointer = false;
2968   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2969     // Within each iteration of the loop, we check the qualifiers to
2970     // determine if this still looks like a qualification
2971     // conversion. Then, if all is well, we unwrap one more level of
2972     // pointers or pointers-to-members and do it all again
2973     // until there are no more pointers or pointers-to-members left to
2974     // unwrap.
2975     UnwrappedAnyPointer = true;
2976 
2977     Qualifiers FromQuals = FromType.getQualifiers();
2978     Qualifiers ToQuals = ToType.getQualifiers();
2979 
2980     // Ignore __unaligned qualifier if this type is void.
2981     if (ToType.getUnqualifiedType()->isVoidType())
2982       FromQuals.removeUnaligned();
2983 
2984     // Objective-C ARC:
2985     //   Check Objective-C lifetime conversions.
2986     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2987         UnwrappedAnyPointer) {
2988       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2989         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2990           ObjCLifetimeConversion = true;
2991         FromQuals.removeObjCLifetime();
2992         ToQuals.removeObjCLifetime();
2993       } else {
2994         // Qualification conversions cannot cast between different
2995         // Objective-C lifetime qualifiers.
2996         return false;
2997       }
2998     }
2999 
3000     // Allow addition/removal of GC attributes but not changing GC attributes.
3001     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3002         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3003       FromQuals.removeObjCGCAttr();
3004       ToQuals.removeObjCGCAttr();
3005     }
3006 
3007     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3008     //      2,j, and similarly for volatile.
3009     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3010       return false;
3011 
3012     //   -- if the cv 1,j and cv 2,j are different, then const is in
3013     //      every cv for 0 < k < j.
3014     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3015         && !PreviousToQualsIncludeConst)
3016       return false;
3017 
3018     // Keep track of whether all prior cv-qualifiers in the "to" type
3019     // include const.
3020     PreviousToQualsIncludeConst
3021       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3022   }
3023 
3024   // We are left with FromType and ToType being the pointee types
3025   // after unwrapping the original FromType and ToType the same number
3026   // of types. If we unwrapped any pointers, and if FromType and
3027   // ToType have the same unqualified type (since we checked
3028   // qualifiers above), then this is a qualification conversion.
3029   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3030 }
3031 
3032 /// \brief - Determine whether this is a conversion from a scalar type to an
3033 /// atomic type.
3034 ///
3035 /// If successful, updates \c SCS's second and third steps in the conversion
3036 /// sequence to finish the conversion.
3037 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3038                                 bool InOverloadResolution,
3039                                 StandardConversionSequence &SCS,
3040                                 bool CStyle) {
3041   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3042   if (!ToAtomic)
3043     return false;
3044 
3045   StandardConversionSequence InnerSCS;
3046   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3047                             InOverloadResolution, InnerSCS,
3048                             CStyle, /*AllowObjCWritebackConversion=*/false))
3049     return false;
3050 
3051   SCS.Second = InnerSCS.Second;
3052   SCS.setToType(1, InnerSCS.getToType(1));
3053   SCS.Third = InnerSCS.Third;
3054   SCS.QualificationIncludesObjCLifetime
3055     = InnerSCS.QualificationIncludesObjCLifetime;
3056   SCS.setToType(2, InnerSCS.getToType(2));
3057   return true;
3058 }
3059 
3060 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3061                                               CXXConstructorDecl *Constructor,
3062                                               QualType Type) {
3063   const FunctionProtoType *CtorType =
3064       Constructor->getType()->getAs<FunctionProtoType>();
3065   if (CtorType->getNumParams() > 0) {
3066     QualType FirstArg = CtorType->getParamType(0);
3067     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3068       return true;
3069   }
3070   return false;
3071 }
3072 
3073 static OverloadingResult
3074 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3075                                        CXXRecordDecl *To,
3076                                        UserDefinedConversionSequence &User,
3077                                        OverloadCandidateSet &CandidateSet,
3078                                        bool AllowExplicit) {
3079   for (auto *D : S.LookupConstructors(To)) {
3080     auto Info = getConstructorInfo(D);
3081     if (!Info)
3082       continue;
3083 
3084     bool Usable = !Info.Constructor->isInvalidDecl() &&
3085                   S.isInitListConstructor(Info.Constructor) &&
3086                   (AllowExplicit || !Info.Constructor->isExplicit());
3087     if (Usable) {
3088       // If the first argument is (a reference to) the target type,
3089       // suppress conversions.
3090       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3091           S.Context, Info.Constructor, ToType);
3092       if (Info.ConstructorTmpl)
3093         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3094                                        /*ExplicitArgs*/ nullptr, From,
3095                                        CandidateSet, SuppressUserConversions);
3096       else
3097         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3098                                CandidateSet, SuppressUserConversions);
3099     }
3100   }
3101 
3102   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3103 
3104   OverloadCandidateSet::iterator Best;
3105   switch (auto Result =
3106             CandidateSet.BestViableFunction(S, From->getLocStart(),
3107                                             Best, true)) {
3108   case OR_Deleted:
3109   case OR_Success: {
3110     // Record the standard conversion we used and the conversion function.
3111     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3112     QualType ThisType = Constructor->getThisType(S.Context);
3113     // Initializer lists don't have conversions as such.
3114     User.Before.setAsIdentityConversion();
3115     User.HadMultipleCandidates = HadMultipleCandidates;
3116     User.ConversionFunction = Constructor;
3117     User.FoundConversionFunction = Best->FoundDecl;
3118     User.After.setAsIdentityConversion();
3119     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3120     User.After.setAllToTypes(ToType);
3121     return Result;
3122   }
3123 
3124   case OR_No_Viable_Function:
3125     return OR_No_Viable_Function;
3126   case OR_Ambiguous:
3127     return OR_Ambiguous;
3128   }
3129 
3130   llvm_unreachable("Invalid OverloadResult!");
3131 }
3132 
3133 /// Determines whether there is a user-defined conversion sequence
3134 /// (C++ [over.ics.user]) that converts expression From to the type
3135 /// ToType. If such a conversion exists, User will contain the
3136 /// user-defined conversion sequence that performs such a conversion
3137 /// and this routine will return true. Otherwise, this routine returns
3138 /// false and User is unspecified.
3139 ///
3140 /// \param AllowExplicit  true if the conversion should consider C++0x
3141 /// "explicit" conversion functions as well as non-explicit conversion
3142 /// functions (C++0x [class.conv.fct]p2).
3143 ///
3144 /// \param AllowObjCConversionOnExplicit true if the conversion should
3145 /// allow an extra Objective-C pointer conversion on uses of explicit
3146 /// constructors. Requires \c AllowExplicit to also be set.
3147 static OverloadingResult
3148 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3149                         UserDefinedConversionSequence &User,
3150                         OverloadCandidateSet &CandidateSet,
3151                         bool AllowExplicit,
3152                         bool AllowObjCConversionOnExplicit) {
3153   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3154 
3155   // Whether we will only visit constructors.
3156   bool ConstructorsOnly = false;
3157 
3158   // If the type we are conversion to is a class type, enumerate its
3159   // constructors.
3160   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3161     // C++ [over.match.ctor]p1:
3162     //   When objects of class type are direct-initialized (8.5), or
3163     //   copy-initialized from an expression of the same or a
3164     //   derived class type (8.5), overload resolution selects the
3165     //   constructor. [...] For copy-initialization, the candidate
3166     //   functions are all the converting constructors (12.3.1) of
3167     //   that class. The argument list is the expression-list within
3168     //   the parentheses of the initializer.
3169     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3170         (From->getType()->getAs<RecordType>() &&
3171          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3172       ConstructorsOnly = true;
3173 
3174     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3175       // We're not going to find any constructors.
3176     } else if (CXXRecordDecl *ToRecordDecl
3177                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3178 
3179       Expr **Args = &From;
3180       unsigned NumArgs = 1;
3181       bool ListInitializing = false;
3182       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3183         // But first, see if there is an init-list-constructor that will work.
3184         OverloadingResult Result = IsInitializerListConstructorConversion(
3185             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3186         if (Result != OR_No_Viable_Function)
3187           return Result;
3188         // Never mind.
3189         CandidateSet.clear();
3190 
3191         // If we're list-initializing, we pass the individual elements as
3192         // arguments, not the entire list.
3193         Args = InitList->getInits();
3194         NumArgs = InitList->getNumInits();
3195         ListInitializing = true;
3196       }
3197 
3198       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3199         auto Info = getConstructorInfo(D);
3200         if (!Info)
3201           continue;
3202 
3203         bool Usable = !Info.Constructor->isInvalidDecl();
3204         if (ListInitializing)
3205           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3206         else
3207           Usable = Usable &&
3208                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3209         if (Usable) {
3210           bool SuppressUserConversions = !ConstructorsOnly;
3211           if (SuppressUserConversions && ListInitializing) {
3212             SuppressUserConversions = false;
3213             if (NumArgs == 1) {
3214               // If the first argument is (a reference to) the target type,
3215               // suppress conversions.
3216               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3217                   S.Context, Info.Constructor, ToType);
3218             }
3219           }
3220           if (Info.ConstructorTmpl)
3221             S.AddTemplateOverloadCandidate(
3222                 Info.ConstructorTmpl, Info.FoundDecl,
3223                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3224                 CandidateSet, SuppressUserConversions);
3225           else
3226             // Allow one user-defined conversion when user specifies a
3227             // From->ToType conversion via an static cast (c-style, etc).
3228             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3229                                    llvm::makeArrayRef(Args, NumArgs),
3230                                    CandidateSet, SuppressUserConversions);
3231         }
3232       }
3233     }
3234   }
3235 
3236   // Enumerate conversion functions, if we're allowed to.
3237   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3238   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3239     // No conversion functions from incomplete types.
3240   } else if (const RecordType *FromRecordType
3241                                    = From->getType()->getAs<RecordType>()) {
3242     if (CXXRecordDecl *FromRecordDecl
3243          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3244       // Add all of the conversion functions as candidates.
3245       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3246       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3247         DeclAccessPair FoundDecl = I.getPair();
3248         NamedDecl *D = FoundDecl.getDecl();
3249         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3250         if (isa<UsingShadowDecl>(D))
3251           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3252 
3253         CXXConversionDecl *Conv;
3254         FunctionTemplateDecl *ConvTemplate;
3255         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3256           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3257         else
3258           Conv = cast<CXXConversionDecl>(D);
3259 
3260         if (AllowExplicit || !Conv->isExplicit()) {
3261           if (ConvTemplate)
3262             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3263                                              ActingContext, From, ToType,
3264                                              CandidateSet,
3265                                              AllowObjCConversionOnExplicit);
3266           else
3267             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3268                                      From, ToType, CandidateSet,
3269                                      AllowObjCConversionOnExplicit);
3270         }
3271       }
3272     }
3273   }
3274 
3275   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3276 
3277   OverloadCandidateSet::iterator Best;
3278   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3279                                                         Best, true)) {
3280   case OR_Success:
3281   case OR_Deleted:
3282     // Record the standard conversion we used and the conversion function.
3283     if (CXXConstructorDecl *Constructor
3284           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3285       // C++ [over.ics.user]p1:
3286       //   If the user-defined conversion is specified by a
3287       //   constructor (12.3.1), the initial standard conversion
3288       //   sequence converts the source type to the type required by
3289       //   the argument of the constructor.
3290       //
3291       QualType ThisType = Constructor->getThisType(S.Context);
3292       if (isa<InitListExpr>(From)) {
3293         // Initializer lists don't have conversions as such.
3294         User.Before.setAsIdentityConversion();
3295       } else {
3296         if (Best->Conversions[0].isEllipsis())
3297           User.EllipsisConversion = true;
3298         else {
3299           User.Before = Best->Conversions[0].Standard;
3300           User.EllipsisConversion = false;
3301         }
3302       }
3303       User.HadMultipleCandidates = HadMultipleCandidates;
3304       User.ConversionFunction = Constructor;
3305       User.FoundConversionFunction = Best->FoundDecl;
3306       User.After.setAsIdentityConversion();
3307       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3308       User.After.setAllToTypes(ToType);
3309       return Result;
3310     }
3311     if (CXXConversionDecl *Conversion
3312                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3313       // C++ [over.ics.user]p1:
3314       //
3315       //   [...] If the user-defined conversion is specified by a
3316       //   conversion function (12.3.2), the initial standard
3317       //   conversion sequence converts the source type to the
3318       //   implicit object parameter of the conversion function.
3319       User.Before = Best->Conversions[0].Standard;
3320       User.HadMultipleCandidates = HadMultipleCandidates;
3321       User.ConversionFunction = Conversion;
3322       User.FoundConversionFunction = Best->FoundDecl;
3323       User.EllipsisConversion = false;
3324 
3325       // C++ [over.ics.user]p2:
3326       //   The second standard conversion sequence converts the
3327       //   result of the user-defined conversion to the target type
3328       //   for the sequence. Since an implicit conversion sequence
3329       //   is an initialization, the special rules for
3330       //   initialization by user-defined conversion apply when
3331       //   selecting the best user-defined conversion for a
3332       //   user-defined conversion sequence (see 13.3.3 and
3333       //   13.3.3.1).
3334       User.After = Best->FinalConversion;
3335       return Result;
3336     }
3337     llvm_unreachable("Not a constructor or conversion function?");
3338 
3339   case OR_No_Viable_Function:
3340     return OR_No_Viable_Function;
3341 
3342   case OR_Ambiguous:
3343     return OR_Ambiguous;
3344   }
3345 
3346   llvm_unreachable("Invalid OverloadResult!");
3347 }
3348 
3349 bool
3350 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3351   ImplicitConversionSequence ICS;
3352   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3353                                     OverloadCandidateSet::CSK_Normal);
3354   OverloadingResult OvResult =
3355     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3356                             CandidateSet, false, false);
3357   if (OvResult == OR_Ambiguous)
3358     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3359         << From->getType() << ToType << From->getSourceRange();
3360   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3361     if (!RequireCompleteType(From->getLocStart(), ToType,
3362                              diag::err_typecheck_nonviable_condition_incomplete,
3363                              From->getType(), From->getSourceRange()))
3364       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3365           << false << From->getType() << From->getSourceRange() << ToType;
3366   } else
3367     return false;
3368   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3369   return true;
3370 }
3371 
3372 /// \brief Compare the user-defined conversion functions or constructors
3373 /// of two user-defined conversion sequences to determine whether any ordering
3374 /// is possible.
3375 static ImplicitConversionSequence::CompareKind
3376 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3377                            FunctionDecl *Function2) {
3378   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3379     return ImplicitConversionSequence::Indistinguishable;
3380 
3381   // Objective-C++:
3382   //   If both conversion functions are implicitly-declared conversions from
3383   //   a lambda closure type to a function pointer and a block pointer,
3384   //   respectively, always prefer the conversion to a function pointer,
3385   //   because the function pointer is more lightweight and is more likely
3386   //   to keep code working.
3387   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3388   if (!Conv1)
3389     return ImplicitConversionSequence::Indistinguishable;
3390 
3391   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3392   if (!Conv2)
3393     return ImplicitConversionSequence::Indistinguishable;
3394 
3395   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3396     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3397     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3398     if (Block1 != Block2)
3399       return Block1 ? ImplicitConversionSequence::Worse
3400                     : ImplicitConversionSequence::Better;
3401   }
3402 
3403   return ImplicitConversionSequence::Indistinguishable;
3404 }
3405 
3406 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3407     const ImplicitConversionSequence &ICS) {
3408   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3409          (ICS.isUserDefined() &&
3410           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3411 }
3412 
3413 /// CompareImplicitConversionSequences - Compare two implicit
3414 /// conversion sequences to determine whether one is better than the
3415 /// other or if they are indistinguishable (C++ 13.3.3.2).
3416 static ImplicitConversionSequence::CompareKind
3417 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3418                                    const ImplicitConversionSequence& ICS1,
3419                                    const ImplicitConversionSequence& ICS2)
3420 {
3421   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3422   // conversion sequences (as defined in 13.3.3.1)
3423   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3424   //      conversion sequence than a user-defined conversion sequence or
3425   //      an ellipsis conversion sequence, and
3426   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3427   //      conversion sequence than an ellipsis conversion sequence
3428   //      (13.3.3.1.3).
3429   //
3430   // C++0x [over.best.ics]p10:
3431   //   For the purpose of ranking implicit conversion sequences as
3432   //   described in 13.3.3.2, the ambiguous conversion sequence is
3433   //   treated as a user-defined sequence that is indistinguishable
3434   //   from any other user-defined conversion sequence.
3435 
3436   // String literal to 'char *' conversion has been deprecated in C++03. It has
3437   // been removed from C++11. We still accept this conversion, if it happens at
3438   // the best viable function. Otherwise, this conversion is considered worse
3439   // than ellipsis conversion. Consider this as an extension; this is not in the
3440   // standard. For example:
3441   //
3442   // int &f(...);    // #1
3443   // void f(char*);  // #2
3444   // void g() { int &r = f("foo"); }
3445   //
3446   // In C++03, we pick #2 as the best viable function.
3447   // In C++11, we pick #1 as the best viable function, because ellipsis
3448   // conversion is better than string-literal to char* conversion (since there
3449   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3450   // convert arguments, #2 would be the best viable function in C++11.
3451   // If the best viable function has this conversion, a warning will be issued
3452   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3453 
3454   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3455       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3456       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3457     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3458                ? ImplicitConversionSequence::Worse
3459                : ImplicitConversionSequence::Better;
3460 
3461   if (ICS1.getKindRank() < ICS2.getKindRank())
3462     return ImplicitConversionSequence::Better;
3463   if (ICS2.getKindRank() < ICS1.getKindRank())
3464     return ImplicitConversionSequence::Worse;
3465 
3466   // The following checks require both conversion sequences to be of
3467   // the same kind.
3468   if (ICS1.getKind() != ICS2.getKind())
3469     return ImplicitConversionSequence::Indistinguishable;
3470 
3471   ImplicitConversionSequence::CompareKind Result =
3472       ImplicitConversionSequence::Indistinguishable;
3473 
3474   // Two implicit conversion sequences of the same form are
3475   // indistinguishable conversion sequences unless one of the
3476   // following rules apply: (C++ 13.3.3.2p3):
3477 
3478   // List-initialization sequence L1 is a better conversion sequence than
3479   // list-initialization sequence L2 if:
3480   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3481   //   if not that,
3482   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3483   //   and N1 is smaller than N2.,
3484   // even if one of the other rules in this paragraph would otherwise apply.
3485   if (!ICS1.isBad()) {
3486     if (ICS1.isStdInitializerListElement() &&
3487         !ICS2.isStdInitializerListElement())
3488       return ImplicitConversionSequence::Better;
3489     if (!ICS1.isStdInitializerListElement() &&
3490         ICS2.isStdInitializerListElement())
3491       return ImplicitConversionSequence::Worse;
3492   }
3493 
3494   if (ICS1.isStandard())
3495     // Standard conversion sequence S1 is a better conversion sequence than
3496     // standard conversion sequence S2 if [...]
3497     Result = CompareStandardConversionSequences(S, Loc,
3498                                                 ICS1.Standard, ICS2.Standard);
3499   else if (ICS1.isUserDefined()) {
3500     // User-defined conversion sequence U1 is a better conversion
3501     // sequence than another user-defined conversion sequence U2 if
3502     // they contain the same user-defined conversion function or
3503     // constructor and if the second standard conversion sequence of
3504     // U1 is better than the second standard conversion sequence of
3505     // U2 (C++ 13.3.3.2p3).
3506     if (ICS1.UserDefined.ConversionFunction ==
3507           ICS2.UserDefined.ConversionFunction)
3508       Result = CompareStandardConversionSequences(S, Loc,
3509                                                   ICS1.UserDefined.After,
3510                                                   ICS2.UserDefined.After);
3511     else
3512       Result = compareConversionFunctions(S,
3513                                           ICS1.UserDefined.ConversionFunction,
3514                                           ICS2.UserDefined.ConversionFunction);
3515   }
3516 
3517   return Result;
3518 }
3519 
3520 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3521   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3522     Qualifiers Quals;
3523     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3524     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3525   }
3526 
3527   return Context.hasSameUnqualifiedType(T1, T2);
3528 }
3529 
3530 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3531 // determine if one is a proper subset of the other.
3532 static ImplicitConversionSequence::CompareKind
3533 compareStandardConversionSubsets(ASTContext &Context,
3534                                  const StandardConversionSequence& SCS1,
3535                                  const StandardConversionSequence& SCS2) {
3536   ImplicitConversionSequence::CompareKind Result
3537     = ImplicitConversionSequence::Indistinguishable;
3538 
3539   // the identity conversion sequence is considered to be a subsequence of
3540   // any non-identity conversion sequence
3541   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3542     return ImplicitConversionSequence::Better;
3543   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3544     return ImplicitConversionSequence::Worse;
3545 
3546   if (SCS1.Second != SCS2.Second) {
3547     if (SCS1.Second == ICK_Identity)
3548       Result = ImplicitConversionSequence::Better;
3549     else if (SCS2.Second == ICK_Identity)
3550       Result = ImplicitConversionSequence::Worse;
3551     else
3552       return ImplicitConversionSequence::Indistinguishable;
3553   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3554     return ImplicitConversionSequence::Indistinguishable;
3555 
3556   if (SCS1.Third == SCS2.Third) {
3557     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3558                              : ImplicitConversionSequence::Indistinguishable;
3559   }
3560 
3561   if (SCS1.Third == ICK_Identity)
3562     return Result == ImplicitConversionSequence::Worse
3563              ? ImplicitConversionSequence::Indistinguishable
3564              : ImplicitConversionSequence::Better;
3565 
3566   if (SCS2.Third == ICK_Identity)
3567     return Result == ImplicitConversionSequence::Better
3568              ? ImplicitConversionSequence::Indistinguishable
3569              : ImplicitConversionSequence::Worse;
3570 
3571   return ImplicitConversionSequence::Indistinguishable;
3572 }
3573 
3574 /// \brief Determine whether one of the given reference bindings is better
3575 /// than the other based on what kind of bindings they are.
3576 static bool
3577 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3578                              const StandardConversionSequence &SCS2) {
3579   // C++0x [over.ics.rank]p3b4:
3580   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3581   //      implicit object parameter of a non-static member function declared
3582   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3583   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3584   //      lvalue reference to a function lvalue and S2 binds an rvalue
3585   //      reference*.
3586   //
3587   // FIXME: Rvalue references. We're going rogue with the above edits,
3588   // because the semantics in the current C++0x working paper (N3225 at the
3589   // time of this writing) break the standard definition of std::forward
3590   // and std::reference_wrapper when dealing with references to functions.
3591   // Proposed wording changes submitted to CWG for consideration.
3592   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3593       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3594     return false;
3595 
3596   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3597           SCS2.IsLvalueReference) ||
3598          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3599           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3600 }
3601 
3602 /// CompareStandardConversionSequences - Compare two standard
3603 /// conversion sequences to determine whether one is better than the
3604 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3605 static ImplicitConversionSequence::CompareKind
3606 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3607                                    const StandardConversionSequence& SCS1,
3608                                    const StandardConversionSequence& SCS2)
3609 {
3610   // Standard conversion sequence S1 is a better conversion sequence
3611   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3612 
3613   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3614   //     sequences in the canonical form defined by 13.3.3.1.1,
3615   //     excluding any Lvalue Transformation; the identity conversion
3616   //     sequence is considered to be a subsequence of any
3617   //     non-identity conversion sequence) or, if not that,
3618   if (ImplicitConversionSequence::CompareKind CK
3619         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3620     return CK;
3621 
3622   //  -- the rank of S1 is better than the rank of S2 (by the rules
3623   //     defined below), or, if not that,
3624   ImplicitConversionRank Rank1 = SCS1.getRank();
3625   ImplicitConversionRank Rank2 = SCS2.getRank();
3626   if (Rank1 < Rank2)
3627     return ImplicitConversionSequence::Better;
3628   else if (Rank2 < Rank1)
3629     return ImplicitConversionSequence::Worse;
3630 
3631   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3632   // are indistinguishable unless one of the following rules
3633   // applies:
3634 
3635   //   A conversion that is not a conversion of a pointer, or
3636   //   pointer to member, to bool is better than another conversion
3637   //   that is such a conversion.
3638   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3639     return SCS2.isPointerConversionToBool()
3640              ? ImplicitConversionSequence::Better
3641              : ImplicitConversionSequence::Worse;
3642 
3643   // C++ [over.ics.rank]p4b2:
3644   //
3645   //   If class B is derived directly or indirectly from class A,
3646   //   conversion of B* to A* is better than conversion of B* to
3647   //   void*, and conversion of A* to void* is better than conversion
3648   //   of B* to void*.
3649   bool SCS1ConvertsToVoid
3650     = SCS1.isPointerConversionToVoidPointer(S.Context);
3651   bool SCS2ConvertsToVoid
3652     = SCS2.isPointerConversionToVoidPointer(S.Context);
3653   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3654     // Exactly one of the conversion sequences is a conversion to
3655     // a void pointer; it's the worse conversion.
3656     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3657                               : ImplicitConversionSequence::Worse;
3658   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3659     // Neither conversion sequence converts to a void pointer; compare
3660     // their derived-to-base conversions.
3661     if (ImplicitConversionSequence::CompareKind DerivedCK
3662           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3663       return DerivedCK;
3664   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3665              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3666     // Both conversion sequences are conversions to void
3667     // pointers. Compare the source types to determine if there's an
3668     // inheritance relationship in their sources.
3669     QualType FromType1 = SCS1.getFromType();
3670     QualType FromType2 = SCS2.getFromType();
3671 
3672     // Adjust the types we're converting from via the array-to-pointer
3673     // conversion, if we need to.
3674     if (SCS1.First == ICK_Array_To_Pointer)
3675       FromType1 = S.Context.getArrayDecayedType(FromType1);
3676     if (SCS2.First == ICK_Array_To_Pointer)
3677       FromType2 = S.Context.getArrayDecayedType(FromType2);
3678 
3679     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3680     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3681 
3682     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3683       return ImplicitConversionSequence::Better;
3684     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3685       return ImplicitConversionSequence::Worse;
3686 
3687     // Objective-C++: If one interface is more specific than the
3688     // other, it is the better one.
3689     const ObjCObjectPointerType* FromObjCPtr1
3690       = FromType1->getAs<ObjCObjectPointerType>();
3691     const ObjCObjectPointerType* FromObjCPtr2
3692       = FromType2->getAs<ObjCObjectPointerType>();
3693     if (FromObjCPtr1 && FromObjCPtr2) {
3694       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3695                                                           FromObjCPtr2);
3696       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3697                                                            FromObjCPtr1);
3698       if (AssignLeft != AssignRight) {
3699         return AssignLeft? ImplicitConversionSequence::Better
3700                          : ImplicitConversionSequence::Worse;
3701       }
3702     }
3703   }
3704 
3705   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3706   // bullet 3).
3707   if (ImplicitConversionSequence::CompareKind QualCK
3708         = CompareQualificationConversions(S, SCS1, SCS2))
3709     return QualCK;
3710 
3711   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3712     // Check for a better reference binding based on the kind of bindings.
3713     if (isBetterReferenceBindingKind(SCS1, SCS2))
3714       return ImplicitConversionSequence::Better;
3715     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3716       return ImplicitConversionSequence::Worse;
3717 
3718     // C++ [over.ics.rank]p3b4:
3719     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3720     //      which the references refer are the same type except for
3721     //      top-level cv-qualifiers, and the type to which the reference
3722     //      initialized by S2 refers is more cv-qualified than the type
3723     //      to which the reference initialized by S1 refers.
3724     QualType T1 = SCS1.getToType(2);
3725     QualType T2 = SCS2.getToType(2);
3726     T1 = S.Context.getCanonicalType(T1);
3727     T2 = S.Context.getCanonicalType(T2);
3728     Qualifiers T1Quals, T2Quals;
3729     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3730     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3731     if (UnqualT1 == UnqualT2) {
3732       // Objective-C++ ARC: If the references refer to objects with different
3733       // lifetimes, prefer bindings that don't change lifetime.
3734       if (SCS1.ObjCLifetimeConversionBinding !=
3735                                           SCS2.ObjCLifetimeConversionBinding) {
3736         return SCS1.ObjCLifetimeConversionBinding
3737                                            ? ImplicitConversionSequence::Worse
3738                                            : ImplicitConversionSequence::Better;
3739       }
3740 
3741       // If the type is an array type, promote the element qualifiers to the
3742       // type for comparison.
3743       if (isa<ArrayType>(T1) && T1Quals)
3744         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3745       if (isa<ArrayType>(T2) && T2Quals)
3746         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3747       if (T2.isMoreQualifiedThan(T1))
3748         return ImplicitConversionSequence::Better;
3749       else if (T1.isMoreQualifiedThan(T2))
3750         return ImplicitConversionSequence::Worse;
3751     }
3752   }
3753 
3754   // In Microsoft mode, prefer an integral conversion to a
3755   // floating-to-integral conversion if the integral conversion
3756   // is between types of the same size.
3757   // For example:
3758   // void f(float);
3759   // void f(int);
3760   // int main {
3761   //    long a;
3762   //    f(a);
3763   // }
3764   // Here, MSVC will call f(int) instead of generating a compile error
3765   // as clang will do in standard mode.
3766   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3767       SCS2.Second == ICK_Floating_Integral &&
3768       S.Context.getTypeSize(SCS1.getFromType()) ==
3769           S.Context.getTypeSize(SCS1.getToType(2)))
3770     return ImplicitConversionSequence::Better;
3771 
3772   return ImplicitConversionSequence::Indistinguishable;
3773 }
3774 
3775 /// CompareQualificationConversions - Compares two standard conversion
3776 /// sequences to determine whether they can be ranked based on their
3777 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3778 static ImplicitConversionSequence::CompareKind
3779 CompareQualificationConversions(Sema &S,
3780                                 const StandardConversionSequence& SCS1,
3781                                 const StandardConversionSequence& SCS2) {
3782   // C++ 13.3.3.2p3:
3783   //  -- S1 and S2 differ only in their qualification conversion and
3784   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3785   //     cv-qualification signature of type T1 is a proper subset of
3786   //     the cv-qualification signature of type T2, and S1 is not the
3787   //     deprecated string literal array-to-pointer conversion (4.2).
3788   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3789       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3790     return ImplicitConversionSequence::Indistinguishable;
3791 
3792   // FIXME: the example in the standard doesn't use a qualification
3793   // conversion (!)
3794   QualType T1 = SCS1.getToType(2);
3795   QualType T2 = SCS2.getToType(2);
3796   T1 = S.Context.getCanonicalType(T1);
3797   T2 = S.Context.getCanonicalType(T2);
3798   Qualifiers T1Quals, T2Quals;
3799   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3800   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3801 
3802   // If the types are the same, we won't learn anything by unwrapped
3803   // them.
3804   if (UnqualT1 == UnqualT2)
3805     return ImplicitConversionSequence::Indistinguishable;
3806 
3807   // If the type is an array type, promote the element qualifiers to the type
3808   // for comparison.
3809   if (isa<ArrayType>(T1) && T1Quals)
3810     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3811   if (isa<ArrayType>(T2) && T2Quals)
3812     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3813 
3814   ImplicitConversionSequence::CompareKind Result
3815     = ImplicitConversionSequence::Indistinguishable;
3816 
3817   // Objective-C++ ARC:
3818   //   Prefer qualification conversions not involving a change in lifetime
3819   //   to qualification conversions that do not change lifetime.
3820   if (SCS1.QualificationIncludesObjCLifetime !=
3821                                       SCS2.QualificationIncludesObjCLifetime) {
3822     Result = SCS1.QualificationIncludesObjCLifetime
3823                ? ImplicitConversionSequence::Worse
3824                : ImplicitConversionSequence::Better;
3825   }
3826 
3827   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3828     // Within each iteration of the loop, we check the qualifiers to
3829     // determine if this still looks like a qualification
3830     // conversion. Then, if all is well, we unwrap one more level of
3831     // pointers or pointers-to-members and do it all again
3832     // until there are no more pointers or pointers-to-members left
3833     // to unwrap. This essentially mimics what
3834     // IsQualificationConversion does, but here we're checking for a
3835     // strict subset of qualifiers.
3836     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3837       // The qualifiers are the same, so this doesn't tell us anything
3838       // about how the sequences rank.
3839       ;
3840     else if (T2.isMoreQualifiedThan(T1)) {
3841       // T1 has fewer qualifiers, so it could be the better sequence.
3842       if (Result == ImplicitConversionSequence::Worse)
3843         // Neither has qualifiers that are a subset of the other's
3844         // qualifiers.
3845         return ImplicitConversionSequence::Indistinguishable;
3846 
3847       Result = ImplicitConversionSequence::Better;
3848     } else if (T1.isMoreQualifiedThan(T2)) {
3849       // T2 has fewer qualifiers, so it could be the better sequence.
3850       if (Result == ImplicitConversionSequence::Better)
3851         // Neither has qualifiers that are a subset of the other's
3852         // qualifiers.
3853         return ImplicitConversionSequence::Indistinguishable;
3854 
3855       Result = ImplicitConversionSequence::Worse;
3856     } else {
3857       // Qualifiers are disjoint.
3858       return ImplicitConversionSequence::Indistinguishable;
3859     }
3860 
3861     // If the types after this point are equivalent, we're done.
3862     if (S.Context.hasSameUnqualifiedType(T1, T2))
3863       break;
3864   }
3865 
3866   // Check that the winning standard conversion sequence isn't using
3867   // the deprecated string literal array to pointer conversion.
3868   switch (Result) {
3869   case ImplicitConversionSequence::Better:
3870     if (SCS1.DeprecatedStringLiteralToCharPtr)
3871       Result = ImplicitConversionSequence::Indistinguishable;
3872     break;
3873 
3874   case ImplicitConversionSequence::Indistinguishable:
3875     break;
3876 
3877   case ImplicitConversionSequence::Worse:
3878     if (SCS2.DeprecatedStringLiteralToCharPtr)
3879       Result = ImplicitConversionSequence::Indistinguishable;
3880     break;
3881   }
3882 
3883   return Result;
3884 }
3885 
3886 /// CompareDerivedToBaseConversions - Compares two standard conversion
3887 /// sequences to determine whether they can be ranked based on their
3888 /// various kinds of derived-to-base conversions (C++
3889 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3890 /// conversions between Objective-C interface types.
3891 static ImplicitConversionSequence::CompareKind
3892 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3893                                 const StandardConversionSequence& SCS1,
3894                                 const StandardConversionSequence& SCS2) {
3895   QualType FromType1 = SCS1.getFromType();
3896   QualType ToType1 = SCS1.getToType(1);
3897   QualType FromType2 = SCS2.getFromType();
3898   QualType ToType2 = SCS2.getToType(1);
3899 
3900   // Adjust the types we're converting from via the array-to-pointer
3901   // conversion, if we need to.
3902   if (SCS1.First == ICK_Array_To_Pointer)
3903     FromType1 = S.Context.getArrayDecayedType(FromType1);
3904   if (SCS2.First == ICK_Array_To_Pointer)
3905     FromType2 = S.Context.getArrayDecayedType(FromType2);
3906 
3907   // Canonicalize all of the types.
3908   FromType1 = S.Context.getCanonicalType(FromType1);
3909   ToType1 = S.Context.getCanonicalType(ToType1);
3910   FromType2 = S.Context.getCanonicalType(FromType2);
3911   ToType2 = S.Context.getCanonicalType(ToType2);
3912 
3913   // C++ [over.ics.rank]p4b3:
3914   //
3915   //   If class B is derived directly or indirectly from class A and
3916   //   class C is derived directly or indirectly from B,
3917   //
3918   // Compare based on pointer conversions.
3919   if (SCS1.Second == ICK_Pointer_Conversion &&
3920       SCS2.Second == ICK_Pointer_Conversion &&
3921       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3922       FromType1->isPointerType() && FromType2->isPointerType() &&
3923       ToType1->isPointerType() && ToType2->isPointerType()) {
3924     QualType FromPointee1
3925       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3926     QualType ToPointee1
3927       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3928     QualType FromPointee2
3929       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3930     QualType ToPointee2
3931       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3932 
3933     //   -- conversion of C* to B* is better than conversion of C* to A*,
3934     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3935       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3936         return ImplicitConversionSequence::Better;
3937       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3938         return ImplicitConversionSequence::Worse;
3939     }
3940 
3941     //   -- conversion of B* to A* is better than conversion of C* to A*,
3942     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3943       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3944         return ImplicitConversionSequence::Better;
3945       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3946         return ImplicitConversionSequence::Worse;
3947     }
3948   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3949              SCS2.Second == ICK_Pointer_Conversion) {
3950     const ObjCObjectPointerType *FromPtr1
3951       = FromType1->getAs<ObjCObjectPointerType>();
3952     const ObjCObjectPointerType *FromPtr2
3953       = FromType2->getAs<ObjCObjectPointerType>();
3954     const ObjCObjectPointerType *ToPtr1
3955       = ToType1->getAs<ObjCObjectPointerType>();
3956     const ObjCObjectPointerType *ToPtr2
3957       = ToType2->getAs<ObjCObjectPointerType>();
3958 
3959     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3960       // Apply the same conversion ranking rules for Objective-C pointer types
3961       // that we do for C++ pointers to class types. However, we employ the
3962       // Objective-C pseudo-subtyping relationship used for assignment of
3963       // Objective-C pointer types.
3964       bool FromAssignLeft
3965         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3966       bool FromAssignRight
3967         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3968       bool ToAssignLeft
3969         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3970       bool ToAssignRight
3971         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3972 
3973       // A conversion to an a non-id object pointer type or qualified 'id'
3974       // type is better than a conversion to 'id'.
3975       if (ToPtr1->isObjCIdType() &&
3976           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3977         return ImplicitConversionSequence::Worse;
3978       if (ToPtr2->isObjCIdType() &&
3979           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3980         return ImplicitConversionSequence::Better;
3981 
3982       // A conversion to a non-id object pointer type is better than a
3983       // conversion to a qualified 'id' type
3984       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3985         return ImplicitConversionSequence::Worse;
3986       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3987         return ImplicitConversionSequence::Better;
3988 
3989       // A conversion to an a non-Class object pointer type or qualified 'Class'
3990       // type is better than a conversion to 'Class'.
3991       if (ToPtr1->isObjCClassType() &&
3992           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3993         return ImplicitConversionSequence::Worse;
3994       if (ToPtr2->isObjCClassType() &&
3995           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3996         return ImplicitConversionSequence::Better;
3997 
3998       // A conversion to a non-Class object pointer type is better than a
3999       // conversion to a qualified 'Class' type.
4000       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4001         return ImplicitConversionSequence::Worse;
4002       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4003         return ImplicitConversionSequence::Better;
4004 
4005       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4006       if (S.Context.hasSameType(FromType1, FromType2) &&
4007           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4008           (ToAssignLeft != ToAssignRight))
4009         return ToAssignLeft? ImplicitConversionSequence::Worse
4010                            : ImplicitConversionSequence::Better;
4011 
4012       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4013       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4014           (FromAssignLeft != FromAssignRight))
4015         return FromAssignLeft? ImplicitConversionSequence::Better
4016         : ImplicitConversionSequence::Worse;
4017     }
4018   }
4019 
4020   // Ranking of member-pointer types.
4021   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4022       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4023       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4024     const MemberPointerType * FromMemPointer1 =
4025                                         FromType1->getAs<MemberPointerType>();
4026     const MemberPointerType * ToMemPointer1 =
4027                                           ToType1->getAs<MemberPointerType>();
4028     const MemberPointerType * FromMemPointer2 =
4029                                           FromType2->getAs<MemberPointerType>();
4030     const MemberPointerType * ToMemPointer2 =
4031                                           ToType2->getAs<MemberPointerType>();
4032     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4033     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4034     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4035     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4036     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4037     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4038     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4039     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4040     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4041     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4042       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4043         return ImplicitConversionSequence::Worse;
4044       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4045         return ImplicitConversionSequence::Better;
4046     }
4047     // conversion of B::* to C::* is better than conversion of A::* to C::*
4048     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4049       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4050         return ImplicitConversionSequence::Better;
4051       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4052         return ImplicitConversionSequence::Worse;
4053     }
4054   }
4055 
4056   if (SCS1.Second == ICK_Derived_To_Base) {
4057     //   -- conversion of C to B is better than conversion of C to A,
4058     //   -- binding of an expression of type C to a reference of type
4059     //      B& is better than binding an expression of type C to a
4060     //      reference of type A&,
4061     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4062         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4063       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4064         return ImplicitConversionSequence::Better;
4065       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4066         return ImplicitConversionSequence::Worse;
4067     }
4068 
4069     //   -- conversion of B to A is better than conversion of C to A.
4070     //   -- binding of an expression of type B to a reference of type
4071     //      A& is better than binding an expression of type C to a
4072     //      reference of type A&,
4073     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4074         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4075       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4076         return ImplicitConversionSequence::Better;
4077       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4078         return ImplicitConversionSequence::Worse;
4079     }
4080   }
4081 
4082   return ImplicitConversionSequence::Indistinguishable;
4083 }
4084 
4085 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4086 /// C++ class.
4087 static bool isTypeValid(QualType T) {
4088   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4089     return !Record->isInvalidDecl();
4090 
4091   return true;
4092 }
4093 
4094 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4095 /// determine whether they are reference-related,
4096 /// reference-compatible, reference-compatible with added
4097 /// qualification, or incompatible, for use in C++ initialization by
4098 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4099 /// type, and the first type (T1) is the pointee type of the reference
4100 /// type being initialized.
4101 Sema::ReferenceCompareResult
4102 Sema::CompareReferenceRelationship(SourceLocation Loc,
4103                                    QualType OrigT1, QualType OrigT2,
4104                                    bool &DerivedToBase,
4105                                    bool &ObjCConversion,
4106                                    bool &ObjCLifetimeConversion) {
4107   assert(!OrigT1->isReferenceType() &&
4108     "T1 must be the pointee type of the reference type");
4109   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4110 
4111   QualType T1 = Context.getCanonicalType(OrigT1);
4112   QualType T2 = Context.getCanonicalType(OrigT2);
4113   Qualifiers T1Quals, T2Quals;
4114   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4115   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4116 
4117   // C++ [dcl.init.ref]p4:
4118   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4119   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4120   //   T1 is a base class of T2.
4121   DerivedToBase = false;
4122   ObjCConversion = false;
4123   ObjCLifetimeConversion = false;
4124   if (UnqualT1 == UnqualT2) {
4125     // Nothing to do.
4126   } else if (isCompleteType(Loc, OrigT2) &&
4127              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4128              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4129     DerivedToBase = true;
4130   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4131            UnqualT2->isObjCObjectOrInterfaceType() &&
4132            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4133     ObjCConversion = true;
4134   else
4135     return Ref_Incompatible;
4136 
4137   // At this point, we know that T1 and T2 are reference-related (at
4138   // least).
4139 
4140   // If the type is an array type, promote the element qualifiers to the type
4141   // for comparison.
4142   if (isa<ArrayType>(T1) && T1Quals)
4143     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4144   if (isa<ArrayType>(T2) && T2Quals)
4145     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4146 
4147   // C++ [dcl.init.ref]p4:
4148   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4149   //   reference-related to T2 and cv1 is the same cv-qualification
4150   //   as, or greater cv-qualification than, cv2. For purposes of
4151   //   overload resolution, cases for which cv1 is greater
4152   //   cv-qualification than cv2 are identified as
4153   //   reference-compatible with added qualification (see 13.3.3.2).
4154   //
4155   // Note that we also require equivalence of Objective-C GC and address-space
4156   // qualifiers when performing these computations, so that e.g., an int in
4157   // address space 1 is not reference-compatible with an int in address
4158   // space 2.
4159   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4160       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4161     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4162       ObjCLifetimeConversion = true;
4163 
4164     T1Quals.removeObjCLifetime();
4165     T2Quals.removeObjCLifetime();
4166   }
4167 
4168   // MS compiler ignores __unaligned qualifier for references; do the same.
4169   T1Quals.removeUnaligned();
4170   T2Quals.removeUnaligned();
4171 
4172   if (T1Quals == T2Quals)
4173     return Ref_Compatible;
4174   else if (T1Quals.compatiblyIncludes(T2Quals))
4175     return Ref_Compatible_With_Added_Qualification;
4176   else
4177     return Ref_Related;
4178 }
4179 
4180 /// \brief Look for a user-defined conversion to an value reference-compatible
4181 ///        with DeclType. Return true if something definite is found.
4182 static bool
4183 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4184                          QualType DeclType, SourceLocation DeclLoc,
4185                          Expr *Init, QualType T2, bool AllowRvalues,
4186                          bool AllowExplicit) {
4187   assert(T2->isRecordType() && "Can only find conversions of record types.");
4188   CXXRecordDecl *T2RecordDecl
4189     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4190 
4191   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4192   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4193   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4194     NamedDecl *D = *I;
4195     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4196     if (isa<UsingShadowDecl>(D))
4197       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4198 
4199     FunctionTemplateDecl *ConvTemplate
4200       = dyn_cast<FunctionTemplateDecl>(D);
4201     CXXConversionDecl *Conv;
4202     if (ConvTemplate)
4203       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4204     else
4205       Conv = cast<CXXConversionDecl>(D);
4206 
4207     // If this is an explicit conversion, and we're not allowed to consider
4208     // explicit conversions, skip it.
4209     if (!AllowExplicit && Conv->isExplicit())
4210       continue;
4211 
4212     if (AllowRvalues) {
4213       bool DerivedToBase = false;
4214       bool ObjCConversion = false;
4215       bool ObjCLifetimeConversion = false;
4216 
4217       // If we are initializing an rvalue reference, don't permit conversion
4218       // functions that return lvalues.
4219       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4220         const ReferenceType *RefType
4221           = Conv->getConversionType()->getAs<LValueReferenceType>();
4222         if (RefType && !RefType->getPointeeType()->isFunctionType())
4223           continue;
4224       }
4225 
4226       if (!ConvTemplate &&
4227           S.CompareReferenceRelationship(
4228             DeclLoc,
4229             Conv->getConversionType().getNonReferenceType()
4230               .getUnqualifiedType(),
4231             DeclType.getNonReferenceType().getUnqualifiedType(),
4232             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4233           Sema::Ref_Incompatible)
4234         continue;
4235     } else {
4236       // If the conversion function doesn't return a reference type,
4237       // it can't be considered for this conversion. An rvalue reference
4238       // is only acceptable if its referencee is a function type.
4239 
4240       const ReferenceType *RefType =
4241         Conv->getConversionType()->getAs<ReferenceType>();
4242       if (!RefType ||
4243           (!RefType->isLValueReferenceType() &&
4244            !RefType->getPointeeType()->isFunctionType()))
4245         continue;
4246     }
4247 
4248     if (ConvTemplate)
4249       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4250                                        Init, DeclType, CandidateSet,
4251                                        /*AllowObjCConversionOnExplicit=*/false);
4252     else
4253       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4254                                DeclType, CandidateSet,
4255                                /*AllowObjCConversionOnExplicit=*/false);
4256   }
4257 
4258   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4259 
4260   OverloadCandidateSet::iterator Best;
4261   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4262   case OR_Success:
4263     // C++ [over.ics.ref]p1:
4264     //
4265     //   [...] If the parameter binds directly to the result of
4266     //   applying a conversion function to the argument
4267     //   expression, the implicit conversion sequence is a
4268     //   user-defined conversion sequence (13.3.3.1.2), with the
4269     //   second standard conversion sequence either an identity
4270     //   conversion or, if the conversion function returns an
4271     //   entity of a type that is a derived class of the parameter
4272     //   type, a derived-to-base Conversion.
4273     if (!Best->FinalConversion.DirectBinding)
4274       return false;
4275 
4276     ICS.setUserDefined();
4277     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4278     ICS.UserDefined.After = Best->FinalConversion;
4279     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4280     ICS.UserDefined.ConversionFunction = Best->Function;
4281     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4282     ICS.UserDefined.EllipsisConversion = false;
4283     assert(ICS.UserDefined.After.ReferenceBinding &&
4284            ICS.UserDefined.After.DirectBinding &&
4285            "Expected a direct reference binding!");
4286     return true;
4287 
4288   case OR_Ambiguous:
4289     ICS.setAmbiguous();
4290     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4291          Cand != CandidateSet.end(); ++Cand)
4292       if (Cand->Viable)
4293         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4294     return true;
4295 
4296   case OR_No_Viable_Function:
4297   case OR_Deleted:
4298     // There was no suitable conversion, or we found a deleted
4299     // conversion; continue with other checks.
4300     return false;
4301   }
4302 
4303   llvm_unreachable("Invalid OverloadResult!");
4304 }
4305 
4306 /// \brief Compute an implicit conversion sequence for reference
4307 /// initialization.
4308 static ImplicitConversionSequence
4309 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4310                  SourceLocation DeclLoc,
4311                  bool SuppressUserConversions,
4312                  bool AllowExplicit) {
4313   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4314 
4315   // Most paths end in a failed conversion.
4316   ImplicitConversionSequence ICS;
4317   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4318 
4319   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4320   QualType T2 = Init->getType();
4321 
4322   // If the initializer is the address of an overloaded function, try
4323   // to resolve the overloaded function. If all goes well, T2 is the
4324   // type of the resulting function.
4325   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4326     DeclAccessPair Found;
4327     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4328                                                                 false, Found))
4329       T2 = Fn->getType();
4330   }
4331 
4332   // Compute some basic properties of the types and the initializer.
4333   bool isRValRef = DeclType->isRValueReferenceType();
4334   bool DerivedToBase = false;
4335   bool ObjCConversion = false;
4336   bool ObjCLifetimeConversion = false;
4337   Expr::Classification InitCategory = Init->Classify(S.Context);
4338   Sema::ReferenceCompareResult RefRelationship
4339     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4340                                      ObjCConversion, ObjCLifetimeConversion);
4341 
4342 
4343   // C++0x [dcl.init.ref]p5:
4344   //   A reference to type "cv1 T1" is initialized by an expression
4345   //   of type "cv2 T2" as follows:
4346 
4347   //     -- If reference is an lvalue reference and the initializer expression
4348   if (!isRValRef) {
4349     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4350     //        reference-compatible with "cv2 T2," or
4351     //
4352     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4353     if (InitCategory.isLValue() &&
4354         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4355       // C++ [over.ics.ref]p1:
4356       //   When a parameter of reference type binds directly (8.5.3)
4357       //   to an argument expression, the implicit conversion sequence
4358       //   is the identity conversion, unless the argument expression
4359       //   has a type that is a derived class of the parameter type,
4360       //   in which case the implicit conversion sequence is a
4361       //   derived-to-base Conversion (13.3.3.1).
4362       ICS.setStandard();
4363       ICS.Standard.First = ICK_Identity;
4364       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4365                          : ObjCConversion? ICK_Compatible_Conversion
4366                          : ICK_Identity;
4367       ICS.Standard.Third = ICK_Identity;
4368       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4369       ICS.Standard.setToType(0, T2);
4370       ICS.Standard.setToType(1, T1);
4371       ICS.Standard.setToType(2, T1);
4372       ICS.Standard.ReferenceBinding = true;
4373       ICS.Standard.DirectBinding = true;
4374       ICS.Standard.IsLvalueReference = !isRValRef;
4375       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4376       ICS.Standard.BindsToRvalue = false;
4377       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4378       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4379       ICS.Standard.CopyConstructor = nullptr;
4380       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4381 
4382       // Nothing more to do: the inaccessibility/ambiguity check for
4383       // derived-to-base conversions is suppressed when we're
4384       // computing the implicit conversion sequence (C++
4385       // [over.best.ics]p2).
4386       return ICS;
4387     }
4388 
4389     //       -- has a class type (i.e., T2 is a class type), where T1 is
4390     //          not reference-related to T2, and can be implicitly
4391     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4392     //          is reference-compatible with "cv3 T3" 92) (this
4393     //          conversion is selected by enumerating the applicable
4394     //          conversion functions (13.3.1.6) and choosing the best
4395     //          one through overload resolution (13.3)),
4396     if (!SuppressUserConversions && T2->isRecordType() &&
4397         S.isCompleteType(DeclLoc, T2) &&
4398         RefRelationship == Sema::Ref_Incompatible) {
4399       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4400                                    Init, T2, /*AllowRvalues=*/false,
4401                                    AllowExplicit))
4402         return ICS;
4403     }
4404   }
4405 
4406   //     -- Otherwise, the reference shall be an lvalue reference to a
4407   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4408   //        shall be an rvalue reference.
4409   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4410     return ICS;
4411 
4412   //       -- If the initializer expression
4413   //
4414   //            -- is an xvalue, class prvalue, array prvalue or function
4415   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4416   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4417       (InitCategory.isXValue() ||
4418       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4419       (InitCategory.isLValue() && T2->isFunctionType()))) {
4420     ICS.setStandard();
4421     ICS.Standard.First = ICK_Identity;
4422     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4423                       : ObjCConversion? ICK_Compatible_Conversion
4424                       : ICK_Identity;
4425     ICS.Standard.Third = ICK_Identity;
4426     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4427     ICS.Standard.setToType(0, T2);
4428     ICS.Standard.setToType(1, T1);
4429     ICS.Standard.setToType(2, T1);
4430     ICS.Standard.ReferenceBinding = true;
4431     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4432     // binding unless we're binding to a class prvalue.
4433     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4434     // allow the use of rvalue references in C++98/03 for the benefit of
4435     // standard library implementors; therefore, we need the xvalue check here.
4436     ICS.Standard.DirectBinding =
4437       S.getLangOpts().CPlusPlus11 ||
4438       !(InitCategory.isPRValue() || T2->isRecordType());
4439     ICS.Standard.IsLvalueReference = !isRValRef;
4440     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4441     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4442     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4443     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4444     ICS.Standard.CopyConstructor = nullptr;
4445     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4446     return ICS;
4447   }
4448 
4449   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4450   //               reference-related to T2, and can be implicitly converted to
4451   //               an xvalue, class prvalue, or function lvalue of type
4452   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4453   //               "cv3 T3",
4454   //
4455   //          then the reference is bound to the value of the initializer
4456   //          expression in the first case and to the result of the conversion
4457   //          in the second case (or, in either case, to an appropriate base
4458   //          class subobject).
4459   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4460       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4461       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4462                                Init, T2, /*AllowRvalues=*/true,
4463                                AllowExplicit)) {
4464     // In the second case, if the reference is an rvalue reference
4465     // and the second standard conversion sequence of the
4466     // user-defined conversion sequence includes an lvalue-to-rvalue
4467     // conversion, the program is ill-formed.
4468     if (ICS.isUserDefined() && isRValRef &&
4469         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4470       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4471 
4472     return ICS;
4473   }
4474 
4475   // A temporary of function type cannot be created; don't even try.
4476   if (T1->isFunctionType())
4477     return ICS;
4478 
4479   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4480   //          initialized from the initializer expression using the
4481   //          rules for a non-reference copy initialization (8.5). The
4482   //          reference is then bound to the temporary. If T1 is
4483   //          reference-related to T2, cv1 must be the same
4484   //          cv-qualification as, or greater cv-qualification than,
4485   //          cv2; otherwise, the program is ill-formed.
4486   if (RefRelationship == Sema::Ref_Related) {
4487     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4488     // we would be reference-compatible or reference-compatible with
4489     // added qualification. But that wasn't the case, so the reference
4490     // initialization fails.
4491     //
4492     // Note that we only want to check address spaces and cvr-qualifiers here.
4493     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4494     Qualifiers T1Quals = T1.getQualifiers();
4495     Qualifiers T2Quals = T2.getQualifiers();
4496     T1Quals.removeObjCGCAttr();
4497     T1Quals.removeObjCLifetime();
4498     T2Quals.removeObjCGCAttr();
4499     T2Quals.removeObjCLifetime();
4500     // MS compiler ignores __unaligned qualifier for references; do the same.
4501     T1Quals.removeUnaligned();
4502     T2Quals.removeUnaligned();
4503     if (!T1Quals.compatiblyIncludes(T2Quals))
4504       return ICS;
4505   }
4506 
4507   // If at least one of the types is a class type, the types are not
4508   // related, and we aren't allowed any user conversions, the
4509   // reference binding fails. This case is important for breaking
4510   // recursion, since TryImplicitConversion below will attempt to
4511   // create a temporary through the use of a copy constructor.
4512   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4513       (T1->isRecordType() || T2->isRecordType()))
4514     return ICS;
4515 
4516   // If T1 is reference-related to T2 and the reference is an rvalue
4517   // reference, the initializer expression shall not be an lvalue.
4518   if (RefRelationship >= Sema::Ref_Related &&
4519       isRValRef && Init->Classify(S.Context).isLValue())
4520     return ICS;
4521 
4522   // C++ [over.ics.ref]p2:
4523   //   When a parameter of reference type is not bound directly to
4524   //   an argument expression, the conversion sequence is the one
4525   //   required to convert the argument expression to the
4526   //   underlying type of the reference according to
4527   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4528   //   to copy-initializing a temporary of the underlying type with
4529   //   the argument expression. Any difference in top-level
4530   //   cv-qualification is subsumed by the initialization itself
4531   //   and does not constitute a conversion.
4532   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4533                               /*AllowExplicit=*/false,
4534                               /*InOverloadResolution=*/false,
4535                               /*CStyle=*/false,
4536                               /*AllowObjCWritebackConversion=*/false,
4537                               /*AllowObjCConversionOnExplicit=*/false);
4538 
4539   // Of course, that's still a reference binding.
4540   if (ICS.isStandard()) {
4541     ICS.Standard.ReferenceBinding = true;
4542     ICS.Standard.IsLvalueReference = !isRValRef;
4543     ICS.Standard.BindsToFunctionLvalue = false;
4544     ICS.Standard.BindsToRvalue = true;
4545     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4546     ICS.Standard.ObjCLifetimeConversionBinding = false;
4547   } else if (ICS.isUserDefined()) {
4548     const ReferenceType *LValRefType =
4549         ICS.UserDefined.ConversionFunction->getReturnType()
4550             ->getAs<LValueReferenceType>();
4551 
4552     // C++ [over.ics.ref]p3:
4553     //   Except for an implicit object parameter, for which see 13.3.1, a
4554     //   standard conversion sequence cannot be formed if it requires [...]
4555     //   binding an rvalue reference to an lvalue other than a function
4556     //   lvalue.
4557     // Note that the function case is not possible here.
4558     if (DeclType->isRValueReferenceType() && LValRefType) {
4559       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4560       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4561       // reference to an rvalue!
4562       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4563       return ICS;
4564     }
4565 
4566     ICS.UserDefined.After.ReferenceBinding = true;
4567     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4568     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4569     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4570     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4571     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4572   }
4573 
4574   return ICS;
4575 }
4576 
4577 static ImplicitConversionSequence
4578 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4579                       bool SuppressUserConversions,
4580                       bool InOverloadResolution,
4581                       bool AllowObjCWritebackConversion,
4582                       bool AllowExplicit = false);
4583 
4584 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4585 /// initializer list From.
4586 static ImplicitConversionSequence
4587 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4588                   bool SuppressUserConversions,
4589                   bool InOverloadResolution,
4590                   bool AllowObjCWritebackConversion) {
4591   // C++11 [over.ics.list]p1:
4592   //   When an argument is an initializer list, it is not an expression and
4593   //   special rules apply for converting it to a parameter type.
4594 
4595   ImplicitConversionSequence Result;
4596   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4597 
4598   // We need a complete type for what follows. Incomplete types can never be
4599   // initialized from init lists.
4600   if (!S.isCompleteType(From->getLocStart(), ToType))
4601     return Result;
4602 
4603   // Per DR1467:
4604   //   If the parameter type is a class X and the initializer list has a single
4605   //   element of type cv U, where U is X or a class derived from X, the
4606   //   implicit conversion sequence is the one required to convert the element
4607   //   to the parameter type.
4608   //
4609   //   Otherwise, if the parameter type is a character array [... ]
4610   //   and the initializer list has a single element that is an
4611   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4612   //   implicit conversion sequence is the identity conversion.
4613   if (From->getNumInits() == 1) {
4614     if (ToType->isRecordType()) {
4615       QualType InitType = From->getInit(0)->getType();
4616       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4617           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4618         return TryCopyInitialization(S, From->getInit(0), ToType,
4619                                      SuppressUserConversions,
4620                                      InOverloadResolution,
4621                                      AllowObjCWritebackConversion);
4622     }
4623     // FIXME: Check the other conditions here: array of character type,
4624     // initializer is a string literal.
4625     if (ToType->isArrayType()) {
4626       InitializedEntity Entity =
4627         InitializedEntity::InitializeParameter(S.Context, ToType,
4628                                                /*Consumed=*/false);
4629       if (S.CanPerformCopyInitialization(Entity, From)) {
4630         Result.setStandard();
4631         Result.Standard.setAsIdentityConversion();
4632         Result.Standard.setFromType(ToType);
4633         Result.Standard.setAllToTypes(ToType);
4634         return Result;
4635       }
4636     }
4637   }
4638 
4639   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4640   // C++11 [over.ics.list]p2:
4641   //   If the parameter type is std::initializer_list<X> or "array of X" and
4642   //   all the elements can be implicitly converted to X, the implicit
4643   //   conversion sequence is the worst conversion necessary to convert an
4644   //   element of the list to X.
4645   //
4646   // C++14 [over.ics.list]p3:
4647   //   Otherwise, if the parameter type is "array of N X", if the initializer
4648   //   list has exactly N elements or if it has fewer than N elements and X is
4649   //   default-constructible, and if all the elements of the initializer list
4650   //   can be implicitly converted to X, the implicit conversion sequence is
4651   //   the worst conversion necessary to convert an element of the list to X.
4652   //
4653   // FIXME: We're missing a lot of these checks.
4654   bool toStdInitializerList = false;
4655   QualType X;
4656   if (ToType->isArrayType())
4657     X = S.Context.getAsArrayType(ToType)->getElementType();
4658   else
4659     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4660   if (!X.isNull()) {
4661     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4662       Expr *Init = From->getInit(i);
4663       ImplicitConversionSequence ICS =
4664           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4665                                 InOverloadResolution,
4666                                 AllowObjCWritebackConversion);
4667       // If a single element isn't convertible, fail.
4668       if (ICS.isBad()) {
4669         Result = ICS;
4670         break;
4671       }
4672       // Otherwise, look for the worst conversion.
4673       if (Result.isBad() ||
4674           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4675                                              Result) ==
4676               ImplicitConversionSequence::Worse)
4677         Result = ICS;
4678     }
4679 
4680     // For an empty list, we won't have computed any conversion sequence.
4681     // Introduce the identity conversion sequence.
4682     if (From->getNumInits() == 0) {
4683       Result.setStandard();
4684       Result.Standard.setAsIdentityConversion();
4685       Result.Standard.setFromType(ToType);
4686       Result.Standard.setAllToTypes(ToType);
4687     }
4688 
4689     Result.setStdInitializerListElement(toStdInitializerList);
4690     return Result;
4691   }
4692 
4693   // C++14 [over.ics.list]p4:
4694   // C++11 [over.ics.list]p3:
4695   //   Otherwise, if the parameter is a non-aggregate class X and overload
4696   //   resolution chooses a single best constructor [...] the implicit
4697   //   conversion sequence is a user-defined conversion sequence. If multiple
4698   //   constructors are viable but none is better than the others, the
4699   //   implicit conversion sequence is a user-defined conversion sequence.
4700   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4701     // This function can deal with initializer lists.
4702     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4703                                     /*AllowExplicit=*/false,
4704                                     InOverloadResolution, /*CStyle=*/false,
4705                                     AllowObjCWritebackConversion,
4706                                     /*AllowObjCConversionOnExplicit=*/false);
4707   }
4708 
4709   // C++14 [over.ics.list]p5:
4710   // C++11 [over.ics.list]p4:
4711   //   Otherwise, if the parameter has an aggregate type which can be
4712   //   initialized from the initializer list [...] the implicit conversion
4713   //   sequence is a user-defined conversion sequence.
4714   if (ToType->isAggregateType()) {
4715     // Type is an aggregate, argument is an init list. At this point it comes
4716     // down to checking whether the initialization works.
4717     // FIXME: Find out whether this parameter is consumed or not.
4718     InitializedEntity Entity =
4719         InitializedEntity::InitializeParameter(S.Context, ToType,
4720                                                /*Consumed=*/false);
4721     if (S.CanPerformCopyInitialization(Entity, From)) {
4722       Result.setUserDefined();
4723       Result.UserDefined.Before.setAsIdentityConversion();
4724       // Initializer lists don't have a type.
4725       Result.UserDefined.Before.setFromType(QualType());
4726       Result.UserDefined.Before.setAllToTypes(QualType());
4727 
4728       Result.UserDefined.After.setAsIdentityConversion();
4729       Result.UserDefined.After.setFromType(ToType);
4730       Result.UserDefined.After.setAllToTypes(ToType);
4731       Result.UserDefined.ConversionFunction = nullptr;
4732     }
4733     return Result;
4734   }
4735 
4736   // C++14 [over.ics.list]p6:
4737   // C++11 [over.ics.list]p5:
4738   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4739   if (ToType->isReferenceType()) {
4740     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4741     // mention initializer lists in any way. So we go by what list-
4742     // initialization would do and try to extrapolate from that.
4743 
4744     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4745 
4746     // If the initializer list has a single element that is reference-related
4747     // to the parameter type, we initialize the reference from that.
4748     if (From->getNumInits() == 1) {
4749       Expr *Init = From->getInit(0);
4750 
4751       QualType T2 = Init->getType();
4752 
4753       // If the initializer is the address of an overloaded function, try
4754       // to resolve the overloaded function. If all goes well, T2 is the
4755       // type of the resulting function.
4756       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4757         DeclAccessPair Found;
4758         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4759                                    Init, ToType, false, Found))
4760           T2 = Fn->getType();
4761       }
4762 
4763       // Compute some basic properties of the types and the initializer.
4764       bool dummy1 = false;
4765       bool dummy2 = false;
4766       bool dummy3 = false;
4767       Sema::ReferenceCompareResult RefRelationship
4768         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4769                                          dummy2, dummy3);
4770 
4771       if (RefRelationship >= Sema::Ref_Related) {
4772         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4773                                 SuppressUserConversions,
4774                                 /*AllowExplicit=*/false);
4775       }
4776     }
4777 
4778     // Otherwise, we bind the reference to a temporary created from the
4779     // initializer list.
4780     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4781                                InOverloadResolution,
4782                                AllowObjCWritebackConversion);
4783     if (Result.isFailure())
4784       return Result;
4785     assert(!Result.isEllipsis() &&
4786            "Sub-initialization cannot result in ellipsis conversion.");
4787 
4788     // Can we even bind to a temporary?
4789     if (ToType->isRValueReferenceType() ||
4790         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4791       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4792                                             Result.UserDefined.After;
4793       SCS.ReferenceBinding = true;
4794       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4795       SCS.BindsToRvalue = true;
4796       SCS.BindsToFunctionLvalue = false;
4797       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4798       SCS.ObjCLifetimeConversionBinding = false;
4799     } else
4800       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4801                     From, ToType);
4802     return Result;
4803   }
4804 
4805   // C++14 [over.ics.list]p7:
4806   // C++11 [over.ics.list]p6:
4807   //   Otherwise, if the parameter type is not a class:
4808   if (!ToType->isRecordType()) {
4809     //    - if the initializer list has one element that is not itself an
4810     //      initializer list, the implicit conversion sequence is the one
4811     //      required to convert the element to the parameter type.
4812     unsigned NumInits = From->getNumInits();
4813     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4814       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4815                                      SuppressUserConversions,
4816                                      InOverloadResolution,
4817                                      AllowObjCWritebackConversion);
4818     //    - if the initializer list has no elements, the implicit conversion
4819     //      sequence is the identity conversion.
4820     else if (NumInits == 0) {
4821       Result.setStandard();
4822       Result.Standard.setAsIdentityConversion();
4823       Result.Standard.setFromType(ToType);
4824       Result.Standard.setAllToTypes(ToType);
4825     }
4826     return Result;
4827   }
4828 
4829   // C++14 [over.ics.list]p8:
4830   // C++11 [over.ics.list]p7:
4831   //   In all cases other than those enumerated above, no conversion is possible
4832   return Result;
4833 }
4834 
4835 /// TryCopyInitialization - Try to copy-initialize a value of type
4836 /// ToType from the expression From. Return the implicit conversion
4837 /// sequence required to pass this argument, which may be a bad
4838 /// conversion sequence (meaning that the argument cannot be passed to
4839 /// a parameter of this type). If @p SuppressUserConversions, then we
4840 /// do not permit any user-defined conversion sequences.
4841 static ImplicitConversionSequence
4842 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4843                       bool SuppressUserConversions,
4844                       bool InOverloadResolution,
4845                       bool AllowObjCWritebackConversion,
4846                       bool AllowExplicit) {
4847   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4848     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4849                              InOverloadResolution,AllowObjCWritebackConversion);
4850 
4851   if (ToType->isReferenceType())
4852     return TryReferenceInit(S, From, ToType,
4853                             /*FIXME:*/From->getLocStart(),
4854                             SuppressUserConversions,
4855                             AllowExplicit);
4856 
4857   return TryImplicitConversion(S, From, ToType,
4858                                SuppressUserConversions,
4859                                /*AllowExplicit=*/false,
4860                                InOverloadResolution,
4861                                /*CStyle=*/false,
4862                                AllowObjCWritebackConversion,
4863                                /*AllowObjCConversionOnExplicit=*/false);
4864 }
4865 
4866 static bool TryCopyInitialization(const CanQualType FromQTy,
4867                                   const CanQualType ToQTy,
4868                                   Sema &S,
4869                                   SourceLocation Loc,
4870                                   ExprValueKind FromVK) {
4871   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4872   ImplicitConversionSequence ICS =
4873     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4874 
4875   return !ICS.isBad();
4876 }
4877 
4878 /// TryObjectArgumentInitialization - Try to initialize the object
4879 /// parameter of the given member function (@c Method) from the
4880 /// expression @p From.
4881 static ImplicitConversionSequence
4882 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4883                                 Expr::Classification FromClassification,
4884                                 CXXMethodDecl *Method,
4885                                 CXXRecordDecl *ActingContext) {
4886   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4887   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4888   //                 const volatile object.
4889   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4890     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4891   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4892 
4893   // Set up the conversion sequence as a "bad" conversion, to allow us
4894   // to exit early.
4895   ImplicitConversionSequence ICS;
4896 
4897   // We need to have an object of class type.
4898   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4899     FromType = PT->getPointeeType();
4900 
4901     // When we had a pointer, it's implicitly dereferenced, so we
4902     // better have an lvalue.
4903     assert(FromClassification.isLValue());
4904   }
4905 
4906   assert(FromType->isRecordType());
4907 
4908   // C++0x [over.match.funcs]p4:
4909   //   For non-static member functions, the type of the implicit object
4910   //   parameter is
4911   //
4912   //     - "lvalue reference to cv X" for functions declared without a
4913   //        ref-qualifier or with the & ref-qualifier
4914   //     - "rvalue reference to cv X" for functions declared with the &&
4915   //        ref-qualifier
4916   //
4917   // where X is the class of which the function is a member and cv is the
4918   // cv-qualification on the member function declaration.
4919   //
4920   // However, when finding an implicit conversion sequence for the argument, we
4921   // are not allowed to create temporaries or perform user-defined conversions
4922   // (C++ [over.match.funcs]p5). We perform a simplified version of
4923   // reference binding here, that allows class rvalues to bind to
4924   // non-constant references.
4925 
4926   // First check the qualifiers.
4927   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4928   if (ImplicitParamType.getCVRQualifiers()
4929                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4930       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4931     ICS.setBad(BadConversionSequence::bad_qualifiers,
4932                FromType, ImplicitParamType);
4933     return ICS;
4934   }
4935 
4936   // Check that we have either the same type or a derived type. It
4937   // affects the conversion rank.
4938   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4939   ImplicitConversionKind SecondKind;
4940   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4941     SecondKind = ICK_Identity;
4942   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4943     SecondKind = ICK_Derived_To_Base;
4944   else {
4945     ICS.setBad(BadConversionSequence::unrelated_class,
4946                FromType, ImplicitParamType);
4947     return ICS;
4948   }
4949 
4950   // Check the ref-qualifier.
4951   switch (Method->getRefQualifier()) {
4952   case RQ_None:
4953     // Do nothing; we don't care about lvalueness or rvalueness.
4954     break;
4955 
4956   case RQ_LValue:
4957     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4958       // non-const lvalue reference cannot bind to an rvalue
4959       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4960                  ImplicitParamType);
4961       return ICS;
4962     }
4963     break;
4964 
4965   case RQ_RValue:
4966     if (!FromClassification.isRValue()) {
4967       // rvalue reference cannot bind to an lvalue
4968       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4969                  ImplicitParamType);
4970       return ICS;
4971     }
4972     break;
4973   }
4974 
4975   // Success. Mark this as a reference binding.
4976   ICS.setStandard();
4977   ICS.Standard.setAsIdentityConversion();
4978   ICS.Standard.Second = SecondKind;
4979   ICS.Standard.setFromType(FromType);
4980   ICS.Standard.setAllToTypes(ImplicitParamType);
4981   ICS.Standard.ReferenceBinding = true;
4982   ICS.Standard.DirectBinding = true;
4983   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4984   ICS.Standard.BindsToFunctionLvalue = false;
4985   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4986   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4987     = (Method->getRefQualifier() == RQ_None);
4988   return ICS;
4989 }
4990 
4991 /// PerformObjectArgumentInitialization - Perform initialization of
4992 /// the implicit object parameter for the given Method with the given
4993 /// expression.
4994 ExprResult
4995 Sema::PerformObjectArgumentInitialization(Expr *From,
4996                                           NestedNameSpecifier *Qualifier,
4997                                           NamedDecl *FoundDecl,
4998                                           CXXMethodDecl *Method) {
4999   QualType FromRecordType, DestType;
5000   QualType ImplicitParamRecordType  =
5001     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5002 
5003   Expr::Classification FromClassification;
5004   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5005     FromRecordType = PT->getPointeeType();
5006     DestType = Method->getThisType(Context);
5007     FromClassification = Expr::Classification::makeSimpleLValue();
5008   } else {
5009     FromRecordType = From->getType();
5010     DestType = ImplicitParamRecordType;
5011     FromClassification = From->Classify(Context);
5012   }
5013 
5014   // Note that we always use the true parent context when performing
5015   // the actual argument initialization.
5016   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5017       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5018       Method->getParent());
5019   if (ICS.isBad()) {
5020     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5021       Qualifiers FromQs = FromRecordType.getQualifiers();
5022       Qualifiers ToQs = DestType.getQualifiers();
5023       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5024       if (CVR) {
5025         Diag(From->getLocStart(),
5026              diag::err_member_function_call_bad_cvr)
5027           << Method->getDeclName() << FromRecordType << (CVR - 1)
5028           << From->getSourceRange();
5029         Diag(Method->getLocation(), diag::note_previous_decl)
5030           << Method->getDeclName();
5031         return ExprError();
5032       }
5033     }
5034 
5035     return Diag(From->getLocStart(),
5036                 diag::err_implicit_object_parameter_init)
5037        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5038   }
5039 
5040   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5041     ExprResult FromRes =
5042       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5043     if (FromRes.isInvalid())
5044       return ExprError();
5045     From = FromRes.get();
5046   }
5047 
5048   if (!Context.hasSameType(From->getType(), DestType))
5049     From = ImpCastExprToType(From, DestType, CK_NoOp,
5050                              From->getValueKind()).get();
5051   return From;
5052 }
5053 
5054 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5055 /// expression From to bool (C++0x [conv]p3).
5056 static ImplicitConversionSequence
5057 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5058   return TryImplicitConversion(S, From, S.Context.BoolTy,
5059                                /*SuppressUserConversions=*/false,
5060                                /*AllowExplicit=*/true,
5061                                /*InOverloadResolution=*/false,
5062                                /*CStyle=*/false,
5063                                /*AllowObjCWritebackConversion=*/false,
5064                                /*AllowObjCConversionOnExplicit=*/false);
5065 }
5066 
5067 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5068 /// of the expression From to bool (C++0x [conv]p3).
5069 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5070   if (checkPlaceholderForOverload(*this, From))
5071     return ExprError();
5072 
5073   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5074   if (!ICS.isBad())
5075     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5076 
5077   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5078     return Diag(From->getLocStart(),
5079                 diag::err_typecheck_bool_condition)
5080                   << From->getType() << From->getSourceRange();
5081   return ExprError();
5082 }
5083 
5084 /// Check that the specified conversion is permitted in a converted constant
5085 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5086 /// is acceptable.
5087 static bool CheckConvertedConstantConversions(Sema &S,
5088                                               StandardConversionSequence &SCS) {
5089   // Since we know that the target type is an integral or unscoped enumeration
5090   // type, most conversion kinds are impossible. All possible First and Third
5091   // conversions are fine.
5092   switch (SCS.Second) {
5093   case ICK_Identity:
5094   case ICK_NoReturn_Adjustment:
5095   case ICK_Integral_Promotion:
5096   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5097     return true;
5098 
5099   case ICK_Boolean_Conversion:
5100     // Conversion from an integral or unscoped enumeration type to bool is
5101     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5102     // conversion, so we allow it in a converted constant expression.
5103     //
5104     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5105     // a lot of popular code. We should at least add a warning for this
5106     // (non-conforming) extension.
5107     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5108            SCS.getToType(2)->isBooleanType();
5109 
5110   case ICK_Pointer_Conversion:
5111   case ICK_Pointer_Member:
5112     // C++1z: null pointer conversions and null member pointer conversions are
5113     // only permitted if the source type is std::nullptr_t.
5114     return SCS.getFromType()->isNullPtrType();
5115 
5116   case ICK_Floating_Promotion:
5117   case ICK_Complex_Promotion:
5118   case ICK_Floating_Conversion:
5119   case ICK_Complex_Conversion:
5120   case ICK_Floating_Integral:
5121   case ICK_Compatible_Conversion:
5122   case ICK_Derived_To_Base:
5123   case ICK_Vector_Conversion:
5124   case ICK_Vector_Splat:
5125   case ICK_Complex_Real:
5126   case ICK_Block_Pointer_Conversion:
5127   case ICK_TransparentUnionConversion:
5128   case ICK_Writeback_Conversion:
5129   case ICK_Zero_Event_Conversion:
5130   case ICK_C_Only_Conversion:
5131   case ICK_Incompatible_Pointer_Conversion:
5132     return false;
5133 
5134   case ICK_Lvalue_To_Rvalue:
5135   case ICK_Array_To_Pointer:
5136   case ICK_Function_To_Pointer:
5137     llvm_unreachable("found a first conversion kind in Second");
5138 
5139   case ICK_Qualification:
5140     llvm_unreachable("found a third conversion kind in Second");
5141 
5142   case ICK_Num_Conversion_Kinds:
5143     break;
5144   }
5145 
5146   llvm_unreachable("unknown conversion kind");
5147 }
5148 
5149 /// CheckConvertedConstantExpression - Check that the expression From is a
5150 /// converted constant expression of type T, perform the conversion and produce
5151 /// the converted expression, per C++11 [expr.const]p3.
5152 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5153                                                    QualType T, APValue &Value,
5154                                                    Sema::CCEKind CCE,
5155                                                    bool RequireInt) {
5156   assert(S.getLangOpts().CPlusPlus11 &&
5157          "converted constant expression outside C++11");
5158 
5159   if (checkPlaceholderForOverload(S, From))
5160     return ExprError();
5161 
5162   // C++1z [expr.const]p3:
5163   //  A converted constant expression of type T is an expression,
5164   //  implicitly converted to type T, where the converted
5165   //  expression is a constant expression and the implicit conversion
5166   //  sequence contains only [... list of conversions ...].
5167   // C++1z [stmt.if]p2:
5168   //  If the if statement is of the form if constexpr, the value of the
5169   //  condition shall be a contextually converted constant expression of type
5170   //  bool.
5171   ImplicitConversionSequence ICS =
5172       CCE == Sema::CCEK_ConstexprIf
5173           ? TryContextuallyConvertToBool(S, From)
5174           : TryCopyInitialization(S, From, T,
5175                                   /*SuppressUserConversions=*/false,
5176                                   /*InOverloadResolution=*/false,
5177                                   /*AllowObjcWritebackConversion=*/false,
5178                                   /*AllowExplicit=*/false);
5179   StandardConversionSequence *SCS = nullptr;
5180   switch (ICS.getKind()) {
5181   case ImplicitConversionSequence::StandardConversion:
5182     SCS = &ICS.Standard;
5183     break;
5184   case ImplicitConversionSequence::UserDefinedConversion:
5185     // We are converting to a non-class type, so the Before sequence
5186     // must be trivial.
5187     SCS = &ICS.UserDefined.After;
5188     break;
5189   case ImplicitConversionSequence::AmbiguousConversion:
5190   case ImplicitConversionSequence::BadConversion:
5191     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5192       return S.Diag(From->getLocStart(),
5193                     diag::err_typecheck_converted_constant_expression)
5194                 << From->getType() << From->getSourceRange() << T;
5195     return ExprError();
5196 
5197   case ImplicitConversionSequence::EllipsisConversion:
5198     llvm_unreachable("ellipsis conversion in converted constant expression");
5199   }
5200 
5201   // Check that we would only use permitted conversions.
5202   if (!CheckConvertedConstantConversions(S, *SCS)) {
5203     return S.Diag(From->getLocStart(),
5204                   diag::err_typecheck_converted_constant_expression_disallowed)
5205              << From->getType() << From->getSourceRange() << T;
5206   }
5207   // [...] and where the reference binding (if any) binds directly.
5208   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5209     return S.Diag(From->getLocStart(),
5210                   diag::err_typecheck_converted_constant_expression_indirect)
5211              << From->getType() << From->getSourceRange() << T;
5212   }
5213 
5214   ExprResult Result =
5215       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5216   if (Result.isInvalid())
5217     return Result;
5218 
5219   // Check for a narrowing implicit conversion.
5220   APValue PreNarrowingValue;
5221   QualType PreNarrowingType;
5222   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5223                                 PreNarrowingType)) {
5224   case NK_Variable_Narrowing:
5225     // Implicit conversion to a narrower type, and the value is not a constant
5226     // expression. We'll diagnose this in a moment.
5227   case NK_Not_Narrowing:
5228     break;
5229 
5230   case NK_Constant_Narrowing:
5231     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5232       << CCE << /*Constant*/1
5233       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5234     break;
5235 
5236   case NK_Type_Narrowing:
5237     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5238       << CCE << /*Constant*/0 << From->getType() << T;
5239     break;
5240   }
5241 
5242   // Check the expression is a constant expression.
5243   SmallVector<PartialDiagnosticAt, 8> Notes;
5244   Expr::EvalResult Eval;
5245   Eval.Diag = &Notes;
5246 
5247   if ((T->isReferenceType()
5248            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5249            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5250       (RequireInt && !Eval.Val.isInt())) {
5251     // The expression can't be folded, so we can't keep it at this position in
5252     // the AST.
5253     Result = ExprError();
5254   } else {
5255     Value = Eval.Val;
5256 
5257     if (Notes.empty()) {
5258       // It's a constant expression.
5259       return Result;
5260     }
5261   }
5262 
5263   // It's not a constant expression. Produce an appropriate diagnostic.
5264   if (Notes.size() == 1 &&
5265       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5266     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5267   else {
5268     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5269       << CCE << From->getSourceRange();
5270     for (unsigned I = 0; I < Notes.size(); ++I)
5271       S.Diag(Notes[I].first, Notes[I].second);
5272   }
5273   return ExprError();
5274 }
5275 
5276 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5277                                                   APValue &Value, CCEKind CCE) {
5278   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5279 }
5280 
5281 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5282                                                   llvm::APSInt &Value,
5283                                                   CCEKind CCE) {
5284   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5285 
5286   APValue V;
5287   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5288   if (!R.isInvalid())
5289     Value = V.getInt();
5290   return R;
5291 }
5292 
5293 
5294 /// dropPointerConversions - If the given standard conversion sequence
5295 /// involves any pointer conversions, remove them.  This may change
5296 /// the result type of the conversion sequence.
5297 static void dropPointerConversion(StandardConversionSequence &SCS) {
5298   if (SCS.Second == ICK_Pointer_Conversion) {
5299     SCS.Second = ICK_Identity;
5300     SCS.Third = ICK_Identity;
5301     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5302   }
5303 }
5304 
5305 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5306 /// convert the expression From to an Objective-C pointer type.
5307 static ImplicitConversionSequence
5308 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5309   // Do an implicit conversion to 'id'.
5310   QualType Ty = S.Context.getObjCIdType();
5311   ImplicitConversionSequence ICS
5312     = TryImplicitConversion(S, From, Ty,
5313                             // FIXME: Are these flags correct?
5314                             /*SuppressUserConversions=*/false,
5315                             /*AllowExplicit=*/true,
5316                             /*InOverloadResolution=*/false,
5317                             /*CStyle=*/false,
5318                             /*AllowObjCWritebackConversion=*/false,
5319                             /*AllowObjCConversionOnExplicit=*/true);
5320 
5321   // Strip off any final conversions to 'id'.
5322   switch (ICS.getKind()) {
5323   case ImplicitConversionSequence::BadConversion:
5324   case ImplicitConversionSequence::AmbiguousConversion:
5325   case ImplicitConversionSequence::EllipsisConversion:
5326     break;
5327 
5328   case ImplicitConversionSequence::UserDefinedConversion:
5329     dropPointerConversion(ICS.UserDefined.After);
5330     break;
5331 
5332   case ImplicitConversionSequence::StandardConversion:
5333     dropPointerConversion(ICS.Standard);
5334     break;
5335   }
5336 
5337   return ICS;
5338 }
5339 
5340 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5341 /// conversion of the expression From to an Objective-C pointer type.
5342 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5343   if (checkPlaceholderForOverload(*this, From))
5344     return ExprError();
5345 
5346   QualType Ty = Context.getObjCIdType();
5347   ImplicitConversionSequence ICS =
5348     TryContextuallyConvertToObjCPointer(*this, From);
5349   if (!ICS.isBad())
5350     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5351   return ExprError();
5352 }
5353 
5354 /// Determine whether the provided type is an integral type, or an enumeration
5355 /// type of a permitted flavor.
5356 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5357   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5358                                  : T->isIntegralOrUnscopedEnumerationType();
5359 }
5360 
5361 static ExprResult
5362 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5363                             Sema::ContextualImplicitConverter &Converter,
5364                             QualType T, UnresolvedSetImpl &ViableConversions) {
5365 
5366   if (Converter.Suppress)
5367     return ExprError();
5368 
5369   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5370   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5371     CXXConversionDecl *Conv =
5372         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5373     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5374     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5375   }
5376   return From;
5377 }
5378 
5379 static bool
5380 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5381                            Sema::ContextualImplicitConverter &Converter,
5382                            QualType T, bool HadMultipleCandidates,
5383                            UnresolvedSetImpl &ExplicitConversions) {
5384   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5385     DeclAccessPair Found = ExplicitConversions[0];
5386     CXXConversionDecl *Conversion =
5387         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5388 
5389     // The user probably meant to invoke the given explicit
5390     // conversion; use it.
5391     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5392     std::string TypeStr;
5393     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5394 
5395     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5396         << FixItHint::CreateInsertion(From->getLocStart(),
5397                                       "static_cast<" + TypeStr + ">(")
5398         << FixItHint::CreateInsertion(
5399                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5400     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5401 
5402     // If we aren't in a SFINAE context, build a call to the
5403     // explicit conversion function.
5404     if (SemaRef.isSFINAEContext())
5405       return true;
5406 
5407     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5408     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5409                                                        HadMultipleCandidates);
5410     if (Result.isInvalid())
5411       return true;
5412     // Record usage of conversion in an implicit cast.
5413     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5414                                     CK_UserDefinedConversion, Result.get(),
5415                                     nullptr, Result.get()->getValueKind());
5416   }
5417   return false;
5418 }
5419 
5420 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5421                              Sema::ContextualImplicitConverter &Converter,
5422                              QualType T, bool HadMultipleCandidates,
5423                              DeclAccessPair &Found) {
5424   CXXConversionDecl *Conversion =
5425       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5426   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5427 
5428   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5429   if (!Converter.SuppressConversion) {
5430     if (SemaRef.isSFINAEContext())
5431       return true;
5432 
5433     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5434         << From->getSourceRange();
5435   }
5436 
5437   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5438                                                      HadMultipleCandidates);
5439   if (Result.isInvalid())
5440     return true;
5441   // Record usage of conversion in an implicit cast.
5442   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5443                                   CK_UserDefinedConversion, Result.get(),
5444                                   nullptr, Result.get()->getValueKind());
5445   return false;
5446 }
5447 
5448 static ExprResult finishContextualImplicitConversion(
5449     Sema &SemaRef, SourceLocation Loc, Expr *From,
5450     Sema::ContextualImplicitConverter &Converter) {
5451   if (!Converter.match(From->getType()) && !Converter.Suppress)
5452     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5453         << From->getSourceRange();
5454 
5455   return SemaRef.DefaultLvalueConversion(From);
5456 }
5457 
5458 static void
5459 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5460                                   UnresolvedSetImpl &ViableConversions,
5461                                   OverloadCandidateSet &CandidateSet) {
5462   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5463     DeclAccessPair FoundDecl = ViableConversions[I];
5464     NamedDecl *D = FoundDecl.getDecl();
5465     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5466     if (isa<UsingShadowDecl>(D))
5467       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5468 
5469     CXXConversionDecl *Conv;
5470     FunctionTemplateDecl *ConvTemplate;
5471     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5472       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5473     else
5474       Conv = cast<CXXConversionDecl>(D);
5475 
5476     if (ConvTemplate)
5477       SemaRef.AddTemplateConversionCandidate(
5478         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5479         /*AllowObjCConversionOnExplicit=*/false);
5480     else
5481       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5482                                      ToType, CandidateSet,
5483                                      /*AllowObjCConversionOnExplicit=*/false);
5484   }
5485 }
5486 
5487 /// \brief Attempt to convert the given expression to a type which is accepted
5488 /// by the given converter.
5489 ///
5490 /// This routine will attempt to convert an expression of class type to a
5491 /// type accepted by the specified converter. In C++11 and before, the class
5492 /// must have a single non-explicit conversion function converting to a matching
5493 /// type. In C++1y, there can be multiple such conversion functions, but only
5494 /// one target type.
5495 ///
5496 /// \param Loc The source location of the construct that requires the
5497 /// conversion.
5498 ///
5499 /// \param From The expression we're converting from.
5500 ///
5501 /// \param Converter Used to control and diagnose the conversion process.
5502 ///
5503 /// \returns The expression, converted to an integral or enumeration type if
5504 /// successful.
5505 ExprResult Sema::PerformContextualImplicitConversion(
5506     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5507   // We can't perform any more checking for type-dependent expressions.
5508   if (From->isTypeDependent())
5509     return From;
5510 
5511   // Process placeholders immediately.
5512   if (From->hasPlaceholderType()) {
5513     ExprResult result = CheckPlaceholderExpr(From);
5514     if (result.isInvalid())
5515       return result;
5516     From = result.get();
5517   }
5518 
5519   // If the expression already has a matching type, we're golden.
5520   QualType T = From->getType();
5521   if (Converter.match(T))
5522     return DefaultLvalueConversion(From);
5523 
5524   // FIXME: Check for missing '()' if T is a function type?
5525 
5526   // We can only perform contextual implicit conversions on objects of class
5527   // type.
5528   const RecordType *RecordTy = T->getAs<RecordType>();
5529   if (!RecordTy || !getLangOpts().CPlusPlus) {
5530     if (!Converter.Suppress)
5531       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5532     return From;
5533   }
5534 
5535   // We must have a complete class type.
5536   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5537     ContextualImplicitConverter &Converter;
5538     Expr *From;
5539 
5540     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5541         : Converter(Converter), From(From) {}
5542 
5543     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5544       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5545     }
5546   } IncompleteDiagnoser(Converter, From);
5547 
5548   if (Converter.Suppress ? !isCompleteType(Loc, T)
5549                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5550     return From;
5551 
5552   // Look for a conversion to an integral or enumeration type.
5553   UnresolvedSet<4>
5554       ViableConversions; // These are *potentially* viable in C++1y.
5555   UnresolvedSet<4> ExplicitConversions;
5556   const auto &Conversions =
5557       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5558 
5559   bool HadMultipleCandidates =
5560       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5561 
5562   // To check that there is only one target type, in C++1y:
5563   QualType ToType;
5564   bool HasUniqueTargetType = true;
5565 
5566   // Collect explicit or viable (potentially in C++1y) conversions.
5567   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5568     NamedDecl *D = (*I)->getUnderlyingDecl();
5569     CXXConversionDecl *Conversion;
5570     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5571     if (ConvTemplate) {
5572       if (getLangOpts().CPlusPlus14)
5573         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5574       else
5575         continue; // C++11 does not consider conversion operator templates(?).
5576     } else
5577       Conversion = cast<CXXConversionDecl>(D);
5578 
5579     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5580            "Conversion operator templates are considered potentially "
5581            "viable in C++1y");
5582 
5583     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5584     if (Converter.match(CurToType) || ConvTemplate) {
5585 
5586       if (Conversion->isExplicit()) {
5587         // FIXME: For C++1y, do we need this restriction?
5588         // cf. diagnoseNoViableConversion()
5589         if (!ConvTemplate)
5590           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5591       } else {
5592         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5593           if (ToType.isNull())
5594             ToType = CurToType.getUnqualifiedType();
5595           else if (HasUniqueTargetType &&
5596                    (CurToType.getUnqualifiedType() != ToType))
5597             HasUniqueTargetType = false;
5598         }
5599         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5600       }
5601     }
5602   }
5603 
5604   if (getLangOpts().CPlusPlus14) {
5605     // C++1y [conv]p6:
5606     // ... An expression e of class type E appearing in such a context
5607     // is said to be contextually implicitly converted to a specified
5608     // type T and is well-formed if and only if e can be implicitly
5609     // converted to a type T that is determined as follows: E is searched
5610     // for conversion functions whose return type is cv T or reference to
5611     // cv T such that T is allowed by the context. There shall be
5612     // exactly one such T.
5613 
5614     // If no unique T is found:
5615     if (ToType.isNull()) {
5616       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5617                                      HadMultipleCandidates,
5618                                      ExplicitConversions))
5619         return ExprError();
5620       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5621     }
5622 
5623     // If more than one unique Ts are found:
5624     if (!HasUniqueTargetType)
5625       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5626                                          ViableConversions);
5627 
5628     // If one unique T is found:
5629     // First, build a candidate set from the previously recorded
5630     // potentially viable conversions.
5631     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5632     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5633                                       CandidateSet);
5634 
5635     // Then, perform overload resolution over the candidate set.
5636     OverloadCandidateSet::iterator Best;
5637     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5638     case OR_Success: {
5639       // Apply this conversion.
5640       DeclAccessPair Found =
5641           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5642       if (recordConversion(*this, Loc, From, Converter, T,
5643                            HadMultipleCandidates, Found))
5644         return ExprError();
5645       break;
5646     }
5647     case OR_Ambiguous:
5648       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5649                                          ViableConversions);
5650     case OR_No_Viable_Function:
5651       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5652                                      HadMultipleCandidates,
5653                                      ExplicitConversions))
5654         return ExprError();
5655     // fall through 'OR_Deleted' case.
5656     case OR_Deleted:
5657       // We'll complain below about a non-integral condition type.
5658       break;
5659     }
5660   } else {
5661     switch (ViableConversions.size()) {
5662     case 0: {
5663       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5664                                      HadMultipleCandidates,
5665                                      ExplicitConversions))
5666         return ExprError();
5667 
5668       // We'll complain below about a non-integral condition type.
5669       break;
5670     }
5671     case 1: {
5672       // Apply this conversion.
5673       DeclAccessPair Found = ViableConversions[0];
5674       if (recordConversion(*this, Loc, From, Converter, T,
5675                            HadMultipleCandidates, Found))
5676         return ExprError();
5677       break;
5678     }
5679     default:
5680       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5681                                          ViableConversions);
5682     }
5683   }
5684 
5685   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5686 }
5687 
5688 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5689 /// an acceptable non-member overloaded operator for a call whose
5690 /// arguments have types T1 (and, if non-empty, T2). This routine
5691 /// implements the check in C++ [over.match.oper]p3b2 concerning
5692 /// enumeration types.
5693 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5694                                                    FunctionDecl *Fn,
5695                                                    ArrayRef<Expr *> Args) {
5696   QualType T1 = Args[0]->getType();
5697   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5698 
5699   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5700     return true;
5701 
5702   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5703     return true;
5704 
5705   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5706   if (Proto->getNumParams() < 1)
5707     return false;
5708 
5709   if (T1->isEnumeralType()) {
5710     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5711     if (Context.hasSameUnqualifiedType(T1, ArgType))
5712       return true;
5713   }
5714 
5715   if (Proto->getNumParams() < 2)
5716     return false;
5717 
5718   if (!T2.isNull() && T2->isEnumeralType()) {
5719     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5720     if (Context.hasSameUnqualifiedType(T2, ArgType))
5721       return true;
5722   }
5723 
5724   return false;
5725 }
5726 
5727 /// AddOverloadCandidate - Adds the given function to the set of
5728 /// candidate functions, using the given function call arguments.  If
5729 /// @p SuppressUserConversions, then don't allow user-defined
5730 /// conversions via constructors or conversion operators.
5731 ///
5732 /// \param PartialOverloading true if we are performing "partial" overloading
5733 /// based on an incomplete set of function arguments. This feature is used by
5734 /// code completion.
5735 void
5736 Sema::AddOverloadCandidate(FunctionDecl *Function,
5737                            DeclAccessPair FoundDecl,
5738                            ArrayRef<Expr *> Args,
5739                            OverloadCandidateSet &CandidateSet,
5740                            bool SuppressUserConversions,
5741                            bool PartialOverloading,
5742                            bool AllowExplicit) {
5743   const FunctionProtoType *Proto
5744     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5745   assert(Proto && "Functions without a prototype cannot be overloaded");
5746   assert(!Function->getDescribedFunctionTemplate() &&
5747          "Use AddTemplateOverloadCandidate for function templates");
5748 
5749   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5750     if (!isa<CXXConstructorDecl>(Method)) {
5751       // If we get here, it's because we're calling a member function
5752       // that is named without a member access expression (e.g.,
5753       // "this->f") that was either written explicitly or created
5754       // implicitly. This can happen with a qualified call to a member
5755       // function, e.g., X::f(). We use an empty type for the implied
5756       // object argument (C++ [over.call.func]p3), and the acting context
5757       // is irrelevant.
5758       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5759                          QualType(), Expr::Classification::makeSimpleLValue(),
5760                          Args, CandidateSet, SuppressUserConversions,
5761                          PartialOverloading);
5762       return;
5763     }
5764     // We treat a constructor like a non-member function, since its object
5765     // argument doesn't participate in overload resolution.
5766   }
5767 
5768   if (!CandidateSet.isNewCandidate(Function))
5769     return;
5770 
5771   // C++ [over.match.oper]p3:
5772   //   if no operand has a class type, only those non-member functions in the
5773   //   lookup set that have a first parameter of type T1 or "reference to
5774   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5775   //   is a right operand) a second parameter of type T2 or "reference to
5776   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5777   //   candidate functions.
5778   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5779       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5780     return;
5781 
5782   // C++11 [class.copy]p11: [DR1402]
5783   //   A defaulted move constructor that is defined as deleted is ignored by
5784   //   overload resolution.
5785   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5786   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5787       Constructor->isMoveConstructor())
5788     return;
5789 
5790   // Overload resolution is always an unevaluated context.
5791   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5792 
5793   // Add this candidate
5794   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5795   Candidate.FoundDecl = FoundDecl;
5796   Candidate.Function = Function;
5797   Candidate.Viable = true;
5798   Candidate.IsSurrogate = false;
5799   Candidate.IgnoreObjectArgument = false;
5800   Candidate.ExplicitCallArguments = Args.size();
5801 
5802   if (Constructor) {
5803     // C++ [class.copy]p3:
5804     //   A member function template is never instantiated to perform the copy
5805     //   of a class object to an object of its class type.
5806     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5807     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5808         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5809          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5810                        ClassType))) {
5811       Candidate.Viable = false;
5812       Candidate.FailureKind = ovl_fail_illegal_constructor;
5813       return;
5814     }
5815   }
5816 
5817   unsigned NumParams = Proto->getNumParams();
5818 
5819   // (C++ 13.3.2p2): A candidate function having fewer than m
5820   // parameters is viable only if it has an ellipsis in its parameter
5821   // list (8.3.5).
5822   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5823       !Proto->isVariadic()) {
5824     Candidate.Viable = false;
5825     Candidate.FailureKind = ovl_fail_too_many_arguments;
5826     return;
5827   }
5828 
5829   // (C++ 13.3.2p2): A candidate function having more than m parameters
5830   // is viable only if the (m+1)st parameter has a default argument
5831   // (8.3.6). For the purposes of overload resolution, the
5832   // parameter list is truncated on the right, so that there are
5833   // exactly m parameters.
5834   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5835   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5836     // Not enough arguments.
5837     Candidate.Viable = false;
5838     Candidate.FailureKind = ovl_fail_too_few_arguments;
5839     return;
5840   }
5841 
5842   // (CUDA B.1): Check for invalid calls between targets.
5843   if (getLangOpts().CUDA)
5844     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5845       // Skip the check for callers that are implicit members, because in this
5846       // case we may not yet know what the member's target is; the target is
5847       // inferred for the member automatically, based on the bases and fields of
5848       // the class.
5849       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5850         Candidate.Viable = false;
5851         Candidate.FailureKind = ovl_fail_bad_target;
5852         return;
5853       }
5854 
5855   // Determine the implicit conversion sequences for each of the
5856   // arguments.
5857   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5858     if (ArgIdx < NumParams) {
5859       // (C++ 13.3.2p3): for F to be a viable function, there shall
5860       // exist for each argument an implicit conversion sequence
5861       // (13.3.3.1) that converts that argument to the corresponding
5862       // parameter of F.
5863       QualType ParamType = Proto->getParamType(ArgIdx);
5864       Candidate.Conversions[ArgIdx]
5865         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5866                                 SuppressUserConversions,
5867                                 /*InOverloadResolution=*/true,
5868                                 /*AllowObjCWritebackConversion=*/
5869                                   getLangOpts().ObjCAutoRefCount,
5870                                 AllowExplicit);
5871       if (Candidate.Conversions[ArgIdx].isBad()) {
5872         Candidate.Viable = false;
5873         Candidate.FailureKind = ovl_fail_bad_conversion;
5874         return;
5875       }
5876     } else {
5877       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5878       // argument for which there is no corresponding parameter is
5879       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5880       Candidate.Conversions[ArgIdx].setEllipsis();
5881     }
5882   }
5883 
5884   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5885     Candidate.Viable = false;
5886     Candidate.FailureKind = ovl_fail_enable_if;
5887     Candidate.DeductionFailure.Data = FailedAttr;
5888     return;
5889   }
5890 }
5891 
5892 ObjCMethodDecl *
5893 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5894                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5895   if (Methods.size() <= 1)
5896     return nullptr;
5897 
5898   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5899     bool Match = true;
5900     ObjCMethodDecl *Method = Methods[b];
5901     unsigned NumNamedArgs = Sel.getNumArgs();
5902     // Method might have more arguments than selector indicates. This is due
5903     // to addition of c-style arguments in method.
5904     if (Method->param_size() > NumNamedArgs)
5905       NumNamedArgs = Method->param_size();
5906     if (Args.size() < NumNamedArgs)
5907       continue;
5908 
5909     for (unsigned i = 0; i < NumNamedArgs; i++) {
5910       // We can't do any type-checking on a type-dependent argument.
5911       if (Args[i]->isTypeDependent()) {
5912         Match = false;
5913         break;
5914       }
5915 
5916       ParmVarDecl *param = Method->parameters()[i];
5917       Expr *argExpr = Args[i];
5918       assert(argExpr && "SelectBestMethod(): missing expression");
5919 
5920       // Strip the unbridged-cast placeholder expression off unless it's
5921       // a consumed argument.
5922       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5923           !param->hasAttr<CFConsumedAttr>())
5924         argExpr = stripARCUnbridgedCast(argExpr);
5925 
5926       // If the parameter is __unknown_anytype, move on to the next method.
5927       if (param->getType() == Context.UnknownAnyTy) {
5928         Match = false;
5929         break;
5930       }
5931 
5932       ImplicitConversionSequence ConversionState
5933         = TryCopyInitialization(*this, argExpr, param->getType(),
5934                                 /*SuppressUserConversions*/false,
5935                                 /*InOverloadResolution=*/true,
5936                                 /*AllowObjCWritebackConversion=*/
5937                                 getLangOpts().ObjCAutoRefCount,
5938                                 /*AllowExplicit*/false);
5939       // This function looks for a reasonably-exact match, so we consider
5940       // incompatible pointer conversions to be a failure here.
5941       if (ConversionState.isBad() ||
5942           (ConversionState.isStandard() &&
5943            ConversionState.Standard.Second ==
5944                ICK_Incompatible_Pointer_Conversion)) {
5945         Match = false;
5946         break;
5947       }
5948     }
5949     // Promote additional arguments to variadic methods.
5950     if (Match && Method->isVariadic()) {
5951       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5952         if (Args[i]->isTypeDependent()) {
5953           Match = false;
5954           break;
5955         }
5956         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5957                                                           nullptr);
5958         if (Arg.isInvalid()) {
5959           Match = false;
5960           break;
5961         }
5962       }
5963     } else {
5964       // Check for extra arguments to non-variadic methods.
5965       if (Args.size() != NumNamedArgs)
5966         Match = false;
5967       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5968         // Special case when selectors have no argument. In this case, select
5969         // one with the most general result type of 'id'.
5970         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5971           QualType ReturnT = Methods[b]->getReturnType();
5972           if (ReturnT->isObjCIdType())
5973             return Methods[b];
5974         }
5975       }
5976     }
5977 
5978     if (Match)
5979       return Method;
5980   }
5981   return nullptr;
5982 }
5983 
5984 // specific_attr_iterator iterates over enable_if attributes in reverse, and
5985 // enable_if is order-sensitive. As a result, we need to reverse things
5986 // sometimes. Size of 4 elements is arbitrary.
5987 static SmallVector<EnableIfAttr *, 4>
5988 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5989   SmallVector<EnableIfAttr *, 4> Result;
5990   if (!Function->hasAttrs())
5991     return Result;
5992 
5993   const auto &FuncAttrs = Function->getAttrs();
5994   for (Attr *Attr : FuncAttrs)
5995     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5996       Result.push_back(EnableIf);
5997 
5998   std::reverse(Result.begin(), Result.end());
5999   return Result;
6000 }
6001 
6002 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6003                                   bool MissingImplicitThis) {
6004   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6005   if (EnableIfAttrs.empty())
6006     return nullptr;
6007 
6008   SFINAETrap Trap(*this);
6009   SmallVector<Expr *, 16> ConvertedArgs;
6010   bool InitializationFailed = false;
6011 
6012   // Ignore any variadic arguments. Converting them is pointless, since the
6013   // user can't refer to them in the enable_if condition.
6014   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6015 
6016   // Convert the arguments.
6017   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6018     ExprResult R;
6019     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
6020         !cast<CXXMethodDecl>(Function)->isStatic() &&
6021         !isa<CXXConstructorDecl>(Function)) {
6022       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6023       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6024                                               Method, Method);
6025     } else {
6026       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6027                                         Context, Function->getParamDecl(I)),
6028                                     SourceLocation(), Args[I]);
6029     }
6030 
6031     if (R.isInvalid()) {
6032       InitializationFailed = true;
6033       break;
6034     }
6035 
6036     ConvertedArgs.push_back(R.get());
6037   }
6038 
6039   if (InitializationFailed || Trap.hasErrorOccurred())
6040     return EnableIfAttrs[0];
6041 
6042   // Push default arguments if needed.
6043   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6044     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6045       ParmVarDecl *P = Function->getParamDecl(i);
6046       ExprResult R = PerformCopyInitialization(
6047           InitializedEntity::InitializeParameter(Context,
6048                                                  Function->getParamDecl(i)),
6049           SourceLocation(),
6050           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6051                                            : P->getDefaultArg());
6052       if (R.isInvalid()) {
6053         InitializationFailed = true;
6054         break;
6055       }
6056       ConvertedArgs.push_back(R.get());
6057     }
6058 
6059     if (InitializationFailed || Trap.hasErrorOccurred())
6060       return EnableIfAttrs[0];
6061   }
6062 
6063   for (auto *EIA : EnableIfAttrs) {
6064     APValue Result;
6065     // FIXME: This doesn't consider value-dependent cases, because doing so is
6066     // very difficult. Ideally, we should handle them more gracefully.
6067     if (!EIA->getCond()->EvaluateWithSubstitution(
6068             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6069       return EIA;
6070 
6071     if (!Result.isInt() || !Result.getInt().getBoolValue())
6072       return EIA;
6073   }
6074   return nullptr;
6075 }
6076 
6077 /// \brief Add all of the function declarations in the given function set to
6078 /// the overload candidate set.
6079 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6080                                  ArrayRef<Expr *> Args,
6081                                  OverloadCandidateSet& CandidateSet,
6082                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6083                                  bool SuppressUserConversions,
6084                                  bool PartialOverloading) {
6085   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6086     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6087     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6088       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6089         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6090                            cast<CXXMethodDecl>(FD)->getParent(),
6091                            Args[0]->getType(), Args[0]->Classify(Context),
6092                            Args.slice(1), CandidateSet,
6093                            SuppressUserConversions, PartialOverloading);
6094       else
6095         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6096                              SuppressUserConversions, PartialOverloading);
6097     } else {
6098       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6099       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6100           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6101         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6102                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6103                                    ExplicitTemplateArgs,
6104                                    Args[0]->getType(),
6105                                    Args[0]->Classify(Context), Args.slice(1),
6106                                    CandidateSet, SuppressUserConversions,
6107                                    PartialOverloading);
6108       else
6109         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6110                                      ExplicitTemplateArgs, Args,
6111                                      CandidateSet, SuppressUserConversions,
6112                                      PartialOverloading);
6113     }
6114   }
6115 }
6116 
6117 /// AddMethodCandidate - Adds a named decl (which is some kind of
6118 /// method) as a method candidate to the given overload set.
6119 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6120                               QualType ObjectType,
6121                               Expr::Classification ObjectClassification,
6122                               ArrayRef<Expr *> Args,
6123                               OverloadCandidateSet& CandidateSet,
6124                               bool SuppressUserConversions) {
6125   NamedDecl *Decl = FoundDecl.getDecl();
6126   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6127 
6128   if (isa<UsingShadowDecl>(Decl))
6129     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6130 
6131   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6132     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6133            "Expected a member function template");
6134     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6135                                /*ExplicitArgs*/ nullptr,
6136                                ObjectType, ObjectClassification,
6137                                Args, CandidateSet,
6138                                SuppressUserConversions);
6139   } else {
6140     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6141                        ObjectType, ObjectClassification,
6142                        Args,
6143                        CandidateSet, SuppressUserConversions);
6144   }
6145 }
6146 
6147 /// AddMethodCandidate - Adds the given C++ member function to the set
6148 /// of candidate functions, using the given function call arguments
6149 /// and the object argument (@c Object). For example, in a call
6150 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6151 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6152 /// allow user-defined conversions via constructors or conversion
6153 /// operators.
6154 void
6155 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6156                          CXXRecordDecl *ActingContext, QualType ObjectType,
6157                          Expr::Classification ObjectClassification,
6158                          ArrayRef<Expr *> Args,
6159                          OverloadCandidateSet &CandidateSet,
6160                          bool SuppressUserConversions,
6161                          bool PartialOverloading) {
6162   const FunctionProtoType *Proto
6163     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6164   assert(Proto && "Methods without a prototype cannot be overloaded");
6165   assert(!isa<CXXConstructorDecl>(Method) &&
6166          "Use AddOverloadCandidate for constructors");
6167 
6168   if (!CandidateSet.isNewCandidate(Method))
6169     return;
6170 
6171   // C++11 [class.copy]p23: [DR1402]
6172   //   A defaulted move assignment operator that is defined as deleted is
6173   //   ignored by overload resolution.
6174   if (Method->isDefaulted() && Method->isDeleted() &&
6175       Method->isMoveAssignmentOperator())
6176     return;
6177 
6178   // Overload resolution is always an unevaluated context.
6179   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6180 
6181   // Add this candidate
6182   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6183   Candidate.FoundDecl = FoundDecl;
6184   Candidate.Function = Method;
6185   Candidate.IsSurrogate = false;
6186   Candidate.IgnoreObjectArgument = false;
6187   Candidate.ExplicitCallArguments = Args.size();
6188 
6189   unsigned NumParams = Proto->getNumParams();
6190 
6191   // (C++ 13.3.2p2): A candidate function having fewer than m
6192   // parameters is viable only if it has an ellipsis in its parameter
6193   // list (8.3.5).
6194   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6195       !Proto->isVariadic()) {
6196     Candidate.Viable = false;
6197     Candidate.FailureKind = ovl_fail_too_many_arguments;
6198     return;
6199   }
6200 
6201   // (C++ 13.3.2p2): A candidate function having more than m parameters
6202   // is viable only if the (m+1)st parameter has a default argument
6203   // (8.3.6). For the purposes of overload resolution, the
6204   // parameter list is truncated on the right, so that there are
6205   // exactly m parameters.
6206   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6207   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6208     // Not enough arguments.
6209     Candidate.Viable = false;
6210     Candidate.FailureKind = ovl_fail_too_few_arguments;
6211     return;
6212   }
6213 
6214   Candidate.Viable = true;
6215 
6216   if (Method->isStatic() || ObjectType.isNull())
6217     // The implicit object argument is ignored.
6218     Candidate.IgnoreObjectArgument = true;
6219   else {
6220     // Determine the implicit conversion sequence for the object
6221     // parameter.
6222     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6223         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6224         Method, ActingContext);
6225     if (Candidate.Conversions[0].isBad()) {
6226       Candidate.Viable = false;
6227       Candidate.FailureKind = ovl_fail_bad_conversion;
6228       return;
6229     }
6230   }
6231 
6232   // (CUDA B.1): Check for invalid calls between targets.
6233   if (getLangOpts().CUDA)
6234     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6235       if (!IsAllowedCUDACall(Caller, Method)) {
6236         Candidate.Viable = false;
6237         Candidate.FailureKind = ovl_fail_bad_target;
6238         return;
6239       }
6240 
6241   // Determine the implicit conversion sequences for each of the
6242   // arguments.
6243   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6244     if (ArgIdx < NumParams) {
6245       // (C++ 13.3.2p3): for F to be a viable function, there shall
6246       // exist for each argument an implicit conversion sequence
6247       // (13.3.3.1) that converts that argument to the corresponding
6248       // parameter of F.
6249       QualType ParamType = Proto->getParamType(ArgIdx);
6250       Candidate.Conversions[ArgIdx + 1]
6251         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6252                                 SuppressUserConversions,
6253                                 /*InOverloadResolution=*/true,
6254                                 /*AllowObjCWritebackConversion=*/
6255                                   getLangOpts().ObjCAutoRefCount);
6256       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6257         Candidate.Viable = false;
6258         Candidate.FailureKind = ovl_fail_bad_conversion;
6259         return;
6260       }
6261     } else {
6262       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6263       // argument for which there is no corresponding parameter is
6264       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6265       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6266     }
6267   }
6268 
6269   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6270     Candidate.Viable = false;
6271     Candidate.FailureKind = ovl_fail_enable_if;
6272     Candidate.DeductionFailure.Data = FailedAttr;
6273     return;
6274   }
6275 }
6276 
6277 /// \brief Add a C++ member function template as a candidate to the candidate
6278 /// set, using template argument deduction to produce an appropriate member
6279 /// function template specialization.
6280 void
6281 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6282                                  DeclAccessPair FoundDecl,
6283                                  CXXRecordDecl *ActingContext,
6284                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6285                                  QualType ObjectType,
6286                                  Expr::Classification ObjectClassification,
6287                                  ArrayRef<Expr *> Args,
6288                                  OverloadCandidateSet& CandidateSet,
6289                                  bool SuppressUserConversions,
6290                                  bool PartialOverloading) {
6291   if (!CandidateSet.isNewCandidate(MethodTmpl))
6292     return;
6293 
6294   // C++ [over.match.funcs]p7:
6295   //   In each case where a candidate is a function template, candidate
6296   //   function template specializations are generated using template argument
6297   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6298   //   candidate functions in the usual way.113) A given name can refer to one
6299   //   or more function templates and also to a set of overloaded non-template
6300   //   functions. In such a case, the candidate functions generated from each
6301   //   function template are combined with the set of non-template candidate
6302   //   functions.
6303   TemplateDeductionInfo Info(CandidateSet.getLocation());
6304   FunctionDecl *Specialization = nullptr;
6305   if (TemplateDeductionResult Result
6306       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6307                                 Specialization, Info, PartialOverloading)) {
6308     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6309     Candidate.FoundDecl = FoundDecl;
6310     Candidate.Function = MethodTmpl->getTemplatedDecl();
6311     Candidate.Viable = false;
6312     Candidate.FailureKind = ovl_fail_bad_deduction;
6313     Candidate.IsSurrogate = false;
6314     Candidate.IgnoreObjectArgument = false;
6315     Candidate.ExplicitCallArguments = Args.size();
6316     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6317                                                           Info);
6318     return;
6319   }
6320 
6321   // Add the function template specialization produced by template argument
6322   // deduction as a candidate.
6323   assert(Specialization && "Missing member function template specialization?");
6324   assert(isa<CXXMethodDecl>(Specialization) &&
6325          "Specialization is not a member function?");
6326   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6327                      ActingContext, ObjectType, ObjectClassification, Args,
6328                      CandidateSet, SuppressUserConversions, PartialOverloading);
6329 }
6330 
6331 /// \brief Add a C++ function template specialization as a candidate
6332 /// in the candidate set, using template argument deduction to produce
6333 /// an appropriate function template specialization.
6334 void
6335 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6336                                    DeclAccessPair FoundDecl,
6337                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6338                                    ArrayRef<Expr *> Args,
6339                                    OverloadCandidateSet& CandidateSet,
6340                                    bool SuppressUserConversions,
6341                                    bool PartialOverloading) {
6342   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6343     return;
6344 
6345   // C++ [over.match.funcs]p7:
6346   //   In each case where a candidate is a function template, candidate
6347   //   function template specializations are generated using template argument
6348   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6349   //   candidate functions in the usual way.113) A given name can refer to one
6350   //   or more function templates and also to a set of overloaded non-template
6351   //   functions. In such a case, the candidate functions generated from each
6352   //   function template are combined with the set of non-template candidate
6353   //   functions.
6354   TemplateDeductionInfo Info(CandidateSet.getLocation());
6355   FunctionDecl *Specialization = nullptr;
6356   if (TemplateDeductionResult Result
6357         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6358                                   Specialization, Info, PartialOverloading)) {
6359     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6360     Candidate.FoundDecl = FoundDecl;
6361     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6362     Candidate.Viable = false;
6363     Candidate.FailureKind = ovl_fail_bad_deduction;
6364     Candidate.IsSurrogate = false;
6365     Candidate.IgnoreObjectArgument = false;
6366     Candidate.ExplicitCallArguments = Args.size();
6367     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6368                                                           Info);
6369     return;
6370   }
6371 
6372   // Add the function template specialization produced by template argument
6373   // deduction as a candidate.
6374   assert(Specialization && "Missing function template specialization?");
6375   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6376                        SuppressUserConversions, PartialOverloading);
6377 }
6378 
6379 /// Determine whether this is an allowable conversion from the result
6380 /// of an explicit conversion operator to the expected type, per C++
6381 /// [over.match.conv]p1 and [over.match.ref]p1.
6382 ///
6383 /// \param ConvType The return type of the conversion function.
6384 ///
6385 /// \param ToType The type we are converting to.
6386 ///
6387 /// \param AllowObjCPointerConversion Allow a conversion from one
6388 /// Objective-C pointer to another.
6389 ///
6390 /// \returns true if the conversion is allowable, false otherwise.
6391 static bool isAllowableExplicitConversion(Sema &S,
6392                                           QualType ConvType, QualType ToType,
6393                                           bool AllowObjCPointerConversion) {
6394   QualType ToNonRefType = ToType.getNonReferenceType();
6395 
6396   // Easy case: the types are the same.
6397   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6398     return true;
6399 
6400   // Allow qualification conversions.
6401   bool ObjCLifetimeConversion;
6402   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6403                                   ObjCLifetimeConversion))
6404     return true;
6405 
6406   // If we're not allowed to consider Objective-C pointer conversions,
6407   // we're done.
6408   if (!AllowObjCPointerConversion)
6409     return false;
6410 
6411   // Is this an Objective-C pointer conversion?
6412   bool IncompatibleObjC = false;
6413   QualType ConvertedType;
6414   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6415                                    IncompatibleObjC);
6416 }
6417 
6418 /// AddConversionCandidate - Add a C++ conversion function as a
6419 /// candidate in the candidate set (C++ [over.match.conv],
6420 /// C++ [over.match.copy]). From is the expression we're converting from,
6421 /// and ToType is the type that we're eventually trying to convert to
6422 /// (which may or may not be the same type as the type that the
6423 /// conversion function produces).
6424 void
6425 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6426                              DeclAccessPair FoundDecl,
6427                              CXXRecordDecl *ActingContext,
6428                              Expr *From, QualType ToType,
6429                              OverloadCandidateSet& CandidateSet,
6430                              bool AllowObjCConversionOnExplicit) {
6431   assert(!Conversion->getDescribedFunctionTemplate() &&
6432          "Conversion function templates use AddTemplateConversionCandidate");
6433   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6434   if (!CandidateSet.isNewCandidate(Conversion))
6435     return;
6436 
6437   // If the conversion function has an undeduced return type, trigger its
6438   // deduction now.
6439   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6440     if (DeduceReturnType(Conversion, From->getExprLoc()))
6441       return;
6442     ConvType = Conversion->getConversionType().getNonReferenceType();
6443   }
6444 
6445   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6446   // operator is only a candidate if its return type is the target type or
6447   // can be converted to the target type with a qualification conversion.
6448   if (Conversion->isExplicit() &&
6449       !isAllowableExplicitConversion(*this, ConvType, ToType,
6450                                      AllowObjCConversionOnExplicit))
6451     return;
6452 
6453   // Overload resolution is always an unevaluated context.
6454   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6455 
6456   // Add this candidate
6457   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6458   Candidate.FoundDecl = FoundDecl;
6459   Candidate.Function = Conversion;
6460   Candidate.IsSurrogate = false;
6461   Candidate.IgnoreObjectArgument = false;
6462   Candidate.FinalConversion.setAsIdentityConversion();
6463   Candidate.FinalConversion.setFromType(ConvType);
6464   Candidate.FinalConversion.setAllToTypes(ToType);
6465   Candidate.Viable = true;
6466   Candidate.ExplicitCallArguments = 1;
6467 
6468   // C++ [over.match.funcs]p4:
6469   //   For conversion functions, the function is considered to be a member of
6470   //   the class of the implicit implied object argument for the purpose of
6471   //   defining the type of the implicit object parameter.
6472   //
6473   // Determine the implicit conversion sequence for the implicit
6474   // object parameter.
6475   QualType ImplicitParamType = From->getType();
6476   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6477     ImplicitParamType = FromPtrType->getPointeeType();
6478   CXXRecordDecl *ConversionContext
6479     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6480 
6481   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6482       *this, CandidateSet.getLocation(), From->getType(),
6483       From->Classify(Context), Conversion, ConversionContext);
6484 
6485   if (Candidate.Conversions[0].isBad()) {
6486     Candidate.Viable = false;
6487     Candidate.FailureKind = ovl_fail_bad_conversion;
6488     return;
6489   }
6490 
6491   // We won't go through a user-defined type conversion function to convert a
6492   // derived to base as such conversions are given Conversion Rank. They only
6493   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6494   QualType FromCanon
6495     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6496   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6497   if (FromCanon == ToCanon ||
6498       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6499     Candidate.Viable = false;
6500     Candidate.FailureKind = ovl_fail_trivial_conversion;
6501     return;
6502   }
6503 
6504   // To determine what the conversion from the result of calling the
6505   // conversion function to the type we're eventually trying to
6506   // convert to (ToType), we need to synthesize a call to the
6507   // conversion function and attempt copy initialization from it. This
6508   // makes sure that we get the right semantics with respect to
6509   // lvalues/rvalues and the type. Fortunately, we can allocate this
6510   // call on the stack and we don't need its arguments to be
6511   // well-formed.
6512   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6513                             VK_LValue, From->getLocStart());
6514   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6515                                 Context.getPointerType(Conversion->getType()),
6516                                 CK_FunctionToPointerDecay,
6517                                 &ConversionRef, VK_RValue);
6518 
6519   QualType ConversionType = Conversion->getConversionType();
6520   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6521     Candidate.Viable = false;
6522     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6523     return;
6524   }
6525 
6526   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6527 
6528   // Note that it is safe to allocate CallExpr on the stack here because
6529   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6530   // allocator).
6531   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6532   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6533                 From->getLocStart());
6534   ImplicitConversionSequence ICS =
6535     TryCopyInitialization(*this, &Call, ToType,
6536                           /*SuppressUserConversions=*/true,
6537                           /*InOverloadResolution=*/false,
6538                           /*AllowObjCWritebackConversion=*/false);
6539 
6540   switch (ICS.getKind()) {
6541   case ImplicitConversionSequence::StandardConversion:
6542     Candidate.FinalConversion = ICS.Standard;
6543 
6544     // C++ [over.ics.user]p3:
6545     //   If the user-defined conversion is specified by a specialization of a
6546     //   conversion function template, the second standard conversion sequence
6547     //   shall have exact match rank.
6548     if (Conversion->getPrimaryTemplate() &&
6549         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6550       Candidate.Viable = false;
6551       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6552       return;
6553     }
6554 
6555     // C++0x [dcl.init.ref]p5:
6556     //    In the second case, if the reference is an rvalue reference and
6557     //    the second standard conversion sequence of the user-defined
6558     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6559     //    program is ill-formed.
6560     if (ToType->isRValueReferenceType() &&
6561         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6562       Candidate.Viable = false;
6563       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6564       return;
6565     }
6566     break;
6567 
6568   case ImplicitConversionSequence::BadConversion:
6569     Candidate.Viable = false;
6570     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6571     return;
6572 
6573   default:
6574     llvm_unreachable(
6575            "Can only end up with a standard conversion sequence or failure");
6576   }
6577 
6578   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6579     Candidate.Viable = false;
6580     Candidate.FailureKind = ovl_fail_enable_if;
6581     Candidate.DeductionFailure.Data = FailedAttr;
6582     return;
6583   }
6584 }
6585 
6586 /// \brief Adds a conversion function template specialization
6587 /// candidate to the overload set, using template argument deduction
6588 /// to deduce the template arguments of the conversion function
6589 /// template from the type that we are converting to (C++
6590 /// [temp.deduct.conv]).
6591 void
6592 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6593                                      DeclAccessPair FoundDecl,
6594                                      CXXRecordDecl *ActingDC,
6595                                      Expr *From, QualType ToType,
6596                                      OverloadCandidateSet &CandidateSet,
6597                                      bool AllowObjCConversionOnExplicit) {
6598   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6599          "Only conversion function templates permitted here");
6600 
6601   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6602     return;
6603 
6604   TemplateDeductionInfo Info(CandidateSet.getLocation());
6605   CXXConversionDecl *Specialization = nullptr;
6606   if (TemplateDeductionResult Result
6607         = DeduceTemplateArguments(FunctionTemplate, ToType,
6608                                   Specialization, Info)) {
6609     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6610     Candidate.FoundDecl = FoundDecl;
6611     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6612     Candidate.Viable = false;
6613     Candidate.FailureKind = ovl_fail_bad_deduction;
6614     Candidate.IsSurrogate = false;
6615     Candidate.IgnoreObjectArgument = false;
6616     Candidate.ExplicitCallArguments = 1;
6617     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6618                                                           Info);
6619     return;
6620   }
6621 
6622   // Add the conversion function template specialization produced by
6623   // template argument deduction as a candidate.
6624   assert(Specialization && "Missing function template specialization?");
6625   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6626                          CandidateSet, AllowObjCConversionOnExplicit);
6627 }
6628 
6629 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6630 /// converts the given @c Object to a function pointer via the
6631 /// conversion function @c Conversion, and then attempts to call it
6632 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6633 /// the type of function that we'll eventually be calling.
6634 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6635                                  DeclAccessPair FoundDecl,
6636                                  CXXRecordDecl *ActingContext,
6637                                  const FunctionProtoType *Proto,
6638                                  Expr *Object,
6639                                  ArrayRef<Expr *> Args,
6640                                  OverloadCandidateSet& CandidateSet) {
6641   if (!CandidateSet.isNewCandidate(Conversion))
6642     return;
6643 
6644   // Overload resolution is always an unevaluated context.
6645   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6646 
6647   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6648   Candidate.FoundDecl = FoundDecl;
6649   Candidate.Function = nullptr;
6650   Candidate.Surrogate = Conversion;
6651   Candidate.Viable = true;
6652   Candidate.IsSurrogate = true;
6653   Candidate.IgnoreObjectArgument = false;
6654   Candidate.ExplicitCallArguments = Args.size();
6655 
6656   // Determine the implicit conversion sequence for the implicit
6657   // object parameter.
6658   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6659       *this, CandidateSet.getLocation(), Object->getType(),
6660       Object->Classify(Context), Conversion, ActingContext);
6661   if (ObjectInit.isBad()) {
6662     Candidate.Viable = false;
6663     Candidate.FailureKind = ovl_fail_bad_conversion;
6664     Candidate.Conversions[0] = ObjectInit;
6665     return;
6666   }
6667 
6668   // The first conversion is actually a user-defined conversion whose
6669   // first conversion is ObjectInit's standard conversion (which is
6670   // effectively a reference binding). Record it as such.
6671   Candidate.Conversions[0].setUserDefined();
6672   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6673   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6674   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6675   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6676   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6677   Candidate.Conversions[0].UserDefined.After
6678     = Candidate.Conversions[0].UserDefined.Before;
6679   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6680 
6681   // Find the
6682   unsigned NumParams = Proto->getNumParams();
6683 
6684   // (C++ 13.3.2p2): A candidate function having fewer than m
6685   // parameters is viable only if it has an ellipsis in its parameter
6686   // list (8.3.5).
6687   if (Args.size() > NumParams && !Proto->isVariadic()) {
6688     Candidate.Viable = false;
6689     Candidate.FailureKind = ovl_fail_too_many_arguments;
6690     return;
6691   }
6692 
6693   // Function types don't have any default arguments, so just check if
6694   // we have enough arguments.
6695   if (Args.size() < NumParams) {
6696     // Not enough arguments.
6697     Candidate.Viable = false;
6698     Candidate.FailureKind = ovl_fail_too_few_arguments;
6699     return;
6700   }
6701 
6702   // Determine the implicit conversion sequences for each of the
6703   // arguments.
6704   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6705     if (ArgIdx < NumParams) {
6706       // (C++ 13.3.2p3): for F to be a viable function, there shall
6707       // exist for each argument an implicit conversion sequence
6708       // (13.3.3.1) that converts that argument to the corresponding
6709       // parameter of F.
6710       QualType ParamType = Proto->getParamType(ArgIdx);
6711       Candidate.Conversions[ArgIdx + 1]
6712         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6713                                 /*SuppressUserConversions=*/false,
6714                                 /*InOverloadResolution=*/false,
6715                                 /*AllowObjCWritebackConversion=*/
6716                                   getLangOpts().ObjCAutoRefCount);
6717       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6718         Candidate.Viable = false;
6719         Candidate.FailureKind = ovl_fail_bad_conversion;
6720         return;
6721       }
6722     } else {
6723       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6724       // argument for which there is no corresponding parameter is
6725       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6726       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6727     }
6728   }
6729 
6730   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6731     Candidate.Viable = false;
6732     Candidate.FailureKind = ovl_fail_enable_if;
6733     Candidate.DeductionFailure.Data = FailedAttr;
6734     return;
6735   }
6736 }
6737 
6738 /// \brief Add overload candidates for overloaded operators that are
6739 /// member functions.
6740 ///
6741 /// Add the overloaded operator candidates that are member functions
6742 /// for the operator Op that was used in an operator expression such
6743 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6744 /// CandidateSet will store the added overload candidates. (C++
6745 /// [over.match.oper]).
6746 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6747                                        SourceLocation OpLoc,
6748                                        ArrayRef<Expr *> Args,
6749                                        OverloadCandidateSet& CandidateSet,
6750                                        SourceRange OpRange) {
6751   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6752 
6753   // C++ [over.match.oper]p3:
6754   //   For a unary operator @ with an operand of a type whose
6755   //   cv-unqualified version is T1, and for a binary operator @ with
6756   //   a left operand of a type whose cv-unqualified version is T1 and
6757   //   a right operand of a type whose cv-unqualified version is T2,
6758   //   three sets of candidate functions, designated member
6759   //   candidates, non-member candidates and built-in candidates, are
6760   //   constructed as follows:
6761   QualType T1 = Args[0]->getType();
6762 
6763   //     -- If T1 is a complete class type or a class currently being
6764   //        defined, the set of member candidates is the result of the
6765   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6766   //        the set of member candidates is empty.
6767   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6768     // Complete the type if it can be completed.
6769     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6770       return;
6771     // If the type is neither complete nor being defined, bail out now.
6772     if (!T1Rec->getDecl()->getDefinition())
6773       return;
6774 
6775     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6776     LookupQualifiedName(Operators, T1Rec->getDecl());
6777     Operators.suppressDiagnostics();
6778 
6779     for (LookupResult::iterator Oper = Operators.begin(),
6780                              OperEnd = Operators.end();
6781          Oper != OperEnd;
6782          ++Oper)
6783       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6784                          Args[0]->Classify(Context),
6785                          Args.slice(1),
6786                          CandidateSet,
6787                          /* SuppressUserConversions = */ false);
6788   }
6789 }
6790 
6791 /// AddBuiltinCandidate - Add a candidate for a built-in
6792 /// operator. ResultTy and ParamTys are the result and parameter types
6793 /// of the built-in candidate, respectively. Args and NumArgs are the
6794 /// arguments being passed to the candidate. IsAssignmentOperator
6795 /// should be true when this built-in candidate is an assignment
6796 /// operator. NumContextualBoolArguments is the number of arguments
6797 /// (at the beginning of the argument list) that will be contextually
6798 /// converted to bool.
6799 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6800                                ArrayRef<Expr *> Args,
6801                                OverloadCandidateSet& CandidateSet,
6802                                bool IsAssignmentOperator,
6803                                unsigned NumContextualBoolArguments) {
6804   // Overload resolution is always an unevaluated context.
6805   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6806 
6807   // Add this candidate
6808   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6809   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6810   Candidate.Function = nullptr;
6811   Candidate.IsSurrogate = false;
6812   Candidate.IgnoreObjectArgument = false;
6813   Candidate.BuiltinTypes.ResultTy = ResultTy;
6814   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6815     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6816 
6817   // Determine the implicit conversion sequences for each of the
6818   // arguments.
6819   Candidate.Viable = true;
6820   Candidate.ExplicitCallArguments = Args.size();
6821   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6822     // C++ [over.match.oper]p4:
6823     //   For the built-in assignment operators, conversions of the
6824     //   left operand are restricted as follows:
6825     //     -- no temporaries are introduced to hold the left operand, and
6826     //     -- no user-defined conversions are applied to the left
6827     //        operand to achieve a type match with the left-most
6828     //        parameter of a built-in candidate.
6829     //
6830     // We block these conversions by turning off user-defined
6831     // conversions, since that is the only way that initialization of
6832     // a reference to a non-class type can occur from something that
6833     // is not of the same type.
6834     if (ArgIdx < NumContextualBoolArguments) {
6835       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6836              "Contextual conversion to bool requires bool type");
6837       Candidate.Conversions[ArgIdx]
6838         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6839     } else {
6840       Candidate.Conversions[ArgIdx]
6841         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6842                                 ArgIdx == 0 && IsAssignmentOperator,
6843                                 /*InOverloadResolution=*/false,
6844                                 /*AllowObjCWritebackConversion=*/
6845                                   getLangOpts().ObjCAutoRefCount);
6846     }
6847     if (Candidate.Conversions[ArgIdx].isBad()) {
6848       Candidate.Viable = false;
6849       Candidate.FailureKind = ovl_fail_bad_conversion;
6850       break;
6851     }
6852   }
6853 }
6854 
6855 namespace {
6856 
6857 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6858 /// candidate operator functions for built-in operators (C++
6859 /// [over.built]). The types are separated into pointer types and
6860 /// enumeration types.
6861 class BuiltinCandidateTypeSet  {
6862   /// TypeSet - A set of types.
6863   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6864                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6865 
6866   /// PointerTypes - The set of pointer types that will be used in the
6867   /// built-in candidates.
6868   TypeSet PointerTypes;
6869 
6870   /// MemberPointerTypes - The set of member pointer types that will be
6871   /// used in the built-in candidates.
6872   TypeSet MemberPointerTypes;
6873 
6874   /// EnumerationTypes - The set of enumeration types that will be
6875   /// used in the built-in candidates.
6876   TypeSet EnumerationTypes;
6877 
6878   /// \brief The set of vector types that will be used in the built-in
6879   /// candidates.
6880   TypeSet VectorTypes;
6881 
6882   /// \brief A flag indicating non-record types are viable candidates
6883   bool HasNonRecordTypes;
6884 
6885   /// \brief A flag indicating whether either arithmetic or enumeration types
6886   /// were present in the candidate set.
6887   bool HasArithmeticOrEnumeralTypes;
6888 
6889   /// \brief A flag indicating whether the nullptr type was present in the
6890   /// candidate set.
6891   bool HasNullPtrType;
6892 
6893   /// Sema - The semantic analysis instance where we are building the
6894   /// candidate type set.
6895   Sema &SemaRef;
6896 
6897   /// Context - The AST context in which we will build the type sets.
6898   ASTContext &Context;
6899 
6900   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6901                                                const Qualifiers &VisibleQuals);
6902   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6903 
6904 public:
6905   /// iterator - Iterates through the types that are part of the set.
6906   typedef TypeSet::iterator iterator;
6907 
6908   BuiltinCandidateTypeSet(Sema &SemaRef)
6909     : HasNonRecordTypes(false),
6910       HasArithmeticOrEnumeralTypes(false),
6911       HasNullPtrType(false),
6912       SemaRef(SemaRef),
6913       Context(SemaRef.Context) { }
6914 
6915   void AddTypesConvertedFrom(QualType Ty,
6916                              SourceLocation Loc,
6917                              bool AllowUserConversions,
6918                              bool AllowExplicitConversions,
6919                              const Qualifiers &VisibleTypeConversionsQuals);
6920 
6921   /// pointer_begin - First pointer type found;
6922   iterator pointer_begin() { return PointerTypes.begin(); }
6923 
6924   /// pointer_end - Past the last pointer type found;
6925   iterator pointer_end() { return PointerTypes.end(); }
6926 
6927   /// member_pointer_begin - First member pointer type found;
6928   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6929 
6930   /// member_pointer_end - Past the last member pointer type found;
6931   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6932 
6933   /// enumeration_begin - First enumeration type found;
6934   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6935 
6936   /// enumeration_end - Past the last enumeration type found;
6937   iterator enumeration_end() { return EnumerationTypes.end(); }
6938 
6939   iterator vector_begin() { return VectorTypes.begin(); }
6940   iterator vector_end() { return VectorTypes.end(); }
6941 
6942   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6943   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6944   bool hasNullPtrType() const { return HasNullPtrType; }
6945 };
6946 
6947 } // end anonymous namespace
6948 
6949 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6950 /// the set of pointer types along with any more-qualified variants of
6951 /// that type. For example, if @p Ty is "int const *", this routine
6952 /// will add "int const *", "int const volatile *", "int const
6953 /// restrict *", and "int const volatile restrict *" to the set of
6954 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6955 /// false otherwise.
6956 ///
6957 /// FIXME: what to do about extended qualifiers?
6958 bool
6959 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6960                                              const Qualifiers &VisibleQuals) {
6961 
6962   // Insert this type.
6963   if (!PointerTypes.insert(Ty))
6964     return false;
6965 
6966   QualType PointeeTy;
6967   const PointerType *PointerTy = Ty->getAs<PointerType>();
6968   bool buildObjCPtr = false;
6969   if (!PointerTy) {
6970     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6971     PointeeTy = PTy->getPointeeType();
6972     buildObjCPtr = true;
6973   } else {
6974     PointeeTy = PointerTy->getPointeeType();
6975   }
6976 
6977   // Don't add qualified variants of arrays. For one, they're not allowed
6978   // (the qualifier would sink to the element type), and for another, the
6979   // only overload situation where it matters is subscript or pointer +- int,
6980   // and those shouldn't have qualifier variants anyway.
6981   if (PointeeTy->isArrayType())
6982     return true;
6983 
6984   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6985   bool hasVolatile = VisibleQuals.hasVolatile();
6986   bool hasRestrict = VisibleQuals.hasRestrict();
6987 
6988   // Iterate through all strict supersets of BaseCVR.
6989   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6990     if ((CVR | BaseCVR) != CVR) continue;
6991     // Skip over volatile if no volatile found anywhere in the types.
6992     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6993 
6994     // Skip over restrict if no restrict found anywhere in the types, or if
6995     // the type cannot be restrict-qualified.
6996     if ((CVR & Qualifiers::Restrict) &&
6997         (!hasRestrict ||
6998          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6999       continue;
7000 
7001     // Build qualified pointee type.
7002     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7003 
7004     // Build qualified pointer type.
7005     QualType QPointerTy;
7006     if (!buildObjCPtr)
7007       QPointerTy = Context.getPointerType(QPointeeTy);
7008     else
7009       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7010 
7011     // Insert qualified pointer type.
7012     PointerTypes.insert(QPointerTy);
7013   }
7014 
7015   return true;
7016 }
7017 
7018 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7019 /// to the set of pointer types along with any more-qualified variants of
7020 /// that type. For example, if @p Ty is "int const *", this routine
7021 /// will add "int const *", "int const volatile *", "int const
7022 /// restrict *", and "int const volatile restrict *" to the set of
7023 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7024 /// false otherwise.
7025 ///
7026 /// FIXME: what to do about extended qualifiers?
7027 bool
7028 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7029     QualType Ty) {
7030   // Insert this type.
7031   if (!MemberPointerTypes.insert(Ty))
7032     return false;
7033 
7034   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7035   assert(PointerTy && "type was not a member pointer type!");
7036 
7037   QualType PointeeTy = PointerTy->getPointeeType();
7038   // Don't add qualified variants of arrays. For one, they're not allowed
7039   // (the qualifier would sink to the element type), and for another, the
7040   // only overload situation where it matters is subscript or pointer +- int,
7041   // and those shouldn't have qualifier variants anyway.
7042   if (PointeeTy->isArrayType())
7043     return true;
7044   const Type *ClassTy = PointerTy->getClass();
7045 
7046   // Iterate through all strict supersets of the pointee type's CVR
7047   // qualifiers.
7048   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7049   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7050     if ((CVR | BaseCVR) != CVR) continue;
7051 
7052     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7053     MemberPointerTypes.insert(
7054       Context.getMemberPointerType(QPointeeTy, ClassTy));
7055   }
7056 
7057   return true;
7058 }
7059 
7060 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7061 /// Ty can be implicit converted to the given set of @p Types. We're
7062 /// primarily interested in pointer types and enumeration types. We also
7063 /// take member pointer types, for the conditional operator.
7064 /// AllowUserConversions is true if we should look at the conversion
7065 /// functions of a class type, and AllowExplicitConversions if we
7066 /// should also include the explicit conversion functions of a class
7067 /// type.
7068 void
7069 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7070                                                SourceLocation Loc,
7071                                                bool AllowUserConversions,
7072                                                bool AllowExplicitConversions,
7073                                                const Qualifiers &VisibleQuals) {
7074   // Only deal with canonical types.
7075   Ty = Context.getCanonicalType(Ty);
7076 
7077   // Look through reference types; they aren't part of the type of an
7078   // expression for the purposes of conversions.
7079   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7080     Ty = RefTy->getPointeeType();
7081 
7082   // If we're dealing with an array type, decay to the pointer.
7083   if (Ty->isArrayType())
7084     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7085 
7086   // Otherwise, we don't care about qualifiers on the type.
7087   Ty = Ty.getLocalUnqualifiedType();
7088 
7089   // Flag if we ever add a non-record type.
7090   const RecordType *TyRec = Ty->getAs<RecordType>();
7091   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7092 
7093   // Flag if we encounter an arithmetic type.
7094   HasArithmeticOrEnumeralTypes =
7095     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7096 
7097   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7098     PointerTypes.insert(Ty);
7099   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7100     // Insert our type, and its more-qualified variants, into the set
7101     // of types.
7102     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7103       return;
7104   } else if (Ty->isMemberPointerType()) {
7105     // Member pointers are far easier, since the pointee can't be converted.
7106     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7107       return;
7108   } else if (Ty->isEnumeralType()) {
7109     HasArithmeticOrEnumeralTypes = true;
7110     EnumerationTypes.insert(Ty);
7111   } else if (Ty->isVectorType()) {
7112     // We treat vector types as arithmetic types in many contexts as an
7113     // extension.
7114     HasArithmeticOrEnumeralTypes = true;
7115     VectorTypes.insert(Ty);
7116   } else if (Ty->isNullPtrType()) {
7117     HasNullPtrType = true;
7118   } else if (AllowUserConversions && TyRec) {
7119     // No conversion functions in incomplete types.
7120     if (!SemaRef.isCompleteType(Loc, Ty))
7121       return;
7122 
7123     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7124     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7125       if (isa<UsingShadowDecl>(D))
7126         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7127 
7128       // Skip conversion function templates; they don't tell us anything
7129       // about which builtin types we can convert to.
7130       if (isa<FunctionTemplateDecl>(D))
7131         continue;
7132 
7133       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7134       if (AllowExplicitConversions || !Conv->isExplicit()) {
7135         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7136                               VisibleQuals);
7137       }
7138     }
7139   }
7140 }
7141 
7142 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7143 /// the volatile- and non-volatile-qualified assignment operators for the
7144 /// given type to the candidate set.
7145 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7146                                                    QualType T,
7147                                                    ArrayRef<Expr *> Args,
7148                                     OverloadCandidateSet &CandidateSet) {
7149   QualType ParamTypes[2];
7150 
7151   // T& operator=(T&, T)
7152   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7153   ParamTypes[1] = T;
7154   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7155                         /*IsAssignmentOperator=*/true);
7156 
7157   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7158     // volatile T& operator=(volatile T&, T)
7159     ParamTypes[0]
7160       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7161     ParamTypes[1] = T;
7162     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7163                           /*IsAssignmentOperator=*/true);
7164   }
7165 }
7166 
7167 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7168 /// if any, found in visible type conversion functions found in ArgExpr's type.
7169 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7170     Qualifiers VRQuals;
7171     const RecordType *TyRec;
7172     if (const MemberPointerType *RHSMPType =
7173         ArgExpr->getType()->getAs<MemberPointerType>())
7174       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7175     else
7176       TyRec = ArgExpr->getType()->getAs<RecordType>();
7177     if (!TyRec) {
7178       // Just to be safe, assume the worst case.
7179       VRQuals.addVolatile();
7180       VRQuals.addRestrict();
7181       return VRQuals;
7182     }
7183 
7184     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7185     if (!ClassDecl->hasDefinition())
7186       return VRQuals;
7187 
7188     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7189       if (isa<UsingShadowDecl>(D))
7190         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7191       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7192         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7193         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7194           CanTy = ResTypeRef->getPointeeType();
7195         // Need to go down the pointer/mempointer chain and add qualifiers
7196         // as see them.
7197         bool done = false;
7198         while (!done) {
7199           if (CanTy.isRestrictQualified())
7200             VRQuals.addRestrict();
7201           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7202             CanTy = ResTypePtr->getPointeeType();
7203           else if (const MemberPointerType *ResTypeMPtr =
7204                 CanTy->getAs<MemberPointerType>())
7205             CanTy = ResTypeMPtr->getPointeeType();
7206           else
7207             done = true;
7208           if (CanTy.isVolatileQualified())
7209             VRQuals.addVolatile();
7210           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7211             return VRQuals;
7212         }
7213       }
7214     }
7215     return VRQuals;
7216 }
7217 
7218 namespace {
7219 
7220 /// \brief Helper class to manage the addition of builtin operator overload
7221 /// candidates. It provides shared state and utility methods used throughout
7222 /// the process, as well as a helper method to add each group of builtin
7223 /// operator overloads from the standard to a candidate set.
7224 class BuiltinOperatorOverloadBuilder {
7225   // Common instance state available to all overload candidate addition methods.
7226   Sema &S;
7227   ArrayRef<Expr *> Args;
7228   Qualifiers VisibleTypeConversionsQuals;
7229   bool HasArithmeticOrEnumeralCandidateType;
7230   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7231   OverloadCandidateSet &CandidateSet;
7232 
7233   // Define some constants used to index and iterate over the arithemetic types
7234   // provided via the getArithmeticType() method below.
7235   // The "promoted arithmetic types" are the arithmetic
7236   // types are that preserved by promotion (C++ [over.built]p2).
7237   static const unsigned FirstIntegralType = 4;
7238   static const unsigned LastIntegralType = 21;
7239   static const unsigned FirstPromotedIntegralType = 4,
7240                         LastPromotedIntegralType = 12;
7241   static const unsigned FirstPromotedArithmeticType = 0,
7242                         LastPromotedArithmeticType = 12;
7243   static const unsigned NumArithmeticTypes = 21;
7244 
7245   /// \brief Get the canonical type for a given arithmetic type index.
7246   CanQualType getArithmeticType(unsigned index) {
7247     assert(index < NumArithmeticTypes);
7248     static CanQualType ASTContext::* const
7249       ArithmeticTypes[NumArithmeticTypes] = {
7250       // Start of promoted types.
7251       &ASTContext::FloatTy,
7252       &ASTContext::DoubleTy,
7253       &ASTContext::LongDoubleTy,
7254       &ASTContext::Float128Ty,
7255 
7256       // Start of integral types.
7257       &ASTContext::IntTy,
7258       &ASTContext::LongTy,
7259       &ASTContext::LongLongTy,
7260       &ASTContext::Int128Ty,
7261       &ASTContext::UnsignedIntTy,
7262       &ASTContext::UnsignedLongTy,
7263       &ASTContext::UnsignedLongLongTy,
7264       &ASTContext::UnsignedInt128Ty,
7265       // End of promoted types.
7266 
7267       &ASTContext::BoolTy,
7268       &ASTContext::CharTy,
7269       &ASTContext::WCharTy,
7270       &ASTContext::Char16Ty,
7271       &ASTContext::Char32Ty,
7272       &ASTContext::SignedCharTy,
7273       &ASTContext::ShortTy,
7274       &ASTContext::UnsignedCharTy,
7275       &ASTContext::UnsignedShortTy,
7276       // End of integral types.
7277       // FIXME: What about complex? What about half?
7278     };
7279     return S.Context.*ArithmeticTypes[index];
7280   }
7281 
7282   /// \brief Gets the canonical type resulting from the usual arithemetic
7283   /// converions for the given arithmetic types.
7284   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7285     // Accelerator table for performing the usual arithmetic conversions.
7286     // The rules are basically:
7287     //   - if either is floating-point, use the wider floating-point
7288     //   - if same signedness, use the higher rank
7289     //   - if same size, use unsigned of the higher rank
7290     //   - use the larger type
7291     // These rules, together with the axiom that higher ranks are
7292     // never smaller, are sufficient to precompute all of these results
7293     // *except* when dealing with signed types of higher rank.
7294     // (we could precompute SLL x UI for all known platforms, but it's
7295     // better not to make any assumptions).
7296     // We assume that int128 has a higher rank than long long on all platforms.
7297     enum PromotedType : int8_t {
7298             Dep=-1,
7299             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7300     };
7301     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7302                                         [LastPromotedArithmeticType] = {
7303 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7304 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7305 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7306 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7307 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7308 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7309 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7310 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7311 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7312 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7313 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7314     };
7315 
7316     assert(L < LastPromotedArithmeticType);
7317     assert(R < LastPromotedArithmeticType);
7318     int Idx = ConversionsTable[L][R];
7319 
7320     // Fast path: the table gives us a concrete answer.
7321     if (Idx != Dep) return getArithmeticType(Idx);
7322 
7323     // Slow path: we need to compare widths.
7324     // An invariant is that the signed type has higher rank.
7325     CanQualType LT = getArithmeticType(L),
7326                 RT = getArithmeticType(R);
7327     unsigned LW = S.Context.getIntWidth(LT),
7328              RW = S.Context.getIntWidth(RT);
7329 
7330     // If they're different widths, use the signed type.
7331     if (LW > RW) return LT;
7332     else if (LW < RW) return RT;
7333 
7334     // Otherwise, use the unsigned type of the signed type's rank.
7335     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7336     assert(L == SLL || R == SLL);
7337     return S.Context.UnsignedLongLongTy;
7338   }
7339 
7340   /// \brief Helper method to factor out the common pattern of adding overloads
7341   /// for '++' and '--' builtin operators.
7342   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7343                                            bool HasVolatile,
7344                                            bool HasRestrict) {
7345     QualType ParamTypes[2] = {
7346       S.Context.getLValueReferenceType(CandidateTy),
7347       S.Context.IntTy
7348     };
7349 
7350     // Non-volatile version.
7351     if (Args.size() == 1)
7352       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7353     else
7354       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7355 
7356     // Use a heuristic to reduce number of builtin candidates in the set:
7357     // add volatile version only if there are conversions to a volatile type.
7358     if (HasVolatile) {
7359       ParamTypes[0] =
7360         S.Context.getLValueReferenceType(
7361           S.Context.getVolatileType(CandidateTy));
7362       if (Args.size() == 1)
7363         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7364       else
7365         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7366     }
7367 
7368     // Add restrict version only if there are conversions to a restrict type
7369     // and our candidate type is a non-restrict-qualified pointer.
7370     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7371         !CandidateTy.isRestrictQualified()) {
7372       ParamTypes[0]
7373         = S.Context.getLValueReferenceType(
7374             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7375       if (Args.size() == 1)
7376         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7377       else
7378         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7379 
7380       if (HasVolatile) {
7381         ParamTypes[0]
7382           = S.Context.getLValueReferenceType(
7383               S.Context.getCVRQualifiedType(CandidateTy,
7384                                             (Qualifiers::Volatile |
7385                                              Qualifiers::Restrict)));
7386         if (Args.size() == 1)
7387           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7388         else
7389           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7390       }
7391     }
7392 
7393   }
7394 
7395 public:
7396   BuiltinOperatorOverloadBuilder(
7397     Sema &S, ArrayRef<Expr *> Args,
7398     Qualifiers VisibleTypeConversionsQuals,
7399     bool HasArithmeticOrEnumeralCandidateType,
7400     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7401     OverloadCandidateSet &CandidateSet)
7402     : S(S), Args(Args),
7403       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7404       HasArithmeticOrEnumeralCandidateType(
7405         HasArithmeticOrEnumeralCandidateType),
7406       CandidateTypes(CandidateTypes),
7407       CandidateSet(CandidateSet) {
7408     // Validate some of our static helper constants in debug builds.
7409     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7410            "Invalid first promoted integral type");
7411     assert(getArithmeticType(LastPromotedIntegralType - 1)
7412              == S.Context.UnsignedInt128Ty &&
7413            "Invalid last promoted integral type");
7414     assert(getArithmeticType(FirstPromotedArithmeticType)
7415              == S.Context.FloatTy &&
7416            "Invalid first promoted arithmetic type");
7417     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7418              == S.Context.UnsignedInt128Ty &&
7419            "Invalid last promoted arithmetic type");
7420   }
7421 
7422   // C++ [over.built]p3:
7423   //
7424   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7425   //   is either volatile or empty, there exist candidate operator
7426   //   functions of the form
7427   //
7428   //       VQ T&      operator++(VQ T&);
7429   //       T          operator++(VQ T&, int);
7430   //
7431   // C++ [over.built]p4:
7432   //
7433   //   For every pair (T, VQ), where T is an arithmetic type other
7434   //   than bool, and VQ is either volatile or empty, there exist
7435   //   candidate operator functions of the form
7436   //
7437   //       VQ T&      operator--(VQ T&);
7438   //       T          operator--(VQ T&, int);
7439   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7440     if (!HasArithmeticOrEnumeralCandidateType)
7441       return;
7442 
7443     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7444          Arith < NumArithmeticTypes; ++Arith) {
7445       addPlusPlusMinusMinusStyleOverloads(
7446         getArithmeticType(Arith),
7447         VisibleTypeConversionsQuals.hasVolatile(),
7448         VisibleTypeConversionsQuals.hasRestrict());
7449     }
7450   }
7451 
7452   // C++ [over.built]p5:
7453   //
7454   //   For every pair (T, VQ), where T is a cv-qualified or
7455   //   cv-unqualified object type, and VQ is either volatile or
7456   //   empty, there exist candidate operator functions of the form
7457   //
7458   //       T*VQ&      operator++(T*VQ&);
7459   //       T*VQ&      operator--(T*VQ&);
7460   //       T*         operator++(T*VQ&, int);
7461   //       T*         operator--(T*VQ&, int);
7462   void addPlusPlusMinusMinusPointerOverloads() {
7463     for (BuiltinCandidateTypeSet::iterator
7464               Ptr = CandidateTypes[0].pointer_begin(),
7465            PtrEnd = CandidateTypes[0].pointer_end();
7466          Ptr != PtrEnd; ++Ptr) {
7467       // Skip pointer types that aren't pointers to object types.
7468       if (!(*Ptr)->getPointeeType()->isObjectType())
7469         continue;
7470 
7471       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7472         (!(*Ptr).isVolatileQualified() &&
7473          VisibleTypeConversionsQuals.hasVolatile()),
7474         (!(*Ptr).isRestrictQualified() &&
7475          VisibleTypeConversionsQuals.hasRestrict()));
7476     }
7477   }
7478 
7479   // C++ [over.built]p6:
7480   //   For every cv-qualified or cv-unqualified object type T, there
7481   //   exist candidate operator functions of the form
7482   //
7483   //       T&         operator*(T*);
7484   //
7485   // C++ [over.built]p7:
7486   //   For every function type T that does not have cv-qualifiers or a
7487   //   ref-qualifier, there exist candidate operator functions of the form
7488   //       T&         operator*(T*);
7489   void addUnaryStarPointerOverloads() {
7490     for (BuiltinCandidateTypeSet::iterator
7491               Ptr = CandidateTypes[0].pointer_begin(),
7492            PtrEnd = CandidateTypes[0].pointer_end();
7493          Ptr != PtrEnd; ++Ptr) {
7494       QualType ParamTy = *Ptr;
7495       QualType PointeeTy = ParamTy->getPointeeType();
7496       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7497         continue;
7498 
7499       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7500         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7501           continue;
7502 
7503       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7504                             &ParamTy, Args, CandidateSet);
7505     }
7506   }
7507 
7508   // C++ [over.built]p9:
7509   //  For every promoted arithmetic type T, there exist candidate
7510   //  operator functions of the form
7511   //
7512   //       T         operator+(T);
7513   //       T         operator-(T);
7514   void addUnaryPlusOrMinusArithmeticOverloads() {
7515     if (!HasArithmeticOrEnumeralCandidateType)
7516       return;
7517 
7518     for (unsigned Arith = FirstPromotedArithmeticType;
7519          Arith < LastPromotedArithmeticType; ++Arith) {
7520       QualType ArithTy = getArithmeticType(Arith);
7521       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7522     }
7523 
7524     // Extension: We also add these operators for vector types.
7525     for (BuiltinCandidateTypeSet::iterator
7526               Vec = CandidateTypes[0].vector_begin(),
7527            VecEnd = CandidateTypes[0].vector_end();
7528          Vec != VecEnd; ++Vec) {
7529       QualType VecTy = *Vec;
7530       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7531     }
7532   }
7533 
7534   // C++ [over.built]p8:
7535   //   For every type T, there exist candidate operator functions of
7536   //   the form
7537   //
7538   //       T*         operator+(T*);
7539   void addUnaryPlusPointerOverloads() {
7540     for (BuiltinCandidateTypeSet::iterator
7541               Ptr = CandidateTypes[0].pointer_begin(),
7542            PtrEnd = CandidateTypes[0].pointer_end();
7543          Ptr != PtrEnd; ++Ptr) {
7544       QualType ParamTy = *Ptr;
7545       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7546     }
7547   }
7548 
7549   // C++ [over.built]p10:
7550   //   For every promoted integral type T, there exist candidate
7551   //   operator functions of the form
7552   //
7553   //        T         operator~(T);
7554   void addUnaryTildePromotedIntegralOverloads() {
7555     if (!HasArithmeticOrEnumeralCandidateType)
7556       return;
7557 
7558     for (unsigned Int = FirstPromotedIntegralType;
7559          Int < LastPromotedIntegralType; ++Int) {
7560       QualType IntTy = getArithmeticType(Int);
7561       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7562     }
7563 
7564     // Extension: We also add this operator for vector types.
7565     for (BuiltinCandidateTypeSet::iterator
7566               Vec = CandidateTypes[0].vector_begin(),
7567            VecEnd = CandidateTypes[0].vector_end();
7568          Vec != VecEnd; ++Vec) {
7569       QualType VecTy = *Vec;
7570       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7571     }
7572   }
7573 
7574   // C++ [over.match.oper]p16:
7575   //   For every pointer to member type T, there exist candidate operator
7576   //   functions of the form
7577   //
7578   //        bool operator==(T,T);
7579   //        bool operator!=(T,T);
7580   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7581     /// Set of (canonical) types that we've already handled.
7582     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7583 
7584     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7585       for (BuiltinCandidateTypeSet::iterator
7586                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7587              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7588            MemPtr != MemPtrEnd;
7589            ++MemPtr) {
7590         // Don't add the same builtin candidate twice.
7591         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7592           continue;
7593 
7594         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7595         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7596       }
7597     }
7598   }
7599 
7600   // C++ [over.built]p15:
7601   //
7602   //   For every T, where T is an enumeration type, a pointer type, or
7603   //   std::nullptr_t, there exist candidate operator functions of the form
7604   //
7605   //        bool       operator<(T, T);
7606   //        bool       operator>(T, T);
7607   //        bool       operator<=(T, T);
7608   //        bool       operator>=(T, T);
7609   //        bool       operator==(T, T);
7610   //        bool       operator!=(T, T);
7611   void addRelationalPointerOrEnumeralOverloads() {
7612     // C++ [over.match.oper]p3:
7613     //   [...]the built-in candidates include all of the candidate operator
7614     //   functions defined in 13.6 that, compared to the given operator, [...]
7615     //   do not have the same parameter-type-list as any non-template non-member
7616     //   candidate.
7617     //
7618     // Note that in practice, this only affects enumeration types because there
7619     // aren't any built-in candidates of record type, and a user-defined operator
7620     // must have an operand of record or enumeration type. Also, the only other
7621     // overloaded operator with enumeration arguments, operator=,
7622     // cannot be overloaded for enumeration types, so this is the only place
7623     // where we must suppress candidates like this.
7624     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7625       UserDefinedBinaryOperators;
7626 
7627     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7628       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7629           CandidateTypes[ArgIdx].enumeration_end()) {
7630         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7631                                          CEnd = CandidateSet.end();
7632              C != CEnd; ++C) {
7633           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7634             continue;
7635 
7636           if (C->Function->isFunctionTemplateSpecialization())
7637             continue;
7638 
7639           QualType FirstParamType =
7640             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7641           QualType SecondParamType =
7642             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7643 
7644           // Skip if either parameter isn't of enumeral type.
7645           if (!FirstParamType->isEnumeralType() ||
7646               !SecondParamType->isEnumeralType())
7647             continue;
7648 
7649           // Add this operator to the set of known user-defined operators.
7650           UserDefinedBinaryOperators.insert(
7651             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7652                            S.Context.getCanonicalType(SecondParamType)));
7653         }
7654       }
7655     }
7656 
7657     /// Set of (canonical) types that we've already handled.
7658     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7659 
7660     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7661       for (BuiltinCandidateTypeSet::iterator
7662                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7663              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7664            Ptr != PtrEnd; ++Ptr) {
7665         // Don't add the same builtin candidate twice.
7666         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7667           continue;
7668 
7669         QualType ParamTypes[2] = { *Ptr, *Ptr };
7670         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7671       }
7672       for (BuiltinCandidateTypeSet::iterator
7673                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7674              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7675            Enum != EnumEnd; ++Enum) {
7676         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7677 
7678         // Don't add the same builtin candidate twice, or if a user defined
7679         // candidate exists.
7680         if (!AddedTypes.insert(CanonType).second ||
7681             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7682                                                             CanonType)))
7683           continue;
7684 
7685         QualType ParamTypes[2] = { *Enum, *Enum };
7686         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7687       }
7688 
7689       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7690         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7691         if (AddedTypes.insert(NullPtrTy).second &&
7692             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7693                                                              NullPtrTy))) {
7694           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7695           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7696                                 CandidateSet);
7697         }
7698       }
7699     }
7700   }
7701 
7702   // C++ [over.built]p13:
7703   //
7704   //   For every cv-qualified or cv-unqualified object type T
7705   //   there exist candidate operator functions of the form
7706   //
7707   //      T*         operator+(T*, ptrdiff_t);
7708   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7709   //      T*         operator-(T*, ptrdiff_t);
7710   //      T*         operator+(ptrdiff_t, T*);
7711   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7712   //
7713   // C++ [over.built]p14:
7714   //
7715   //   For every T, where T is a pointer to object type, there
7716   //   exist candidate operator functions of the form
7717   //
7718   //      ptrdiff_t  operator-(T, T);
7719   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7720     /// Set of (canonical) types that we've already handled.
7721     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7722 
7723     for (int Arg = 0; Arg < 2; ++Arg) {
7724       QualType AsymmetricParamTypes[2] = {
7725         S.Context.getPointerDiffType(),
7726         S.Context.getPointerDiffType(),
7727       };
7728       for (BuiltinCandidateTypeSet::iterator
7729                 Ptr = CandidateTypes[Arg].pointer_begin(),
7730              PtrEnd = CandidateTypes[Arg].pointer_end();
7731            Ptr != PtrEnd; ++Ptr) {
7732         QualType PointeeTy = (*Ptr)->getPointeeType();
7733         if (!PointeeTy->isObjectType())
7734           continue;
7735 
7736         AsymmetricParamTypes[Arg] = *Ptr;
7737         if (Arg == 0 || Op == OO_Plus) {
7738           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7739           // T* operator+(ptrdiff_t, T*);
7740           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7741         }
7742         if (Op == OO_Minus) {
7743           // ptrdiff_t operator-(T, T);
7744           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7745             continue;
7746 
7747           QualType ParamTypes[2] = { *Ptr, *Ptr };
7748           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7749                                 Args, CandidateSet);
7750         }
7751       }
7752     }
7753   }
7754 
7755   // C++ [over.built]p12:
7756   //
7757   //   For every pair of promoted arithmetic types L and R, there
7758   //   exist candidate operator functions of the form
7759   //
7760   //        LR         operator*(L, R);
7761   //        LR         operator/(L, R);
7762   //        LR         operator+(L, R);
7763   //        LR         operator-(L, R);
7764   //        bool       operator<(L, R);
7765   //        bool       operator>(L, R);
7766   //        bool       operator<=(L, R);
7767   //        bool       operator>=(L, R);
7768   //        bool       operator==(L, R);
7769   //        bool       operator!=(L, R);
7770   //
7771   //   where LR is the result of the usual arithmetic conversions
7772   //   between types L and R.
7773   //
7774   // C++ [over.built]p24:
7775   //
7776   //   For every pair of promoted arithmetic types L and R, there exist
7777   //   candidate operator functions of the form
7778   //
7779   //        LR       operator?(bool, L, R);
7780   //
7781   //   where LR is the result of the usual arithmetic conversions
7782   //   between types L and R.
7783   // Our candidates ignore the first parameter.
7784   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7785     if (!HasArithmeticOrEnumeralCandidateType)
7786       return;
7787 
7788     for (unsigned Left = FirstPromotedArithmeticType;
7789          Left < LastPromotedArithmeticType; ++Left) {
7790       for (unsigned Right = FirstPromotedArithmeticType;
7791            Right < LastPromotedArithmeticType; ++Right) {
7792         QualType LandR[2] = { getArithmeticType(Left),
7793                               getArithmeticType(Right) };
7794         QualType Result =
7795           isComparison ? S.Context.BoolTy
7796                        : getUsualArithmeticConversions(Left, Right);
7797         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7798       }
7799     }
7800 
7801     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7802     // conditional operator for vector types.
7803     for (BuiltinCandidateTypeSet::iterator
7804               Vec1 = CandidateTypes[0].vector_begin(),
7805            Vec1End = CandidateTypes[0].vector_end();
7806          Vec1 != Vec1End; ++Vec1) {
7807       for (BuiltinCandidateTypeSet::iterator
7808                 Vec2 = CandidateTypes[1].vector_begin(),
7809              Vec2End = CandidateTypes[1].vector_end();
7810            Vec2 != Vec2End; ++Vec2) {
7811         QualType LandR[2] = { *Vec1, *Vec2 };
7812         QualType Result = S.Context.BoolTy;
7813         if (!isComparison) {
7814           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7815             Result = *Vec1;
7816           else
7817             Result = *Vec2;
7818         }
7819 
7820         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7821       }
7822     }
7823   }
7824 
7825   // C++ [over.built]p17:
7826   //
7827   //   For every pair of promoted integral types L and R, there
7828   //   exist candidate operator functions of the form
7829   //
7830   //      LR         operator%(L, R);
7831   //      LR         operator&(L, R);
7832   //      LR         operator^(L, R);
7833   //      LR         operator|(L, R);
7834   //      L          operator<<(L, R);
7835   //      L          operator>>(L, R);
7836   //
7837   //   where LR is the result of the usual arithmetic conversions
7838   //   between types L and R.
7839   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7840     if (!HasArithmeticOrEnumeralCandidateType)
7841       return;
7842 
7843     for (unsigned Left = FirstPromotedIntegralType;
7844          Left < LastPromotedIntegralType; ++Left) {
7845       for (unsigned Right = FirstPromotedIntegralType;
7846            Right < LastPromotedIntegralType; ++Right) {
7847         QualType LandR[2] = { getArithmeticType(Left),
7848                               getArithmeticType(Right) };
7849         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7850             ? LandR[0]
7851             : getUsualArithmeticConversions(Left, Right);
7852         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7853       }
7854     }
7855   }
7856 
7857   // C++ [over.built]p20:
7858   //
7859   //   For every pair (T, VQ), where T is an enumeration or
7860   //   pointer to member type and VQ is either volatile or
7861   //   empty, there exist candidate operator functions of the form
7862   //
7863   //        VQ T&      operator=(VQ T&, T);
7864   void addAssignmentMemberPointerOrEnumeralOverloads() {
7865     /// Set of (canonical) types that we've already handled.
7866     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7867 
7868     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7869       for (BuiltinCandidateTypeSet::iterator
7870                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7871              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7872            Enum != EnumEnd; ++Enum) {
7873         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7874           continue;
7875 
7876         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7877       }
7878 
7879       for (BuiltinCandidateTypeSet::iterator
7880                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7881              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7882            MemPtr != MemPtrEnd; ++MemPtr) {
7883         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7884           continue;
7885 
7886         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7887       }
7888     }
7889   }
7890 
7891   // C++ [over.built]p19:
7892   //
7893   //   For every pair (T, VQ), where T is any type and VQ is either
7894   //   volatile or empty, there exist candidate operator functions
7895   //   of the form
7896   //
7897   //        T*VQ&      operator=(T*VQ&, T*);
7898   //
7899   // C++ [over.built]p21:
7900   //
7901   //   For every pair (T, VQ), where T is a cv-qualified or
7902   //   cv-unqualified object type and VQ is either volatile or
7903   //   empty, there exist candidate operator functions of the form
7904   //
7905   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7906   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7907   void addAssignmentPointerOverloads(bool isEqualOp) {
7908     /// Set of (canonical) types that we've already handled.
7909     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7910 
7911     for (BuiltinCandidateTypeSet::iterator
7912               Ptr = CandidateTypes[0].pointer_begin(),
7913            PtrEnd = CandidateTypes[0].pointer_end();
7914          Ptr != PtrEnd; ++Ptr) {
7915       // If this is operator=, keep track of the builtin candidates we added.
7916       if (isEqualOp)
7917         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7918       else if (!(*Ptr)->getPointeeType()->isObjectType())
7919         continue;
7920 
7921       // non-volatile version
7922       QualType ParamTypes[2] = {
7923         S.Context.getLValueReferenceType(*Ptr),
7924         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7925       };
7926       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7927                             /*IsAssigmentOperator=*/ isEqualOp);
7928 
7929       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7930                           VisibleTypeConversionsQuals.hasVolatile();
7931       if (NeedVolatile) {
7932         // volatile version
7933         ParamTypes[0] =
7934           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7935         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7936                               /*IsAssigmentOperator=*/isEqualOp);
7937       }
7938 
7939       if (!(*Ptr).isRestrictQualified() &&
7940           VisibleTypeConversionsQuals.hasRestrict()) {
7941         // restrict version
7942         ParamTypes[0]
7943           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7944         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7945                               /*IsAssigmentOperator=*/isEqualOp);
7946 
7947         if (NeedVolatile) {
7948           // volatile restrict version
7949           ParamTypes[0]
7950             = S.Context.getLValueReferenceType(
7951                 S.Context.getCVRQualifiedType(*Ptr,
7952                                               (Qualifiers::Volatile |
7953                                                Qualifiers::Restrict)));
7954           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7955                                 /*IsAssigmentOperator=*/isEqualOp);
7956         }
7957       }
7958     }
7959 
7960     if (isEqualOp) {
7961       for (BuiltinCandidateTypeSet::iterator
7962                 Ptr = CandidateTypes[1].pointer_begin(),
7963              PtrEnd = CandidateTypes[1].pointer_end();
7964            Ptr != PtrEnd; ++Ptr) {
7965         // Make sure we don't add the same candidate twice.
7966         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7967           continue;
7968 
7969         QualType ParamTypes[2] = {
7970           S.Context.getLValueReferenceType(*Ptr),
7971           *Ptr,
7972         };
7973 
7974         // non-volatile version
7975         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7976                               /*IsAssigmentOperator=*/true);
7977 
7978         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7979                            VisibleTypeConversionsQuals.hasVolatile();
7980         if (NeedVolatile) {
7981           // volatile version
7982           ParamTypes[0] =
7983             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7984           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7985                                 /*IsAssigmentOperator=*/true);
7986         }
7987 
7988         if (!(*Ptr).isRestrictQualified() &&
7989             VisibleTypeConversionsQuals.hasRestrict()) {
7990           // restrict version
7991           ParamTypes[0]
7992             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7993           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7994                                 /*IsAssigmentOperator=*/true);
7995 
7996           if (NeedVolatile) {
7997             // volatile restrict version
7998             ParamTypes[0]
7999               = S.Context.getLValueReferenceType(
8000                   S.Context.getCVRQualifiedType(*Ptr,
8001                                                 (Qualifiers::Volatile |
8002                                                  Qualifiers::Restrict)));
8003             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8004                                   /*IsAssigmentOperator=*/true);
8005           }
8006         }
8007       }
8008     }
8009   }
8010 
8011   // C++ [over.built]p18:
8012   //
8013   //   For every triple (L, VQ, R), where L is an arithmetic type,
8014   //   VQ is either volatile or empty, and R is a promoted
8015   //   arithmetic type, there exist candidate operator functions of
8016   //   the form
8017   //
8018   //        VQ L&      operator=(VQ L&, R);
8019   //        VQ L&      operator*=(VQ L&, R);
8020   //        VQ L&      operator/=(VQ L&, R);
8021   //        VQ L&      operator+=(VQ L&, R);
8022   //        VQ L&      operator-=(VQ L&, R);
8023   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8024     if (!HasArithmeticOrEnumeralCandidateType)
8025       return;
8026 
8027     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8028       for (unsigned Right = FirstPromotedArithmeticType;
8029            Right < LastPromotedArithmeticType; ++Right) {
8030         QualType ParamTypes[2];
8031         ParamTypes[1] = getArithmeticType(Right);
8032 
8033         // Add this built-in operator as a candidate (VQ is empty).
8034         ParamTypes[0] =
8035           S.Context.getLValueReferenceType(getArithmeticType(Left));
8036         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8037                               /*IsAssigmentOperator=*/isEqualOp);
8038 
8039         // Add this built-in operator as a candidate (VQ is 'volatile').
8040         if (VisibleTypeConversionsQuals.hasVolatile()) {
8041           ParamTypes[0] =
8042             S.Context.getVolatileType(getArithmeticType(Left));
8043           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8044           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8045                                 /*IsAssigmentOperator=*/isEqualOp);
8046         }
8047       }
8048     }
8049 
8050     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8051     for (BuiltinCandidateTypeSet::iterator
8052               Vec1 = CandidateTypes[0].vector_begin(),
8053            Vec1End = CandidateTypes[0].vector_end();
8054          Vec1 != Vec1End; ++Vec1) {
8055       for (BuiltinCandidateTypeSet::iterator
8056                 Vec2 = CandidateTypes[1].vector_begin(),
8057              Vec2End = CandidateTypes[1].vector_end();
8058            Vec2 != Vec2End; ++Vec2) {
8059         QualType ParamTypes[2];
8060         ParamTypes[1] = *Vec2;
8061         // Add this built-in operator as a candidate (VQ is empty).
8062         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8063         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8064                               /*IsAssigmentOperator=*/isEqualOp);
8065 
8066         // Add this built-in operator as a candidate (VQ is 'volatile').
8067         if (VisibleTypeConversionsQuals.hasVolatile()) {
8068           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8069           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8070           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8071                                 /*IsAssigmentOperator=*/isEqualOp);
8072         }
8073       }
8074     }
8075   }
8076 
8077   // C++ [over.built]p22:
8078   //
8079   //   For every triple (L, VQ, R), where L is an integral type, VQ
8080   //   is either volatile or empty, and R is a promoted integral
8081   //   type, there exist candidate operator functions of the form
8082   //
8083   //        VQ L&       operator%=(VQ L&, R);
8084   //        VQ L&       operator<<=(VQ L&, R);
8085   //        VQ L&       operator>>=(VQ L&, R);
8086   //        VQ L&       operator&=(VQ L&, R);
8087   //        VQ L&       operator^=(VQ L&, R);
8088   //        VQ L&       operator|=(VQ L&, R);
8089   void addAssignmentIntegralOverloads() {
8090     if (!HasArithmeticOrEnumeralCandidateType)
8091       return;
8092 
8093     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8094       for (unsigned Right = FirstPromotedIntegralType;
8095            Right < LastPromotedIntegralType; ++Right) {
8096         QualType ParamTypes[2];
8097         ParamTypes[1] = getArithmeticType(Right);
8098 
8099         // Add this built-in operator as a candidate (VQ is empty).
8100         ParamTypes[0] =
8101           S.Context.getLValueReferenceType(getArithmeticType(Left));
8102         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8103         if (VisibleTypeConversionsQuals.hasVolatile()) {
8104           // Add this built-in operator as a candidate (VQ is 'volatile').
8105           ParamTypes[0] = getArithmeticType(Left);
8106           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8107           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8108           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8109         }
8110       }
8111     }
8112   }
8113 
8114   // C++ [over.operator]p23:
8115   //
8116   //   There also exist candidate operator functions of the form
8117   //
8118   //        bool        operator!(bool);
8119   //        bool        operator&&(bool, bool);
8120   //        bool        operator||(bool, bool);
8121   void addExclaimOverload() {
8122     QualType ParamTy = S.Context.BoolTy;
8123     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8124                           /*IsAssignmentOperator=*/false,
8125                           /*NumContextualBoolArguments=*/1);
8126   }
8127   void addAmpAmpOrPipePipeOverload() {
8128     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8129     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8130                           /*IsAssignmentOperator=*/false,
8131                           /*NumContextualBoolArguments=*/2);
8132   }
8133 
8134   // C++ [over.built]p13:
8135   //
8136   //   For every cv-qualified or cv-unqualified object type T there
8137   //   exist candidate operator functions of the form
8138   //
8139   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8140   //        T&         operator[](T*, ptrdiff_t);
8141   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8142   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8143   //        T&         operator[](ptrdiff_t, T*);
8144   void addSubscriptOverloads() {
8145     for (BuiltinCandidateTypeSet::iterator
8146               Ptr = CandidateTypes[0].pointer_begin(),
8147            PtrEnd = CandidateTypes[0].pointer_end();
8148          Ptr != PtrEnd; ++Ptr) {
8149       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8150       QualType PointeeType = (*Ptr)->getPointeeType();
8151       if (!PointeeType->isObjectType())
8152         continue;
8153 
8154       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8155 
8156       // T& operator[](T*, ptrdiff_t)
8157       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8158     }
8159 
8160     for (BuiltinCandidateTypeSet::iterator
8161               Ptr = CandidateTypes[1].pointer_begin(),
8162            PtrEnd = CandidateTypes[1].pointer_end();
8163          Ptr != PtrEnd; ++Ptr) {
8164       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8165       QualType PointeeType = (*Ptr)->getPointeeType();
8166       if (!PointeeType->isObjectType())
8167         continue;
8168 
8169       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8170 
8171       // T& operator[](ptrdiff_t, T*)
8172       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8173     }
8174   }
8175 
8176   // C++ [over.built]p11:
8177   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8178   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8179   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8180   //    there exist candidate operator functions of the form
8181   //
8182   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8183   //
8184   //    where CV12 is the union of CV1 and CV2.
8185   void addArrowStarOverloads() {
8186     for (BuiltinCandidateTypeSet::iterator
8187              Ptr = CandidateTypes[0].pointer_begin(),
8188            PtrEnd = CandidateTypes[0].pointer_end();
8189          Ptr != PtrEnd; ++Ptr) {
8190       QualType C1Ty = (*Ptr);
8191       QualType C1;
8192       QualifierCollector Q1;
8193       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8194       if (!isa<RecordType>(C1))
8195         continue;
8196       // heuristic to reduce number of builtin candidates in the set.
8197       // Add volatile/restrict version only if there are conversions to a
8198       // volatile/restrict type.
8199       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8200         continue;
8201       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8202         continue;
8203       for (BuiltinCandidateTypeSet::iterator
8204                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8205              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8206            MemPtr != MemPtrEnd; ++MemPtr) {
8207         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8208         QualType C2 = QualType(mptr->getClass(), 0);
8209         C2 = C2.getUnqualifiedType();
8210         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8211           break;
8212         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8213         // build CV12 T&
8214         QualType T = mptr->getPointeeType();
8215         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8216             T.isVolatileQualified())
8217           continue;
8218         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8219             T.isRestrictQualified())
8220           continue;
8221         T = Q1.apply(S.Context, T);
8222         QualType ResultTy = S.Context.getLValueReferenceType(T);
8223         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8224       }
8225     }
8226   }
8227 
8228   // Note that we don't consider the first argument, since it has been
8229   // contextually converted to bool long ago. The candidates below are
8230   // therefore added as binary.
8231   //
8232   // C++ [over.built]p25:
8233   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8234   //   enumeration type, there exist candidate operator functions of the form
8235   //
8236   //        T        operator?(bool, T, T);
8237   //
8238   void addConditionalOperatorOverloads() {
8239     /// Set of (canonical) types that we've already handled.
8240     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8241 
8242     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8243       for (BuiltinCandidateTypeSet::iterator
8244                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8245              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8246            Ptr != PtrEnd; ++Ptr) {
8247         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8248           continue;
8249 
8250         QualType ParamTypes[2] = { *Ptr, *Ptr };
8251         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8252       }
8253 
8254       for (BuiltinCandidateTypeSet::iterator
8255                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8256              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8257            MemPtr != MemPtrEnd; ++MemPtr) {
8258         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8259           continue;
8260 
8261         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8262         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8263       }
8264 
8265       if (S.getLangOpts().CPlusPlus11) {
8266         for (BuiltinCandidateTypeSet::iterator
8267                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8268                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8269              Enum != EnumEnd; ++Enum) {
8270           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8271             continue;
8272 
8273           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8274             continue;
8275 
8276           QualType ParamTypes[2] = { *Enum, *Enum };
8277           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8278         }
8279       }
8280     }
8281   }
8282 };
8283 
8284 } // end anonymous namespace
8285 
8286 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8287 /// operator overloads to the candidate set (C++ [over.built]), based
8288 /// on the operator @p Op and the arguments given. For example, if the
8289 /// operator is a binary '+', this routine might add "int
8290 /// operator+(int, int)" to cover integer addition.
8291 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8292                                         SourceLocation OpLoc,
8293                                         ArrayRef<Expr *> Args,
8294                                         OverloadCandidateSet &CandidateSet) {
8295   // Find all of the types that the arguments can convert to, but only
8296   // if the operator we're looking at has built-in operator candidates
8297   // that make use of these types. Also record whether we encounter non-record
8298   // candidate types or either arithmetic or enumeral candidate types.
8299   Qualifiers VisibleTypeConversionsQuals;
8300   VisibleTypeConversionsQuals.addConst();
8301   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8302     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8303 
8304   bool HasNonRecordCandidateType = false;
8305   bool HasArithmeticOrEnumeralCandidateType = false;
8306   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8307   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8308     CandidateTypes.emplace_back(*this);
8309     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8310                                                  OpLoc,
8311                                                  true,
8312                                                  (Op == OO_Exclaim ||
8313                                                   Op == OO_AmpAmp ||
8314                                                   Op == OO_PipePipe),
8315                                                  VisibleTypeConversionsQuals);
8316     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8317         CandidateTypes[ArgIdx].hasNonRecordTypes();
8318     HasArithmeticOrEnumeralCandidateType =
8319         HasArithmeticOrEnumeralCandidateType ||
8320         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8321   }
8322 
8323   // Exit early when no non-record types have been added to the candidate set
8324   // for any of the arguments to the operator.
8325   //
8326   // We can't exit early for !, ||, or &&, since there we have always have
8327   // 'bool' overloads.
8328   if (!HasNonRecordCandidateType &&
8329       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8330     return;
8331 
8332   // Setup an object to manage the common state for building overloads.
8333   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8334                                            VisibleTypeConversionsQuals,
8335                                            HasArithmeticOrEnumeralCandidateType,
8336                                            CandidateTypes, CandidateSet);
8337 
8338   // Dispatch over the operation to add in only those overloads which apply.
8339   switch (Op) {
8340   case OO_None:
8341   case NUM_OVERLOADED_OPERATORS:
8342     llvm_unreachable("Expected an overloaded operator");
8343 
8344   case OO_New:
8345   case OO_Delete:
8346   case OO_Array_New:
8347   case OO_Array_Delete:
8348   case OO_Call:
8349     llvm_unreachable(
8350                     "Special operators don't use AddBuiltinOperatorCandidates");
8351 
8352   case OO_Comma:
8353   case OO_Arrow:
8354   case OO_Coawait:
8355     // C++ [over.match.oper]p3:
8356     //   -- For the operator ',', the unary operator '&', the
8357     //      operator '->', or the operator 'co_await', the
8358     //      built-in candidates set is empty.
8359     break;
8360 
8361   case OO_Plus: // '+' is either unary or binary
8362     if (Args.size() == 1)
8363       OpBuilder.addUnaryPlusPointerOverloads();
8364     // Fall through.
8365 
8366   case OO_Minus: // '-' is either unary or binary
8367     if (Args.size() == 1) {
8368       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8369     } else {
8370       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8371       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8372     }
8373     break;
8374 
8375   case OO_Star: // '*' is either unary or binary
8376     if (Args.size() == 1)
8377       OpBuilder.addUnaryStarPointerOverloads();
8378     else
8379       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8380     break;
8381 
8382   case OO_Slash:
8383     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8384     break;
8385 
8386   case OO_PlusPlus:
8387   case OO_MinusMinus:
8388     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8389     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8390     break;
8391 
8392   case OO_EqualEqual:
8393   case OO_ExclaimEqual:
8394     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8395     // Fall through.
8396 
8397   case OO_Less:
8398   case OO_Greater:
8399   case OO_LessEqual:
8400   case OO_GreaterEqual:
8401     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8402     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8403     break;
8404 
8405   case OO_Percent:
8406   case OO_Caret:
8407   case OO_Pipe:
8408   case OO_LessLess:
8409   case OO_GreaterGreater:
8410     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8411     break;
8412 
8413   case OO_Amp: // '&' is either unary or binary
8414     if (Args.size() == 1)
8415       // C++ [over.match.oper]p3:
8416       //   -- For the operator ',', the unary operator '&', or the
8417       //      operator '->', the built-in candidates set is empty.
8418       break;
8419 
8420     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8421     break;
8422 
8423   case OO_Tilde:
8424     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8425     break;
8426 
8427   case OO_Equal:
8428     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8429     // Fall through.
8430 
8431   case OO_PlusEqual:
8432   case OO_MinusEqual:
8433     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8434     // Fall through.
8435 
8436   case OO_StarEqual:
8437   case OO_SlashEqual:
8438     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8439     break;
8440 
8441   case OO_PercentEqual:
8442   case OO_LessLessEqual:
8443   case OO_GreaterGreaterEqual:
8444   case OO_AmpEqual:
8445   case OO_CaretEqual:
8446   case OO_PipeEqual:
8447     OpBuilder.addAssignmentIntegralOverloads();
8448     break;
8449 
8450   case OO_Exclaim:
8451     OpBuilder.addExclaimOverload();
8452     break;
8453 
8454   case OO_AmpAmp:
8455   case OO_PipePipe:
8456     OpBuilder.addAmpAmpOrPipePipeOverload();
8457     break;
8458 
8459   case OO_Subscript:
8460     OpBuilder.addSubscriptOverloads();
8461     break;
8462 
8463   case OO_ArrowStar:
8464     OpBuilder.addArrowStarOverloads();
8465     break;
8466 
8467   case OO_Conditional:
8468     OpBuilder.addConditionalOperatorOverloads();
8469     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8470     break;
8471   }
8472 }
8473 
8474 /// \brief Add function candidates found via argument-dependent lookup
8475 /// to the set of overloading candidates.
8476 ///
8477 /// This routine performs argument-dependent name lookup based on the
8478 /// given function name (which may also be an operator name) and adds
8479 /// all of the overload candidates found by ADL to the overload
8480 /// candidate set (C++ [basic.lookup.argdep]).
8481 void
8482 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8483                                            SourceLocation Loc,
8484                                            ArrayRef<Expr *> Args,
8485                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8486                                            OverloadCandidateSet& CandidateSet,
8487                                            bool PartialOverloading) {
8488   ADLResult Fns;
8489 
8490   // FIXME: This approach for uniquing ADL results (and removing
8491   // redundant candidates from the set) relies on pointer-equality,
8492   // which means we need to key off the canonical decl.  However,
8493   // always going back to the canonical decl might not get us the
8494   // right set of default arguments.  What default arguments are
8495   // we supposed to consider on ADL candidates, anyway?
8496 
8497   // FIXME: Pass in the explicit template arguments?
8498   ArgumentDependentLookup(Name, Loc, Args, Fns);
8499 
8500   // Erase all of the candidates we already knew about.
8501   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8502                                    CandEnd = CandidateSet.end();
8503        Cand != CandEnd; ++Cand)
8504     if (Cand->Function) {
8505       Fns.erase(Cand->Function);
8506       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8507         Fns.erase(FunTmpl);
8508     }
8509 
8510   // For each of the ADL candidates we found, add it to the overload
8511   // set.
8512   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8513     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8514     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8515       if (ExplicitTemplateArgs)
8516         continue;
8517 
8518       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8519                            PartialOverloading);
8520     } else
8521       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8522                                    FoundDecl, ExplicitTemplateArgs,
8523                                    Args, CandidateSet, PartialOverloading);
8524   }
8525 }
8526 
8527 namespace {
8528 enum class Comparison { Equal, Better, Worse };
8529 }
8530 
8531 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8532 /// overload resolution.
8533 ///
8534 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8535 /// Cand1's first N enable_if attributes have precisely the same conditions as
8536 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8537 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8538 ///
8539 /// Note that you can have a pair of candidates such that Cand1's enable_if
8540 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8541 /// worse than Cand1's.
8542 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8543                                        const FunctionDecl *Cand2) {
8544   // Common case: One (or both) decls don't have enable_if attrs.
8545   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8546   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8547   if (!Cand1Attr || !Cand2Attr) {
8548     if (Cand1Attr == Cand2Attr)
8549       return Comparison::Equal;
8550     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8551   }
8552 
8553   // FIXME: The next several lines are just
8554   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8555   // instead of reverse order which is how they're stored in the AST.
8556   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8557   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8558 
8559   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8560   // has fewer enable_if attributes than Cand2.
8561   if (Cand1Attrs.size() < Cand2Attrs.size())
8562     return Comparison::Worse;
8563 
8564   auto Cand1I = Cand1Attrs.begin();
8565   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8566   for (auto &Cand2A : Cand2Attrs) {
8567     Cand1ID.clear();
8568     Cand2ID.clear();
8569 
8570     auto &Cand1A = *Cand1I++;
8571     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8572     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8573     if (Cand1ID != Cand2ID)
8574       return Comparison::Worse;
8575   }
8576 
8577   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8578 }
8579 
8580 /// isBetterOverloadCandidate - Determines whether the first overload
8581 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8582 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8583                                       const OverloadCandidate &Cand2,
8584                                       SourceLocation Loc,
8585                                       bool UserDefinedConversion) {
8586   // Define viable functions to be better candidates than non-viable
8587   // functions.
8588   if (!Cand2.Viable)
8589     return Cand1.Viable;
8590   else if (!Cand1.Viable)
8591     return false;
8592 
8593   // C++ [over.match.best]p1:
8594   //
8595   //   -- if F is a static member function, ICS1(F) is defined such
8596   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8597   //      any function G, and, symmetrically, ICS1(G) is neither
8598   //      better nor worse than ICS1(F).
8599   unsigned StartArg = 0;
8600   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8601     StartArg = 1;
8602 
8603   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8604     // We don't allow incompatible pointer conversions in C++.
8605     if (!S.getLangOpts().CPlusPlus)
8606       return ICS.isStandard() &&
8607              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8608 
8609     // The only ill-formed conversion we allow in C++ is the string literal to
8610     // char* conversion, which is only considered ill-formed after C++11.
8611     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8612            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8613   };
8614 
8615   // Define functions that don't require ill-formed conversions for a given
8616   // argument to be better candidates than functions that do.
8617   unsigned NumArgs = Cand1.NumConversions;
8618   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8619   bool HasBetterConversion = false;
8620   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8621     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8622     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8623     if (Cand1Bad != Cand2Bad) {
8624       if (Cand1Bad)
8625         return false;
8626       HasBetterConversion = true;
8627     }
8628   }
8629 
8630   if (HasBetterConversion)
8631     return true;
8632 
8633   // C++ [over.match.best]p1:
8634   //   A viable function F1 is defined to be a better function than another
8635   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8636   //   conversion sequence than ICSi(F2), and then...
8637   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8638     switch (CompareImplicitConversionSequences(S, Loc,
8639                                                Cand1.Conversions[ArgIdx],
8640                                                Cand2.Conversions[ArgIdx])) {
8641     case ImplicitConversionSequence::Better:
8642       // Cand1 has a better conversion sequence.
8643       HasBetterConversion = true;
8644       break;
8645 
8646     case ImplicitConversionSequence::Worse:
8647       // Cand1 can't be better than Cand2.
8648       return false;
8649 
8650     case ImplicitConversionSequence::Indistinguishable:
8651       // Do nothing.
8652       break;
8653     }
8654   }
8655 
8656   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8657   //       ICSj(F2), or, if not that,
8658   if (HasBetterConversion)
8659     return true;
8660 
8661   //   -- the context is an initialization by user-defined conversion
8662   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8663   //      from the return type of F1 to the destination type (i.e.,
8664   //      the type of the entity being initialized) is a better
8665   //      conversion sequence than the standard conversion sequence
8666   //      from the return type of F2 to the destination type.
8667   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8668       isa<CXXConversionDecl>(Cand1.Function) &&
8669       isa<CXXConversionDecl>(Cand2.Function)) {
8670     // First check whether we prefer one of the conversion functions over the
8671     // other. This only distinguishes the results in non-standard, extension
8672     // cases such as the conversion from a lambda closure type to a function
8673     // pointer or block.
8674     ImplicitConversionSequence::CompareKind Result =
8675         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8676     if (Result == ImplicitConversionSequence::Indistinguishable)
8677       Result = CompareStandardConversionSequences(S, Loc,
8678                                                   Cand1.FinalConversion,
8679                                                   Cand2.FinalConversion);
8680 
8681     if (Result != ImplicitConversionSequence::Indistinguishable)
8682       return Result == ImplicitConversionSequence::Better;
8683 
8684     // FIXME: Compare kind of reference binding if conversion functions
8685     // convert to a reference type used in direct reference binding, per
8686     // C++14 [over.match.best]p1 section 2 bullet 3.
8687   }
8688 
8689   //    -- F1 is a non-template function and F2 is a function template
8690   //       specialization, or, if not that,
8691   bool Cand1IsSpecialization = Cand1.Function &&
8692                                Cand1.Function->getPrimaryTemplate();
8693   bool Cand2IsSpecialization = Cand2.Function &&
8694                                Cand2.Function->getPrimaryTemplate();
8695   if (Cand1IsSpecialization != Cand2IsSpecialization)
8696     return Cand2IsSpecialization;
8697 
8698   //   -- F1 and F2 are function template specializations, and the function
8699   //      template for F1 is more specialized than the template for F2
8700   //      according to the partial ordering rules described in 14.5.5.2, or,
8701   //      if not that,
8702   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8703     if (FunctionTemplateDecl *BetterTemplate
8704           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8705                                          Cand2.Function->getPrimaryTemplate(),
8706                                          Loc,
8707                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8708                                                              : TPOC_Call,
8709                                          Cand1.ExplicitCallArguments,
8710                                          Cand2.ExplicitCallArguments))
8711       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8712   }
8713 
8714   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8715   // A derived-class constructor beats an (inherited) base class constructor.
8716   bool Cand1IsInherited =
8717       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8718   bool Cand2IsInherited =
8719       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8720   if (Cand1IsInherited != Cand2IsInherited)
8721     return Cand2IsInherited;
8722   else if (Cand1IsInherited) {
8723     assert(Cand2IsInherited);
8724     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8725     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8726     if (Cand1Class->isDerivedFrom(Cand2Class))
8727       return true;
8728     if (Cand2Class->isDerivedFrom(Cand1Class))
8729       return false;
8730     // Inherited from sibling base classes: still ambiguous.
8731   }
8732 
8733   // Check for enable_if value-based overload resolution.
8734   if (Cand1.Function && Cand2.Function) {
8735     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8736     if (Cmp != Comparison::Equal)
8737       return Cmp == Comparison::Better;
8738   }
8739 
8740   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8741     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8742     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8743            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8744   }
8745 
8746   bool HasPS1 = Cand1.Function != nullptr &&
8747                 functionHasPassObjectSizeParams(Cand1.Function);
8748   bool HasPS2 = Cand2.Function != nullptr &&
8749                 functionHasPassObjectSizeParams(Cand2.Function);
8750   return HasPS1 != HasPS2 && HasPS1;
8751 }
8752 
8753 /// Determine whether two declarations are "equivalent" for the purposes of
8754 /// name lookup and overload resolution. This applies when the same internal/no
8755 /// linkage entity is defined by two modules (probably by textually including
8756 /// the same header). In such a case, we don't consider the declarations to
8757 /// declare the same entity, but we also don't want lookups with both
8758 /// declarations visible to be ambiguous in some cases (this happens when using
8759 /// a modularized libstdc++).
8760 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8761                                                   const NamedDecl *B) {
8762   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8763   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8764   if (!VA || !VB)
8765     return false;
8766 
8767   // The declarations must be declaring the same name as an internal linkage
8768   // entity in different modules.
8769   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8770           VB->getDeclContext()->getRedeclContext()) ||
8771       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8772           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8773       VA->isExternallyVisible() || VB->isExternallyVisible())
8774     return false;
8775 
8776   // Check that the declarations appear to be equivalent.
8777   //
8778   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8779   // For constants and functions, we should check the initializer or body is
8780   // the same. For non-constant variables, we shouldn't allow it at all.
8781   if (Context.hasSameType(VA->getType(), VB->getType()))
8782     return true;
8783 
8784   // Enum constants within unnamed enumerations will have different types, but
8785   // may still be similar enough to be interchangeable for our purposes.
8786   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8787     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8788       // Only handle anonymous enums. If the enumerations were named and
8789       // equivalent, they would have been merged to the same type.
8790       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8791       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8792       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8793           !Context.hasSameType(EnumA->getIntegerType(),
8794                                EnumB->getIntegerType()))
8795         return false;
8796       // Allow this only if the value is the same for both enumerators.
8797       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8798     }
8799   }
8800 
8801   // Nothing else is sufficiently similar.
8802   return false;
8803 }
8804 
8805 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8806     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8807   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8808 
8809   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8810   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8811       << !M << (M ? M->getFullModuleName() : "");
8812 
8813   for (auto *E : Equiv) {
8814     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8815     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8816         << !M << (M ? M->getFullModuleName() : "");
8817   }
8818 }
8819 
8820 /// \brief Computes the best viable function (C++ 13.3.3)
8821 /// within an overload candidate set.
8822 ///
8823 /// \param Loc The location of the function name (or operator symbol) for
8824 /// which overload resolution occurs.
8825 ///
8826 /// \param Best If overload resolution was successful or found a deleted
8827 /// function, \p Best points to the candidate function found.
8828 ///
8829 /// \returns The result of overload resolution.
8830 OverloadingResult
8831 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8832                                          iterator &Best,
8833                                          bool UserDefinedConversion) {
8834   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8835   std::transform(begin(), end(), std::back_inserter(Candidates),
8836                  [](OverloadCandidate &Cand) { return &Cand; });
8837 
8838   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8839   // are accepted by both clang and NVCC. However, during a particular
8840   // compilation mode only one call variant is viable. We need to
8841   // exclude non-viable overload candidates from consideration based
8842   // only on their host/device attributes. Specifically, if one
8843   // candidate call is WrongSide and the other is SameSide, we ignore
8844   // the WrongSide candidate.
8845   if (S.getLangOpts().CUDA) {
8846     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8847     bool ContainsSameSideCandidate =
8848         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8849           return Cand->Function &&
8850                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8851                      Sema::CFP_SameSide;
8852         });
8853     if (ContainsSameSideCandidate) {
8854       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8855         return Cand->Function &&
8856                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8857                    Sema::CFP_WrongSide;
8858       };
8859       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8860                                       IsWrongSideCandidate),
8861                        Candidates.end());
8862     }
8863   }
8864 
8865   // Find the best viable function.
8866   Best = end();
8867   for (auto *Cand : Candidates)
8868     if (Cand->Viable)
8869       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8870                                                      UserDefinedConversion))
8871         Best = Cand;
8872 
8873   // If we didn't find any viable functions, abort.
8874   if (Best == end())
8875     return OR_No_Viable_Function;
8876 
8877   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8878 
8879   // Make sure that this function is better than every other viable
8880   // function. If not, we have an ambiguity.
8881   for (auto *Cand : Candidates) {
8882     if (Cand->Viable &&
8883         Cand != Best &&
8884         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8885                                    UserDefinedConversion)) {
8886       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8887                                                    Cand->Function)) {
8888         EquivalentCands.push_back(Cand->Function);
8889         continue;
8890       }
8891 
8892       Best = end();
8893       return OR_Ambiguous;
8894     }
8895   }
8896 
8897   // Best is the best viable function.
8898   if (Best->Function &&
8899       (Best->Function->isDeleted() ||
8900        S.isFunctionConsideredUnavailable(Best->Function)))
8901     return OR_Deleted;
8902 
8903   if (!EquivalentCands.empty())
8904     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8905                                                     EquivalentCands);
8906 
8907   return OR_Success;
8908 }
8909 
8910 namespace {
8911 
8912 enum OverloadCandidateKind {
8913   oc_function,
8914   oc_method,
8915   oc_constructor,
8916   oc_function_template,
8917   oc_method_template,
8918   oc_constructor_template,
8919   oc_implicit_default_constructor,
8920   oc_implicit_copy_constructor,
8921   oc_implicit_move_constructor,
8922   oc_implicit_copy_assignment,
8923   oc_implicit_move_assignment,
8924   oc_inherited_constructor,
8925   oc_inherited_constructor_template
8926 };
8927 
8928 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8929                                                 NamedDecl *Found,
8930                                                 FunctionDecl *Fn,
8931                                                 std::string &Description) {
8932   bool isTemplate = false;
8933 
8934   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8935     isTemplate = true;
8936     Description = S.getTemplateArgumentBindingsText(
8937       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8938   }
8939 
8940   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8941     if (!Ctor->isImplicit()) {
8942       if (isa<ConstructorUsingShadowDecl>(Found))
8943         return isTemplate ? oc_inherited_constructor_template
8944                           : oc_inherited_constructor;
8945       else
8946         return isTemplate ? oc_constructor_template : oc_constructor;
8947     }
8948 
8949     if (Ctor->isDefaultConstructor())
8950       return oc_implicit_default_constructor;
8951 
8952     if (Ctor->isMoveConstructor())
8953       return oc_implicit_move_constructor;
8954 
8955     assert(Ctor->isCopyConstructor() &&
8956            "unexpected sort of implicit constructor");
8957     return oc_implicit_copy_constructor;
8958   }
8959 
8960   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8961     // This actually gets spelled 'candidate function' for now, but
8962     // it doesn't hurt to split it out.
8963     if (!Meth->isImplicit())
8964       return isTemplate ? oc_method_template : oc_method;
8965 
8966     if (Meth->isMoveAssignmentOperator())
8967       return oc_implicit_move_assignment;
8968 
8969     if (Meth->isCopyAssignmentOperator())
8970       return oc_implicit_copy_assignment;
8971 
8972     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8973     return oc_method;
8974   }
8975 
8976   return isTemplate ? oc_function_template : oc_function;
8977 }
8978 
8979 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8980   // FIXME: It'd be nice to only emit a note once per using-decl per overload
8981   // set.
8982   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8983     S.Diag(FoundDecl->getLocation(),
8984            diag::note_ovl_candidate_inherited_constructor)
8985       << Shadow->getNominatedBaseClass();
8986 }
8987 
8988 } // end anonymous namespace
8989 
8990 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8991                                     const FunctionDecl *FD) {
8992   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8993     bool AlwaysTrue;
8994     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8995       return false;
8996     if (!AlwaysTrue)
8997       return false;
8998   }
8999   return true;
9000 }
9001 
9002 /// \brief Returns true if we can take the address of the function.
9003 ///
9004 /// \param Complain - If true, we'll emit a diagnostic
9005 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9006 ///   we in overload resolution?
9007 /// \param Loc - The location of the statement we're complaining about. Ignored
9008 ///   if we're not complaining, or if we're in overload resolution.
9009 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9010                                               bool Complain,
9011                                               bool InOverloadResolution,
9012                                               SourceLocation Loc) {
9013   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9014     if (Complain) {
9015       if (InOverloadResolution)
9016         S.Diag(FD->getLocStart(),
9017                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9018       else
9019         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9020     }
9021     return false;
9022   }
9023 
9024   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9025     return P->hasAttr<PassObjectSizeAttr>();
9026   });
9027   if (I == FD->param_end())
9028     return true;
9029 
9030   if (Complain) {
9031     // Add one to ParamNo because it's user-facing
9032     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9033     if (InOverloadResolution)
9034       S.Diag(FD->getLocation(),
9035              diag::note_ovl_candidate_has_pass_object_size_params)
9036           << ParamNo;
9037     else
9038       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9039           << FD << ParamNo;
9040   }
9041   return false;
9042 }
9043 
9044 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9045                                                const FunctionDecl *FD) {
9046   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9047                                            /*InOverloadResolution=*/true,
9048                                            /*Loc=*/SourceLocation());
9049 }
9050 
9051 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9052                                              bool Complain,
9053                                              SourceLocation Loc) {
9054   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9055                                              /*InOverloadResolution=*/false,
9056                                              Loc);
9057 }
9058 
9059 // Notes the location of an overload candidate.
9060 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9061                                  QualType DestType, bool TakingAddress) {
9062   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9063     return;
9064 
9065   std::string FnDesc;
9066   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9067   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9068                              << (unsigned) K << FnDesc;
9069 
9070   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9071   Diag(Fn->getLocation(), PD);
9072   MaybeEmitInheritedConstructorNote(*this, Found);
9073 }
9074 
9075 // Notes the location of all overload candidates designated through
9076 // OverloadedExpr
9077 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9078                                      bool TakingAddress) {
9079   assert(OverloadedExpr->getType() == Context.OverloadTy);
9080 
9081   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9082   OverloadExpr *OvlExpr = Ovl.Expression;
9083 
9084   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9085                             IEnd = OvlExpr->decls_end();
9086        I != IEnd; ++I) {
9087     if (FunctionTemplateDecl *FunTmpl =
9088                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9089       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9090                             TakingAddress);
9091     } else if (FunctionDecl *Fun
9092                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9093       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9094     }
9095   }
9096 }
9097 
9098 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9099 /// "lead" diagnostic; it will be given two arguments, the source and
9100 /// target types of the conversion.
9101 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9102                                  Sema &S,
9103                                  SourceLocation CaretLoc,
9104                                  const PartialDiagnostic &PDiag) const {
9105   S.Diag(CaretLoc, PDiag)
9106     << Ambiguous.getFromType() << Ambiguous.getToType();
9107   // FIXME: The note limiting machinery is borrowed from
9108   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9109   // refactoring here.
9110   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9111   unsigned CandsShown = 0;
9112   AmbiguousConversionSequence::const_iterator I, E;
9113   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9114     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9115       break;
9116     ++CandsShown;
9117     S.NoteOverloadCandidate(I->first, I->second);
9118   }
9119   if (I != E)
9120     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9121 }
9122 
9123 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9124                                   unsigned I, bool TakingCandidateAddress) {
9125   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9126   assert(Conv.isBad());
9127   assert(Cand->Function && "for now, candidate must be a function");
9128   FunctionDecl *Fn = Cand->Function;
9129 
9130   // There's a conversion slot for the object argument if this is a
9131   // non-constructor method.  Note that 'I' corresponds the
9132   // conversion-slot index.
9133   bool isObjectArgument = false;
9134   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9135     if (I == 0)
9136       isObjectArgument = true;
9137     else
9138       I--;
9139   }
9140 
9141   std::string FnDesc;
9142   OverloadCandidateKind FnKind =
9143       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9144 
9145   Expr *FromExpr = Conv.Bad.FromExpr;
9146   QualType FromTy = Conv.Bad.getFromType();
9147   QualType ToTy = Conv.Bad.getToType();
9148 
9149   if (FromTy == S.Context.OverloadTy) {
9150     assert(FromExpr && "overload set argument came from implicit argument?");
9151     Expr *E = FromExpr->IgnoreParens();
9152     if (isa<UnaryOperator>(E))
9153       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9154     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9155 
9156     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9157       << (unsigned) FnKind << FnDesc
9158       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9159       << ToTy << Name << I+1;
9160     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9161     return;
9162   }
9163 
9164   // Do some hand-waving analysis to see if the non-viability is due
9165   // to a qualifier mismatch.
9166   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9167   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9168   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9169     CToTy = RT->getPointeeType();
9170   else {
9171     // TODO: detect and diagnose the full richness of const mismatches.
9172     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9173       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9174         CFromTy = FromPT->getPointeeType();
9175         CToTy = ToPT->getPointeeType();
9176       }
9177   }
9178 
9179   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9180       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9181     Qualifiers FromQs = CFromTy.getQualifiers();
9182     Qualifiers ToQs = CToTy.getQualifiers();
9183 
9184     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9185       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9186         << (unsigned) FnKind << FnDesc
9187         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9188         << FromTy
9189         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9190         << (unsigned) isObjectArgument << I+1;
9191       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9192       return;
9193     }
9194 
9195     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9196       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9197         << (unsigned) FnKind << FnDesc
9198         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9199         << FromTy
9200         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9201         << (unsigned) isObjectArgument << I+1;
9202       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9203       return;
9204     }
9205 
9206     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9207       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9208       << (unsigned) FnKind << FnDesc
9209       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9210       << FromTy
9211       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9212       << (unsigned) isObjectArgument << I+1;
9213       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9214       return;
9215     }
9216 
9217     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9218       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9219         << (unsigned) FnKind << FnDesc
9220         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9221         << FromTy << FromQs.hasUnaligned() << I+1;
9222       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9223       return;
9224     }
9225 
9226     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9227     assert(CVR && "unexpected qualifiers mismatch");
9228 
9229     if (isObjectArgument) {
9230       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9231         << (unsigned) FnKind << FnDesc
9232         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9233         << FromTy << (CVR - 1);
9234     } else {
9235       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9236         << (unsigned) FnKind << FnDesc
9237         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9238         << FromTy << (CVR - 1) << I+1;
9239     }
9240     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9241     return;
9242   }
9243 
9244   // Special diagnostic for failure to convert an initializer list, since
9245   // telling the user that it has type void is not useful.
9246   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9247     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9248       << (unsigned) FnKind << FnDesc
9249       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9250       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9251     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9252     return;
9253   }
9254 
9255   // Diagnose references or pointers to incomplete types differently,
9256   // since it's far from impossible that the incompleteness triggered
9257   // the failure.
9258   QualType TempFromTy = FromTy.getNonReferenceType();
9259   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9260     TempFromTy = PTy->getPointeeType();
9261   if (TempFromTy->isIncompleteType()) {
9262     // Emit the generic diagnostic and, optionally, add the hints to it.
9263     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9264       << (unsigned) FnKind << FnDesc
9265       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9266       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9267       << (unsigned) (Cand->Fix.Kind);
9268 
9269     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9270     return;
9271   }
9272 
9273   // Diagnose base -> derived pointer conversions.
9274   unsigned BaseToDerivedConversion = 0;
9275   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9276     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9277       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9278                                                FromPtrTy->getPointeeType()) &&
9279           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9280           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9281           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9282                           FromPtrTy->getPointeeType()))
9283         BaseToDerivedConversion = 1;
9284     }
9285   } else if (const ObjCObjectPointerType *FromPtrTy
9286                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9287     if (const ObjCObjectPointerType *ToPtrTy
9288                                         = ToTy->getAs<ObjCObjectPointerType>())
9289       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9290         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9291           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9292                                                 FromPtrTy->getPointeeType()) &&
9293               FromIface->isSuperClassOf(ToIface))
9294             BaseToDerivedConversion = 2;
9295   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9296     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9297         !FromTy->isIncompleteType() &&
9298         !ToRefTy->getPointeeType()->isIncompleteType() &&
9299         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9300       BaseToDerivedConversion = 3;
9301     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9302                ToTy.getNonReferenceType().getCanonicalType() ==
9303                FromTy.getNonReferenceType().getCanonicalType()) {
9304       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9305         << (unsigned) FnKind << FnDesc
9306         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9307         << (unsigned) isObjectArgument << I + 1;
9308       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9309       return;
9310     }
9311   }
9312 
9313   if (BaseToDerivedConversion) {
9314     S.Diag(Fn->getLocation(),
9315            diag::note_ovl_candidate_bad_base_to_derived_conv)
9316       << (unsigned) FnKind << FnDesc
9317       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9318       << (BaseToDerivedConversion - 1)
9319       << FromTy << ToTy << I+1;
9320     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9321     return;
9322   }
9323 
9324   if (isa<ObjCObjectPointerType>(CFromTy) &&
9325       isa<PointerType>(CToTy)) {
9326       Qualifiers FromQs = CFromTy.getQualifiers();
9327       Qualifiers ToQs = CToTy.getQualifiers();
9328       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9329         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9330         << (unsigned) FnKind << FnDesc
9331         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9332         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9333         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9334         return;
9335       }
9336   }
9337 
9338   if (TakingCandidateAddress &&
9339       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9340     return;
9341 
9342   // Emit the generic diagnostic and, optionally, add the hints to it.
9343   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9344   FDiag << (unsigned) FnKind << FnDesc
9345     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9346     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9347     << (unsigned) (Cand->Fix.Kind);
9348 
9349   // If we can fix the conversion, suggest the FixIts.
9350   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9351        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9352     FDiag << *HI;
9353   S.Diag(Fn->getLocation(), FDiag);
9354 
9355   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9356 }
9357 
9358 /// Additional arity mismatch diagnosis specific to a function overload
9359 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9360 /// over a candidate in any candidate set.
9361 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9362                                unsigned NumArgs) {
9363   FunctionDecl *Fn = Cand->Function;
9364   unsigned MinParams = Fn->getMinRequiredArguments();
9365 
9366   // With invalid overloaded operators, it's possible that we think we
9367   // have an arity mismatch when in fact it looks like we have the
9368   // right number of arguments, because only overloaded operators have
9369   // the weird behavior of overloading member and non-member functions.
9370   // Just don't report anything.
9371   if (Fn->isInvalidDecl() &&
9372       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9373     return true;
9374 
9375   if (NumArgs < MinParams) {
9376     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9377            (Cand->FailureKind == ovl_fail_bad_deduction &&
9378             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9379   } else {
9380     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9381            (Cand->FailureKind == ovl_fail_bad_deduction &&
9382             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9383   }
9384 
9385   return false;
9386 }
9387 
9388 /// General arity mismatch diagnosis over a candidate in a candidate set.
9389 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9390                                   unsigned NumFormalArgs) {
9391   assert(isa<FunctionDecl>(D) &&
9392       "The templated declaration should at least be a function"
9393       " when diagnosing bad template argument deduction due to too many"
9394       " or too few arguments");
9395 
9396   FunctionDecl *Fn = cast<FunctionDecl>(D);
9397 
9398   // TODO: treat calls to a missing default constructor as a special case
9399   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9400   unsigned MinParams = Fn->getMinRequiredArguments();
9401 
9402   // at least / at most / exactly
9403   unsigned mode, modeCount;
9404   if (NumFormalArgs < MinParams) {
9405     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9406         FnTy->isTemplateVariadic())
9407       mode = 0; // "at least"
9408     else
9409       mode = 2; // "exactly"
9410     modeCount = MinParams;
9411   } else {
9412     if (MinParams != FnTy->getNumParams())
9413       mode = 1; // "at most"
9414     else
9415       mode = 2; // "exactly"
9416     modeCount = FnTy->getNumParams();
9417   }
9418 
9419   std::string Description;
9420   OverloadCandidateKind FnKind =
9421       ClassifyOverloadCandidate(S, Found, Fn, Description);
9422 
9423   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9424     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9425       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9426       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9427   else
9428     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9429       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9430       << mode << modeCount << NumFormalArgs;
9431   MaybeEmitInheritedConstructorNote(S, Found);
9432 }
9433 
9434 /// Arity mismatch diagnosis specific to a function overload candidate.
9435 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9436                                   unsigned NumFormalArgs) {
9437   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9438     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9439 }
9440 
9441 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9442   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9443     return TD;
9444   llvm_unreachable("Unsupported: Getting the described template declaration"
9445                    " for bad deduction diagnosis");
9446 }
9447 
9448 /// Diagnose a failed template-argument deduction.
9449 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9450                                  DeductionFailureInfo &DeductionFailure,
9451                                  unsigned NumArgs,
9452                                  bool TakingCandidateAddress) {
9453   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9454   NamedDecl *ParamD;
9455   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9456   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9457   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9458   switch (DeductionFailure.Result) {
9459   case Sema::TDK_Success:
9460     llvm_unreachable("TDK_success while diagnosing bad deduction");
9461 
9462   case Sema::TDK_Incomplete: {
9463     assert(ParamD && "no parameter found for incomplete deduction result");
9464     S.Diag(Templated->getLocation(),
9465            diag::note_ovl_candidate_incomplete_deduction)
9466         << ParamD->getDeclName();
9467     MaybeEmitInheritedConstructorNote(S, Found);
9468     return;
9469   }
9470 
9471   case Sema::TDK_Underqualified: {
9472     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9473     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9474 
9475     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9476 
9477     // Param will have been canonicalized, but it should just be a
9478     // qualified version of ParamD, so move the qualifiers to that.
9479     QualifierCollector Qs;
9480     Qs.strip(Param);
9481     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9482     assert(S.Context.hasSameType(Param, NonCanonParam));
9483 
9484     // Arg has also been canonicalized, but there's nothing we can do
9485     // about that.  It also doesn't matter as much, because it won't
9486     // have any template parameters in it (because deduction isn't
9487     // done on dependent types).
9488     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9489 
9490     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9491         << ParamD->getDeclName() << Arg << NonCanonParam;
9492     MaybeEmitInheritedConstructorNote(S, Found);
9493     return;
9494   }
9495 
9496   case Sema::TDK_Inconsistent: {
9497     assert(ParamD && "no parameter found for inconsistent deduction result");
9498     int which = 0;
9499     if (isa<TemplateTypeParmDecl>(ParamD))
9500       which = 0;
9501     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9502       which = 1;
9503     else {
9504       which = 2;
9505     }
9506 
9507     S.Diag(Templated->getLocation(),
9508            diag::note_ovl_candidate_inconsistent_deduction)
9509         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9510         << *DeductionFailure.getSecondArg();
9511     MaybeEmitInheritedConstructorNote(S, Found);
9512     return;
9513   }
9514 
9515   case Sema::TDK_InvalidExplicitArguments:
9516     assert(ParamD && "no parameter found for invalid explicit arguments");
9517     if (ParamD->getDeclName())
9518       S.Diag(Templated->getLocation(),
9519              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9520           << ParamD->getDeclName();
9521     else {
9522       int index = 0;
9523       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9524         index = TTP->getIndex();
9525       else if (NonTypeTemplateParmDecl *NTTP
9526                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9527         index = NTTP->getIndex();
9528       else
9529         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9530       S.Diag(Templated->getLocation(),
9531              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9532           << (index + 1);
9533     }
9534     MaybeEmitInheritedConstructorNote(S, Found);
9535     return;
9536 
9537   case Sema::TDK_TooManyArguments:
9538   case Sema::TDK_TooFewArguments:
9539     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9540     return;
9541 
9542   case Sema::TDK_InstantiationDepth:
9543     S.Diag(Templated->getLocation(),
9544            diag::note_ovl_candidate_instantiation_depth);
9545     MaybeEmitInheritedConstructorNote(S, Found);
9546     return;
9547 
9548   case Sema::TDK_SubstitutionFailure: {
9549     // Format the template argument list into the argument string.
9550     SmallString<128> TemplateArgString;
9551     if (TemplateArgumentList *Args =
9552             DeductionFailure.getTemplateArgumentList()) {
9553       TemplateArgString = " ";
9554       TemplateArgString += S.getTemplateArgumentBindingsText(
9555           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9556     }
9557 
9558     // If this candidate was disabled by enable_if, say so.
9559     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9560     if (PDiag && PDiag->second.getDiagID() ==
9561           diag::err_typename_nested_not_found_enable_if) {
9562       // FIXME: Use the source range of the condition, and the fully-qualified
9563       //        name of the enable_if template. These are both present in PDiag.
9564       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9565         << "'enable_if'" << TemplateArgString;
9566       return;
9567     }
9568 
9569     // Format the SFINAE diagnostic into the argument string.
9570     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9571     //        formatted message in another diagnostic.
9572     SmallString<128> SFINAEArgString;
9573     SourceRange R;
9574     if (PDiag) {
9575       SFINAEArgString = ": ";
9576       R = SourceRange(PDiag->first, PDiag->first);
9577       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9578     }
9579 
9580     S.Diag(Templated->getLocation(),
9581            diag::note_ovl_candidate_substitution_failure)
9582         << TemplateArgString << SFINAEArgString << R;
9583     MaybeEmitInheritedConstructorNote(S, Found);
9584     return;
9585   }
9586 
9587   case Sema::TDK_FailedOverloadResolution: {
9588     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9589     S.Diag(Templated->getLocation(),
9590            diag::note_ovl_candidate_failed_overload_resolution)
9591         << R.Expression->getName();
9592     return;
9593   }
9594 
9595   case Sema::TDK_DeducedMismatch: {
9596     // Format the template argument list into the argument string.
9597     SmallString<128> TemplateArgString;
9598     if (TemplateArgumentList *Args =
9599             DeductionFailure.getTemplateArgumentList()) {
9600       TemplateArgString = " ";
9601       TemplateArgString += S.getTemplateArgumentBindingsText(
9602           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9603     }
9604 
9605     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9606         << (*DeductionFailure.getCallArgIndex() + 1)
9607         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9608         << TemplateArgString;
9609     break;
9610   }
9611 
9612   case Sema::TDK_NonDeducedMismatch: {
9613     // FIXME: Provide a source location to indicate what we couldn't match.
9614     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9615     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9616     if (FirstTA.getKind() == TemplateArgument::Template &&
9617         SecondTA.getKind() == TemplateArgument::Template) {
9618       TemplateName FirstTN = FirstTA.getAsTemplate();
9619       TemplateName SecondTN = SecondTA.getAsTemplate();
9620       if (FirstTN.getKind() == TemplateName::Template &&
9621           SecondTN.getKind() == TemplateName::Template) {
9622         if (FirstTN.getAsTemplateDecl()->getName() ==
9623             SecondTN.getAsTemplateDecl()->getName()) {
9624           // FIXME: This fixes a bad diagnostic where both templates are named
9625           // the same.  This particular case is a bit difficult since:
9626           // 1) It is passed as a string to the diagnostic printer.
9627           // 2) The diagnostic printer only attempts to find a better
9628           //    name for types, not decls.
9629           // Ideally, this should folded into the diagnostic printer.
9630           S.Diag(Templated->getLocation(),
9631                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9632               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9633           return;
9634         }
9635       }
9636     }
9637 
9638     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9639         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9640       return;
9641 
9642     // FIXME: For generic lambda parameters, check if the function is a lambda
9643     // call operator, and if so, emit a prettier and more informative
9644     // diagnostic that mentions 'auto' and lambda in addition to
9645     // (or instead of?) the canonical template type parameters.
9646     S.Diag(Templated->getLocation(),
9647            diag::note_ovl_candidate_non_deduced_mismatch)
9648         << FirstTA << SecondTA;
9649     return;
9650   }
9651   // TODO: diagnose these individually, then kill off
9652   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9653   case Sema::TDK_MiscellaneousDeductionFailure:
9654     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9655     MaybeEmitInheritedConstructorNote(S, Found);
9656     return;
9657   }
9658 }
9659 
9660 /// Diagnose a failed template-argument deduction, for function calls.
9661 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9662                                  unsigned NumArgs,
9663                                  bool TakingCandidateAddress) {
9664   unsigned TDK = Cand->DeductionFailure.Result;
9665   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9666     if (CheckArityMismatch(S, Cand, NumArgs))
9667       return;
9668   }
9669   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9670                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9671 }
9672 
9673 /// CUDA: diagnose an invalid call across targets.
9674 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9675   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9676   FunctionDecl *Callee = Cand->Function;
9677 
9678   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9679                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9680 
9681   std::string FnDesc;
9682   OverloadCandidateKind FnKind =
9683       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9684 
9685   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9686       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9687 
9688   // This could be an implicit constructor for which we could not infer the
9689   // target due to a collsion. Diagnose that case.
9690   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9691   if (Meth != nullptr && Meth->isImplicit()) {
9692     CXXRecordDecl *ParentClass = Meth->getParent();
9693     Sema::CXXSpecialMember CSM;
9694 
9695     switch (FnKind) {
9696     default:
9697       return;
9698     case oc_implicit_default_constructor:
9699       CSM = Sema::CXXDefaultConstructor;
9700       break;
9701     case oc_implicit_copy_constructor:
9702       CSM = Sema::CXXCopyConstructor;
9703       break;
9704     case oc_implicit_move_constructor:
9705       CSM = Sema::CXXMoveConstructor;
9706       break;
9707     case oc_implicit_copy_assignment:
9708       CSM = Sema::CXXCopyAssignment;
9709       break;
9710     case oc_implicit_move_assignment:
9711       CSM = Sema::CXXMoveAssignment;
9712       break;
9713     };
9714 
9715     bool ConstRHS = false;
9716     if (Meth->getNumParams()) {
9717       if (const ReferenceType *RT =
9718               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9719         ConstRHS = RT->getPointeeType().isConstQualified();
9720       }
9721     }
9722 
9723     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9724                                               /* ConstRHS */ ConstRHS,
9725                                               /* Diagnose */ true);
9726   }
9727 }
9728 
9729 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9730   FunctionDecl *Callee = Cand->Function;
9731   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9732 
9733   S.Diag(Callee->getLocation(),
9734          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9735       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9736 }
9737 
9738 /// Generates a 'note' diagnostic for an overload candidate.  We've
9739 /// already generated a primary error at the call site.
9740 ///
9741 /// It really does need to be a single diagnostic with its caret
9742 /// pointed at the candidate declaration.  Yes, this creates some
9743 /// major challenges of technical writing.  Yes, this makes pointing
9744 /// out problems with specific arguments quite awkward.  It's still
9745 /// better than generating twenty screens of text for every failed
9746 /// overload.
9747 ///
9748 /// It would be great to be able to express per-candidate problems
9749 /// more richly for those diagnostic clients that cared, but we'd
9750 /// still have to be just as careful with the default diagnostics.
9751 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9752                                   unsigned NumArgs,
9753                                   bool TakingCandidateAddress) {
9754   FunctionDecl *Fn = Cand->Function;
9755 
9756   // Note deleted candidates, but only if they're viable.
9757   if (Cand->Viable && (Fn->isDeleted() ||
9758       S.isFunctionConsideredUnavailable(Fn))) {
9759     std::string FnDesc;
9760     OverloadCandidateKind FnKind =
9761         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9762 
9763     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9764       << FnKind << FnDesc
9765       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9766     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9767     return;
9768   }
9769 
9770   // We don't really have anything else to say about viable candidates.
9771   if (Cand->Viable) {
9772     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9773     return;
9774   }
9775 
9776   switch (Cand->FailureKind) {
9777   case ovl_fail_too_many_arguments:
9778   case ovl_fail_too_few_arguments:
9779     return DiagnoseArityMismatch(S, Cand, NumArgs);
9780 
9781   case ovl_fail_bad_deduction:
9782     return DiagnoseBadDeduction(S, Cand, NumArgs,
9783                                 TakingCandidateAddress);
9784 
9785   case ovl_fail_illegal_constructor: {
9786     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9787       << (Fn->getPrimaryTemplate() ? 1 : 0);
9788     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9789     return;
9790   }
9791 
9792   case ovl_fail_trivial_conversion:
9793   case ovl_fail_bad_final_conversion:
9794   case ovl_fail_final_conversion_not_exact:
9795     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9796 
9797   case ovl_fail_bad_conversion: {
9798     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9799     for (unsigned N = Cand->NumConversions; I != N; ++I)
9800       if (Cand->Conversions[I].isBad())
9801         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9802 
9803     // FIXME: this currently happens when we're called from SemaInit
9804     // when user-conversion overload fails.  Figure out how to handle
9805     // those conditions and diagnose them well.
9806     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9807   }
9808 
9809   case ovl_fail_bad_target:
9810     return DiagnoseBadTarget(S, Cand);
9811 
9812   case ovl_fail_enable_if:
9813     return DiagnoseFailedEnableIfAttr(S, Cand);
9814 
9815   case ovl_fail_addr_not_available: {
9816     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9817     (void)Available;
9818     assert(!Available);
9819     break;
9820   }
9821   }
9822 }
9823 
9824 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9825   // Desugar the type of the surrogate down to a function type,
9826   // retaining as many typedefs as possible while still showing
9827   // the function type (and, therefore, its parameter types).
9828   QualType FnType = Cand->Surrogate->getConversionType();
9829   bool isLValueReference = false;
9830   bool isRValueReference = false;
9831   bool isPointer = false;
9832   if (const LValueReferenceType *FnTypeRef =
9833         FnType->getAs<LValueReferenceType>()) {
9834     FnType = FnTypeRef->getPointeeType();
9835     isLValueReference = true;
9836   } else if (const RValueReferenceType *FnTypeRef =
9837                FnType->getAs<RValueReferenceType>()) {
9838     FnType = FnTypeRef->getPointeeType();
9839     isRValueReference = true;
9840   }
9841   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9842     FnType = FnTypePtr->getPointeeType();
9843     isPointer = true;
9844   }
9845   // Desugar down to a function type.
9846   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9847   // Reconstruct the pointer/reference as appropriate.
9848   if (isPointer) FnType = S.Context.getPointerType(FnType);
9849   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9850   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9851 
9852   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9853     << FnType;
9854 }
9855 
9856 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9857                                          SourceLocation OpLoc,
9858                                          OverloadCandidate *Cand) {
9859   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9860   std::string TypeStr("operator");
9861   TypeStr += Opc;
9862   TypeStr += "(";
9863   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9864   if (Cand->NumConversions == 1) {
9865     TypeStr += ")";
9866     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9867   } else {
9868     TypeStr += ", ";
9869     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9870     TypeStr += ")";
9871     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9872   }
9873 }
9874 
9875 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9876                                          OverloadCandidate *Cand) {
9877   unsigned NoOperands = Cand->NumConversions;
9878   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9879     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9880     if (ICS.isBad()) break; // all meaningless after first invalid
9881     if (!ICS.isAmbiguous()) continue;
9882 
9883     ICS.DiagnoseAmbiguousConversion(
9884         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9885   }
9886 }
9887 
9888 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9889   if (Cand->Function)
9890     return Cand->Function->getLocation();
9891   if (Cand->IsSurrogate)
9892     return Cand->Surrogate->getLocation();
9893   return SourceLocation();
9894 }
9895 
9896 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9897   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9898   case Sema::TDK_Success:
9899     llvm_unreachable("TDK_success while diagnosing bad deduction");
9900 
9901   case Sema::TDK_Invalid:
9902   case Sema::TDK_Incomplete:
9903     return 1;
9904 
9905   case Sema::TDK_Underqualified:
9906   case Sema::TDK_Inconsistent:
9907     return 2;
9908 
9909   case Sema::TDK_SubstitutionFailure:
9910   case Sema::TDK_DeducedMismatch:
9911   case Sema::TDK_NonDeducedMismatch:
9912   case Sema::TDK_MiscellaneousDeductionFailure:
9913     return 3;
9914 
9915   case Sema::TDK_InstantiationDepth:
9916   case Sema::TDK_FailedOverloadResolution:
9917     return 4;
9918 
9919   case Sema::TDK_InvalidExplicitArguments:
9920     return 5;
9921 
9922   case Sema::TDK_TooManyArguments:
9923   case Sema::TDK_TooFewArguments:
9924     return 6;
9925   }
9926   llvm_unreachable("Unhandled deduction result");
9927 }
9928 
9929 namespace {
9930 struct CompareOverloadCandidatesForDisplay {
9931   Sema &S;
9932   SourceLocation Loc;
9933   size_t NumArgs;
9934 
9935   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9936       : S(S), NumArgs(nArgs) {}
9937 
9938   bool operator()(const OverloadCandidate *L,
9939                   const OverloadCandidate *R) {
9940     // Fast-path this check.
9941     if (L == R) return false;
9942 
9943     // Order first by viability.
9944     if (L->Viable) {
9945       if (!R->Viable) return true;
9946 
9947       // TODO: introduce a tri-valued comparison for overload
9948       // candidates.  Would be more worthwhile if we had a sort
9949       // that could exploit it.
9950       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9951       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9952     } else if (R->Viable)
9953       return false;
9954 
9955     assert(L->Viable == R->Viable);
9956 
9957     // Criteria by which we can sort non-viable candidates:
9958     if (!L->Viable) {
9959       // 1. Arity mismatches come after other candidates.
9960       if (L->FailureKind == ovl_fail_too_many_arguments ||
9961           L->FailureKind == ovl_fail_too_few_arguments) {
9962         if (R->FailureKind == ovl_fail_too_many_arguments ||
9963             R->FailureKind == ovl_fail_too_few_arguments) {
9964           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9965           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9966           if (LDist == RDist) {
9967             if (L->FailureKind == R->FailureKind)
9968               // Sort non-surrogates before surrogates.
9969               return !L->IsSurrogate && R->IsSurrogate;
9970             // Sort candidates requiring fewer parameters than there were
9971             // arguments given after candidates requiring more parameters
9972             // than there were arguments given.
9973             return L->FailureKind == ovl_fail_too_many_arguments;
9974           }
9975           return LDist < RDist;
9976         }
9977         return false;
9978       }
9979       if (R->FailureKind == ovl_fail_too_many_arguments ||
9980           R->FailureKind == ovl_fail_too_few_arguments)
9981         return true;
9982 
9983       // 2. Bad conversions come first and are ordered by the number
9984       // of bad conversions and quality of good conversions.
9985       if (L->FailureKind == ovl_fail_bad_conversion) {
9986         if (R->FailureKind != ovl_fail_bad_conversion)
9987           return true;
9988 
9989         // The conversion that can be fixed with a smaller number of changes,
9990         // comes first.
9991         unsigned numLFixes = L->Fix.NumConversionsFixed;
9992         unsigned numRFixes = R->Fix.NumConversionsFixed;
9993         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9994         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9995         if (numLFixes != numRFixes) {
9996           return numLFixes < numRFixes;
9997         }
9998 
9999         // If there's any ordering between the defined conversions...
10000         // FIXME: this might not be transitive.
10001         assert(L->NumConversions == R->NumConversions);
10002 
10003         int leftBetter = 0;
10004         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10005         for (unsigned E = L->NumConversions; I != E; ++I) {
10006           switch (CompareImplicitConversionSequences(S, Loc,
10007                                                      L->Conversions[I],
10008                                                      R->Conversions[I])) {
10009           case ImplicitConversionSequence::Better:
10010             leftBetter++;
10011             break;
10012 
10013           case ImplicitConversionSequence::Worse:
10014             leftBetter--;
10015             break;
10016 
10017           case ImplicitConversionSequence::Indistinguishable:
10018             break;
10019           }
10020         }
10021         if (leftBetter > 0) return true;
10022         if (leftBetter < 0) return false;
10023 
10024       } else if (R->FailureKind == ovl_fail_bad_conversion)
10025         return false;
10026 
10027       if (L->FailureKind == ovl_fail_bad_deduction) {
10028         if (R->FailureKind != ovl_fail_bad_deduction)
10029           return true;
10030 
10031         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10032           return RankDeductionFailure(L->DeductionFailure)
10033                < RankDeductionFailure(R->DeductionFailure);
10034       } else if (R->FailureKind == ovl_fail_bad_deduction)
10035         return false;
10036 
10037       // TODO: others?
10038     }
10039 
10040     // Sort everything else by location.
10041     SourceLocation LLoc = GetLocationForCandidate(L);
10042     SourceLocation RLoc = GetLocationForCandidate(R);
10043 
10044     // Put candidates without locations (e.g. builtins) at the end.
10045     if (LLoc.isInvalid()) return false;
10046     if (RLoc.isInvalid()) return true;
10047 
10048     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10049   }
10050 };
10051 }
10052 
10053 /// CompleteNonViableCandidate - Normally, overload resolution only
10054 /// computes up to the first. Produces the FixIt set if possible.
10055 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10056                                        ArrayRef<Expr *> Args) {
10057   assert(!Cand->Viable);
10058 
10059   // Don't do anything on failures other than bad conversion.
10060   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10061 
10062   // We only want the FixIts if all the arguments can be corrected.
10063   bool Unfixable = false;
10064   // Use a implicit copy initialization to check conversion fixes.
10065   Cand->Fix.setConversionChecker(TryCopyInitialization);
10066 
10067   // Skip forward to the first bad conversion.
10068   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10069   unsigned ConvCount = Cand->NumConversions;
10070   while (true) {
10071     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10072     ConvIdx++;
10073     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10074       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10075       break;
10076     }
10077   }
10078 
10079   if (ConvIdx == ConvCount)
10080     return;
10081 
10082   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10083          "remaining conversion is initialized?");
10084 
10085   // FIXME: this should probably be preserved from the overload
10086   // operation somehow.
10087   bool SuppressUserConversions = false;
10088 
10089   const FunctionProtoType* Proto;
10090   unsigned ArgIdx = ConvIdx;
10091 
10092   if (Cand->IsSurrogate) {
10093     QualType ConvType
10094       = Cand->Surrogate->getConversionType().getNonReferenceType();
10095     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10096       ConvType = ConvPtrType->getPointeeType();
10097     Proto = ConvType->getAs<FunctionProtoType>();
10098     ArgIdx--;
10099   } else if (Cand->Function) {
10100     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10101     if (isa<CXXMethodDecl>(Cand->Function) &&
10102         !isa<CXXConstructorDecl>(Cand->Function))
10103       ArgIdx--;
10104   } else {
10105     // Builtin binary operator with a bad first conversion.
10106     assert(ConvCount <= 3);
10107     for (; ConvIdx != ConvCount; ++ConvIdx)
10108       Cand->Conversions[ConvIdx]
10109         = TryCopyInitialization(S, Args[ConvIdx],
10110                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10111                                 SuppressUserConversions,
10112                                 /*InOverloadResolution*/ true,
10113                                 /*AllowObjCWritebackConversion=*/
10114                                   S.getLangOpts().ObjCAutoRefCount);
10115     return;
10116   }
10117 
10118   // Fill in the rest of the conversions.
10119   unsigned NumParams = Proto->getNumParams();
10120   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10121     if (ArgIdx < NumParams) {
10122       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10123           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10124           /*InOverloadResolution=*/true,
10125           /*AllowObjCWritebackConversion=*/
10126           S.getLangOpts().ObjCAutoRefCount);
10127       // Store the FixIt in the candidate if it exists.
10128       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10129         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10130     }
10131     else
10132       Cand->Conversions[ConvIdx].setEllipsis();
10133   }
10134 }
10135 
10136 /// PrintOverloadCandidates - When overload resolution fails, prints
10137 /// diagnostic messages containing the candidates in the candidate
10138 /// set.
10139 void OverloadCandidateSet::NoteCandidates(Sema &S,
10140                                           OverloadCandidateDisplayKind OCD,
10141                                           ArrayRef<Expr *> Args,
10142                                           StringRef Opc,
10143                                           SourceLocation OpLoc) {
10144   // Sort the candidates by viability and position.  Sorting directly would
10145   // be prohibitive, so we make a set of pointers and sort those.
10146   SmallVector<OverloadCandidate*, 32> Cands;
10147   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10148   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10149     if (Cand->Viable)
10150       Cands.push_back(Cand);
10151     else if (OCD == OCD_AllCandidates) {
10152       CompleteNonViableCandidate(S, Cand, Args);
10153       if (Cand->Function || Cand->IsSurrogate)
10154         Cands.push_back(Cand);
10155       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10156       // want to list every possible builtin candidate.
10157     }
10158   }
10159 
10160   std::sort(Cands.begin(), Cands.end(),
10161             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10162 
10163   bool ReportedAmbiguousConversions = false;
10164 
10165   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10166   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10167   unsigned CandsShown = 0;
10168   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10169     OverloadCandidate *Cand = *I;
10170 
10171     // Set an arbitrary limit on the number of candidate functions we'll spam
10172     // the user with.  FIXME: This limit should depend on details of the
10173     // candidate list.
10174     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10175       break;
10176     }
10177     ++CandsShown;
10178 
10179     if (Cand->Function)
10180       NoteFunctionCandidate(S, Cand, Args.size(),
10181                             /*TakingCandidateAddress=*/false);
10182     else if (Cand->IsSurrogate)
10183       NoteSurrogateCandidate(S, Cand);
10184     else {
10185       assert(Cand->Viable &&
10186              "Non-viable built-in candidates are not added to Cands.");
10187       // Generally we only see ambiguities including viable builtin
10188       // operators if overload resolution got screwed up by an
10189       // ambiguous user-defined conversion.
10190       //
10191       // FIXME: It's quite possible for different conversions to see
10192       // different ambiguities, though.
10193       if (!ReportedAmbiguousConversions) {
10194         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10195         ReportedAmbiguousConversions = true;
10196       }
10197 
10198       // If this is a viable builtin, print it.
10199       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10200     }
10201   }
10202 
10203   if (I != E)
10204     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10205 }
10206 
10207 static SourceLocation
10208 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10209   return Cand->Specialization ? Cand->Specialization->getLocation()
10210                               : SourceLocation();
10211 }
10212 
10213 namespace {
10214 struct CompareTemplateSpecCandidatesForDisplay {
10215   Sema &S;
10216   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10217 
10218   bool operator()(const TemplateSpecCandidate *L,
10219                   const TemplateSpecCandidate *R) {
10220     // Fast-path this check.
10221     if (L == R)
10222       return false;
10223 
10224     // Assuming that both candidates are not matches...
10225 
10226     // Sort by the ranking of deduction failures.
10227     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10228       return RankDeductionFailure(L->DeductionFailure) <
10229              RankDeductionFailure(R->DeductionFailure);
10230 
10231     // Sort everything else by location.
10232     SourceLocation LLoc = GetLocationForCandidate(L);
10233     SourceLocation RLoc = GetLocationForCandidate(R);
10234 
10235     // Put candidates without locations (e.g. builtins) at the end.
10236     if (LLoc.isInvalid())
10237       return false;
10238     if (RLoc.isInvalid())
10239       return true;
10240 
10241     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10242   }
10243 };
10244 }
10245 
10246 /// Diagnose a template argument deduction failure.
10247 /// We are treating these failures as overload failures due to bad
10248 /// deductions.
10249 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10250                                                  bool ForTakingAddress) {
10251   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10252                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10253 }
10254 
10255 void TemplateSpecCandidateSet::destroyCandidates() {
10256   for (iterator i = begin(), e = end(); i != e; ++i) {
10257     i->DeductionFailure.Destroy();
10258   }
10259 }
10260 
10261 void TemplateSpecCandidateSet::clear() {
10262   destroyCandidates();
10263   Candidates.clear();
10264 }
10265 
10266 /// NoteCandidates - When no template specialization match is found, prints
10267 /// diagnostic messages containing the non-matching specializations that form
10268 /// the candidate set.
10269 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10270 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10271 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10272   // Sort the candidates by position (assuming no candidate is a match).
10273   // Sorting directly would be prohibitive, so we make a set of pointers
10274   // and sort those.
10275   SmallVector<TemplateSpecCandidate *, 32> Cands;
10276   Cands.reserve(size());
10277   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10278     if (Cand->Specialization)
10279       Cands.push_back(Cand);
10280     // Otherwise, this is a non-matching builtin candidate.  We do not,
10281     // in general, want to list every possible builtin candidate.
10282   }
10283 
10284   std::sort(Cands.begin(), Cands.end(),
10285             CompareTemplateSpecCandidatesForDisplay(S));
10286 
10287   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10288   // for generalization purposes (?).
10289   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10290 
10291   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10292   unsigned CandsShown = 0;
10293   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10294     TemplateSpecCandidate *Cand = *I;
10295 
10296     // Set an arbitrary limit on the number of candidates we'll spam
10297     // the user with.  FIXME: This limit should depend on details of the
10298     // candidate list.
10299     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10300       break;
10301     ++CandsShown;
10302 
10303     assert(Cand->Specialization &&
10304            "Non-matching built-in candidates are not added to Cands.");
10305     Cand->NoteDeductionFailure(S, ForTakingAddress);
10306   }
10307 
10308   if (I != E)
10309     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10310 }
10311 
10312 // [PossiblyAFunctionType]  -->   [Return]
10313 // NonFunctionType --> NonFunctionType
10314 // R (A) --> R(A)
10315 // R (*)(A) --> R (A)
10316 // R (&)(A) --> R (A)
10317 // R (S::*)(A) --> R (A)
10318 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10319   QualType Ret = PossiblyAFunctionType;
10320   if (const PointerType *ToTypePtr =
10321     PossiblyAFunctionType->getAs<PointerType>())
10322     Ret = ToTypePtr->getPointeeType();
10323   else if (const ReferenceType *ToTypeRef =
10324     PossiblyAFunctionType->getAs<ReferenceType>())
10325     Ret = ToTypeRef->getPointeeType();
10326   else if (const MemberPointerType *MemTypePtr =
10327     PossiblyAFunctionType->getAs<MemberPointerType>())
10328     Ret = MemTypePtr->getPointeeType();
10329   Ret =
10330     Context.getCanonicalType(Ret).getUnqualifiedType();
10331   return Ret;
10332 }
10333 
10334 namespace {
10335 // A helper class to help with address of function resolution
10336 // - allows us to avoid passing around all those ugly parameters
10337 class AddressOfFunctionResolver {
10338   Sema& S;
10339   Expr* SourceExpr;
10340   const QualType& TargetType;
10341   QualType TargetFunctionType; // Extracted function type from target type
10342 
10343   bool Complain;
10344   //DeclAccessPair& ResultFunctionAccessPair;
10345   ASTContext& Context;
10346 
10347   bool TargetTypeIsNonStaticMemberFunction;
10348   bool FoundNonTemplateFunction;
10349   bool StaticMemberFunctionFromBoundPointer;
10350   bool HasComplained;
10351 
10352   OverloadExpr::FindResult OvlExprInfo;
10353   OverloadExpr *OvlExpr;
10354   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10355   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10356   TemplateSpecCandidateSet FailedCandidates;
10357 
10358 public:
10359   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10360                             const QualType &TargetType, bool Complain)
10361       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10362         Complain(Complain), Context(S.getASTContext()),
10363         TargetTypeIsNonStaticMemberFunction(
10364             !!TargetType->getAs<MemberPointerType>()),
10365         FoundNonTemplateFunction(false),
10366         StaticMemberFunctionFromBoundPointer(false),
10367         HasComplained(false),
10368         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10369         OvlExpr(OvlExprInfo.Expression),
10370         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10371     ExtractUnqualifiedFunctionTypeFromTargetType();
10372 
10373     if (TargetFunctionType->isFunctionType()) {
10374       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10375         if (!UME->isImplicitAccess() &&
10376             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10377           StaticMemberFunctionFromBoundPointer = true;
10378     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10379       DeclAccessPair dap;
10380       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10381               OvlExpr, false, &dap)) {
10382         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10383           if (!Method->isStatic()) {
10384             // If the target type is a non-function type and the function found
10385             // is a non-static member function, pretend as if that was the
10386             // target, it's the only possible type to end up with.
10387             TargetTypeIsNonStaticMemberFunction = true;
10388 
10389             // And skip adding the function if its not in the proper form.
10390             // We'll diagnose this due to an empty set of functions.
10391             if (!OvlExprInfo.HasFormOfMemberPointer)
10392               return;
10393           }
10394 
10395         Matches.push_back(std::make_pair(dap, Fn));
10396       }
10397       return;
10398     }
10399 
10400     if (OvlExpr->hasExplicitTemplateArgs())
10401       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10402 
10403     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10404       // C++ [over.over]p4:
10405       //   If more than one function is selected, [...]
10406       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10407         if (FoundNonTemplateFunction)
10408           EliminateAllTemplateMatches();
10409         else
10410           EliminateAllExceptMostSpecializedTemplate();
10411       }
10412     }
10413 
10414     if (S.getLangOpts().CUDA && Matches.size() > 1)
10415       EliminateSuboptimalCudaMatches();
10416   }
10417 
10418   bool hasComplained() const { return HasComplained; }
10419 
10420 private:
10421   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10422     QualType Discard;
10423     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10424            S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10425   }
10426 
10427   /// \return true if A is considered a better overload candidate for the
10428   /// desired type than B.
10429   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10430     // If A doesn't have exactly the correct type, we don't want to classify it
10431     // as "better" than anything else. This way, the user is required to
10432     // disambiguate for us if there are multiple candidates and no exact match.
10433     return candidateHasExactlyCorrectType(A) &&
10434            (!candidateHasExactlyCorrectType(B) ||
10435             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10436   }
10437 
10438   /// \return true if we were able to eliminate all but one overload candidate,
10439   /// false otherwise.
10440   bool eliminiateSuboptimalOverloadCandidates() {
10441     // Same algorithm as overload resolution -- one pass to pick the "best",
10442     // another pass to be sure that nothing is better than the best.
10443     auto Best = Matches.begin();
10444     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10445       if (isBetterCandidate(I->second, Best->second))
10446         Best = I;
10447 
10448     const FunctionDecl *BestFn = Best->second;
10449     auto IsBestOrInferiorToBest = [this, BestFn](
10450         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10451       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10452     };
10453 
10454     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10455     // option, so we can potentially give the user a better error
10456     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10457       return false;
10458     Matches[0] = *Best;
10459     Matches.resize(1);
10460     return true;
10461   }
10462 
10463   bool isTargetTypeAFunction() const {
10464     return TargetFunctionType->isFunctionType();
10465   }
10466 
10467   // [ToType]     [Return]
10468 
10469   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10470   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10471   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10472   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10473     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10474   }
10475 
10476   // return true if any matching specializations were found
10477   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10478                                    const DeclAccessPair& CurAccessFunPair) {
10479     if (CXXMethodDecl *Method
10480               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10481       // Skip non-static function templates when converting to pointer, and
10482       // static when converting to member pointer.
10483       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10484         return false;
10485     }
10486     else if (TargetTypeIsNonStaticMemberFunction)
10487       return false;
10488 
10489     // C++ [over.over]p2:
10490     //   If the name is a function template, template argument deduction is
10491     //   done (14.8.2.2), and if the argument deduction succeeds, the
10492     //   resulting template argument list is used to generate a single
10493     //   function template specialization, which is added to the set of
10494     //   overloaded functions considered.
10495     FunctionDecl *Specialization = nullptr;
10496     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10497     if (Sema::TemplateDeductionResult Result
10498           = S.DeduceTemplateArguments(FunctionTemplate,
10499                                       &OvlExplicitTemplateArgs,
10500                                       TargetFunctionType, Specialization,
10501                                       Info, /*InOverloadResolution=*/true)) {
10502       // Make a note of the failed deduction for diagnostics.
10503       FailedCandidates.addCandidate()
10504           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10505                MakeDeductionFailureInfo(Context, Result, Info));
10506       return false;
10507     }
10508 
10509     // Template argument deduction ensures that we have an exact match or
10510     // compatible pointer-to-function arguments that would be adjusted by ICS.
10511     // This function template specicalization works.
10512     assert(S.isSameOrCompatibleFunctionType(
10513               Context.getCanonicalType(Specialization->getType()),
10514               Context.getCanonicalType(TargetFunctionType)));
10515 
10516     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10517       return false;
10518 
10519     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10520     return true;
10521   }
10522 
10523   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10524                                       const DeclAccessPair& CurAccessFunPair) {
10525     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10526       // Skip non-static functions when converting to pointer, and static
10527       // when converting to member pointer.
10528       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10529         return false;
10530     }
10531     else if (TargetTypeIsNonStaticMemberFunction)
10532       return false;
10533 
10534     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10535       if (S.getLangOpts().CUDA)
10536         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10537           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10538             return false;
10539 
10540       // If any candidate has a placeholder return type, trigger its deduction
10541       // now.
10542       if (S.getLangOpts().CPlusPlus14 &&
10543           FunDecl->getReturnType()->isUndeducedType() &&
10544           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10545         HasComplained |= Complain;
10546         return false;
10547       }
10548 
10549       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10550         return false;
10551 
10552       // If we're in C, we need to support types that aren't exactly identical.
10553       if (!S.getLangOpts().CPlusPlus ||
10554           candidateHasExactlyCorrectType(FunDecl)) {
10555         Matches.push_back(std::make_pair(
10556             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10557         FoundNonTemplateFunction = true;
10558         return true;
10559       }
10560     }
10561 
10562     return false;
10563   }
10564 
10565   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10566     bool Ret = false;
10567 
10568     // If the overload expression doesn't have the form of a pointer to
10569     // member, don't try to convert it to a pointer-to-member type.
10570     if (IsInvalidFormOfPointerToMemberFunction())
10571       return false;
10572 
10573     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10574                                E = OvlExpr->decls_end();
10575          I != E; ++I) {
10576       // Look through any using declarations to find the underlying function.
10577       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10578 
10579       // C++ [over.over]p3:
10580       //   Non-member functions and static member functions match
10581       //   targets of type "pointer-to-function" or "reference-to-function."
10582       //   Nonstatic member functions match targets of
10583       //   type "pointer-to-member-function."
10584       // Note that according to DR 247, the containing class does not matter.
10585       if (FunctionTemplateDecl *FunctionTemplate
10586                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10587         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10588           Ret = true;
10589       }
10590       // If we have explicit template arguments supplied, skip non-templates.
10591       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10592                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10593         Ret = true;
10594     }
10595     assert(Ret || Matches.empty());
10596     return Ret;
10597   }
10598 
10599   void EliminateAllExceptMostSpecializedTemplate() {
10600     //   [...] and any given function template specialization F1 is
10601     //   eliminated if the set contains a second function template
10602     //   specialization whose function template is more specialized
10603     //   than the function template of F1 according to the partial
10604     //   ordering rules of 14.5.5.2.
10605 
10606     // The algorithm specified above is quadratic. We instead use a
10607     // two-pass algorithm (similar to the one used to identify the
10608     // best viable function in an overload set) that identifies the
10609     // best function template (if it exists).
10610 
10611     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10612     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10613       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10614 
10615     // TODO: It looks like FailedCandidates does not serve much purpose
10616     // here, since the no_viable diagnostic has index 0.
10617     UnresolvedSetIterator Result = S.getMostSpecialized(
10618         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10619         SourceExpr->getLocStart(), S.PDiag(),
10620         S.PDiag(diag::err_addr_ovl_ambiguous)
10621           << Matches[0].second->getDeclName(),
10622         S.PDiag(diag::note_ovl_candidate)
10623           << (unsigned)oc_function_template,
10624         Complain, TargetFunctionType);
10625 
10626     if (Result != MatchesCopy.end()) {
10627       // Make it the first and only element
10628       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10629       Matches[0].second = cast<FunctionDecl>(*Result);
10630       Matches.resize(1);
10631     } else
10632       HasComplained |= Complain;
10633   }
10634 
10635   void EliminateAllTemplateMatches() {
10636     //   [...] any function template specializations in the set are
10637     //   eliminated if the set also contains a non-template function, [...]
10638     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10639       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10640         ++I;
10641       else {
10642         Matches[I] = Matches[--N];
10643         Matches.resize(N);
10644       }
10645     }
10646   }
10647 
10648   void EliminateSuboptimalCudaMatches() {
10649     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10650   }
10651 
10652 public:
10653   void ComplainNoMatchesFound() const {
10654     assert(Matches.empty());
10655     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10656         << OvlExpr->getName() << TargetFunctionType
10657         << OvlExpr->getSourceRange();
10658     if (FailedCandidates.empty())
10659       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10660                                   /*TakingAddress=*/true);
10661     else {
10662       // We have some deduction failure messages. Use them to diagnose
10663       // the function templates, and diagnose the non-template candidates
10664       // normally.
10665       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10666                                  IEnd = OvlExpr->decls_end();
10667            I != IEnd; ++I)
10668         if (FunctionDecl *Fun =
10669                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10670           if (!functionHasPassObjectSizeParams(Fun))
10671             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10672                                     /*TakingAddress=*/true);
10673       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10674     }
10675   }
10676 
10677   bool IsInvalidFormOfPointerToMemberFunction() const {
10678     return TargetTypeIsNonStaticMemberFunction &&
10679       !OvlExprInfo.HasFormOfMemberPointer;
10680   }
10681 
10682   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10683       // TODO: Should we condition this on whether any functions might
10684       // have matched, or is it more appropriate to do that in callers?
10685       // TODO: a fixit wouldn't hurt.
10686       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10687         << TargetType << OvlExpr->getSourceRange();
10688   }
10689 
10690   bool IsStaticMemberFunctionFromBoundPointer() const {
10691     return StaticMemberFunctionFromBoundPointer;
10692   }
10693 
10694   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10695     S.Diag(OvlExpr->getLocStart(),
10696            diag::err_invalid_form_pointer_member_function)
10697       << OvlExpr->getSourceRange();
10698   }
10699 
10700   void ComplainOfInvalidConversion() const {
10701     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10702       << OvlExpr->getName() << TargetType;
10703   }
10704 
10705   void ComplainMultipleMatchesFound() const {
10706     assert(Matches.size() > 1);
10707     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10708       << OvlExpr->getName()
10709       << OvlExpr->getSourceRange();
10710     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10711                                 /*TakingAddress=*/true);
10712   }
10713 
10714   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10715 
10716   int getNumMatches() const { return Matches.size(); }
10717 
10718   FunctionDecl* getMatchingFunctionDecl() const {
10719     if (Matches.size() != 1) return nullptr;
10720     return Matches[0].second;
10721   }
10722 
10723   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10724     if (Matches.size() != 1) return nullptr;
10725     return &Matches[0].first;
10726   }
10727 };
10728 }
10729 
10730 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10731 /// an overloaded function (C++ [over.over]), where @p From is an
10732 /// expression with overloaded function type and @p ToType is the type
10733 /// we're trying to resolve to. For example:
10734 ///
10735 /// @code
10736 /// int f(double);
10737 /// int f(int);
10738 ///
10739 /// int (*pfd)(double) = f; // selects f(double)
10740 /// @endcode
10741 ///
10742 /// This routine returns the resulting FunctionDecl if it could be
10743 /// resolved, and NULL otherwise. When @p Complain is true, this
10744 /// routine will emit diagnostics if there is an error.
10745 FunctionDecl *
10746 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10747                                          QualType TargetType,
10748                                          bool Complain,
10749                                          DeclAccessPair &FoundResult,
10750                                          bool *pHadMultipleCandidates) {
10751   assert(AddressOfExpr->getType() == Context.OverloadTy);
10752 
10753   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10754                                      Complain);
10755   int NumMatches = Resolver.getNumMatches();
10756   FunctionDecl *Fn = nullptr;
10757   bool ShouldComplain = Complain && !Resolver.hasComplained();
10758   if (NumMatches == 0 && ShouldComplain) {
10759     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10760       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10761     else
10762       Resolver.ComplainNoMatchesFound();
10763   }
10764   else if (NumMatches > 1 && ShouldComplain)
10765     Resolver.ComplainMultipleMatchesFound();
10766   else if (NumMatches == 1) {
10767     Fn = Resolver.getMatchingFunctionDecl();
10768     assert(Fn);
10769     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10770     if (Complain) {
10771       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10772         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10773       else
10774         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10775     }
10776   }
10777 
10778   if (pHadMultipleCandidates)
10779     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10780   return Fn;
10781 }
10782 
10783 /// \brief Given an expression that refers to an overloaded function, try to
10784 /// resolve that function to a single function that can have its address taken.
10785 /// This will modify `Pair` iff it returns non-null.
10786 ///
10787 /// This routine can only realistically succeed if all but one candidates in the
10788 /// overload set for SrcExpr cannot have their addresses taken.
10789 FunctionDecl *
10790 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10791                                                   DeclAccessPair &Pair) {
10792   OverloadExpr::FindResult R = OverloadExpr::find(E);
10793   OverloadExpr *Ovl = R.Expression;
10794   FunctionDecl *Result = nullptr;
10795   DeclAccessPair DAP;
10796   // Don't use the AddressOfResolver because we're specifically looking for
10797   // cases where we have one overload candidate that lacks
10798   // enable_if/pass_object_size/...
10799   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10800     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10801     if (!FD)
10802       return nullptr;
10803 
10804     if (!checkAddressOfFunctionIsAvailable(FD))
10805       continue;
10806 
10807     // We have more than one result; quit.
10808     if (Result)
10809       return nullptr;
10810     DAP = I.getPair();
10811     Result = FD;
10812   }
10813 
10814   if (Result)
10815     Pair = DAP;
10816   return Result;
10817 }
10818 
10819 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10820 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10821 /// will perform access checks, diagnose the use of the resultant decl, and, if
10822 /// necessary, perform a function-to-pointer decay.
10823 ///
10824 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10825 /// Otherwise, returns true. This may emit diagnostics and return true.
10826 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10827     ExprResult &SrcExpr) {
10828   Expr *E = SrcExpr.get();
10829   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10830 
10831   DeclAccessPair DAP;
10832   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10833   if (!Found)
10834     return false;
10835 
10836   // Emitting multiple diagnostics for a function that is both inaccessible and
10837   // unavailable is consistent with our behavior elsewhere. So, always check
10838   // for both.
10839   DiagnoseUseOfDecl(Found, E->getExprLoc());
10840   CheckAddressOfMemberAccess(E, DAP);
10841   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10842   if (Fixed->getType()->isFunctionType())
10843     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10844   else
10845     SrcExpr = Fixed;
10846   return true;
10847 }
10848 
10849 /// \brief Given an expression that refers to an overloaded function, try to
10850 /// resolve that overloaded function expression down to a single function.
10851 ///
10852 /// This routine can only resolve template-ids that refer to a single function
10853 /// template, where that template-id refers to a single template whose template
10854 /// arguments are either provided by the template-id or have defaults,
10855 /// as described in C++0x [temp.arg.explicit]p3.
10856 ///
10857 /// If no template-ids are found, no diagnostics are emitted and NULL is
10858 /// returned.
10859 FunctionDecl *
10860 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10861                                                   bool Complain,
10862                                                   DeclAccessPair *FoundResult) {
10863   // C++ [over.over]p1:
10864   //   [...] [Note: any redundant set of parentheses surrounding the
10865   //   overloaded function name is ignored (5.1). ]
10866   // C++ [over.over]p1:
10867   //   [...] The overloaded function name can be preceded by the &
10868   //   operator.
10869 
10870   // If we didn't actually find any template-ids, we're done.
10871   if (!ovl->hasExplicitTemplateArgs())
10872     return nullptr;
10873 
10874   TemplateArgumentListInfo ExplicitTemplateArgs;
10875   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10876   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10877 
10878   // Look through all of the overloaded functions, searching for one
10879   // whose type matches exactly.
10880   FunctionDecl *Matched = nullptr;
10881   for (UnresolvedSetIterator I = ovl->decls_begin(),
10882          E = ovl->decls_end(); I != E; ++I) {
10883     // C++0x [temp.arg.explicit]p3:
10884     //   [...] In contexts where deduction is done and fails, or in contexts
10885     //   where deduction is not done, if a template argument list is
10886     //   specified and it, along with any default template arguments,
10887     //   identifies a single function template specialization, then the
10888     //   template-id is an lvalue for the function template specialization.
10889     FunctionTemplateDecl *FunctionTemplate
10890       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10891 
10892     // C++ [over.over]p2:
10893     //   If the name is a function template, template argument deduction is
10894     //   done (14.8.2.2), and if the argument deduction succeeds, the
10895     //   resulting template argument list is used to generate a single
10896     //   function template specialization, which is added to the set of
10897     //   overloaded functions considered.
10898     FunctionDecl *Specialization = nullptr;
10899     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10900     if (TemplateDeductionResult Result
10901           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10902                                     Specialization, Info,
10903                                     /*InOverloadResolution=*/true)) {
10904       // Make a note of the failed deduction for diagnostics.
10905       // TODO: Actually use the failed-deduction info?
10906       FailedCandidates.addCandidate()
10907           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10908                MakeDeductionFailureInfo(Context, Result, Info));
10909       continue;
10910     }
10911 
10912     assert(Specialization && "no specialization and no error?");
10913 
10914     // Multiple matches; we can't resolve to a single declaration.
10915     if (Matched) {
10916       if (Complain) {
10917         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10918           << ovl->getName();
10919         NoteAllOverloadCandidates(ovl);
10920       }
10921       return nullptr;
10922     }
10923 
10924     Matched = Specialization;
10925     if (FoundResult) *FoundResult = I.getPair();
10926   }
10927 
10928   if (Matched && getLangOpts().CPlusPlus14 &&
10929       Matched->getReturnType()->isUndeducedType() &&
10930       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10931     return nullptr;
10932 
10933   return Matched;
10934 }
10935 
10936 
10937 
10938 
10939 // Resolve and fix an overloaded expression that can be resolved
10940 // because it identifies a single function template specialization.
10941 //
10942 // Last three arguments should only be supplied if Complain = true
10943 //
10944 // Return true if it was logically possible to so resolve the
10945 // expression, regardless of whether or not it succeeded.  Always
10946 // returns true if 'complain' is set.
10947 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10948                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10949                       bool complain, SourceRange OpRangeForComplaining,
10950                                            QualType DestTypeForComplaining,
10951                                             unsigned DiagIDForComplaining) {
10952   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10953 
10954   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10955 
10956   DeclAccessPair found;
10957   ExprResult SingleFunctionExpression;
10958   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10959                            ovl.Expression, /*complain*/ false, &found)) {
10960     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10961       SrcExpr = ExprError();
10962       return true;
10963     }
10964 
10965     // It is only correct to resolve to an instance method if we're
10966     // resolving a form that's permitted to be a pointer to member.
10967     // Otherwise we'll end up making a bound member expression, which
10968     // is illegal in all the contexts we resolve like this.
10969     if (!ovl.HasFormOfMemberPointer &&
10970         isa<CXXMethodDecl>(fn) &&
10971         cast<CXXMethodDecl>(fn)->isInstance()) {
10972       if (!complain) return false;
10973 
10974       Diag(ovl.Expression->getExprLoc(),
10975            diag::err_bound_member_function)
10976         << 0 << ovl.Expression->getSourceRange();
10977 
10978       // TODO: I believe we only end up here if there's a mix of
10979       // static and non-static candidates (otherwise the expression
10980       // would have 'bound member' type, not 'overload' type).
10981       // Ideally we would note which candidate was chosen and why
10982       // the static candidates were rejected.
10983       SrcExpr = ExprError();
10984       return true;
10985     }
10986 
10987     // Fix the expression to refer to 'fn'.
10988     SingleFunctionExpression =
10989         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10990 
10991     // If desired, do function-to-pointer decay.
10992     if (doFunctionPointerConverion) {
10993       SingleFunctionExpression =
10994         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10995       if (SingleFunctionExpression.isInvalid()) {
10996         SrcExpr = ExprError();
10997         return true;
10998       }
10999     }
11000   }
11001 
11002   if (!SingleFunctionExpression.isUsable()) {
11003     if (complain) {
11004       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11005         << ovl.Expression->getName()
11006         << DestTypeForComplaining
11007         << OpRangeForComplaining
11008         << ovl.Expression->getQualifierLoc().getSourceRange();
11009       NoteAllOverloadCandidates(SrcExpr.get());
11010 
11011       SrcExpr = ExprError();
11012       return true;
11013     }
11014 
11015     return false;
11016   }
11017 
11018   SrcExpr = SingleFunctionExpression;
11019   return true;
11020 }
11021 
11022 /// \brief Add a single candidate to the overload set.
11023 static void AddOverloadedCallCandidate(Sema &S,
11024                                        DeclAccessPair FoundDecl,
11025                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11026                                        ArrayRef<Expr *> Args,
11027                                        OverloadCandidateSet &CandidateSet,
11028                                        bool PartialOverloading,
11029                                        bool KnownValid) {
11030   NamedDecl *Callee = FoundDecl.getDecl();
11031   if (isa<UsingShadowDecl>(Callee))
11032     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11033 
11034   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11035     if (ExplicitTemplateArgs) {
11036       assert(!KnownValid && "Explicit template arguments?");
11037       return;
11038     }
11039     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11040                            /*SuppressUsedConversions=*/false,
11041                            PartialOverloading);
11042     return;
11043   }
11044 
11045   if (FunctionTemplateDecl *FuncTemplate
11046       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11047     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11048                                    ExplicitTemplateArgs, Args, CandidateSet,
11049                                    /*SuppressUsedConversions=*/false,
11050                                    PartialOverloading);
11051     return;
11052   }
11053 
11054   assert(!KnownValid && "unhandled case in overloaded call candidate");
11055 }
11056 
11057 /// \brief Add the overload candidates named by callee and/or found by argument
11058 /// dependent lookup to the given overload set.
11059 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11060                                        ArrayRef<Expr *> Args,
11061                                        OverloadCandidateSet &CandidateSet,
11062                                        bool PartialOverloading) {
11063 
11064 #ifndef NDEBUG
11065   // Verify that ArgumentDependentLookup is consistent with the rules
11066   // in C++0x [basic.lookup.argdep]p3:
11067   //
11068   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11069   //   and let Y be the lookup set produced by argument dependent
11070   //   lookup (defined as follows). If X contains
11071   //
11072   //     -- a declaration of a class member, or
11073   //
11074   //     -- a block-scope function declaration that is not a
11075   //        using-declaration, or
11076   //
11077   //     -- a declaration that is neither a function or a function
11078   //        template
11079   //
11080   //   then Y is empty.
11081 
11082   if (ULE->requiresADL()) {
11083     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11084            E = ULE->decls_end(); I != E; ++I) {
11085       assert(!(*I)->getDeclContext()->isRecord());
11086       assert(isa<UsingShadowDecl>(*I) ||
11087              !(*I)->getDeclContext()->isFunctionOrMethod());
11088       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11089     }
11090   }
11091 #endif
11092 
11093   // It would be nice to avoid this copy.
11094   TemplateArgumentListInfo TABuffer;
11095   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11096   if (ULE->hasExplicitTemplateArgs()) {
11097     ULE->copyTemplateArgumentsInto(TABuffer);
11098     ExplicitTemplateArgs = &TABuffer;
11099   }
11100 
11101   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11102          E = ULE->decls_end(); I != E; ++I)
11103     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11104                                CandidateSet, PartialOverloading,
11105                                /*KnownValid*/ true);
11106 
11107   if (ULE->requiresADL())
11108     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11109                                          Args, ExplicitTemplateArgs,
11110                                          CandidateSet, PartialOverloading);
11111 }
11112 
11113 /// Determine whether a declaration with the specified name could be moved into
11114 /// a different namespace.
11115 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11116   switch (Name.getCXXOverloadedOperator()) {
11117   case OO_New: case OO_Array_New:
11118   case OO_Delete: case OO_Array_Delete:
11119     return false;
11120 
11121   default:
11122     return true;
11123   }
11124 }
11125 
11126 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11127 /// template, where the non-dependent name was declared after the template
11128 /// was defined. This is common in code written for a compilers which do not
11129 /// correctly implement two-stage name lookup.
11130 ///
11131 /// Returns true if a viable candidate was found and a diagnostic was issued.
11132 static bool
11133 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11134                        const CXXScopeSpec &SS, LookupResult &R,
11135                        OverloadCandidateSet::CandidateSetKind CSK,
11136                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11137                        ArrayRef<Expr *> Args,
11138                        bool *DoDiagnoseEmptyLookup = nullptr) {
11139   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11140     return false;
11141 
11142   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11143     if (DC->isTransparentContext())
11144       continue;
11145 
11146     SemaRef.LookupQualifiedName(R, DC);
11147 
11148     if (!R.empty()) {
11149       R.suppressDiagnostics();
11150 
11151       if (isa<CXXRecordDecl>(DC)) {
11152         // Don't diagnose names we find in classes; we get much better
11153         // diagnostics for these from DiagnoseEmptyLookup.
11154         R.clear();
11155         if (DoDiagnoseEmptyLookup)
11156           *DoDiagnoseEmptyLookup = true;
11157         return false;
11158       }
11159 
11160       OverloadCandidateSet Candidates(FnLoc, CSK);
11161       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11162         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11163                                    ExplicitTemplateArgs, Args,
11164                                    Candidates, false, /*KnownValid*/ false);
11165 
11166       OverloadCandidateSet::iterator Best;
11167       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11168         // No viable functions. Don't bother the user with notes for functions
11169         // which don't work and shouldn't be found anyway.
11170         R.clear();
11171         return false;
11172       }
11173 
11174       // Find the namespaces where ADL would have looked, and suggest
11175       // declaring the function there instead.
11176       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11177       Sema::AssociatedClassSet AssociatedClasses;
11178       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11179                                                  AssociatedNamespaces,
11180                                                  AssociatedClasses);
11181       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11182       if (canBeDeclaredInNamespace(R.getLookupName())) {
11183         DeclContext *Std = SemaRef.getStdNamespace();
11184         for (Sema::AssociatedNamespaceSet::iterator
11185                it = AssociatedNamespaces.begin(),
11186                end = AssociatedNamespaces.end(); it != end; ++it) {
11187           // Never suggest declaring a function within namespace 'std'.
11188           if (Std && Std->Encloses(*it))
11189             continue;
11190 
11191           // Never suggest declaring a function within a namespace with a
11192           // reserved name, like __gnu_cxx.
11193           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11194           if (NS &&
11195               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11196             continue;
11197 
11198           SuggestedNamespaces.insert(*it);
11199         }
11200       }
11201 
11202       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11203         << R.getLookupName();
11204       if (SuggestedNamespaces.empty()) {
11205         SemaRef.Diag(Best->Function->getLocation(),
11206                      diag::note_not_found_by_two_phase_lookup)
11207           << R.getLookupName() << 0;
11208       } else if (SuggestedNamespaces.size() == 1) {
11209         SemaRef.Diag(Best->Function->getLocation(),
11210                      diag::note_not_found_by_two_phase_lookup)
11211           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11212       } else {
11213         // FIXME: It would be useful to list the associated namespaces here,
11214         // but the diagnostics infrastructure doesn't provide a way to produce
11215         // a localized representation of a list of items.
11216         SemaRef.Diag(Best->Function->getLocation(),
11217                      diag::note_not_found_by_two_phase_lookup)
11218           << R.getLookupName() << 2;
11219       }
11220 
11221       // Try to recover by calling this function.
11222       return true;
11223     }
11224 
11225     R.clear();
11226   }
11227 
11228   return false;
11229 }
11230 
11231 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11232 /// template, where the non-dependent operator was declared after the template
11233 /// was defined.
11234 ///
11235 /// Returns true if a viable candidate was found and a diagnostic was issued.
11236 static bool
11237 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11238                                SourceLocation OpLoc,
11239                                ArrayRef<Expr *> Args) {
11240   DeclarationName OpName =
11241     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11242   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11243   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11244                                 OverloadCandidateSet::CSK_Operator,
11245                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11246 }
11247 
11248 namespace {
11249 class BuildRecoveryCallExprRAII {
11250   Sema &SemaRef;
11251 public:
11252   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11253     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11254     SemaRef.IsBuildingRecoveryCallExpr = true;
11255   }
11256 
11257   ~BuildRecoveryCallExprRAII() {
11258     SemaRef.IsBuildingRecoveryCallExpr = false;
11259   }
11260 };
11261 
11262 }
11263 
11264 static std::unique_ptr<CorrectionCandidateCallback>
11265 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11266               bool HasTemplateArgs, bool AllowTypoCorrection) {
11267   if (!AllowTypoCorrection)
11268     return llvm::make_unique<NoTypoCorrectionCCC>();
11269   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11270                                                   HasTemplateArgs, ME);
11271 }
11272 
11273 /// Attempts to recover from a call where no functions were found.
11274 ///
11275 /// Returns true if new candidates were found.
11276 static ExprResult
11277 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11278                       UnresolvedLookupExpr *ULE,
11279                       SourceLocation LParenLoc,
11280                       MutableArrayRef<Expr *> Args,
11281                       SourceLocation RParenLoc,
11282                       bool EmptyLookup, bool AllowTypoCorrection) {
11283   // Do not try to recover if it is already building a recovery call.
11284   // This stops infinite loops for template instantiations like
11285   //
11286   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11287   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11288   //
11289   if (SemaRef.IsBuildingRecoveryCallExpr)
11290     return ExprError();
11291   BuildRecoveryCallExprRAII RCE(SemaRef);
11292 
11293   CXXScopeSpec SS;
11294   SS.Adopt(ULE->getQualifierLoc());
11295   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11296 
11297   TemplateArgumentListInfo TABuffer;
11298   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11299   if (ULE->hasExplicitTemplateArgs()) {
11300     ULE->copyTemplateArgumentsInto(TABuffer);
11301     ExplicitTemplateArgs = &TABuffer;
11302   }
11303 
11304   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11305                  Sema::LookupOrdinaryName);
11306   bool DoDiagnoseEmptyLookup = EmptyLookup;
11307   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11308                               OverloadCandidateSet::CSK_Normal,
11309                               ExplicitTemplateArgs, Args,
11310                               &DoDiagnoseEmptyLookup) &&
11311     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11312         S, SS, R,
11313         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11314                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11315         ExplicitTemplateArgs, Args)))
11316     return ExprError();
11317 
11318   assert(!R.empty() && "lookup results empty despite recovery");
11319 
11320   // Build an implicit member call if appropriate.  Just drop the
11321   // casts and such from the call, we don't really care.
11322   ExprResult NewFn = ExprError();
11323   if ((*R.begin())->isCXXClassMember())
11324     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11325                                                     ExplicitTemplateArgs, S);
11326   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11327     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11328                                         ExplicitTemplateArgs);
11329   else
11330     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11331 
11332   if (NewFn.isInvalid())
11333     return ExprError();
11334 
11335   // This shouldn't cause an infinite loop because we're giving it
11336   // an expression with viable lookup results, which should never
11337   // end up here.
11338   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11339                                MultiExprArg(Args.data(), Args.size()),
11340                                RParenLoc);
11341 }
11342 
11343 /// \brief Constructs and populates an OverloadedCandidateSet from
11344 /// the given function.
11345 /// \returns true when an the ExprResult output parameter has been set.
11346 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11347                                   UnresolvedLookupExpr *ULE,
11348                                   MultiExprArg Args,
11349                                   SourceLocation RParenLoc,
11350                                   OverloadCandidateSet *CandidateSet,
11351                                   ExprResult *Result) {
11352 #ifndef NDEBUG
11353   if (ULE->requiresADL()) {
11354     // To do ADL, we must have found an unqualified name.
11355     assert(!ULE->getQualifier() && "qualified name with ADL");
11356 
11357     // We don't perform ADL for implicit declarations of builtins.
11358     // Verify that this was correctly set up.
11359     FunctionDecl *F;
11360     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11361         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11362         F->getBuiltinID() && F->isImplicit())
11363       llvm_unreachable("performing ADL for builtin");
11364 
11365     // We don't perform ADL in C.
11366     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11367   }
11368 #endif
11369 
11370   UnbridgedCastsSet UnbridgedCasts;
11371   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11372     *Result = ExprError();
11373     return true;
11374   }
11375 
11376   // Add the functions denoted by the callee to the set of candidate
11377   // functions, including those from argument-dependent lookup.
11378   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11379 
11380   if (getLangOpts().MSVCCompat &&
11381       CurContext->isDependentContext() && !isSFINAEContext() &&
11382       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11383 
11384     OverloadCandidateSet::iterator Best;
11385     if (CandidateSet->empty() ||
11386         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11387             OR_No_Viable_Function) {
11388       // In Microsoft mode, if we are inside a template class member function then
11389       // create a type dependent CallExpr. The goal is to postpone name lookup
11390       // to instantiation time to be able to search into type dependent base
11391       // classes.
11392       CallExpr *CE = new (Context) CallExpr(
11393           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11394       CE->setTypeDependent(true);
11395       CE->setValueDependent(true);
11396       CE->setInstantiationDependent(true);
11397       *Result = CE;
11398       return true;
11399     }
11400   }
11401 
11402   if (CandidateSet->empty())
11403     return false;
11404 
11405   UnbridgedCasts.restore();
11406   return false;
11407 }
11408 
11409 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11410 /// the completed call expression. If overload resolution fails, emits
11411 /// diagnostics and returns ExprError()
11412 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11413                                            UnresolvedLookupExpr *ULE,
11414                                            SourceLocation LParenLoc,
11415                                            MultiExprArg Args,
11416                                            SourceLocation RParenLoc,
11417                                            Expr *ExecConfig,
11418                                            OverloadCandidateSet *CandidateSet,
11419                                            OverloadCandidateSet::iterator *Best,
11420                                            OverloadingResult OverloadResult,
11421                                            bool AllowTypoCorrection) {
11422   if (CandidateSet->empty())
11423     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11424                                  RParenLoc, /*EmptyLookup=*/true,
11425                                  AllowTypoCorrection);
11426 
11427   switch (OverloadResult) {
11428   case OR_Success: {
11429     FunctionDecl *FDecl = (*Best)->Function;
11430     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11431     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11432       return ExprError();
11433     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11434     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11435                                          ExecConfig);
11436   }
11437 
11438   case OR_No_Viable_Function: {
11439     // Try to recover by looking for viable functions which the user might
11440     // have meant to call.
11441     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11442                                                 Args, RParenLoc,
11443                                                 /*EmptyLookup=*/false,
11444                                                 AllowTypoCorrection);
11445     if (!Recovery.isInvalid())
11446       return Recovery;
11447 
11448     // If the user passes in a function that we can't take the address of, we
11449     // generally end up emitting really bad error messages. Here, we attempt to
11450     // emit better ones.
11451     for (const Expr *Arg : Args) {
11452       if (!Arg->getType()->isFunctionType())
11453         continue;
11454       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11455         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11456         if (FD &&
11457             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11458                                                        Arg->getExprLoc()))
11459           return ExprError();
11460       }
11461     }
11462 
11463     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11464         << ULE->getName() << Fn->getSourceRange();
11465     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11466     break;
11467   }
11468 
11469   case OR_Ambiguous:
11470     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11471       << ULE->getName() << Fn->getSourceRange();
11472     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11473     break;
11474 
11475   case OR_Deleted: {
11476     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11477       << (*Best)->Function->isDeleted()
11478       << ULE->getName()
11479       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11480       << Fn->getSourceRange();
11481     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11482 
11483     // We emitted an error for the unvailable/deleted function call but keep
11484     // the call in the AST.
11485     FunctionDecl *FDecl = (*Best)->Function;
11486     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11487     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11488                                          ExecConfig);
11489   }
11490   }
11491 
11492   // Overload resolution failed.
11493   return ExprError();
11494 }
11495 
11496 static void markUnaddressableCandidatesUnviable(Sema &S,
11497                                                 OverloadCandidateSet &CS) {
11498   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11499     if (I->Viable &&
11500         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11501       I->Viable = false;
11502       I->FailureKind = ovl_fail_addr_not_available;
11503     }
11504   }
11505 }
11506 
11507 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11508 /// (which eventually refers to the declaration Func) and the call
11509 /// arguments Args/NumArgs, attempt to resolve the function call down
11510 /// to a specific function. If overload resolution succeeds, returns
11511 /// the call expression produced by overload resolution.
11512 /// Otherwise, emits diagnostics and returns ExprError.
11513 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11514                                          UnresolvedLookupExpr *ULE,
11515                                          SourceLocation LParenLoc,
11516                                          MultiExprArg Args,
11517                                          SourceLocation RParenLoc,
11518                                          Expr *ExecConfig,
11519                                          bool AllowTypoCorrection,
11520                                          bool CalleesAddressIsTaken) {
11521   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11522                                     OverloadCandidateSet::CSK_Normal);
11523   ExprResult result;
11524 
11525   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11526                              &result))
11527     return result;
11528 
11529   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11530   // functions that aren't addressible are considered unviable.
11531   if (CalleesAddressIsTaken)
11532     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11533 
11534   OverloadCandidateSet::iterator Best;
11535   OverloadingResult OverloadResult =
11536       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11537 
11538   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11539                                   RParenLoc, ExecConfig, &CandidateSet,
11540                                   &Best, OverloadResult,
11541                                   AllowTypoCorrection);
11542 }
11543 
11544 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11545   return Functions.size() > 1 ||
11546     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11547 }
11548 
11549 /// \brief Create a unary operation that may resolve to an overloaded
11550 /// operator.
11551 ///
11552 /// \param OpLoc The location of the operator itself (e.g., '*').
11553 ///
11554 /// \param Opc The UnaryOperatorKind that describes this operator.
11555 ///
11556 /// \param Fns The set of non-member functions that will be
11557 /// considered by overload resolution. The caller needs to build this
11558 /// set based on the context using, e.g.,
11559 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11560 /// set should not contain any member functions; those will be added
11561 /// by CreateOverloadedUnaryOp().
11562 ///
11563 /// \param Input The input argument.
11564 ExprResult
11565 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11566                               const UnresolvedSetImpl &Fns,
11567                               Expr *Input) {
11568   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11569   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11570   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11571   // TODO: provide better source location info.
11572   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11573 
11574   if (checkPlaceholderForOverload(*this, Input))
11575     return ExprError();
11576 
11577   Expr *Args[2] = { Input, nullptr };
11578   unsigned NumArgs = 1;
11579 
11580   // For post-increment and post-decrement, add the implicit '0' as
11581   // the second argument, so that we know this is a post-increment or
11582   // post-decrement.
11583   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11584     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11585     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11586                                      SourceLocation());
11587     NumArgs = 2;
11588   }
11589 
11590   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11591 
11592   if (Input->isTypeDependent()) {
11593     if (Fns.empty())
11594       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11595                                          VK_RValue, OK_Ordinary, OpLoc);
11596 
11597     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11598     UnresolvedLookupExpr *Fn
11599       = UnresolvedLookupExpr::Create(Context, NamingClass,
11600                                      NestedNameSpecifierLoc(), OpNameInfo,
11601                                      /*ADL*/ true, IsOverloaded(Fns),
11602                                      Fns.begin(), Fns.end());
11603     return new (Context)
11604         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11605                             VK_RValue, OpLoc, false);
11606   }
11607 
11608   // Build an empty overload set.
11609   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11610 
11611   // Add the candidates from the given function set.
11612   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11613 
11614   // Add operator candidates that are member functions.
11615   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11616 
11617   // Add candidates from ADL.
11618   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11619                                        /*ExplicitTemplateArgs*/nullptr,
11620                                        CandidateSet);
11621 
11622   // Add builtin operator candidates.
11623   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11624 
11625   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11626 
11627   // Perform overload resolution.
11628   OverloadCandidateSet::iterator Best;
11629   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11630   case OR_Success: {
11631     // We found a built-in operator or an overloaded operator.
11632     FunctionDecl *FnDecl = Best->Function;
11633 
11634     if (FnDecl) {
11635       // We matched an overloaded operator. Build a call to that
11636       // operator.
11637 
11638       // Convert the arguments.
11639       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11640         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11641 
11642         ExprResult InputRes =
11643           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11644                                               Best->FoundDecl, Method);
11645         if (InputRes.isInvalid())
11646           return ExprError();
11647         Input = InputRes.get();
11648       } else {
11649         // Convert the arguments.
11650         ExprResult InputInit
11651           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11652                                                       Context,
11653                                                       FnDecl->getParamDecl(0)),
11654                                       SourceLocation(),
11655                                       Input);
11656         if (InputInit.isInvalid())
11657           return ExprError();
11658         Input = InputInit.get();
11659       }
11660 
11661       // Build the actual expression node.
11662       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11663                                                 HadMultipleCandidates, OpLoc);
11664       if (FnExpr.isInvalid())
11665         return ExprError();
11666 
11667       // Determine the result type.
11668       QualType ResultTy = FnDecl->getReturnType();
11669       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11670       ResultTy = ResultTy.getNonLValueExprType(Context);
11671 
11672       Args[0] = Input;
11673       CallExpr *TheCall =
11674         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11675                                           ResultTy, VK, OpLoc, false);
11676 
11677       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11678         return ExprError();
11679 
11680       return MaybeBindToTemporary(TheCall);
11681     } else {
11682       // We matched a built-in operator. Convert the arguments, then
11683       // break out so that we will build the appropriate built-in
11684       // operator node.
11685       ExprResult InputRes =
11686         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11687                                   Best->Conversions[0], AA_Passing);
11688       if (InputRes.isInvalid())
11689         return ExprError();
11690       Input = InputRes.get();
11691       break;
11692     }
11693   }
11694 
11695   case OR_No_Viable_Function:
11696     // This is an erroneous use of an operator which can be overloaded by
11697     // a non-member function. Check for non-member operators which were
11698     // defined too late to be candidates.
11699     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11700       // FIXME: Recover by calling the found function.
11701       return ExprError();
11702 
11703     // No viable function; fall through to handling this as a
11704     // built-in operator, which will produce an error message for us.
11705     break;
11706 
11707   case OR_Ambiguous:
11708     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11709         << UnaryOperator::getOpcodeStr(Opc)
11710         << Input->getType()
11711         << Input->getSourceRange();
11712     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11713                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11714     return ExprError();
11715 
11716   case OR_Deleted:
11717     Diag(OpLoc, diag::err_ovl_deleted_oper)
11718       << Best->Function->isDeleted()
11719       << UnaryOperator::getOpcodeStr(Opc)
11720       << getDeletedOrUnavailableSuffix(Best->Function)
11721       << Input->getSourceRange();
11722     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11723                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11724     return ExprError();
11725   }
11726 
11727   // Either we found no viable overloaded operator or we matched a
11728   // built-in operator. In either case, fall through to trying to
11729   // build a built-in operation.
11730   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11731 }
11732 
11733 /// \brief Create a binary operation that may resolve to an overloaded
11734 /// operator.
11735 ///
11736 /// \param OpLoc The location of the operator itself (e.g., '+').
11737 ///
11738 /// \param Opc The BinaryOperatorKind that describes this operator.
11739 ///
11740 /// \param Fns The set of non-member functions that will be
11741 /// considered by overload resolution. The caller needs to build this
11742 /// set based on the context using, e.g.,
11743 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11744 /// set should not contain any member functions; those will be added
11745 /// by CreateOverloadedBinOp().
11746 ///
11747 /// \param LHS Left-hand argument.
11748 /// \param RHS Right-hand argument.
11749 ExprResult
11750 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11751                             BinaryOperatorKind Opc,
11752                             const UnresolvedSetImpl &Fns,
11753                             Expr *LHS, Expr *RHS) {
11754   Expr *Args[2] = { LHS, RHS };
11755   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11756 
11757   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11758   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11759 
11760   // If either side is type-dependent, create an appropriate dependent
11761   // expression.
11762   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11763     if (Fns.empty()) {
11764       // If there are no functions to store, just build a dependent
11765       // BinaryOperator or CompoundAssignment.
11766       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11767         return new (Context) BinaryOperator(
11768             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11769             OpLoc, FPFeatures.fp_contract);
11770 
11771       return new (Context) CompoundAssignOperator(
11772           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11773           Context.DependentTy, Context.DependentTy, OpLoc,
11774           FPFeatures.fp_contract);
11775     }
11776 
11777     // FIXME: save results of ADL from here?
11778     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11779     // TODO: provide better source location info in DNLoc component.
11780     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11781     UnresolvedLookupExpr *Fn
11782       = UnresolvedLookupExpr::Create(Context, NamingClass,
11783                                      NestedNameSpecifierLoc(), OpNameInfo,
11784                                      /*ADL*/ true, IsOverloaded(Fns),
11785                                      Fns.begin(), Fns.end());
11786     return new (Context)
11787         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11788                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11789   }
11790 
11791   // Always do placeholder-like conversions on the RHS.
11792   if (checkPlaceholderForOverload(*this, Args[1]))
11793     return ExprError();
11794 
11795   // Do placeholder-like conversion on the LHS; note that we should
11796   // not get here with a PseudoObject LHS.
11797   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11798   if (checkPlaceholderForOverload(*this, Args[0]))
11799     return ExprError();
11800 
11801   // If this is the assignment operator, we only perform overload resolution
11802   // if the left-hand side is a class or enumeration type. This is actually
11803   // a hack. The standard requires that we do overload resolution between the
11804   // various built-in candidates, but as DR507 points out, this can lead to
11805   // problems. So we do it this way, which pretty much follows what GCC does.
11806   // Note that we go the traditional code path for compound assignment forms.
11807   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11808     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11809 
11810   // If this is the .* operator, which is not overloadable, just
11811   // create a built-in binary operator.
11812   if (Opc == BO_PtrMemD)
11813     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11814 
11815   // Build an empty overload set.
11816   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11817 
11818   // Add the candidates from the given function set.
11819   AddFunctionCandidates(Fns, Args, CandidateSet);
11820 
11821   // Add operator candidates that are member functions.
11822   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11823 
11824   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11825   // performed for an assignment operator (nor for operator[] nor operator->,
11826   // which don't get here).
11827   if (Opc != BO_Assign)
11828     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11829                                          /*ExplicitTemplateArgs*/ nullptr,
11830                                          CandidateSet);
11831 
11832   // Add builtin operator candidates.
11833   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11834 
11835   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11836 
11837   // Perform overload resolution.
11838   OverloadCandidateSet::iterator Best;
11839   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11840     case OR_Success: {
11841       // We found a built-in operator or an overloaded operator.
11842       FunctionDecl *FnDecl = Best->Function;
11843 
11844       if (FnDecl) {
11845         // We matched an overloaded operator. Build a call to that
11846         // operator.
11847 
11848         // Convert the arguments.
11849         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11850           // Best->Access is only meaningful for class members.
11851           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11852 
11853           ExprResult Arg1 =
11854             PerformCopyInitialization(
11855               InitializedEntity::InitializeParameter(Context,
11856                                                      FnDecl->getParamDecl(0)),
11857               SourceLocation(), Args[1]);
11858           if (Arg1.isInvalid())
11859             return ExprError();
11860 
11861           ExprResult Arg0 =
11862             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11863                                                 Best->FoundDecl, Method);
11864           if (Arg0.isInvalid())
11865             return ExprError();
11866           Args[0] = Arg0.getAs<Expr>();
11867           Args[1] = RHS = Arg1.getAs<Expr>();
11868         } else {
11869           // Convert the arguments.
11870           ExprResult Arg0 = PerformCopyInitialization(
11871             InitializedEntity::InitializeParameter(Context,
11872                                                    FnDecl->getParamDecl(0)),
11873             SourceLocation(), Args[0]);
11874           if (Arg0.isInvalid())
11875             return ExprError();
11876 
11877           ExprResult Arg1 =
11878             PerformCopyInitialization(
11879               InitializedEntity::InitializeParameter(Context,
11880                                                      FnDecl->getParamDecl(1)),
11881               SourceLocation(), Args[1]);
11882           if (Arg1.isInvalid())
11883             return ExprError();
11884           Args[0] = LHS = Arg0.getAs<Expr>();
11885           Args[1] = RHS = Arg1.getAs<Expr>();
11886         }
11887 
11888         // Build the actual expression node.
11889         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11890                                                   Best->FoundDecl,
11891                                                   HadMultipleCandidates, OpLoc);
11892         if (FnExpr.isInvalid())
11893           return ExprError();
11894 
11895         // Determine the result type.
11896         QualType ResultTy = FnDecl->getReturnType();
11897         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11898         ResultTy = ResultTy.getNonLValueExprType(Context);
11899 
11900         CXXOperatorCallExpr *TheCall =
11901           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11902                                             Args, ResultTy, VK, OpLoc,
11903                                             FPFeatures.fp_contract);
11904 
11905         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11906                                 FnDecl))
11907           return ExprError();
11908 
11909         ArrayRef<const Expr *> ArgsArray(Args, 2);
11910         // Cut off the implicit 'this'.
11911         if (isa<CXXMethodDecl>(FnDecl))
11912           ArgsArray = ArgsArray.slice(1);
11913 
11914         // Check for a self move.
11915         if (Op == OO_Equal)
11916           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11917 
11918         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11919                   TheCall->getSourceRange(), VariadicDoesNotApply);
11920 
11921         return MaybeBindToTemporary(TheCall);
11922       } else {
11923         // We matched a built-in operator. Convert the arguments, then
11924         // break out so that we will build the appropriate built-in
11925         // operator node.
11926         ExprResult ArgsRes0 =
11927           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11928                                     Best->Conversions[0], AA_Passing);
11929         if (ArgsRes0.isInvalid())
11930           return ExprError();
11931         Args[0] = ArgsRes0.get();
11932 
11933         ExprResult ArgsRes1 =
11934           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11935                                     Best->Conversions[1], AA_Passing);
11936         if (ArgsRes1.isInvalid())
11937           return ExprError();
11938         Args[1] = ArgsRes1.get();
11939         break;
11940       }
11941     }
11942 
11943     case OR_No_Viable_Function: {
11944       // C++ [over.match.oper]p9:
11945       //   If the operator is the operator , [...] and there are no
11946       //   viable functions, then the operator is assumed to be the
11947       //   built-in operator and interpreted according to clause 5.
11948       if (Opc == BO_Comma)
11949         break;
11950 
11951       // For class as left operand for assignment or compound assigment
11952       // operator do not fall through to handling in built-in, but report that
11953       // no overloaded assignment operator found
11954       ExprResult Result = ExprError();
11955       if (Args[0]->getType()->isRecordType() &&
11956           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11957         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11958              << BinaryOperator::getOpcodeStr(Opc)
11959              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11960         if (Args[0]->getType()->isIncompleteType()) {
11961           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11962             << Args[0]->getType()
11963             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11964         }
11965       } else {
11966         // This is an erroneous use of an operator which can be overloaded by
11967         // a non-member function. Check for non-member operators which were
11968         // defined too late to be candidates.
11969         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11970           // FIXME: Recover by calling the found function.
11971           return ExprError();
11972 
11973         // No viable function; try to create a built-in operation, which will
11974         // produce an error. Then, show the non-viable candidates.
11975         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11976       }
11977       assert(Result.isInvalid() &&
11978              "C++ binary operator overloading is missing candidates!");
11979       if (Result.isInvalid())
11980         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11981                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11982       return Result;
11983     }
11984 
11985     case OR_Ambiguous:
11986       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11987           << BinaryOperator::getOpcodeStr(Opc)
11988           << Args[0]->getType() << Args[1]->getType()
11989           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11990       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11991                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11992       return ExprError();
11993 
11994     case OR_Deleted:
11995       if (isImplicitlyDeleted(Best->Function)) {
11996         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11997         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11998           << Context.getRecordType(Method->getParent())
11999           << getSpecialMember(Method);
12000 
12001         // The user probably meant to call this special member. Just
12002         // explain why it's deleted.
12003         NoteDeletedFunction(Method);
12004         return ExprError();
12005       } else {
12006         Diag(OpLoc, diag::err_ovl_deleted_oper)
12007           << Best->Function->isDeleted()
12008           << BinaryOperator::getOpcodeStr(Opc)
12009           << getDeletedOrUnavailableSuffix(Best->Function)
12010           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12011       }
12012       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12013                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12014       return ExprError();
12015   }
12016 
12017   // We matched a built-in operator; build it.
12018   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12019 }
12020 
12021 ExprResult
12022 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12023                                          SourceLocation RLoc,
12024                                          Expr *Base, Expr *Idx) {
12025   Expr *Args[2] = { Base, Idx };
12026   DeclarationName OpName =
12027       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12028 
12029   // If either side is type-dependent, create an appropriate dependent
12030   // expression.
12031   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12032 
12033     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12034     // CHECKME: no 'operator' keyword?
12035     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12036     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12037     UnresolvedLookupExpr *Fn
12038       = UnresolvedLookupExpr::Create(Context, NamingClass,
12039                                      NestedNameSpecifierLoc(), OpNameInfo,
12040                                      /*ADL*/ true, /*Overloaded*/ false,
12041                                      UnresolvedSetIterator(),
12042                                      UnresolvedSetIterator());
12043     // Can't add any actual overloads yet
12044 
12045     return new (Context)
12046         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12047                             Context.DependentTy, VK_RValue, RLoc, false);
12048   }
12049 
12050   // Handle placeholders on both operands.
12051   if (checkPlaceholderForOverload(*this, Args[0]))
12052     return ExprError();
12053   if (checkPlaceholderForOverload(*this, Args[1]))
12054     return ExprError();
12055 
12056   // Build an empty overload set.
12057   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12058 
12059   // Subscript can only be overloaded as a member function.
12060 
12061   // Add operator candidates that are member functions.
12062   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12063 
12064   // Add builtin operator candidates.
12065   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12066 
12067   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12068 
12069   // Perform overload resolution.
12070   OverloadCandidateSet::iterator Best;
12071   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12072     case OR_Success: {
12073       // We found a built-in operator or an overloaded operator.
12074       FunctionDecl *FnDecl = Best->Function;
12075 
12076       if (FnDecl) {
12077         // We matched an overloaded operator. Build a call to that
12078         // operator.
12079 
12080         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12081 
12082         // Convert the arguments.
12083         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12084         ExprResult Arg0 =
12085           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12086                                               Best->FoundDecl, Method);
12087         if (Arg0.isInvalid())
12088           return ExprError();
12089         Args[0] = Arg0.get();
12090 
12091         // Convert the arguments.
12092         ExprResult InputInit
12093           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12094                                                       Context,
12095                                                       FnDecl->getParamDecl(0)),
12096                                       SourceLocation(),
12097                                       Args[1]);
12098         if (InputInit.isInvalid())
12099           return ExprError();
12100 
12101         Args[1] = InputInit.getAs<Expr>();
12102 
12103         // Build the actual expression node.
12104         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12105         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12106         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12107                                                   Best->FoundDecl,
12108                                                   HadMultipleCandidates,
12109                                                   OpLocInfo.getLoc(),
12110                                                   OpLocInfo.getInfo());
12111         if (FnExpr.isInvalid())
12112           return ExprError();
12113 
12114         // Determine the result type
12115         QualType ResultTy = FnDecl->getReturnType();
12116         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12117         ResultTy = ResultTy.getNonLValueExprType(Context);
12118 
12119         CXXOperatorCallExpr *TheCall =
12120           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12121                                             FnExpr.get(), Args,
12122                                             ResultTy, VK, RLoc,
12123                                             false);
12124 
12125         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12126           return ExprError();
12127 
12128         return MaybeBindToTemporary(TheCall);
12129       } else {
12130         // We matched a built-in operator. Convert the arguments, then
12131         // break out so that we will build the appropriate built-in
12132         // operator node.
12133         ExprResult ArgsRes0 =
12134           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12135                                     Best->Conversions[0], AA_Passing);
12136         if (ArgsRes0.isInvalid())
12137           return ExprError();
12138         Args[0] = ArgsRes0.get();
12139 
12140         ExprResult ArgsRes1 =
12141           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12142                                     Best->Conversions[1], AA_Passing);
12143         if (ArgsRes1.isInvalid())
12144           return ExprError();
12145         Args[1] = ArgsRes1.get();
12146 
12147         break;
12148       }
12149     }
12150 
12151     case OR_No_Viable_Function: {
12152       if (CandidateSet.empty())
12153         Diag(LLoc, diag::err_ovl_no_oper)
12154           << Args[0]->getType() << /*subscript*/ 0
12155           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12156       else
12157         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12158           << Args[0]->getType()
12159           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12160       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12161                                   "[]", LLoc);
12162       return ExprError();
12163     }
12164 
12165     case OR_Ambiguous:
12166       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12167           << "[]"
12168           << Args[0]->getType() << Args[1]->getType()
12169           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12170       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12171                                   "[]", LLoc);
12172       return ExprError();
12173 
12174     case OR_Deleted:
12175       Diag(LLoc, diag::err_ovl_deleted_oper)
12176         << Best->Function->isDeleted() << "[]"
12177         << getDeletedOrUnavailableSuffix(Best->Function)
12178         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12179       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12180                                   "[]", LLoc);
12181       return ExprError();
12182     }
12183 
12184   // We matched a built-in operator; build it.
12185   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12186 }
12187 
12188 /// BuildCallToMemberFunction - Build a call to a member
12189 /// function. MemExpr is the expression that refers to the member
12190 /// function (and includes the object parameter), Args/NumArgs are the
12191 /// arguments to the function call (not including the object
12192 /// parameter). The caller needs to validate that the member
12193 /// expression refers to a non-static member function or an overloaded
12194 /// member function.
12195 ExprResult
12196 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12197                                 SourceLocation LParenLoc,
12198                                 MultiExprArg Args,
12199                                 SourceLocation RParenLoc) {
12200   assert(MemExprE->getType() == Context.BoundMemberTy ||
12201          MemExprE->getType() == Context.OverloadTy);
12202 
12203   // Dig out the member expression. This holds both the object
12204   // argument and the member function we're referring to.
12205   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12206 
12207   // Determine whether this is a call to a pointer-to-member function.
12208   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12209     assert(op->getType() == Context.BoundMemberTy);
12210     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12211 
12212     QualType fnType =
12213       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12214 
12215     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12216     QualType resultType = proto->getCallResultType(Context);
12217     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12218 
12219     // Check that the object type isn't more qualified than the
12220     // member function we're calling.
12221     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12222 
12223     QualType objectType = op->getLHS()->getType();
12224     if (op->getOpcode() == BO_PtrMemI)
12225       objectType = objectType->castAs<PointerType>()->getPointeeType();
12226     Qualifiers objectQuals = objectType.getQualifiers();
12227 
12228     Qualifiers difference = objectQuals - funcQuals;
12229     difference.removeObjCGCAttr();
12230     difference.removeAddressSpace();
12231     if (difference) {
12232       std::string qualsString = difference.getAsString();
12233       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12234         << fnType.getUnqualifiedType()
12235         << qualsString
12236         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12237     }
12238 
12239     CXXMemberCallExpr *call
12240       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12241                                         resultType, valueKind, RParenLoc);
12242 
12243     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12244                             call, nullptr))
12245       return ExprError();
12246 
12247     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12248       return ExprError();
12249 
12250     if (CheckOtherCall(call, proto))
12251       return ExprError();
12252 
12253     return MaybeBindToTemporary(call);
12254   }
12255 
12256   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12257     return new (Context)
12258         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12259 
12260   UnbridgedCastsSet UnbridgedCasts;
12261   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12262     return ExprError();
12263 
12264   MemberExpr *MemExpr;
12265   CXXMethodDecl *Method = nullptr;
12266   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12267   NestedNameSpecifier *Qualifier = nullptr;
12268   if (isa<MemberExpr>(NakedMemExpr)) {
12269     MemExpr = cast<MemberExpr>(NakedMemExpr);
12270     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12271     FoundDecl = MemExpr->getFoundDecl();
12272     Qualifier = MemExpr->getQualifier();
12273     UnbridgedCasts.restore();
12274   } else {
12275     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12276     Qualifier = UnresExpr->getQualifier();
12277 
12278     QualType ObjectType = UnresExpr->getBaseType();
12279     Expr::Classification ObjectClassification
12280       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12281                             : UnresExpr->getBase()->Classify(Context);
12282 
12283     // Add overload candidates
12284     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12285                                       OverloadCandidateSet::CSK_Normal);
12286 
12287     // FIXME: avoid copy.
12288     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12289     if (UnresExpr->hasExplicitTemplateArgs()) {
12290       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12291       TemplateArgs = &TemplateArgsBuffer;
12292     }
12293 
12294     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12295            E = UnresExpr->decls_end(); I != E; ++I) {
12296 
12297       NamedDecl *Func = *I;
12298       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12299       if (isa<UsingShadowDecl>(Func))
12300         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12301 
12302 
12303       // Microsoft supports direct constructor calls.
12304       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12305         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12306                              Args, CandidateSet);
12307       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12308         // If explicit template arguments were provided, we can't call a
12309         // non-template member function.
12310         if (TemplateArgs)
12311           continue;
12312 
12313         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12314                            ObjectClassification, Args, CandidateSet,
12315                            /*SuppressUserConversions=*/false);
12316       } else {
12317         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12318                                    I.getPair(), ActingDC, TemplateArgs,
12319                                    ObjectType,  ObjectClassification,
12320                                    Args, CandidateSet,
12321                                    /*SuppressUsedConversions=*/false);
12322       }
12323     }
12324 
12325     DeclarationName DeclName = UnresExpr->getMemberName();
12326 
12327     UnbridgedCasts.restore();
12328 
12329     OverloadCandidateSet::iterator Best;
12330     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12331                                             Best)) {
12332     case OR_Success:
12333       Method = cast<CXXMethodDecl>(Best->Function);
12334       FoundDecl = Best->FoundDecl;
12335       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12336       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12337         return ExprError();
12338       // If FoundDecl is different from Method (such as if one is a template
12339       // and the other a specialization), make sure DiagnoseUseOfDecl is
12340       // called on both.
12341       // FIXME: This would be more comprehensively addressed by modifying
12342       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12343       // being used.
12344       if (Method != FoundDecl.getDecl() &&
12345                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12346         return ExprError();
12347       break;
12348 
12349     case OR_No_Viable_Function:
12350       Diag(UnresExpr->getMemberLoc(),
12351            diag::err_ovl_no_viable_member_function_in_call)
12352         << DeclName << MemExprE->getSourceRange();
12353       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12354       // FIXME: Leaking incoming expressions!
12355       return ExprError();
12356 
12357     case OR_Ambiguous:
12358       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12359         << DeclName << MemExprE->getSourceRange();
12360       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12361       // FIXME: Leaking incoming expressions!
12362       return ExprError();
12363 
12364     case OR_Deleted:
12365       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12366         << Best->Function->isDeleted()
12367         << DeclName
12368         << getDeletedOrUnavailableSuffix(Best->Function)
12369         << MemExprE->getSourceRange();
12370       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12371       // FIXME: Leaking incoming expressions!
12372       return ExprError();
12373     }
12374 
12375     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12376 
12377     // If overload resolution picked a static member, build a
12378     // non-member call based on that function.
12379     if (Method->isStatic()) {
12380       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12381                                    RParenLoc);
12382     }
12383 
12384     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12385   }
12386 
12387   QualType ResultType = Method->getReturnType();
12388   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12389   ResultType = ResultType.getNonLValueExprType(Context);
12390 
12391   assert(Method && "Member call to something that isn't a method?");
12392   CXXMemberCallExpr *TheCall =
12393     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12394                                     ResultType, VK, RParenLoc);
12395 
12396   // Check for a valid return type.
12397   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12398                           TheCall, Method))
12399     return ExprError();
12400 
12401   // Convert the object argument (for a non-static member function call).
12402   // We only need to do this if there was actually an overload; otherwise
12403   // it was done at lookup.
12404   if (!Method->isStatic()) {
12405     ExprResult ObjectArg =
12406       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12407                                           FoundDecl, Method);
12408     if (ObjectArg.isInvalid())
12409       return ExprError();
12410     MemExpr->setBase(ObjectArg.get());
12411   }
12412 
12413   // Convert the rest of the arguments
12414   const FunctionProtoType *Proto =
12415     Method->getType()->getAs<FunctionProtoType>();
12416   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12417                               RParenLoc))
12418     return ExprError();
12419 
12420   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12421 
12422   if (CheckFunctionCall(Method, TheCall, Proto))
12423     return ExprError();
12424 
12425   // In the case the method to call was not selected by the overloading
12426   // resolution process, we still need to handle the enable_if attribute. Do
12427   // that here, so it will not hide previous -- and more relevant -- errors
12428   if (isa<MemberExpr>(NakedMemExpr)) {
12429     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12430       Diag(MemExprE->getLocStart(),
12431            diag::err_ovl_no_viable_member_function_in_call)
12432           << Method << Method->getSourceRange();
12433       Diag(Method->getLocation(),
12434            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12435           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12436       return ExprError();
12437     }
12438   }
12439 
12440   if ((isa<CXXConstructorDecl>(CurContext) ||
12441        isa<CXXDestructorDecl>(CurContext)) &&
12442       TheCall->getMethodDecl()->isPure()) {
12443     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12444 
12445     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12446         MemExpr->performsVirtualDispatch(getLangOpts())) {
12447       Diag(MemExpr->getLocStart(),
12448            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12449         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12450         << MD->getParent()->getDeclName();
12451 
12452       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12453       if (getLangOpts().AppleKext)
12454         Diag(MemExpr->getLocStart(),
12455              diag::note_pure_qualified_call_kext)
12456              << MD->getParent()->getDeclName()
12457              << MD->getDeclName();
12458     }
12459   }
12460 
12461   if (CXXDestructorDecl *DD =
12462           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12463     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12464     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12465     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12466                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12467                          MemExpr->getMemberLoc());
12468   }
12469 
12470   return MaybeBindToTemporary(TheCall);
12471 }
12472 
12473 /// BuildCallToObjectOfClassType - Build a call to an object of class
12474 /// type (C++ [over.call.object]), which can end up invoking an
12475 /// overloaded function call operator (@c operator()) or performing a
12476 /// user-defined conversion on the object argument.
12477 ExprResult
12478 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12479                                    SourceLocation LParenLoc,
12480                                    MultiExprArg Args,
12481                                    SourceLocation RParenLoc) {
12482   if (checkPlaceholderForOverload(*this, Obj))
12483     return ExprError();
12484   ExprResult Object = Obj;
12485 
12486   UnbridgedCastsSet UnbridgedCasts;
12487   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12488     return ExprError();
12489 
12490   assert(Object.get()->getType()->isRecordType() &&
12491          "Requires object type argument");
12492   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12493 
12494   // C++ [over.call.object]p1:
12495   //  If the primary-expression E in the function call syntax
12496   //  evaluates to a class object of type "cv T", then the set of
12497   //  candidate functions includes at least the function call
12498   //  operators of T. The function call operators of T are obtained by
12499   //  ordinary lookup of the name operator() in the context of
12500   //  (E).operator().
12501   OverloadCandidateSet CandidateSet(LParenLoc,
12502                                     OverloadCandidateSet::CSK_Operator);
12503   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12504 
12505   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12506                           diag::err_incomplete_object_call, Object.get()))
12507     return true;
12508 
12509   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12510   LookupQualifiedName(R, Record->getDecl());
12511   R.suppressDiagnostics();
12512 
12513   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12514        Oper != OperEnd; ++Oper) {
12515     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12516                        Object.get()->Classify(Context),
12517                        Args, CandidateSet,
12518                        /*SuppressUserConversions=*/ false);
12519   }
12520 
12521   // C++ [over.call.object]p2:
12522   //   In addition, for each (non-explicit in C++0x) conversion function
12523   //   declared in T of the form
12524   //
12525   //        operator conversion-type-id () cv-qualifier;
12526   //
12527   //   where cv-qualifier is the same cv-qualification as, or a
12528   //   greater cv-qualification than, cv, and where conversion-type-id
12529   //   denotes the type "pointer to function of (P1,...,Pn) returning
12530   //   R", or the type "reference to pointer to function of
12531   //   (P1,...,Pn) returning R", or the type "reference to function
12532   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12533   //   is also considered as a candidate function. Similarly,
12534   //   surrogate call functions are added to the set of candidate
12535   //   functions for each conversion function declared in an
12536   //   accessible base class provided the function is not hidden
12537   //   within T by another intervening declaration.
12538   const auto &Conversions =
12539       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12540   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12541     NamedDecl *D = *I;
12542     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12543     if (isa<UsingShadowDecl>(D))
12544       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12545 
12546     // Skip over templated conversion functions; they aren't
12547     // surrogates.
12548     if (isa<FunctionTemplateDecl>(D))
12549       continue;
12550 
12551     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12552     if (!Conv->isExplicit()) {
12553       // Strip the reference type (if any) and then the pointer type (if
12554       // any) to get down to what might be a function type.
12555       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12556       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12557         ConvType = ConvPtrType->getPointeeType();
12558 
12559       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12560       {
12561         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12562                               Object.get(), Args, CandidateSet);
12563       }
12564     }
12565   }
12566 
12567   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12568 
12569   // Perform overload resolution.
12570   OverloadCandidateSet::iterator Best;
12571   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12572                              Best)) {
12573   case OR_Success:
12574     // Overload resolution succeeded; we'll build the appropriate call
12575     // below.
12576     break;
12577 
12578   case OR_No_Viable_Function:
12579     if (CandidateSet.empty())
12580       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12581         << Object.get()->getType() << /*call*/ 1
12582         << Object.get()->getSourceRange();
12583     else
12584       Diag(Object.get()->getLocStart(),
12585            diag::err_ovl_no_viable_object_call)
12586         << Object.get()->getType() << Object.get()->getSourceRange();
12587     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12588     break;
12589 
12590   case OR_Ambiguous:
12591     Diag(Object.get()->getLocStart(),
12592          diag::err_ovl_ambiguous_object_call)
12593       << Object.get()->getType() << Object.get()->getSourceRange();
12594     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12595     break;
12596 
12597   case OR_Deleted:
12598     Diag(Object.get()->getLocStart(),
12599          diag::err_ovl_deleted_object_call)
12600       << Best->Function->isDeleted()
12601       << Object.get()->getType()
12602       << getDeletedOrUnavailableSuffix(Best->Function)
12603       << Object.get()->getSourceRange();
12604     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12605     break;
12606   }
12607 
12608   if (Best == CandidateSet.end())
12609     return true;
12610 
12611   UnbridgedCasts.restore();
12612 
12613   if (Best->Function == nullptr) {
12614     // Since there is no function declaration, this is one of the
12615     // surrogate candidates. Dig out the conversion function.
12616     CXXConversionDecl *Conv
12617       = cast<CXXConversionDecl>(
12618                          Best->Conversions[0].UserDefined.ConversionFunction);
12619 
12620     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12621                               Best->FoundDecl);
12622     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12623       return ExprError();
12624     assert(Conv == Best->FoundDecl.getDecl() &&
12625              "Found Decl & conversion-to-functionptr should be same, right?!");
12626     // We selected one of the surrogate functions that converts the
12627     // object parameter to a function pointer. Perform the conversion
12628     // on the object argument, then let ActOnCallExpr finish the job.
12629 
12630     // Create an implicit member expr to refer to the conversion operator.
12631     // and then call it.
12632     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12633                                              Conv, HadMultipleCandidates);
12634     if (Call.isInvalid())
12635       return ExprError();
12636     // Record usage of conversion in an implicit cast.
12637     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12638                                     CK_UserDefinedConversion, Call.get(),
12639                                     nullptr, VK_RValue);
12640 
12641     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12642   }
12643 
12644   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12645 
12646   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12647   // that calls this method, using Object for the implicit object
12648   // parameter and passing along the remaining arguments.
12649   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12650 
12651   // An error diagnostic has already been printed when parsing the declaration.
12652   if (Method->isInvalidDecl())
12653     return ExprError();
12654 
12655   const FunctionProtoType *Proto =
12656     Method->getType()->getAs<FunctionProtoType>();
12657 
12658   unsigned NumParams = Proto->getNumParams();
12659 
12660   DeclarationNameInfo OpLocInfo(
12661                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12662   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12663   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12664                                            HadMultipleCandidates,
12665                                            OpLocInfo.getLoc(),
12666                                            OpLocInfo.getInfo());
12667   if (NewFn.isInvalid())
12668     return true;
12669 
12670   // Build the full argument list for the method call (the implicit object
12671   // parameter is placed at the beginning of the list).
12672   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12673   MethodArgs[0] = Object.get();
12674   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12675 
12676   // Once we've built TheCall, all of the expressions are properly
12677   // owned.
12678   QualType ResultTy = Method->getReturnType();
12679   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12680   ResultTy = ResultTy.getNonLValueExprType(Context);
12681 
12682   CXXOperatorCallExpr *TheCall = new (Context)
12683       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12684                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12685                           ResultTy, VK, RParenLoc, false);
12686   MethodArgs.reset();
12687 
12688   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12689     return true;
12690 
12691   // We may have default arguments. If so, we need to allocate more
12692   // slots in the call for them.
12693   if (Args.size() < NumParams)
12694     TheCall->setNumArgs(Context, NumParams + 1);
12695 
12696   bool IsError = false;
12697 
12698   // Initialize the implicit object parameter.
12699   ExprResult ObjRes =
12700     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12701                                         Best->FoundDecl, Method);
12702   if (ObjRes.isInvalid())
12703     IsError = true;
12704   else
12705     Object = ObjRes;
12706   TheCall->setArg(0, Object.get());
12707 
12708   // Check the argument types.
12709   for (unsigned i = 0; i != NumParams; i++) {
12710     Expr *Arg;
12711     if (i < Args.size()) {
12712       Arg = Args[i];
12713 
12714       // Pass the argument.
12715 
12716       ExprResult InputInit
12717         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12718                                                     Context,
12719                                                     Method->getParamDecl(i)),
12720                                     SourceLocation(), Arg);
12721 
12722       IsError |= InputInit.isInvalid();
12723       Arg = InputInit.getAs<Expr>();
12724     } else {
12725       ExprResult DefArg
12726         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12727       if (DefArg.isInvalid()) {
12728         IsError = true;
12729         break;
12730       }
12731 
12732       Arg = DefArg.getAs<Expr>();
12733     }
12734 
12735     TheCall->setArg(i + 1, Arg);
12736   }
12737 
12738   // If this is a variadic call, handle args passed through "...".
12739   if (Proto->isVariadic()) {
12740     // Promote the arguments (C99 6.5.2.2p7).
12741     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12742       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12743                                                         nullptr);
12744       IsError |= Arg.isInvalid();
12745       TheCall->setArg(i + 1, Arg.get());
12746     }
12747   }
12748 
12749   if (IsError) return true;
12750 
12751   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12752 
12753   if (CheckFunctionCall(Method, TheCall, Proto))
12754     return true;
12755 
12756   return MaybeBindToTemporary(TheCall);
12757 }
12758 
12759 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12760 ///  (if one exists), where @c Base is an expression of class type and
12761 /// @c Member is the name of the member we're trying to find.
12762 ExprResult
12763 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12764                                bool *NoArrowOperatorFound) {
12765   assert(Base->getType()->isRecordType() &&
12766          "left-hand side must have class type");
12767 
12768   if (checkPlaceholderForOverload(*this, Base))
12769     return ExprError();
12770 
12771   SourceLocation Loc = Base->getExprLoc();
12772 
12773   // C++ [over.ref]p1:
12774   //
12775   //   [...] An expression x->m is interpreted as (x.operator->())->m
12776   //   for a class object x of type T if T::operator->() exists and if
12777   //   the operator is selected as the best match function by the
12778   //   overload resolution mechanism (13.3).
12779   DeclarationName OpName =
12780     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12781   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12782   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12783 
12784   if (RequireCompleteType(Loc, Base->getType(),
12785                           diag::err_typecheck_incomplete_tag, Base))
12786     return ExprError();
12787 
12788   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12789   LookupQualifiedName(R, BaseRecord->getDecl());
12790   R.suppressDiagnostics();
12791 
12792   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12793        Oper != OperEnd; ++Oper) {
12794     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12795                        None, CandidateSet, /*SuppressUserConversions=*/false);
12796   }
12797 
12798   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12799 
12800   // Perform overload resolution.
12801   OverloadCandidateSet::iterator Best;
12802   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12803   case OR_Success:
12804     // Overload resolution succeeded; we'll build the call below.
12805     break;
12806 
12807   case OR_No_Viable_Function:
12808     if (CandidateSet.empty()) {
12809       QualType BaseType = Base->getType();
12810       if (NoArrowOperatorFound) {
12811         // Report this specific error to the caller instead of emitting a
12812         // diagnostic, as requested.
12813         *NoArrowOperatorFound = true;
12814         return ExprError();
12815       }
12816       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12817         << BaseType << Base->getSourceRange();
12818       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12819         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12820           << FixItHint::CreateReplacement(OpLoc, ".");
12821       }
12822     } else
12823       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12824         << "operator->" << Base->getSourceRange();
12825     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12826     return ExprError();
12827 
12828   case OR_Ambiguous:
12829     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12830       << "->" << Base->getType() << Base->getSourceRange();
12831     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12832     return ExprError();
12833 
12834   case OR_Deleted:
12835     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12836       << Best->Function->isDeleted()
12837       << "->"
12838       << getDeletedOrUnavailableSuffix(Best->Function)
12839       << Base->getSourceRange();
12840     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12841     return ExprError();
12842   }
12843 
12844   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12845 
12846   // Convert the object parameter.
12847   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12848   ExprResult BaseResult =
12849     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12850                                         Best->FoundDecl, Method);
12851   if (BaseResult.isInvalid())
12852     return ExprError();
12853   Base = BaseResult.get();
12854 
12855   // Build the operator call.
12856   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12857                                             HadMultipleCandidates, OpLoc);
12858   if (FnExpr.isInvalid())
12859     return ExprError();
12860 
12861   QualType ResultTy = Method->getReturnType();
12862   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12863   ResultTy = ResultTy.getNonLValueExprType(Context);
12864   CXXOperatorCallExpr *TheCall =
12865     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12866                                       Base, ResultTy, VK, OpLoc, false);
12867 
12868   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12869           return ExprError();
12870 
12871   return MaybeBindToTemporary(TheCall);
12872 }
12873 
12874 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12875 /// a literal operator described by the provided lookup results.
12876 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12877                                           DeclarationNameInfo &SuffixInfo,
12878                                           ArrayRef<Expr*> Args,
12879                                           SourceLocation LitEndLoc,
12880                                        TemplateArgumentListInfo *TemplateArgs) {
12881   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12882 
12883   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12884                                     OverloadCandidateSet::CSK_Normal);
12885   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12886                         /*SuppressUserConversions=*/true);
12887 
12888   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12889 
12890   // Perform overload resolution. This will usually be trivial, but might need
12891   // to perform substitutions for a literal operator template.
12892   OverloadCandidateSet::iterator Best;
12893   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12894   case OR_Success:
12895   case OR_Deleted:
12896     break;
12897 
12898   case OR_No_Viable_Function:
12899     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12900       << R.getLookupName();
12901     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12902     return ExprError();
12903 
12904   case OR_Ambiguous:
12905     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12906     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12907     return ExprError();
12908   }
12909 
12910   FunctionDecl *FD = Best->Function;
12911   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12912                                         HadMultipleCandidates,
12913                                         SuffixInfo.getLoc(),
12914                                         SuffixInfo.getInfo());
12915   if (Fn.isInvalid())
12916     return true;
12917 
12918   // Check the argument types. This should almost always be a no-op, except
12919   // that array-to-pointer decay is applied to string literals.
12920   Expr *ConvArgs[2];
12921   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12922     ExprResult InputInit = PerformCopyInitialization(
12923       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12924       SourceLocation(), Args[ArgIdx]);
12925     if (InputInit.isInvalid())
12926       return true;
12927     ConvArgs[ArgIdx] = InputInit.get();
12928   }
12929 
12930   QualType ResultTy = FD->getReturnType();
12931   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12932   ResultTy = ResultTy.getNonLValueExprType(Context);
12933 
12934   UserDefinedLiteral *UDL =
12935     new (Context) UserDefinedLiteral(Context, Fn.get(),
12936                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12937                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12938 
12939   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12940     return ExprError();
12941 
12942   if (CheckFunctionCall(FD, UDL, nullptr))
12943     return ExprError();
12944 
12945   return MaybeBindToTemporary(UDL);
12946 }
12947 
12948 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12949 /// given LookupResult is non-empty, it is assumed to describe a member which
12950 /// will be invoked. Otherwise, the function will be found via argument
12951 /// dependent lookup.
12952 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12953 /// otherwise CallExpr is set to ExprError() and some non-success value
12954 /// is returned.
12955 Sema::ForRangeStatus
12956 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12957                                 SourceLocation RangeLoc,
12958                                 const DeclarationNameInfo &NameInfo,
12959                                 LookupResult &MemberLookup,
12960                                 OverloadCandidateSet *CandidateSet,
12961                                 Expr *Range, ExprResult *CallExpr) {
12962   Scope *S = nullptr;
12963 
12964   CandidateSet->clear();
12965   if (!MemberLookup.empty()) {
12966     ExprResult MemberRef =
12967         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12968                                  /*IsPtr=*/false, CXXScopeSpec(),
12969                                  /*TemplateKWLoc=*/SourceLocation(),
12970                                  /*FirstQualifierInScope=*/nullptr,
12971                                  MemberLookup,
12972                                  /*TemplateArgs=*/nullptr, S);
12973     if (MemberRef.isInvalid()) {
12974       *CallExpr = ExprError();
12975       return FRS_DiagnosticIssued;
12976     }
12977     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12978     if (CallExpr->isInvalid()) {
12979       *CallExpr = ExprError();
12980       return FRS_DiagnosticIssued;
12981     }
12982   } else {
12983     UnresolvedSet<0> FoundNames;
12984     UnresolvedLookupExpr *Fn =
12985       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12986                                    NestedNameSpecifierLoc(), NameInfo,
12987                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12988                                    FoundNames.begin(), FoundNames.end());
12989 
12990     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12991                                                     CandidateSet, CallExpr);
12992     if (CandidateSet->empty() || CandidateSetError) {
12993       *CallExpr = ExprError();
12994       return FRS_NoViableFunction;
12995     }
12996     OverloadCandidateSet::iterator Best;
12997     OverloadingResult OverloadResult =
12998         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12999 
13000     if (OverloadResult == OR_No_Viable_Function) {
13001       *CallExpr = ExprError();
13002       return FRS_NoViableFunction;
13003     }
13004     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13005                                          Loc, nullptr, CandidateSet, &Best,
13006                                          OverloadResult,
13007                                          /*AllowTypoCorrection=*/false);
13008     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13009       *CallExpr = ExprError();
13010       return FRS_DiagnosticIssued;
13011     }
13012   }
13013   return FRS_Success;
13014 }
13015 
13016 
13017 /// FixOverloadedFunctionReference - E is an expression that refers to
13018 /// a C++ overloaded function (possibly with some parentheses and
13019 /// perhaps a '&' around it). We have resolved the overloaded function
13020 /// to the function declaration Fn, so patch up the expression E to
13021 /// refer (possibly indirectly) to Fn. Returns the new expr.
13022 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13023                                            FunctionDecl *Fn) {
13024   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13025     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13026                                                    Found, Fn);
13027     if (SubExpr == PE->getSubExpr())
13028       return PE;
13029 
13030     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13031   }
13032 
13033   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13034     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13035                                                    Found, Fn);
13036     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13037                                SubExpr->getType()) &&
13038            "Implicit cast type cannot be determined from overload");
13039     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13040     if (SubExpr == ICE->getSubExpr())
13041       return ICE;
13042 
13043     return ImplicitCastExpr::Create(Context, ICE->getType(),
13044                                     ICE->getCastKind(),
13045                                     SubExpr, nullptr,
13046                                     ICE->getValueKind());
13047   }
13048 
13049   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13050     if (!GSE->isResultDependent()) {
13051       Expr *SubExpr =
13052           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13053       if (SubExpr == GSE->getResultExpr())
13054         return GSE;
13055 
13056       // Replace the resulting type information before rebuilding the generic
13057       // selection expression.
13058       ArrayRef<Expr *> A = GSE->getAssocExprs();
13059       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13060       unsigned ResultIdx = GSE->getResultIndex();
13061       AssocExprs[ResultIdx] = SubExpr;
13062 
13063       return new (Context) GenericSelectionExpr(
13064           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13065           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13066           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13067           ResultIdx);
13068     }
13069     // Rather than fall through to the unreachable, return the original generic
13070     // selection expression.
13071     return GSE;
13072   }
13073 
13074   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13075     assert(UnOp->getOpcode() == UO_AddrOf &&
13076            "Can only take the address of an overloaded function");
13077     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13078       if (Method->isStatic()) {
13079         // Do nothing: static member functions aren't any different
13080         // from non-member functions.
13081       } else {
13082         // Fix the subexpression, which really has to be an
13083         // UnresolvedLookupExpr holding an overloaded member function
13084         // or template.
13085         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13086                                                        Found, Fn);
13087         if (SubExpr == UnOp->getSubExpr())
13088           return UnOp;
13089 
13090         assert(isa<DeclRefExpr>(SubExpr)
13091                && "fixed to something other than a decl ref");
13092         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13093                && "fixed to a member ref with no nested name qualifier");
13094 
13095         // We have taken the address of a pointer to member
13096         // function. Perform the computation here so that we get the
13097         // appropriate pointer to member type.
13098         QualType ClassType
13099           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13100         QualType MemPtrType
13101           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13102         // Under the MS ABI, lock down the inheritance model now.
13103         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13104           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13105 
13106         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13107                                            VK_RValue, OK_Ordinary,
13108                                            UnOp->getOperatorLoc());
13109       }
13110     }
13111     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13112                                                    Found, Fn);
13113     if (SubExpr == UnOp->getSubExpr())
13114       return UnOp;
13115 
13116     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13117                                      Context.getPointerType(SubExpr->getType()),
13118                                        VK_RValue, OK_Ordinary,
13119                                        UnOp->getOperatorLoc());
13120   }
13121 
13122   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13123     // FIXME: avoid copy.
13124     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13125     if (ULE->hasExplicitTemplateArgs()) {
13126       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13127       TemplateArgs = &TemplateArgsBuffer;
13128     }
13129 
13130     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13131                                            ULE->getQualifierLoc(),
13132                                            ULE->getTemplateKeywordLoc(),
13133                                            Fn,
13134                                            /*enclosing*/ false, // FIXME?
13135                                            ULE->getNameLoc(),
13136                                            Fn->getType(),
13137                                            VK_LValue,
13138                                            Found.getDecl(),
13139                                            TemplateArgs);
13140     MarkDeclRefReferenced(DRE);
13141     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13142     return DRE;
13143   }
13144 
13145   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13146     // FIXME: avoid copy.
13147     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13148     if (MemExpr->hasExplicitTemplateArgs()) {
13149       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13150       TemplateArgs = &TemplateArgsBuffer;
13151     }
13152 
13153     Expr *Base;
13154 
13155     // If we're filling in a static method where we used to have an
13156     // implicit member access, rewrite to a simple decl ref.
13157     if (MemExpr->isImplicitAccess()) {
13158       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13159         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13160                                                MemExpr->getQualifierLoc(),
13161                                                MemExpr->getTemplateKeywordLoc(),
13162                                                Fn,
13163                                                /*enclosing*/ false,
13164                                                MemExpr->getMemberLoc(),
13165                                                Fn->getType(),
13166                                                VK_LValue,
13167                                                Found.getDecl(),
13168                                                TemplateArgs);
13169         MarkDeclRefReferenced(DRE);
13170         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13171         return DRE;
13172       } else {
13173         SourceLocation Loc = MemExpr->getMemberLoc();
13174         if (MemExpr->getQualifier())
13175           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13176         CheckCXXThisCapture(Loc);
13177         Base = new (Context) CXXThisExpr(Loc,
13178                                          MemExpr->getBaseType(),
13179                                          /*isImplicit=*/true);
13180       }
13181     } else
13182       Base = MemExpr->getBase();
13183 
13184     ExprValueKind valueKind;
13185     QualType type;
13186     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13187       valueKind = VK_LValue;
13188       type = Fn->getType();
13189     } else {
13190       valueKind = VK_RValue;
13191       type = Context.BoundMemberTy;
13192     }
13193 
13194     MemberExpr *ME = MemberExpr::Create(
13195         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13196         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13197         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13198         OK_Ordinary);
13199     ME->setHadMultipleCandidates(true);
13200     MarkMemberReferenced(ME);
13201     return ME;
13202   }
13203 
13204   llvm_unreachable("Invalid reference to overloaded function");
13205 }
13206 
13207 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13208                                                 DeclAccessPair Found,
13209                                                 FunctionDecl *Fn) {
13210   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13211 }
13212