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 std::any_of(FD->param_begin(), FD->param_end(),
43                      std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44 }
45 
46 /// A convenience routine for creating a decayed reference to a function.
47 static ExprResult
48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49                       bool HadMultipleCandidates,
50                       SourceLocation Loc = SourceLocation(),
51                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
52   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
53     return ExprError();
54   // If FoundDecl is different from Fn (such as if one is a template
55   // and the other a specialization), make sure DiagnoseUseOfDecl is
56   // called on both.
57   // FIXME: This would be more comprehensively addressed by modifying
58   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59   // being used.
60   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
61     return ExprError();
62   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
63                                                  VK_LValue, Loc, LocInfo);
64   if (HadMultipleCandidates)
65     DRE->setHadMultipleCandidates(true);
66 
67   S.MarkDeclRefReferenced(DRE);
68   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69                              CK_FunctionToPointerDecay);
70 }
71 
72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73                                  bool InOverloadResolution,
74                                  StandardConversionSequence &SCS,
75                                  bool CStyle,
76                                  bool AllowObjCWritebackConversion);
77 
78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79                                                  QualType &ToType,
80                                                  bool InOverloadResolution,
81                                                  StandardConversionSequence &SCS,
82                                                  bool CStyle);
83 static OverloadingResult
84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85                         UserDefinedConversionSequence& User,
86                         OverloadCandidateSet& Conversions,
87                         bool AllowExplicit,
88                         bool AllowObjCConversionOnExplicit);
89 
90 
91 static ImplicitConversionSequence::CompareKind
92 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
93                                    const StandardConversionSequence& SCS1,
94                                    const StandardConversionSequence& SCS2);
95 
96 static ImplicitConversionSequence::CompareKind
97 CompareQualificationConversions(Sema &S,
98                                 const StandardConversionSequence& SCS1,
99                                 const StandardConversionSequence& SCS2);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
103                                 const StandardConversionSequence& SCS1,
104                                 const StandardConversionSequence& SCS2);
105 
106 /// GetConversionRank - Retrieve the implicit conversion rank
107 /// corresponding to the given implicit conversion kind.
108 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
109   static const ImplicitConversionRank
110     Rank[(int)ICK_Num_Conversion_Kinds] = {
111     ICR_Exact_Match,
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Promotion,
118     ICR_Promotion,
119     ICR_Promotion,
120     ICR_Conversion,
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_Complex_Real_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Writeback_Conversion,
135     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136                      // it was omitted by the patch that added
137                      // ICK_Zero_Event_Conversion
138     ICR_C_Conversion
139   };
140   return Rank[(int)Kind];
141 }
142 
143 /// GetImplicitConversionName - Return the name of this kind of
144 /// implicit conversion.
145 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
146   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
147     "No conversion",
148     "Lvalue-to-rvalue",
149     "Array-to-pointer",
150     "Function-to-pointer",
151     "Noreturn adjustment",
152     "Qualification",
153     "Integral promotion",
154     "Floating point promotion",
155     "Complex promotion",
156     "Integral conversion",
157     "Floating conversion",
158     "Complex conversion",
159     "Floating-integral conversion",
160     "Pointer conversion",
161     "Pointer-to-member conversion",
162     "Boolean conversion",
163     "Compatible-types conversion",
164     "Derived-to-base conversion",
165     "Vector conversion",
166     "Vector splat",
167     "Complex-real conversion",
168     "Block Pointer conversion",
169     "Transparent Union Conversion",
170     "Writeback conversion",
171     "OpenCL Zero Event Conversion",
172     "C specific type conversion"
173   };
174   return Name[Kind];
175 }
176 
177 /// StandardConversionSequence - Set the standard conversion
178 /// sequence to the identity conversion.
179 void StandardConversionSequence::setAsIdentityConversion() {
180   First = ICK_Identity;
181   Second = ICK_Identity;
182   Third = ICK_Identity;
183   DeprecatedStringLiteralToCharPtr = false;
184   QualificationIncludesObjCLifetime = false;
185   ReferenceBinding = false;
186   DirectBinding = false;
187   IsLvalueReference = true;
188   BindsToFunctionLvalue = false;
189   BindsToRvalue = false;
190   BindsImplicitObjectArgumentWithoutRefQualifier = false;
191   ObjCLifetimeConversionBinding = false;
192   CopyConstructor = nullptr;
193 }
194 
195 /// getRank - Retrieve the rank of this standard conversion sequence
196 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197 /// implicit conversions.
198 ImplicitConversionRank StandardConversionSequence::getRank() const {
199   ImplicitConversionRank Rank = ICR_Exact_Match;
200   if  (GetConversionRank(First) > Rank)
201     Rank = GetConversionRank(First);
202   if  (GetConversionRank(Second) > Rank)
203     Rank = GetConversionRank(Second);
204   if  (GetConversionRank(Third) > Rank)
205     Rank = GetConversionRank(Third);
206   return Rank;
207 }
208 
209 /// isPointerConversionToBool - Determines whether this conversion is
210 /// a conversion of a pointer or pointer-to-member to bool. This is
211 /// used as part of the ranking of standard conversion sequences
212 /// (C++ 13.3.3.2p4).
213 bool StandardConversionSequence::isPointerConversionToBool() const {
214   // Note that FromType has not necessarily been transformed by the
215   // array-to-pointer or function-to-pointer implicit conversions, so
216   // check for their presence as well as checking whether FromType is
217   // a pointer.
218   if (getToType(1)->isBooleanType() &&
219       (getFromType()->isPointerType() ||
220        getFromType()->isObjCObjectPointerType() ||
221        getFromType()->isBlockPointerType() ||
222        getFromType()->isNullPtrType() ||
223        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224     return true;
225 
226   return false;
227 }
228 
229 /// isPointerConversionToVoidPointer - Determines whether this
230 /// conversion is a conversion of a pointer to a void pointer. This is
231 /// used as part of the ranking of standard conversion sequences (C++
232 /// 13.3.3.2p4).
233 bool
234 StandardConversionSequence::
235 isPointerConversionToVoidPointer(ASTContext& Context) const {
236   QualType FromType = getFromType();
237   QualType ToType = getToType(1);
238 
239   // Note that FromType has not necessarily been transformed by the
240   // array-to-pointer implicit conversion, so check for its presence
241   // and redo the conversion to get a pointer.
242   if (First == ICK_Array_To_Pointer)
243     FromType = Context.getArrayDecayedType(FromType);
244 
245   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
246     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
247       return ToPtrType->getPointeeType()->isVoidType();
248 
249   return false;
250 }
251 
252 /// Skip any implicit casts which could be either part of a narrowing conversion
253 /// or after one in an implicit conversion.
254 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256     switch (ICE->getCastKind()) {
257     case CK_NoOp:
258     case CK_IntegralCast:
259     case CK_IntegralToBoolean:
260     case CK_IntegralToFloating:
261     case CK_BooleanToSignedIntegral:
262     case CK_FloatingToIntegral:
263     case CK_FloatingToBoolean:
264     case CK_FloatingCast:
265       Converted = ICE->getSubExpr();
266       continue;
267 
268     default:
269       return Converted;
270     }
271   }
272 
273   return Converted;
274 }
275 
276 /// Check if this standard conversion sequence represents a narrowing
277 /// conversion, according to C++11 [dcl.init.list]p7.
278 ///
279 /// \param Ctx  The AST context.
280 /// \param Converted  The result of applying this standard conversion sequence.
281 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
282 ///        value of the expression prior to the narrowing conversion.
283 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
284 ///        type of the expression prior to the narrowing conversion.
285 NarrowingKind
286 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287                                              const Expr *Converted,
288                                              APValue &ConstantValue,
289                                              QualType &ConstantType) const {
290   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
291 
292   // C++11 [dcl.init.list]p7:
293   //   A narrowing conversion is an implicit conversion ...
294   QualType FromType = getToType(0);
295   QualType ToType = getToType(1);
296 
297   // A conversion to an enumeration type is narrowing if the conversion to
298   // the underlying type is narrowing. This only arises for expressions of
299   // the form 'Enum{init}'.
300   if (auto *ET = ToType->getAs<EnumType>())
301     ToType = ET->getDecl()->getIntegerType();
302 
303   switch (Second) {
304   // 'bool' is an integral type; dispatch to the right place to handle it.
305   case ICK_Boolean_Conversion:
306     if (FromType->isRealFloatingType())
307       goto FloatingIntegralConversion;
308     if (FromType->isIntegralOrUnscopedEnumerationType())
309       goto IntegralConversion;
310     // Boolean conversions can be from pointers and pointers to members
311     // [conv.bool], and those aren't considered narrowing conversions.
312     return NK_Not_Narrowing;
313 
314   // -- from a floating-point type to an integer type, or
315   //
316   // -- from an integer type or unscoped enumeration type to a floating-point
317   //    type, except where the source is a constant expression and the actual
318   //    value after conversion will fit into the target type and will produce
319   //    the original value when converted back to the original type, or
320   case ICK_Floating_Integral:
321   FloatingIntegralConversion:
322     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
323       return NK_Type_Narrowing;
324     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
325       llvm::APSInt IntConstantValue;
326       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
327       if (Initializer &&
328           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
329         // Convert the integer to the floating type.
330         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
331         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
332                                 llvm::APFloat::rmNearestTiesToEven);
333         // And back.
334         llvm::APSInt ConvertedValue = IntConstantValue;
335         bool ignored;
336         Result.convertToInteger(ConvertedValue,
337                                 llvm::APFloat::rmTowardZero, &ignored);
338         // If the resulting value is different, this was a narrowing conversion.
339         if (IntConstantValue != ConvertedValue) {
340           ConstantValue = APValue(IntConstantValue);
341           ConstantType = Initializer->getType();
342           return NK_Constant_Narrowing;
343         }
344       } else {
345         // Variables are always narrowings.
346         return NK_Variable_Narrowing;
347       }
348     }
349     return NK_Not_Narrowing;
350 
351   // -- from long double to double or float, or from double to float, except
352   //    where the source is a constant expression and the actual value after
353   //    conversion is within the range of values that can be represented (even
354   //    if it cannot be represented exactly), or
355   case ICK_Floating_Conversion:
356     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
357         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
358       // FromType is larger than ToType.
359       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
360       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
361         // Constant!
362         assert(ConstantValue.isFloat());
363         llvm::APFloat FloatVal = ConstantValue.getFloat();
364         // Convert the source value into the target type.
365         bool ignored;
366         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
367           Ctx.getFloatTypeSemantics(ToType),
368           llvm::APFloat::rmNearestTiesToEven, &ignored);
369         // If there was no overflow, the source value is within the range of
370         // values that can be represented.
371         if (ConvertStatus & llvm::APFloat::opOverflow) {
372           ConstantType = Initializer->getType();
373           return NK_Constant_Narrowing;
374         }
375       } else {
376         return NK_Variable_Narrowing;
377       }
378     }
379     return NK_Not_Narrowing;
380 
381   // -- from an integer type or unscoped enumeration type to an integer type
382   //    that cannot represent all the values of the original type, except where
383   //    the source is a constant expression and the actual value after
384   //    conversion will fit into the target type and will produce the original
385   //    value when converted back to the original type.
386   case ICK_Integral_Conversion:
387   IntegralConversion: {
388     assert(FromType->isIntegralOrUnscopedEnumerationType());
389     assert(ToType->isIntegralOrUnscopedEnumerationType());
390     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
391     const unsigned FromWidth = Ctx.getIntWidth(FromType);
392     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
393     const unsigned ToWidth = Ctx.getIntWidth(ToType);
394 
395     if (FromWidth > ToWidth ||
396         (FromWidth == ToWidth && FromSigned != ToSigned) ||
397         (FromSigned && !ToSigned)) {
398       // Not all values of FromType can be represented in ToType.
399       llvm::APSInt InitializerValue;
400       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
401       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
402         // Such conversions on variables are always narrowing.
403         return NK_Variable_Narrowing;
404       }
405       bool Narrowing = false;
406       if (FromWidth < ToWidth) {
407         // Negative -> unsigned is narrowing. Otherwise, more bits is never
408         // narrowing.
409         if (InitializerValue.isSigned() && InitializerValue.isNegative())
410           Narrowing = true;
411       } else {
412         // Add a bit to the InitializerValue so we don't have to worry about
413         // signed vs. unsigned comparisons.
414         InitializerValue = InitializerValue.extend(
415           InitializerValue.getBitWidth() + 1);
416         // Convert the initializer to and from the target width and signed-ness.
417         llvm::APSInt ConvertedValue = InitializerValue;
418         ConvertedValue = ConvertedValue.trunc(ToWidth);
419         ConvertedValue.setIsSigned(ToSigned);
420         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
421         ConvertedValue.setIsSigned(InitializerValue.isSigned());
422         // If the result is different, this was a narrowing conversion.
423         if (ConvertedValue != InitializerValue)
424           Narrowing = true;
425       }
426       if (Narrowing) {
427         ConstantType = Initializer->getType();
428         ConstantValue = APValue(InitializerValue);
429         return NK_Constant_Narrowing;
430       }
431     }
432     return NK_Not_Narrowing;
433   }
434 
435   default:
436     // Other kinds of conversions are not narrowings.
437     return NK_Not_Narrowing;
438   }
439 }
440 
441 /// dump - Print this standard conversion sequence to standard
442 /// error. Useful for debugging overloading issues.
443 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
444   raw_ostream &OS = llvm::errs();
445   bool PrintedSomething = false;
446   if (First != ICK_Identity) {
447     OS << GetImplicitConversionName(First);
448     PrintedSomething = true;
449   }
450 
451   if (Second != ICK_Identity) {
452     if (PrintedSomething) {
453       OS << " -> ";
454     }
455     OS << GetImplicitConversionName(Second);
456 
457     if (CopyConstructor) {
458       OS << " (by copy constructor)";
459     } else if (DirectBinding) {
460       OS << " (direct reference binding)";
461     } else if (ReferenceBinding) {
462       OS << " (reference binding)";
463     }
464     PrintedSomething = true;
465   }
466 
467   if (Third != ICK_Identity) {
468     if (PrintedSomething) {
469       OS << " -> ";
470     }
471     OS << GetImplicitConversionName(Third);
472     PrintedSomething = true;
473   }
474 
475   if (!PrintedSomething) {
476     OS << "No conversions required";
477   }
478 }
479 
480 /// dump - Print this user-defined conversion sequence to standard
481 /// error. Useful for debugging overloading issues.
482 void UserDefinedConversionSequence::dump() const {
483   raw_ostream &OS = llvm::errs();
484   if (Before.First || Before.Second || Before.Third) {
485     Before.dump();
486     OS << " -> ";
487   }
488   if (ConversionFunction)
489     OS << '\'' << *ConversionFunction << '\'';
490   else
491     OS << "aggregate initialization";
492   if (After.First || After.Second || After.Third) {
493     OS << " -> ";
494     After.dump();
495   }
496 }
497 
498 /// dump - Print this implicit conversion sequence to standard
499 /// error. Useful for debugging overloading issues.
500 void ImplicitConversionSequence::dump() const {
501   raw_ostream &OS = llvm::errs();
502   if (isStdInitializerListElement())
503     OS << "Worst std::initializer_list element conversion: ";
504   switch (ConversionKind) {
505   case StandardConversion:
506     OS << "Standard conversion: ";
507     Standard.dump();
508     break;
509   case UserDefinedConversion:
510     OS << "User-defined conversion: ";
511     UserDefined.dump();
512     break;
513   case EllipsisConversion:
514     OS << "Ellipsis conversion";
515     break;
516   case AmbiguousConversion:
517     OS << "Ambiguous conversion";
518     break;
519   case BadConversion:
520     OS << "Bad conversion";
521     break;
522   }
523 
524   OS << "\n";
525 }
526 
527 void AmbiguousConversionSequence::construct() {
528   new (&conversions()) ConversionSet();
529 }
530 
531 void AmbiguousConversionSequence::destruct() {
532   conversions().~ConversionSet();
533 }
534 
535 void
536 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
537   FromTypePtr = O.FromTypePtr;
538   ToTypePtr = O.ToTypePtr;
539   new (&conversions()) ConversionSet(O.conversions());
540 }
541 
542 namespace {
543   // Structure used by DeductionFailureInfo to store
544   // template argument information.
545   struct DFIArguments {
546     TemplateArgument FirstArg;
547     TemplateArgument SecondArg;
548   };
549   // Structure used by DeductionFailureInfo to store
550   // template parameter and template argument information.
551   struct DFIParamWithArguments : DFIArguments {
552     TemplateParameter Param;
553   };
554   // Structure used by DeductionFailureInfo to store template argument
555   // information and the index of the problematic call argument.
556   struct DFIDeducedMismatchArgs : DFIArguments {
557     TemplateArgumentList *TemplateArgs;
558     unsigned CallArgIndex;
559   };
560 }
561 
562 /// \brief Convert from Sema's representation of template deduction information
563 /// to the form used in overload-candidate information.
564 DeductionFailureInfo
565 clang::MakeDeductionFailureInfo(ASTContext &Context,
566                                 Sema::TemplateDeductionResult TDK,
567                                 TemplateDeductionInfo &Info) {
568   DeductionFailureInfo Result;
569   Result.Result = static_cast<unsigned>(TDK);
570   Result.HasDiagnostic = false;
571   switch (TDK) {
572   case Sema::TDK_Success:
573   case Sema::TDK_Invalid:
574   case Sema::TDK_InstantiationDepth:
575   case Sema::TDK_TooManyArguments:
576   case Sema::TDK_TooFewArguments:
577   case Sema::TDK_MiscellaneousDeductionFailure:
578     Result.Data = nullptr;
579     break;
580 
581   case Sema::TDK_Incomplete:
582   case Sema::TDK_InvalidExplicitArguments:
583     Result.Data = Info.Param.getOpaqueValue();
584     break;
585 
586   case Sema::TDK_DeducedMismatch: {
587     // FIXME: Should allocate from normal heap so that we can free this later.
588     auto *Saved = new (Context) DFIDeducedMismatchArgs;
589     Saved->FirstArg = Info.FirstArg;
590     Saved->SecondArg = Info.SecondArg;
591     Saved->TemplateArgs = Info.take();
592     Saved->CallArgIndex = Info.CallArgIndex;
593     Result.Data = Saved;
594     break;
595   }
596 
597   case Sema::TDK_NonDeducedMismatch: {
598     // FIXME: Should allocate from normal heap so that we can free this later.
599     DFIArguments *Saved = new (Context) DFIArguments;
600     Saved->FirstArg = Info.FirstArg;
601     Saved->SecondArg = Info.SecondArg;
602     Result.Data = Saved;
603     break;
604   }
605 
606   case Sema::TDK_Inconsistent:
607   case Sema::TDK_Underqualified: {
608     // FIXME: Should allocate from normal heap so that we can free this later.
609     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
610     Saved->Param = Info.Param;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Result.Data = Saved;
614     break;
615   }
616 
617   case Sema::TDK_SubstitutionFailure:
618     Result.Data = Info.take();
619     if (Info.hasSFINAEDiagnostic()) {
620       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
621           SourceLocation(), PartialDiagnostic::NullDiagnostic());
622       Info.takeSFINAEDiagnostic(*Diag);
623       Result.HasDiagnostic = true;
624     }
625     break;
626 
627   case Sema::TDK_FailedOverloadResolution:
628     Result.Data = Info.Expression;
629     break;
630   }
631 
632   return Result;
633 }
634 
635 void DeductionFailureInfo::Destroy() {
636   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
637   case Sema::TDK_Success:
638   case Sema::TDK_Invalid:
639   case Sema::TDK_InstantiationDepth:
640   case Sema::TDK_Incomplete:
641   case Sema::TDK_TooManyArguments:
642   case Sema::TDK_TooFewArguments:
643   case Sema::TDK_InvalidExplicitArguments:
644   case Sema::TDK_FailedOverloadResolution:
645     break;
646 
647   case Sema::TDK_Inconsistent:
648   case Sema::TDK_Underqualified:
649   case Sema::TDK_DeducedMismatch:
650   case Sema::TDK_NonDeducedMismatch:
651     // FIXME: Destroy the data?
652     Data = nullptr;
653     break;
654 
655   case Sema::TDK_SubstitutionFailure:
656     // FIXME: Destroy the template argument list?
657     Data = nullptr;
658     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
659       Diag->~PartialDiagnosticAt();
660       HasDiagnostic = false;
661     }
662     break;
663 
664   // Unhandled
665   case Sema::TDK_MiscellaneousDeductionFailure:
666     break;
667   }
668 }
669 
670 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
671   if (HasDiagnostic)
672     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
673   return nullptr;
674 }
675 
676 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
677   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
678   case Sema::TDK_Success:
679   case Sema::TDK_Invalid:
680   case Sema::TDK_InstantiationDepth:
681   case Sema::TDK_TooManyArguments:
682   case Sema::TDK_TooFewArguments:
683   case Sema::TDK_SubstitutionFailure:
684   case Sema::TDK_DeducedMismatch:
685   case Sema::TDK_NonDeducedMismatch:
686   case Sema::TDK_FailedOverloadResolution:
687     return TemplateParameter();
688 
689   case Sema::TDK_Incomplete:
690   case Sema::TDK_InvalidExplicitArguments:
691     return TemplateParameter::getFromOpaqueValue(Data);
692 
693   case Sema::TDK_Inconsistent:
694   case Sema::TDK_Underqualified:
695     return static_cast<DFIParamWithArguments*>(Data)->Param;
696 
697   // Unhandled
698   case Sema::TDK_MiscellaneousDeductionFailure:
699     break;
700   }
701 
702   return TemplateParameter();
703 }
704 
705 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
706   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
707   case Sema::TDK_Success:
708   case Sema::TDK_Invalid:
709   case Sema::TDK_InstantiationDepth:
710   case Sema::TDK_TooManyArguments:
711   case Sema::TDK_TooFewArguments:
712   case Sema::TDK_Incomplete:
713   case Sema::TDK_InvalidExplicitArguments:
714   case Sema::TDK_Inconsistent:
715   case Sema::TDK_Underqualified:
716   case Sema::TDK_NonDeducedMismatch:
717   case Sema::TDK_FailedOverloadResolution:
718     return nullptr;
719 
720   case Sema::TDK_DeducedMismatch:
721     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
722 
723   case Sema::TDK_SubstitutionFailure:
724     return static_cast<TemplateArgumentList*>(Data);
725 
726   // Unhandled
727   case Sema::TDK_MiscellaneousDeductionFailure:
728     break;
729   }
730 
731   return nullptr;
732 }
733 
734 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
735   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736   case Sema::TDK_Success:
737   case Sema::TDK_Invalid:
738   case Sema::TDK_InstantiationDepth:
739   case Sema::TDK_Incomplete:
740   case Sema::TDK_TooManyArguments:
741   case Sema::TDK_TooFewArguments:
742   case Sema::TDK_InvalidExplicitArguments:
743   case Sema::TDK_SubstitutionFailure:
744   case Sema::TDK_FailedOverloadResolution:
745     return nullptr;
746 
747   case Sema::TDK_Inconsistent:
748   case Sema::TDK_Underqualified:
749   case Sema::TDK_DeducedMismatch:
750   case Sema::TDK_NonDeducedMismatch:
751     return &static_cast<DFIArguments*>(Data)->FirstArg;
752 
753   // Unhandled
754   case Sema::TDK_MiscellaneousDeductionFailure:
755     break;
756   }
757 
758   return nullptr;
759 }
760 
761 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
762   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
763   case Sema::TDK_Success:
764   case Sema::TDK_Invalid:
765   case Sema::TDK_InstantiationDepth:
766   case Sema::TDK_Incomplete:
767   case Sema::TDK_TooManyArguments:
768   case Sema::TDK_TooFewArguments:
769   case Sema::TDK_InvalidExplicitArguments:
770   case Sema::TDK_SubstitutionFailure:
771   case Sema::TDK_FailedOverloadResolution:
772     return nullptr;
773 
774   case Sema::TDK_Inconsistent:
775   case Sema::TDK_Underqualified:
776   case Sema::TDK_DeducedMismatch:
777   case Sema::TDK_NonDeducedMismatch:
778     return &static_cast<DFIArguments*>(Data)->SecondArg;
779 
780   // Unhandled
781   case Sema::TDK_MiscellaneousDeductionFailure:
782     break;
783   }
784 
785   return nullptr;
786 }
787 
788 Expr *DeductionFailureInfo::getExpr() {
789   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790         Sema::TDK_FailedOverloadResolution)
791     return static_cast<Expr*>(Data);
792 
793   return nullptr;
794 }
795 
796 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
797   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
798         Sema::TDK_DeducedMismatch)
799     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
800 
801   return llvm::None;
802 }
803 
804 void OverloadCandidateSet::destroyCandidates() {
805   for (iterator i = begin(), e = end(); i != e; ++i) {
806     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
807       i->Conversions[ii].~ImplicitConversionSequence();
808     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
809       i->DeductionFailure.Destroy();
810   }
811 }
812 
813 void OverloadCandidateSet::clear() {
814   destroyCandidates();
815   NumInlineSequences = 0;
816   Candidates.clear();
817   Functions.clear();
818 }
819 
820 namespace {
821   class UnbridgedCastsSet {
822     struct Entry {
823       Expr **Addr;
824       Expr *Saved;
825     };
826     SmallVector<Entry, 2> Entries;
827 
828   public:
829     void save(Sema &S, Expr *&E) {
830       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
831       Entry entry = { &E, E };
832       Entries.push_back(entry);
833       E = S.stripARCUnbridgedCast(E);
834     }
835 
836     void restore() {
837       for (SmallVectorImpl<Entry>::iterator
838              i = Entries.begin(), e = Entries.end(); i != e; ++i)
839         *i->Addr = i->Saved;
840     }
841   };
842 }
843 
844 /// checkPlaceholderForOverload - Do any interesting placeholder-like
845 /// preprocessing on the given expression.
846 ///
847 /// \param unbridgedCasts a collection to which to add unbridged casts;
848 ///   without this, they will be immediately diagnosed as errors
849 ///
850 /// Return true on unrecoverable error.
851 static bool
852 checkPlaceholderForOverload(Sema &S, Expr *&E,
853                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
854   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
855     // We can't handle overloaded expressions here because overload
856     // resolution might reasonably tweak them.
857     if (placeholder->getKind() == BuiltinType::Overload) return false;
858 
859     // If the context potentially accepts unbridged ARC casts, strip
860     // the unbridged cast and add it to the collection for later restoration.
861     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
862         unbridgedCasts) {
863       unbridgedCasts->save(S, E);
864       return false;
865     }
866 
867     // Go ahead and check everything else.
868     ExprResult result = S.CheckPlaceholderExpr(E);
869     if (result.isInvalid())
870       return true;
871 
872     E = result.get();
873     return false;
874   }
875 
876   // Nothing to do.
877   return false;
878 }
879 
880 /// checkArgPlaceholdersForOverload - Check a set of call operands for
881 /// placeholders.
882 static bool checkArgPlaceholdersForOverload(Sema &S,
883                                             MultiExprArg Args,
884                                             UnbridgedCastsSet &unbridged) {
885   for (unsigned i = 0, e = Args.size(); i != e; ++i)
886     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
887       return true;
888 
889   return false;
890 }
891 
892 // IsOverload - Determine whether the given New declaration is an
893 // overload of the declarations in Old. This routine returns false if
894 // New and Old cannot be overloaded, e.g., if New has the same
895 // signature as some function in Old (C++ 1.3.10) or if the Old
896 // declarations aren't functions (or function templates) at all. When
897 // it does return false, MatchedDecl will point to the decl that New
898 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
899 // top of the underlying declaration.
900 //
901 // Example: Given the following input:
902 //
903 //   void f(int, float); // #1
904 //   void f(int, int); // #2
905 //   int f(int, int); // #3
906 //
907 // When we process #1, there is no previous declaration of "f",
908 // so IsOverload will not be used.
909 //
910 // When we process #2, Old contains only the FunctionDecl for #1.  By
911 // comparing the parameter types, we see that #1 and #2 are overloaded
912 // (since they have different signatures), so this routine returns
913 // false; MatchedDecl is unchanged.
914 //
915 // When we process #3, Old is an overload set containing #1 and #2. We
916 // compare the signatures of #3 to #1 (they're overloaded, so we do
917 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
918 // identical (return types of functions are not part of the
919 // signature), IsOverload returns false and MatchedDecl will be set to
920 // point to the FunctionDecl for #2.
921 //
922 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
923 // into a class by a using declaration.  The rules for whether to hide
924 // shadow declarations ignore some properties which otherwise figure
925 // into a function template's signature.
926 Sema::OverloadKind
927 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
928                     NamedDecl *&Match, bool NewIsUsingDecl) {
929   for (LookupResult::iterator I = Old.begin(), E = Old.end();
930          I != E; ++I) {
931     NamedDecl *OldD = *I;
932 
933     bool OldIsUsingDecl = false;
934     if (isa<UsingShadowDecl>(OldD)) {
935       OldIsUsingDecl = true;
936 
937       // We can always introduce two using declarations into the same
938       // context, even if they have identical signatures.
939       if (NewIsUsingDecl) continue;
940 
941       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
942     }
943 
944     // A using-declaration does not conflict with another declaration
945     // if one of them is hidden.
946     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
947       continue;
948 
949     // If either declaration was introduced by a using declaration,
950     // we'll need to use slightly different rules for matching.
951     // Essentially, these rules are the normal rules, except that
952     // function templates hide function templates with different
953     // return types or template parameter lists.
954     bool UseMemberUsingDeclRules =
955       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
956       !New->getFriendObjectKind();
957 
958     if (FunctionDecl *OldF = OldD->getAsFunction()) {
959       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
960         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
961           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
962           continue;
963         }
964 
965         if (!isa<FunctionTemplateDecl>(OldD) &&
966             !shouldLinkPossiblyHiddenDecl(*I, New))
967           continue;
968 
969         Match = *I;
970         return Ovl_Match;
971       }
972     } else if (isa<UsingDecl>(OldD)) {
973       // We can overload with these, which can show up when doing
974       // redeclaration checks for UsingDecls.
975       assert(Old.getLookupKind() == LookupUsingDeclName);
976     } else if (isa<TagDecl>(OldD)) {
977       // We can always overload with tags by hiding them.
978     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
979       // Optimistically assume that an unresolved using decl will
980       // overload; if it doesn't, we'll have to diagnose during
981       // template instantiation.
982     } else {
983       // (C++ 13p1):
984       //   Only function declarations can be overloaded; object and type
985       //   declarations cannot be overloaded.
986       Match = *I;
987       return Ovl_NonFunction;
988     }
989   }
990 
991   return Ovl_Overload;
992 }
993 
994 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
995                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
996   // C++ [basic.start.main]p2: This function shall not be overloaded.
997   if (New->isMain())
998     return false;
999 
1000   // MSVCRT user defined entry points cannot be overloaded.
1001   if (New->isMSVCRTEntryPoint())
1002     return false;
1003 
1004   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1005   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1006 
1007   // C++ [temp.fct]p2:
1008   //   A function template can be overloaded with other function templates
1009   //   and with normal (non-template) functions.
1010   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1011     return true;
1012 
1013   // Is the function New an overload of the function Old?
1014   QualType OldQType = Context.getCanonicalType(Old->getType());
1015   QualType NewQType = Context.getCanonicalType(New->getType());
1016 
1017   // Compare the signatures (C++ 1.3.10) of the two functions to
1018   // determine whether they are overloads. If we find any mismatch
1019   // in the signature, they are overloads.
1020 
1021   // If either of these functions is a K&R-style function (no
1022   // prototype), then we consider them to have matching signatures.
1023   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1024       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1025     return false;
1026 
1027   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1028   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1029 
1030   // The signature of a function includes the types of its
1031   // parameters (C++ 1.3.10), which includes the presence or absence
1032   // of the ellipsis; see C++ DR 357).
1033   if (OldQType != NewQType &&
1034       (OldType->getNumParams() != NewType->getNumParams() ||
1035        OldType->isVariadic() != NewType->isVariadic() ||
1036        !FunctionParamTypesAreEqual(OldType, NewType)))
1037     return true;
1038 
1039   // C++ [temp.over.link]p4:
1040   //   The signature of a function template consists of its function
1041   //   signature, its return type and its template parameter list. The names
1042   //   of the template parameters are significant only for establishing the
1043   //   relationship between the template parameters and the rest of the
1044   //   signature.
1045   //
1046   // We check the return type and template parameter lists for function
1047   // templates first; the remaining checks follow.
1048   //
1049   // However, we don't consider either of these when deciding whether
1050   // a member introduced by a shadow declaration is hidden.
1051   if (!UseMemberUsingDeclRules && NewTemplate &&
1052       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1053                                        OldTemplate->getTemplateParameters(),
1054                                        false, TPL_TemplateMatch) ||
1055        OldType->getReturnType() != NewType->getReturnType()))
1056     return true;
1057 
1058   // If the function is a class member, its signature includes the
1059   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1060   //
1061   // As part of this, also check whether one of the member functions
1062   // is static, in which case they are not overloads (C++
1063   // 13.1p2). While not part of the definition of the signature,
1064   // this check is important to determine whether these functions
1065   // can be overloaded.
1066   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1067   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1068   if (OldMethod && NewMethod &&
1069       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1070     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1071       if (!UseMemberUsingDeclRules &&
1072           (OldMethod->getRefQualifier() == RQ_None ||
1073            NewMethod->getRefQualifier() == RQ_None)) {
1074         // C++0x [over.load]p2:
1075         //   - Member function declarations with the same name and the same
1076         //     parameter-type-list as well as member function template
1077         //     declarations with the same name, the same parameter-type-list, and
1078         //     the same template parameter lists cannot be overloaded if any of
1079         //     them, but not all, have a ref-qualifier (8.3.5).
1080         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1081           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1082         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1083       }
1084       return true;
1085     }
1086 
1087     // We may not have applied the implicit const for a constexpr member
1088     // function yet (because we haven't yet resolved whether this is a static
1089     // or non-static member function). Add it now, on the assumption that this
1090     // is a redeclaration of OldMethod.
1091     unsigned OldQuals = OldMethod->getTypeQualifiers();
1092     unsigned NewQuals = NewMethod->getTypeQualifiers();
1093     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1094         !isa<CXXConstructorDecl>(NewMethod))
1095       NewQuals |= Qualifiers::Const;
1096 
1097     // We do not allow overloading based off of '__restrict'.
1098     OldQuals &= ~Qualifiers::Restrict;
1099     NewQuals &= ~Qualifiers::Restrict;
1100     if (OldQuals != NewQuals)
1101       return true;
1102   }
1103 
1104   // Though pass_object_size is placed on parameters and takes an argument, we
1105   // consider it to be a function-level modifier for the sake of function
1106   // identity. Either the function has one or more parameters with
1107   // pass_object_size or it doesn't.
1108   if (functionHasPassObjectSizeParams(New) !=
1109       functionHasPassObjectSizeParams(Old))
1110     return true;
1111 
1112   // enable_if attributes are an order-sensitive part of the signature.
1113   for (specific_attr_iterator<EnableIfAttr>
1114          NewI = New->specific_attr_begin<EnableIfAttr>(),
1115          NewE = New->specific_attr_end<EnableIfAttr>(),
1116          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1117          OldE = Old->specific_attr_end<EnableIfAttr>();
1118        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1119     if (NewI == NewE || OldI == OldE)
1120       return true;
1121     llvm::FoldingSetNodeID NewID, OldID;
1122     NewI->getCond()->Profile(NewID, Context, true);
1123     OldI->getCond()->Profile(OldID, Context, true);
1124     if (NewID != OldID)
1125       return true;
1126   }
1127 
1128   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1129     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1130                        OldTarget = IdentifyCUDATarget(Old);
1131     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1132       return false;
1133 
1134     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1135 
1136     // Don't allow mixing of HD with other kinds. This guarantees that
1137     // we have only one viable function with this signature on any
1138     // side of CUDA compilation .
1139     // __global__ functions can't be overloaded based on attribute
1140     // difference because, like HD, they also exist on both sides.
1141     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1142         (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1143       return false;
1144 
1145     // Allow overloading of functions with same signature, but
1146     // different CUDA target attributes.
1147     return NewTarget != OldTarget;
1148   }
1149 
1150   // The signatures match; this is not an overload.
1151   return false;
1152 }
1153 
1154 /// \brief Checks availability of the function depending on the current
1155 /// function context. Inside an unavailable function, unavailability is ignored.
1156 ///
1157 /// \returns true if \arg FD is unavailable and current context is inside
1158 /// an available function, false otherwise.
1159 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1160   if (!FD->isUnavailable())
1161     return false;
1162 
1163   // Walk up the context of the caller.
1164   Decl *C = cast<Decl>(CurContext);
1165   do {
1166     if (C->isUnavailable())
1167       return false;
1168   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1169   return true;
1170 }
1171 
1172 /// \brief Tries a user-defined conversion from From to ToType.
1173 ///
1174 /// Produces an implicit conversion sequence for when a standard conversion
1175 /// is not an option. See TryImplicitConversion for more information.
1176 static ImplicitConversionSequence
1177 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1178                          bool SuppressUserConversions,
1179                          bool AllowExplicit,
1180                          bool InOverloadResolution,
1181                          bool CStyle,
1182                          bool AllowObjCWritebackConversion,
1183                          bool AllowObjCConversionOnExplicit) {
1184   ImplicitConversionSequence ICS;
1185 
1186   if (SuppressUserConversions) {
1187     // We're not in the case above, so there is no conversion that
1188     // we can perform.
1189     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1190     return ICS;
1191   }
1192 
1193   // Attempt user-defined conversion.
1194   OverloadCandidateSet Conversions(From->getExprLoc(),
1195                                    OverloadCandidateSet::CSK_Normal);
1196   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1197                                   Conversions, AllowExplicit,
1198                                   AllowObjCConversionOnExplicit)) {
1199   case OR_Success:
1200   case OR_Deleted:
1201     ICS.setUserDefined();
1202     ICS.UserDefined.Before.setAsIdentityConversion();
1203     // C++ [over.ics.user]p4:
1204     //   A conversion of an expression of class type to the same class
1205     //   type is given Exact Match rank, and a conversion of an
1206     //   expression of class type to a base class of that type is
1207     //   given Conversion rank, in spite of the fact that a copy
1208     //   constructor (i.e., a user-defined conversion function) is
1209     //   called for those cases.
1210     if (CXXConstructorDecl *Constructor
1211           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1212       QualType FromCanon
1213         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1214       QualType ToCanon
1215         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1216       if (Constructor->isCopyConstructor() &&
1217           (FromCanon == ToCanon ||
1218            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1219         // Turn this into a "standard" conversion sequence, so that it
1220         // gets ranked with standard conversion sequences.
1221         ICS.setStandard();
1222         ICS.Standard.setAsIdentityConversion();
1223         ICS.Standard.setFromType(From->getType());
1224         ICS.Standard.setAllToTypes(ToType);
1225         ICS.Standard.CopyConstructor = Constructor;
1226         if (ToCanon != FromCanon)
1227           ICS.Standard.Second = ICK_Derived_To_Base;
1228       }
1229     }
1230     break;
1231 
1232   case OR_Ambiguous:
1233     ICS.setAmbiguous();
1234     ICS.Ambiguous.setFromType(From->getType());
1235     ICS.Ambiguous.setToType(ToType);
1236     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1237          Cand != Conversions.end(); ++Cand)
1238       if (Cand->Viable)
1239         ICS.Ambiguous.addConversion(Cand->Function);
1240     break;
1241 
1242     // Fall through.
1243   case OR_No_Viable_Function:
1244     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1245     break;
1246   }
1247 
1248   return ICS;
1249 }
1250 
1251 /// TryImplicitConversion - Attempt to perform an implicit conversion
1252 /// from the given expression (Expr) to the given type (ToType). This
1253 /// function returns an implicit conversion sequence that can be used
1254 /// to perform the initialization. Given
1255 ///
1256 ///   void f(float f);
1257 ///   void g(int i) { f(i); }
1258 ///
1259 /// this routine would produce an implicit conversion sequence to
1260 /// describe the initialization of f from i, which will be a standard
1261 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1262 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1263 //
1264 /// Note that this routine only determines how the conversion can be
1265 /// performed; it does not actually perform the conversion. As such,
1266 /// it will not produce any diagnostics if no conversion is available,
1267 /// but will instead return an implicit conversion sequence of kind
1268 /// "BadConversion".
1269 ///
1270 /// If @p SuppressUserConversions, then user-defined conversions are
1271 /// not permitted.
1272 /// If @p AllowExplicit, then explicit user-defined conversions are
1273 /// permitted.
1274 ///
1275 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1276 /// writeback conversion, which allows __autoreleasing id* parameters to
1277 /// be initialized with __strong id* or __weak id* arguments.
1278 static ImplicitConversionSequence
1279 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1280                       bool SuppressUserConversions,
1281                       bool AllowExplicit,
1282                       bool InOverloadResolution,
1283                       bool CStyle,
1284                       bool AllowObjCWritebackConversion,
1285                       bool AllowObjCConversionOnExplicit) {
1286   ImplicitConversionSequence ICS;
1287   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1288                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1289     ICS.setStandard();
1290     return ICS;
1291   }
1292 
1293   if (!S.getLangOpts().CPlusPlus) {
1294     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1295     return ICS;
1296   }
1297 
1298   // C++ [over.ics.user]p4:
1299   //   A conversion of an expression of class type to the same class
1300   //   type is given Exact Match rank, and a conversion of an
1301   //   expression of class type to a base class of that type is
1302   //   given Conversion rank, in spite of the fact that a copy/move
1303   //   constructor (i.e., a user-defined conversion function) is
1304   //   called for those cases.
1305   QualType FromType = From->getType();
1306   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1307       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1308        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1309     ICS.setStandard();
1310     ICS.Standard.setAsIdentityConversion();
1311     ICS.Standard.setFromType(FromType);
1312     ICS.Standard.setAllToTypes(ToType);
1313 
1314     // We don't actually check at this point whether there is a valid
1315     // copy/move constructor, since overloading just assumes that it
1316     // exists. When we actually perform initialization, we'll find the
1317     // appropriate constructor to copy the returned object, if needed.
1318     ICS.Standard.CopyConstructor = nullptr;
1319 
1320     // Determine whether this is considered a derived-to-base conversion.
1321     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1322       ICS.Standard.Second = ICK_Derived_To_Base;
1323 
1324     return ICS;
1325   }
1326 
1327   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1328                                   AllowExplicit, InOverloadResolution, CStyle,
1329                                   AllowObjCWritebackConversion,
1330                                   AllowObjCConversionOnExplicit);
1331 }
1332 
1333 ImplicitConversionSequence
1334 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1335                             bool SuppressUserConversions,
1336                             bool AllowExplicit,
1337                             bool InOverloadResolution,
1338                             bool CStyle,
1339                             bool AllowObjCWritebackConversion) {
1340   return ::TryImplicitConversion(*this, From, ToType,
1341                                  SuppressUserConversions, AllowExplicit,
1342                                  InOverloadResolution, CStyle,
1343                                  AllowObjCWritebackConversion,
1344                                  /*AllowObjCConversionOnExplicit=*/false);
1345 }
1346 
1347 /// PerformImplicitConversion - Perform an implicit conversion of the
1348 /// expression From to the type ToType. Returns the
1349 /// converted expression. Flavor is the kind of conversion we're
1350 /// performing, used in the error message. If @p AllowExplicit,
1351 /// explicit user-defined conversions are permitted.
1352 ExprResult
1353 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1354                                 AssignmentAction Action, bool AllowExplicit) {
1355   ImplicitConversionSequence ICS;
1356   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1357 }
1358 
1359 ExprResult
1360 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1361                                 AssignmentAction Action, bool AllowExplicit,
1362                                 ImplicitConversionSequence& ICS) {
1363   if (checkPlaceholderForOverload(*this, From))
1364     return ExprError();
1365 
1366   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1367   bool AllowObjCWritebackConversion
1368     = getLangOpts().ObjCAutoRefCount &&
1369       (Action == AA_Passing || Action == AA_Sending);
1370   if (getLangOpts().ObjC1)
1371     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1372                                       ToType, From->getType(), From);
1373   ICS = ::TryImplicitConversion(*this, From, ToType,
1374                                 /*SuppressUserConversions=*/false,
1375                                 AllowExplicit,
1376                                 /*InOverloadResolution=*/false,
1377                                 /*CStyle=*/false,
1378                                 AllowObjCWritebackConversion,
1379                                 /*AllowObjCConversionOnExplicit=*/false);
1380   return PerformImplicitConversion(From, ToType, ICS, Action);
1381 }
1382 
1383 /// \brief Determine whether the conversion from FromType to ToType is a valid
1384 /// conversion that strips "noreturn" off the nested function type.
1385 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1386                                 QualType &ResultTy) {
1387   if (Context.hasSameUnqualifiedType(FromType, ToType))
1388     return false;
1389 
1390   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1391   // where F adds one of the following at most once:
1392   //   - a pointer
1393   //   - a member pointer
1394   //   - a block pointer
1395   CanQualType CanTo = Context.getCanonicalType(ToType);
1396   CanQualType CanFrom = Context.getCanonicalType(FromType);
1397   Type::TypeClass TyClass = CanTo->getTypeClass();
1398   if (TyClass != CanFrom->getTypeClass()) return false;
1399   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1400     if (TyClass == Type::Pointer) {
1401       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1402       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1403     } else if (TyClass == Type::BlockPointer) {
1404       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1405       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1406     } else if (TyClass == Type::MemberPointer) {
1407       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1408       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1409     } else {
1410       return false;
1411     }
1412 
1413     TyClass = CanTo->getTypeClass();
1414     if (TyClass != CanFrom->getTypeClass()) return false;
1415     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1416       return false;
1417   }
1418 
1419   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1420   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1421   if (!EInfo.getNoReturn()) return false;
1422 
1423   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1424   assert(QualType(FromFn, 0).isCanonical());
1425   if (QualType(FromFn, 0) != CanTo) return false;
1426 
1427   ResultTy = ToType;
1428   return true;
1429 }
1430 
1431 /// \brief Determine whether the conversion from FromType to ToType is a valid
1432 /// vector conversion.
1433 ///
1434 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1435 /// conversion.
1436 static bool IsVectorConversion(Sema &S, QualType FromType,
1437                                QualType ToType, ImplicitConversionKind &ICK) {
1438   // We need at least one of these types to be a vector type to have a vector
1439   // conversion.
1440   if (!ToType->isVectorType() && !FromType->isVectorType())
1441     return false;
1442 
1443   // Identical types require no conversions.
1444   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1445     return false;
1446 
1447   // There are no conversions between extended vector types, only identity.
1448   if (ToType->isExtVectorType()) {
1449     // There are no conversions between extended vector types other than the
1450     // identity conversion.
1451     if (FromType->isExtVectorType())
1452       return false;
1453 
1454     // Vector splat from any arithmetic type to a vector.
1455     if (FromType->isArithmeticType()) {
1456       ICK = ICK_Vector_Splat;
1457       return true;
1458     }
1459   }
1460 
1461   // We can perform the conversion between vector types in the following cases:
1462   // 1)vector types are equivalent AltiVec and GCC vector types
1463   // 2)lax vector conversions are permitted and the vector types are of the
1464   //   same size
1465   if (ToType->isVectorType() && FromType->isVectorType()) {
1466     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1467         S.isLaxVectorConversion(FromType, ToType)) {
1468       ICK = ICK_Vector_Conversion;
1469       return true;
1470     }
1471   }
1472 
1473   return false;
1474 }
1475 
1476 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1477                                 bool InOverloadResolution,
1478                                 StandardConversionSequence &SCS,
1479                                 bool CStyle);
1480 
1481 /// IsStandardConversion - Determines whether there is a standard
1482 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1483 /// expression From to the type ToType. Standard conversion sequences
1484 /// only consider non-class types; for conversions that involve class
1485 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1486 /// contain the standard conversion sequence required to perform this
1487 /// conversion and this routine will return true. Otherwise, this
1488 /// routine will return false and the value of SCS is unspecified.
1489 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1490                                  bool InOverloadResolution,
1491                                  StandardConversionSequence &SCS,
1492                                  bool CStyle,
1493                                  bool AllowObjCWritebackConversion) {
1494   QualType FromType = From->getType();
1495 
1496   // Standard conversions (C++ [conv])
1497   SCS.setAsIdentityConversion();
1498   SCS.IncompatibleObjC = false;
1499   SCS.setFromType(FromType);
1500   SCS.CopyConstructor = nullptr;
1501 
1502   // There are no standard conversions for class types in C++, so
1503   // abort early. When overloading in C, however, we do permit them.
1504   if (S.getLangOpts().CPlusPlus &&
1505       (FromType->isRecordType() || ToType->isRecordType()))
1506     return false;
1507 
1508   // The first conversion can be an lvalue-to-rvalue conversion,
1509   // array-to-pointer conversion, or function-to-pointer conversion
1510   // (C++ 4p1).
1511 
1512   if (FromType == S.Context.OverloadTy) {
1513     DeclAccessPair AccessPair;
1514     if (FunctionDecl *Fn
1515           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1516                                                  AccessPair)) {
1517       // We were able to resolve the address of the overloaded function,
1518       // so we can convert to the type of that function.
1519       FromType = Fn->getType();
1520       SCS.setFromType(FromType);
1521 
1522       // we can sometimes resolve &foo<int> regardless of ToType, so check
1523       // if the type matches (identity) or we are converting to bool
1524       if (!S.Context.hasSameUnqualifiedType(
1525                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1526         QualType resultTy;
1527         // if the function type matches except for [[noreturn]], it's ok
1528         if (!S.IsNoReturnConversion(FromType,
1529               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1530           // otherwise, only a boolean conversion is standard
1531           if (!ToType->isBooleanType())
1532             return false;
1533       }
1534 
1535       // Check if the "from" expression is taking the address of an overloaded
1536       // function and recompute the FromType accordingly. Take advantage of the
1537       // fact that non-static member functions *must* have such an address-of
1538       // expression.
1539       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1540       if (Method && !Method->isStatic()) {
1541         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1542                "Non-unary operator on non-static member address");
1543         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1544                == UO_AddrOf &&
1545                "Non-address-of operator on non-static member address");
1546         const Type *ClassType
1547           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1548         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1549       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1550         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1551                UO_AddrOf &&
1552                "Non-address-of operator for overloaded function expression");
1553         FromType = S.Context.getPointerType(FromType);
1554       }
1555 
1556       // Check that we've computed the proper type after overload resolution.
1557       assert(S.Context.hasSameType(
1558         FromType,
1559         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1560     } else {
1561       return false;
1562     }
1563   }
1564   // Lvalue-to-rvalue conversion (C++11 4.1):
1565   //   A glvalue (3.10) of a non-function, non-array type T can
1566   //   be converted to a prvalue.
1567   bool argIsLValue = From->isGLValue();
1568   if (argIsLValue &&
1569       !FromType->isFunctionType() && !FromType->isArrayType() &&
1570       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1571     SCS.First = ICK_Lvalue_To_Rvalue;
1572 
1573     // C11 6.3.2.1p2:
1574     //   ... if the lvalue has atomic type, the value has the non-atomic version
1575     //   of the type of the lvalue ...
1576     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1577       FromType = Atomic->getValueType();
1578 
1579     // If T is a non-class type, the type of the rvalue is the
1580     // cv-unqualified version of T. Otherwise, the type of the rvalue
1581     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1582     // just strip the qualifiers because they don't matter.
1583     FromType = FromType.getUnqualifiedType();
1584   } else if (FromType->isArrayType()) {
1585     // Array-to-pointer conversion (C++ 4.2)
1586     SCS.First = ICK_Array_To_Pointer;
1587 
1588     // An lvalue or rvalue of type "array of N T" or "array of unknown
1589     // bound of T" can be converted to an rvalue of type "pointer to
1590     // T" (C++ 4.2p1).
1591     FromType = S.Context.getArrayDecayedType(FromType);
1592 
1593     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1594       // This conversion is deprecated in C++03 (D.4)
1595       SCS.DeprecatedStringLiteralToCharPtr = true;
1596 
1597       // For the purpose of ranking in overload resolution
1598       // (13.3.3.1.1), this conversion is considered an
1599       // array-to-pointer conversion followed by a qualification
1600       // conversion (4.4). (C++ 4.2p2)
1601       SCS.Second = ICK_Identity;
1602       SCS.Third = ICK_Qualification;
1603       SCS.QualificationIncludesObjCLifetime = false;
1604       SCS.setAllToTypes(FromType);
1605       return true;
1606     }
1607   } else if (FromType->isFunctionType() && argIsLValue) {
1608     // Function-to-pointer conversion (C++ 4.3).
1609     SCS.First = ICK_Function_To_Pointer;
1610 
1611     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1612       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1613         if (!S.checkAddressOfFunctionIsAvailable(FD))
1614           return false;
1615 
1616     // An lvalue of function type T can be converted to an rvalue of
1617     // type "pointer to T." The result is a pointer to the
1618     // function. (C++ 4.3p1).
1619     FromType = S.Context.getPointerType(FromType);
1620   } else {
1621     // We don't require any conversions for the first step.
1622     SCS.First = ICK_Identity;
1623   }
1624   SCS.setToType(0, FromType);
1625 
1626   // The second conversion can be an integral promotion, floating
1627   // point promotion, integral conversion, floating point conversion,
1628   // floating-integral conversion, pointer conversion,
1629   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1630   // For overloading in C, this can also be a "compatible-type"
1631   // conversion.
1632   bool IncompatibleObjC = false;
1633   ImplicitConversionKind SecondICK = ICK_Identity;
1634   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1635     // The unqualified versions of the types are the same: there's no
1636     // conversion to do.
1637     SCS.Second = ICK_Identity;
1638   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1639     // Integral promotion (C++ 4.5).
1640     SCS.Second = ICK_Integral_Promotion;
1641     FromType = ToType.getUnqualifiedType();
1642   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1643     // Floating point promotion (C++ 4.6).
1644     SCS.Second = ICK_Floating_Promotion;
1645     FromType = ToType.getUnqualifiedType();
1646   } else if (S.IsComplexPromotion(FromType, ToType)) {
1647     // Complex promotion (Clang extension)
1648     SCS.Second = ICK_Complex_Promotion;
1649     FromType = ToType.getUnqualifiedType();
1650   } else if (ToType->isBooleanType() &&
1651              (FromType->isArithmeticType() ||
1652               FromType->isAnyPointerType() ||
1653               FromType->isBlockPointerType() ||
1654               FromType->isMemberPointerType() ||
1655               FromType->isNullPtrType())) {
1656     // Boolean conversions (C++ 4.12).
1657     SCS.Second = ICK_Boolean_Conversion;
1658     FromType = S.Context.BoolTy;
1659   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1660              ToType->isIntegralType(S.Context)) {
1661     // Integral conversions (C++ 4.7).
1662     SCS.Second = ICK_Integral_Conversion;
1663     FromType = ToType.getUnqualifiedType();
1664   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1665     // Complex conversions (C99 6.3.1.6)
1666     SCS.Second = ICK_Complex_Conversion;
1667     FromType = ToType.getUnqualifiedType();
1668   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1669              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1670     // Complex-real conversions (C99 6.3.1.7)
1671     SCS.Second = ICK_Complex_Real;
1672     FromType = ToType.getUnqualifiedType();
1673   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1674     // Floating point conversions (C++ 4.8).
1675     SCS.Second = ICK_Floating_Conversion;
1676     FromType = ToType.getUnqualifiedType();
1677   } else if ((FromType->isRealFloatingType() &&
1678               ToType->isIntegralType(S.Context)) ||
1679              (FromType->isIntegralOrUnscopedEnumerationType() &&
1680               ToType->isRealFloatingType())) {
1681     // Floating-integral conversions (C++ 4.9).
1682     SCS.Second = ICK_Floating_Integral;
1683     FromType = ToType.getUnqualifiedType();
1684   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1685     SCS.Second = ICK_Block_Pointer_Conversion;
1686   } else if (AllowObjCWritebackConversion &&
1687              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1688     SCS.Second = ICK_Writeback_Conversion;
1689   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1690                                    FromType, IncompatibleObjC)) {
1691     // Pointer conversions (C++ 4.10).
1692     SCS.Second = ICK_Pointer_Conversion;
1693     SCS.IncompatibleObjC = IncompatibleObjC;
1694     FromType = FromType.getUnqualifiedType();
1695   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1696                                          InOverloadResolution, FromType)) {
1697     // Pointer to member conversions (4.11).
1698     SCS.Second = ICK_Pointer_Member;
1699   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1700     SCS.Second = SecondICK;
1701     FromType = ToType.getUnqualifiedType();
1702   } else if (!S.getLangOpts().CPlusPlus &&
1703              S.Context.typesAreCompatible(ToType, FromType)) {
1704     // Compatible conversions (Clang extension for C function overloading)
1705     SCS.Second = ICK_Compatible_Conversion;
1706     FromType = ToType.getUnqualifiedType();
1707   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1708     // Treat a conversion that strips "noreturn" as an identity conversion.
1709     SCS.Second = ICK_NoReturn_Adjustment;
1710   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1711                                              InOverloadResolution,
1712                                              SCS, CStyle)) {
1713     SCS.Second = ICK_TransparentUnionConversion;
1714     FromType = ToType;
1715   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1716                                  CStyle)) {
1717     // tryAtomicConversion has updated the standard conversion sequence
1718     // appropriately.
1719     return true;
1720   } else if (ToType->isEventT() &&
1721              From->isIntegerConstantExpr(S.getASTContext()) &&
1722              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1723     SCS.Second = ICK_Zero_Event_Conversion;
1724     FromType = ToType;
1725   } else {
1726     // No second conversion required.
1727     SCS.Second = ICK_Identity;
1728   }
1729   SCS.setToType(1, FromType);
1730 
1731   QualType CanonFrom;
1732   QualType CanonTo;
1733   // The third conversion can be a qualification conversion (C++ 4p1).
1734   bool ObjCLifetimeConversion;
1735   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1736                                   ObjCLifetimeConversion)) {
1737     SCS.Third = ICK_Qualification;
1738     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1739     FromType = ToType;
1740     CanonFrom = S.Context.getCanonicalType(FromType);
1741     CanonTo = S.Context.getCanonicalType(ToType);
1742   } else {
1743     // No conversion required
1744     SCS.Third = ICK_Identity;
1745 
1746     // C++ [over.best.ics]p6:
1747     //   [...] Any difference in top-level cv-qualification is
1748     //   subsumed by the initialization itself and does not constitute
1749     //   a conversion. [...]
1750     CanonFrom = S.Context.getCanonicalType(FromType);
1751     CanonTo = S.Context.getCanonicalType(ToType);
1752     if (CanonFrom.getLocalUnqualifiedType()
1753                                        == CanonTo.getLocalUnqualifiedType() &&
1754         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1755       FromType = ToType;
1756       CanonFrom = CanonTo;
1757     }
1758   }
1759   SCS.setToType(2, FromType);
1760 
1761   if (CanonFrom == CanonTo)
1762     return true;
1763 
1764   // If we have not converted the argument type to the parameter type,
1765   // this is a bad conversion sequence, unless we're resolving an overload in C.
1766   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1767     return false;
1768 
1769   ExprResult ER = ExprResult{From};
1770   auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1771                                                  /*Diagnose=*/false,
1772                                                  /*DiagnoseCFAudited=*/false,
1773                                                  /*ConvertRHS=*/false);
1774   if (Conv != Sema::Compatible)
1775     return false;
1776 
1777   SCS.setAllToTypes(ToType);
1778   // We need to set all three because we want this conversion to rank terribly,
1779   // and we don't know what conversions it may overlap with.
1780   SCS.First = ICK_C_Only_Conversion;
1781   SCS.Second = ICK_C_Only_Conversion;
1782   SCS.Third = ICK_C_Only_Conversion;
1783   return true;
1784 }
1785 
1786 static bool
1787 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1788                                      QualType &ToType,
1789                                      bool InOverloadResolution,
1790                                      StandardConversionSequence &SCS,
1791                                      bool CStyle) {
1792 
1793   const RecordType *UT = ToType->getAsUnionType();
1794   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1795     return false;
1796   // The field to initialize within the transparent union.
1797   RecordDecl *UD = UT->getDecl();
1798   // It's compatible if the expression matches any of the fields.
1799   for (const auto *it : UD->fields()) {
1800     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1801                              CStyle, /*ObjCWritebackConversion=*/false)) {
1802       ToType = it->getType();
1803       return true;
1804     }
1805   }
1806   return false;
1807 }
1808 
1809 /// IsIntegralPromotion - Determines whether the conversion from the
1810 /// expression From (whose potentially-adjusted type is FromType) to
1811 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1812 /// sets PromotedType to the promoted type.
1813 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1814   const BuiltinType *To = ToType->getAs<BuiltinType>();
1815   // All integers are built-in.
1816   if (!To) {
1817     return false;
1818   }
1819 
1820   // An rvalue of type char, signed char, unsigned char, short int, or
1821   // unsigned short int can be converted to an rvalue of type int if
1822   // int can represent all the values of the source type; otherwise,
1823   // the source rvalue can be converted to an rvalue of type unsigned
1824   // int (C++ 4.5p1).
1825   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1826       !FromType->isEnumeralType()) {
1827     if (// We can promote any signed, promotable integer type to an int
1828         (FromType->isSignedIntegerType() ||
1829          // We can promote any unsigned integer type whose size is
1830          // less than int to an int.
1831          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1832       return To->getKind() == BuiltinType::Int;
1833     }
1834 
1835     return To->getKind() == BuiltinType::UInt;
1836   }
1837 
1838   // C++11 [conv.prom]p3:
1839   //   A prvalue of an unscoped enumeration type whose underlying type is not
1840   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1841   //   following types that can represent all the values of the enumeration
1842   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1843   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1844   //   long long int. If none of the types in that list can represent all the
1845   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1846   //   type can be converted to an rvalue a prvalue of the extended integer type
1847   //   with lowest integer conversion rank (4.13) greater than the rank of long
1848   //   long in which all the values of the enumeration can be represented. If
1849   //   there are two such extended types, the signed one is chosen.
1850   // C++11 [conv.prom]p4:
1851   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1852   //   can be converted to a prvalue of its underlying type. Moreover, if
1853   //   integral promotion can be applied to its underlying type, a prvalue of an
1854   //   unscoped enumeration type whose underlying type is fixed can also be
1855   //   converted to a prvalue of the promoted underlying type.
1856   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1857     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1858     // provided for a scoped enumeration.
1859     if (FromEnumType->getDecl()->isScoped())
1860       return false;
1861 
1862     // We can perform an integral promotion to the underlying type of the enum,
1863     // even if that's not the promoted type. Note that the check for promoting
1864     // the underlying type is based on the type alone, and does not consider
1865     // the bitfield-ness of the actual source expression.
1866     if (FromEnumType->getDecl()->isFixed()) {
1867       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1868       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1869              IsIntegralPromotion(nullptr, Underlying, ToType);
1870     }
1871 
1872     // We have already pre-calculated the promotion type, so this is trivial.
1873     if (ToType->isIntegerType() &&
1874         isCompleteType(From->getLocStart(), FromType))
1875       return Context.hasSameUnqualifiedType(
1876           ToType, FromEnumType->getDecl()->getPromotionType());
1877   }
1878 
1879   // C++0x [conv.prom]p2:
1880   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1881   //   to an rvalue a prvalue of the first of the following types that can
1882   //   represent all the values of its underlying type: int, unsigned int,
1883   //   long int, unsigned long int, long long int, or unsigned long long int.
1884   //   If none of the types in that list can represent all the values of its
1885   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1886   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1887   //   type.
1888   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1889       ToType->isIntegerType()) {
1890     // Determine whether the type we're converting from is signed or
1891     // unsigned.
1892     bool FromIsSigned = FromType->isSignedIntegerType();
1893     uint64_t FromSize = Context.getTypeSize(FromType);
1894 
1895     // The types we'll try to promote to, in the appropriate
1896     // order. Try each of these types.
1897     QualType PromoteTypes[6] = {
1898       Context.IntTy, Context.UnsignedIntTy,
1899       Context.LongTy, Context.UnsignedLongTy ,
1900       Context.LongLongTy, Context.UnsignedLongLongTy
1901     };
1902     for (int Idx = 0; Idx < 6; ++Idx) {
1903       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1904       if (FromSize < ToSize ||
1905           (FromSize == ToSize &&
1906            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1907         // We found the type that we can promote to. If this is the
1908         // type we wanted, we have a promotion. Otherwise, no
1909         // promotion.
1910         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1911       }
1912     }
1913   }
1914 
1915   // An rvalue for an integral bit-field (9.6) can be converted to an
1916   // rvalue of type int if int can represent all the values of the
1917   // bit-field; otherwise, it can be converted to unsigned int if
1918   // unsigned int can represent all the values of the bit-field. If
1919   // the bit-field is larger yet, no integral promotion applies to
1920   // it. If the bit-field has an enumerated type, it is treated as any
1921   // other value of that type for promotion purposes (C++ 4.5p3).
1922   // FIXME: We should delay checking of bit-fields until we actually perform the
1923   // conversion.
1924   if (From) {
1925     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1926       llvm::APSInt BitWidth;
1927       if (FromType->isIntegralType(Context) &&
1928           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1929         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1930         ToSize = Context.getTypeSize(ToType);
1931 
1932         // Are we promoting to an int from a bitfield that fits in an int?
1933         if (BitWidth < ToSize ||
1934             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1935           return To->getKind() == BuiltinType::Int;
1936         }
1937 
1938         // Are we promoting to an unsigned int from an unsigned bitfield
1939         // that fits into an unsigned int?
1940         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1941           return To->getKind() == BuiltinType::UInt;
1942         }
1943 
1944         return false;
1945       }
1946     }
1947   }
1948 
1949   // An rvalue of type bool can be converted to an rvalue of type int,
1950   // with false becoming zero and true becoming one (C++ 4.5p4).
1951   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1952     return true;
1953   }
1954 
1955   return false;
1956 }
1957 
1958 /// IsFloatingPointPromotion - Determines whether the conversion from
1959 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1960 /// returns true and sets PromotedType to the promoted type.
1961 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1962   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1963     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1964       /// An rvalue of type float can be converted to an rvalue of type
1965       /// double. (C++ 4.6p1).
1966       if (FromBuiltin->getKind() == BuiltinType::Float &&
1967           ToBuiltin->getKind() == BuiltinType::Double)
1968         return true;
1969 
1970       // C99 6.3.1.5p1:
1971       //   When a float is promoted to double or long double, or a
1972       //   double is promoted to long double [...].
1973       if (!getLangOpts().CPlusPlus &&
1974           (FromBuiltin->getKind() == BuiltinType::Float ||
1975            FromBuiltin->getKind() == BuiltinType::Double) &&
1976           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1977         return true;
1978 
1979       // Half can be promoted to float.
1980       if (!getLangOpts().NativeHalfType &&
1981            FromBuiltin->getKind() == BuiltinType::Half &&
1982           ToBuiltin->getKind() == BuiltinType::Float)
1983         return true;
1984     }
1985 
1986   return false;
1987 }
1988 
1989 /// \brief Determine if a conversion is a complex promotion.
1990 ///
1991 /// A complex promotion is defined as a complex -> complex conversion
1992 /// where the conversion between the underlying real types is a
1993 /// floating-point or integral promotion.
1994 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1995   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1996   if (!FromComplex)
1997     return false;
1998 
1999   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2000   if (!ToComplex)
2001     return false;
2002 
2003   return IsFloatingPointPromotion(FromComplex->getElementType(),
2004                                   ToComplex->getElementType()) ||
2005     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2006                         ToComplex->getElementType());
2007 }
2008 
2009 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2010 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2011 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2012 /// if non-empty, will be a pointer to ToType that may or may not have
2013 /// the right set of qualifiers on its pointee.
2014 ///
2015 static QualType
2016 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2017                                    QualType ToPointee, QualType ToType,
2018                                    ASTContext &Context,
2019                                    bool StripObjCLifetime = false) {
2020   assert((FromPtr->getTypeClass() == Type::Pointer ||
2021           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2022          "Invalid similarly-qualified pointer type");
2023 
2024   /// Conversions to 'id' subsume cv-qualifier conversions.
2025   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2026     return ToType.getUnqualifiedType();
2027 
2028   QualType CanonFromPointee
2029     = Context.getCanonicalType(FromPtr->getPointeeType());
2030   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2031   Qualifiers Quals = CanonFromPointee.getQualifiers();
2032 
2033   if (StripObjCLifetime)
2034     Quals.removeObjCLifetime();
2035 
2036   // Exact qualifier match -> return the pointer type we're converting to.
2037   if (CanonToPointee.getLocalQualifiers() == Quals) {
2038     // ToType is exactly what we need. Return it.
2039     if (!ToType.isNull())
2040       return ToType.getUnqualifiedType();
2041 
2042     // Build a pointer to ToPointee. It has the right qualifiers
2043     // already.
2044     if (isa<ObjCObjectPointerType>(ToType))
2045       return Context.getObjCObjectPointerType(ToPointee);
2046     return Context.getPointerType(ToPointee);
2047   }
2048 
2049   // Just build a canonical type that has the right qualifiers.
2050   QualType QualifiedCanonToPointee
2051     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2052 
2053   if (isa<ObjCObjectPointerType>(ToType))
2054     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2055   return Context.getPointerType(QualifiedCanonToPointee);
2056 }
2057 
2058 static bool isNullPointerConstantForConversion(Expr *Expr,
2059                                                bool InOverloadResolution,
2060                                                ASTContext &Context) {
2061   // Handle value-dependent integral null pointer constants correctly.
2062   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2063   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2064       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2065     return !InOverloadResolution;
2066 
2067   return Expr->isNullPointerConstant(Context,
2068                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2069                                         : Expr::NPC_ValueDependentIsNull);
2070 }
2071 
2072 /// IsPointerConversion - Determines whether the conversion of the
2073 /// expression From, which has the (possibly adjusted) type FromType,
2074 /// can be converted to the type ToType via a pointer conversion (C++
2075 /// 4.10). If so, returns true and places the converted type (that
2076 /// might differ from ToType in its cv-qualifiers at some level) into
2077 /// ConvertedType.
2078 ///
2079 /// This routine also supports conversions to and from block pointers
2080 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2081 /// pointers to interfaces. FIXME: Once we've determined the
2082 /// appropriate overloading rules for Objective-C, we may want to
2083 /// split the Objective-C checks into a different routine; however,
2084 /// GCC seems to consider all of these conversions to be pointer
2085 /// conversions, so for now they live here. IncompatibleObjC will be
2086 /// set if the conversion is an allowed Objective-C conversion that
2087 /// should result in a warning.
2088 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2089                                bool InOverloadResolution,
2090                                QualType& ConvertedType,
2091                                bool &IncompatibleObjC) {
2092   IncompatibleObjC = false;
2093   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2094                               IncompatibleObjC))
2095     return true;
2096 
2097   // Conversion from a null pointer constant to any Objective-C pointer type.
2098   if (ToType->isObjCObjectPointerType() &&
2099       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2100     ConvertedType = ToType;
2101     return true;
2102   }
2103 
2104   // Blocks: Block pointers can be converted to void*.
2105   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2106       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2107     ConvertedType = ToType;
2108     return true;
2109   }
2110   // Blocks: A null pointer constant can be converted to a block
2111   // pointer type.
2112   if (ToType->isBlockPointerType() &&
2113       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2114     ConvertedType = ToType;
2115     return true;
2116   }
2117 
2118   // If the left-hand-side is nullptr_t, the right side can be a null
2119   // pointer constant.
2120   if (ToType->isNullPtrType() &&
2121       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2122     ConvertedType = ToType;
2123     return true;
2124   }
2125 
2126   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2127   if (!ToTypePtr)
2128     return false;
2129 
2130   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2131   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2132     ConvertedType = ToType;
2133     return true;
2134   }
2135 
2136   // Beyond this point, both types need to be pointers
2137   // , including objective-c pointers.
2138   QualType ToPointeeType = ToTypePtr->getPointeeType();
2139   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2140       !getLangOpts().ObjCAutoRefCount) {
2141     ConvertedType = BuildSimilarlyQualifiedPointerType(
2142                                       FromType->getAs<ObjCObjectPointerType>(),
2143                                                        ToPointeeType,
2144                                                        ToType, Context);
2145     return true;
2146   }
2147   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2148   if (!FromTypePtr)
2149     return false;
2150 
2151   QualType FromPointeeType = FromTypePtr->getPointeeType();
2152 
2153   // If the unqualified pointee types are the same, this can't be a
2154   // pointer conversion, so don't do all of the work below.
2155   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2156     return false;
2157 
2158   // An rvalue of type "pointer to cv T," where T is an object type,
2159   // can be converted to an rvalue of type "pointer to cv void" (C++
2160   // 4.10p2).
2161   if (FromPointeeType->isIncompleteOrObjectType() &&
2162       ToPointeeType->isVoidType()) {
2163     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2164                                                        ToPointeeType,
2165                                                        ToType, Context,
2166                                                    /*StripObjCLifetime=*/true);
2167     return true;
2168   }
2169 
2170   // MSVC allows implicit function to void* type conversion.
2171   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2172       ToPointeeType->isVoidType()) {
2173     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2174                                                        ToPointeeType,
2175                                                        ToType, Context);
2176     return true;
2177   }
2178 
2179   // When we're overloading in C, we allow a special kind of pointer
2180   // conversion for compatible-but-not-identical pointee types.
2181   if (!getLangOpts().CPlusPlus &&
2182       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2183     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2184                                                        ToPointeeType,
2185                                                        ToType, Context);
2186     return true;
2187   }
2188 
2189   // C++ [conv.ptr]p3:
2190   //
2191   //   An rvalue of type "pointer to cv D," where D is a class type,
2192   //   can be converted to an rvalue of type "pointer to cv B," where
2193   //   B is a base class (clause 10) of D. If B is an inaccessible
2194   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2195   //   necessitates this conversion is ill-formed. The result of the
2196   //   conversion is a pointer to the base class sub-object of the
2197   //   derived class object. The null pointer value is converted to
2198   //   the null pointer value of the destination type.
2199   //
2200   // Note that we do not check for ambiguity or inaccessibility
2201   // here. That is handled by CheckPointerConversion.
2202   if (getLangOpts().CPlusPlus &&
2203       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2204       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2205       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2206     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2207                                                        ToPointeeType,
2208                                                        ToType, Context);
2209     return true;
2210   }
2211 
2212   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2213       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2214     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2215                                                        ToPointeeType,
2216                                                        ToType, Context);
2217     return true;
2218   }
2219 
2220   return false;
2221 }
2222 
2223 /// \brief Adopt the given qualifiers for the given type.
2224 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2225   Qualifiers TQs = T.getQualifiers();
2226 
2227   // Check whether qualifiers already match.
2228   if (TQs == Qs)
2229     return T;
2230 
2231   if (Qs.compatiblyIncludes(TQs))
2232     return Context.getQualifiedType(T, Qs);
2233 
2234   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2235 }
2236 
2237 /// isObjCPointerConversion - Determines whether this is an
2238 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2239 /// with the same arguments and return values.
2240 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2241                                    QualType& ConvertedType,
2242                                    bool &IncompatibleObjC) {
2243   if (!getLangOpts().ObjC1)
2244     return false;
2245 
2246   // The set of qualifiers on the type we're converting from.
2247   Qualifiers FromQualifiers = FromType.getQualifiers();
2248 
2249   // First, we handle all conversions on ObjC object pointer types.
2250   const ObjCObjectPointerType* ToObjCPtr =
2251     ToType->getAs<ObjCObjectPointerType>();
2252   const ObjCObjectPointerType *FromObjCPtr =
2253     FromType->getAs<ObjCObjectPointerType>();
2254 
2255   if (ToObjCPtr && FromObjCPtr) {
2256     // If the pointee types are the same (ignoring qualifications),
2257     // then this is not a pointer conversion.
2258     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2259                                        FromObjCPtr->getPointeeType()))
2260       return false;
2261 
2262     // Conversion between Objective-C pointers.
2263     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2264       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2265       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2266       if (getLangOpts().CPlusPlus && LHS && RHS &&
2267           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2268                                                 FromObjCPtr->getPointeeType()))
2269         return false;
2270       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2271                                                    ToObjCPtr->getPointeeType(),
2272                                                          ToType, Context);
2273       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2274       return true;
2275     }
2276 
2277     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2278       // Okay: this is some kind of implicit downcast of Objective-C
2279       // interfaces, which is permitted. However, we're going to
2280       // complain about it.
2281       IncompatibleObjC = true;
2282       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2283                                                    ToObjCPtr->getPointeeType(),
2284                                                          ToType, Context);
2285       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2286       return true;
2287     }
2288   }
2289   // Beyond this point, both types need to be C pointers or block pointers.
2290   QualType ToPointeeType;
2291   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2292     ToPointeeType = ToCPtr->getPointeeType();
2293   else if (const BlockPointerType *ToBlockPtr =
2294             ToType->getAs<BlockPointerType>()) {
2295     // Objective C++: We're able to convert from a pointer to any object
2296     // to a block pointer type.
2297     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2298       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2299       return true;
2300     }
2301     ToPointeeType = ToBlockPtr->getPointeeType();
2302   }
2303   else if (FromType->getAs<BlockPointerType>() &&
2304            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2305     // Objective C++: We're able to convert from a block pointer type to a
2306     // pointer to any object.
2307     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2308     return true;
2309   }
2310   else
2311     return false;
2312 
2313   QualType FromPointeeType;
2314   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2315     FromPointeeType = FromCPtr->getPointeeType();
2316   else if (const BlockPointerType *FromBlockPtr =
2317            FromType->getAs<BlockPointerType>())
2318     FromPointeeType = FromBlockPtr->getPointeeType();
2319   else
2320     return false;
2321 
2322   // If we have pointers to pointers, recursively check whether this
2323   // is an Objective-C conversion.
2324   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2325       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2326                               IncompatibleObjC)) {
2327     // We always complain about this conversion.
2328     IncompatibleObjC = true;
2329     ConvertedType = Context.getPointerType(ConvertedType);
2330     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2331     return true;
2332   }
2333   // Allow conversion of pointee being objective-c pointer to another one;
2334   // as in I* to id.
2335   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2336       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2337       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2338                               IncompatibleObjC)) {
2339 
2340     ConvertedType = Context.getPointerType(ConvertedType);
2341     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2342     return true;
2343   }
2344 
2345   // If we have pointers to functions or blocks, check whether the only
2346   // differences in the argument and result types are in Objective-C
2347   // pointer conversions. If so, we permit the conversion (but
2348   // complain about it).
2349   const FunctionProtoType *FromFunctionType
2350     = FromPointeeType->getAs<FunctionProtoType>();
2351   const FunctionProtoType *ToFunctionType
2352     = ToPointeeType->getAs<FunctionProtoType>();
2353   if (FromFunctionType && ToFunctionType) {
2354     // If the function types are exactly the same, this isn't an
2355     // Objective-C pointer conversion.
2356     if (Context.getCanonicalType(FromPointeeType)
2357           == Context.getCanonicalType(ToPointeeType))
2358       return false;
2359 
2360     // Perform the quick checks that will tell us whether these
2361     // function types are obviously different.
2362     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2363         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2364         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2365       return false;
2366 
2367     bool HasObjCConversion = false;
2368     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2369         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2370       // Okay, the types match exactly. Nothing to do.
2371     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2372                                        ToFunctionType->getReturnType(),
2373                                        ConvertedType, IncompatibleObjC)) {
2374       // Okay, we have an Objective-C pointer conversion.
2375       HasObjCConversion = true;
2376     } else {
2377       // Function types are too different. Abort.
2378       return false;
2379     }
2380 
2381     // Check argument types.
2382     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2383          ArgIdx != NumArgs; ++ArgIdx) {
2384       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2385       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2386       if (Context.getCanonicalType(FromArgType)
2387             == Context.getCanonicalType(ToArgType)) {
2388         // Okay, the types match exactly. Nothing to do.
2389       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2390                                          ConvertedType, IncompatibleObjC)) {
2391         // Okay, we have an Objective-C pointer conversion.
2392         HasObjCConversion = true;
2393       } else {
2394         // Argument types are too different. Abort.
2395         return false;
2396       }
2397     }
2398 
2399     if (HasObjCConversion) {
2400       // We had an Objective-C conversion. Allow this pointer
2401       // conversion, but complain about it.
2402       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2403       IncompatibleObjC = true;
2404       return true;
2405     }
2406   }
2407 
2408   return false;
2409 }
2410 
2411 /// \brief Determine whether this is an Objective-C writeback conversion,
2412 /// used for parameter passing when performing automatic reference counting.
2413 ///
2414 /// \param FromType The type we're converting form.
2415 ///
2416 /// \param ToType The type we're converting to.
2417 ///
2418 /// \param ConvertedType The type that will be produced after applying
2419 /// this conversion.
2420 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2421                                      QualType &ConvertedType) {
2422   if (!getLangOpts().ObjCAutoRefCount ||
2423       Context.hasSameUnqualifiedType(FromType, ToType))
2424     return false;
2425 
2426   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2427   QualType ToPointee;
2428   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2429     ToPointee = ToPointer->getPointeeType();
2430   else
2431     return false;
2432 
2433   Qualifiers ToQuals = ToPointee.getQualifiers();
2434   if (!ToPointee->isObjCLifetimeType() ||
2435       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2436       !ToQuals.withoutObjCLifetime().empty())
2437     return false;
2438 
2439   // Argument must be a pointer to __strong to __weak.
2440   QualType FromPointee;
2441   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2442     FromPointee = FromPointer->getPointeeType();
2443   else
2444     return false;
2445 
2446   Qualifiers FromQuals = FromPointee.getQualifiers();
2447   if (!FromPointee->isObjCLifetimeType() ||
2448       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2449        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2450     return false;
2451 
2452   // Make sure that we have compatible qualifiers.
2453   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2454   if (!ToQuals.compatiblyIncludes(FromQuals))
2455     return false;
2456 
2457   // Remove qualifiers from the pointee type we're converting from; they
2458   // aren't used in the compatibility check belong, and we'll be adding back
2459   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2460   FromPointee = FromPointee.getUnqualifiedType();
2461 
2462   // The unqualified form of the pointee types must be compatible.
2463   ToPointee = ToPointee.getUnqualifiedType();
2464   bool IncompatibleObjC;
2465   if (Context.typesAreCompatible(FromPointee, ToPointee))
2466     FromPointee = ToPointee;
2467   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2468                                     IncompatibleObjC))
2469     return false;
2470 
2471   /// \brief Construct the type we're converting to, which is a pointer to
2472   /// __autoreleasing pointee.
2473   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2474   ConvertedType = Context.getPointerType(FromPointee);
2475   return true;
2476 }
2477 
2478 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2479                                     QualType& ConvertedType) {
2480   QualType ToPointeeType;
2481   if (const BlockPointerType *ToBlockPtr =
2482         ToType->getAs<BlockPointerType>())
2483     ToPointeeType = ToBlockPtr->getPointeeType();
2484   else
2485     return false;
2486 
2487   QualType FromPointeeType;
2488   if (const BlockPointerType *FromBlockPtr =
2489       FromType->getAs<BlockPointerType>())
2490     FromPointeeType = FromBlockPtr->getPointeeType();
2491   else
2492     return false;
2493   // We have pointer to blocks, check whether the only
2494   // differences in the argument and result types are in Objective-C
2495   // pointer conversions. If so, we permit the conversion.
2496 
2497   const FunctionProtoType *FromFunctionType
2498     = FromPointeeType->getAs<FunctionProtoType>();
2499   const FunctionProtoType *ToFunctionType
2500     = ToPointeeType->getAs<FunctionProtoType>();
2501 
2502   if (!FromFunctionType || !ToFunctionType)
2503     return false;
2504 
2505   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2506     return true;
2507 
2508   // Perform the quick checks that will tell us whether these
2509   // function types are obviously different.
2510   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2511       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2512     return false;
2513 
2514   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2515   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2516   if (FromEInfo != ToEInfo)
2517     return false;
2518 
2519   bool IncompatibleObjC = false;
2520   if (Context.hasSameType(FromFunctionType->getReturnType(),
2521                           ToFunctionType->getReturnType())) {
2522     // Okay, the types match exactly. Nothing to do.
2523   } else {
2524     QualType RHS = FromFunctionType->getReturnType();
2525     QualType LHS = ToFunctionType->getReturnType();
2526     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2527         !RHS.hasQualifiers() && LHS.hasQualifiers())
2528        LHS = LHS.getUnqualifiedType();
2529 
2530      if (Context.hasSameType(RHS,LHS)) {
2531        // OK exact match.
2532      } else if (isObjCPointerConversion(RHS, LHS,
2533                                         ConvertedType, IncompatibleObjC)) {
2534      if (IncompatibleObjC)
2535        return false;
2536      // Okay, we have an Objective-C pointer conversion.
2537      }
2538      else
2539        return false;
2540    }
2541 
2542    // Check argument types.
2543    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2544         ArgIdx != NumArgs; ++ArgIdx) {
2545      IncompatibleObjC = false;
2546      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2547      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2548      if (Context.hasSameType(FromArgType, ToArgType)) {
2549        // Okay, the types match exactly. Nothing to do.
2550      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2551                                         ConvertedType, IncompatibleObjC)) {
2552        if (IncompatibleObjC)
2553          return false;
2554        // Okay, we have an Objective-C pointer conversion.
2555      } else
2556        // Argument types are too different. Abort.
2557        return false;
2558    }
2559    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2560                                                         ToFunctionType))
2561      return false;
2562 
2563    ConvertedType = ToType;
2564    return true;
2565 }
2566 
2567 enum {
2568   ft_default,
2569   ft_different_class,
2570   ft_parameter_arity,
2571   ft_parameter_mismatch,
2572   ft_return_type,
2573   ft_qualifer_mismatch
2574 };
2575 
2576 /// Attempts to get the FunctionProtoType from a Type. Handles
2577 /// MemberFunctionPointers properly.
2578 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2579   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2580     return FPT;
2581 
2582   if (auto *MPT = FromType->getAs<MemberPointerType>())
2583     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2584 
2585   return nullptr;
2586 }
2587 
2588 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2589 /// function types.  Catches different number of parameter, mismatch in
2590 /// parameter types, and different return types.
2591 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2592                                       QualType FromType, QualType ToType) {
2593   // If either type is not valid, include no extra info.
2594   if (FromType.isNull() || ToType.isNull()) {
2595     PDiag << ft_default;
2596     return;
2597   }
2598 
2599   // Get the function type from the pointers.
2600   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2601     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2602                             *ToMember = ToType->getAs<MemberPointerType>();
2603     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2604       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2605             << QualType(FromMember->getClass(), 0);
2606       return;
2607     }
2608     FromType = FromMember->getPointeeType();
2609     ToType = ToMember->getPointeeType();
2610   }
2611 
2612   if (FromType->isPointerType())
2613     FromType = FromType->getPointeeType();
2614   if (ToType->isPointerType())
2615     ToType = ToType->getPointeeType();
2616 
2617   // Remove references.
2618   FromType = FromType.getNonReferenceType();
2619   ToType = ToType.getNonReferenceType();
2620 
2621   // Don't print extra info for non-specialized template functions.
2622   if (FromType->isInstantiationDependentType() &&
2623       !FromType->getAs<TemplateSpecializationType>()) {
2624     PDiag << ft_default;
2625     return;
2626   }
2627 
2628   // No extra info for same types.
2629   if (Context.hasSameType(FromType, ToType)) {
2630     PDiag << ft_default;
2631     return;
2632   }
2633 
2634   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2635                           *ToFunction = tryGetFunctionProtoType(ToType);
2636 
2637   // Both types need to be function types.
2638   if (!FromFunction || !ToFunction) {
2639     PDiag << ft_default;
2640     return;
2641   }
2642 
2643   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2644     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2645           << FromFunction->getNumParams();
2646     return;
2647   }
2648 
2649   // Handle different parameter types.
2650   unsigned ArgPos;
2651   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2652     PDiag << ft_parameter_mismatch << ArgPos + 1
2653           << ToFunction->getParamType(ArgPos)
2654           << FromFunction->getParamType(ArgPos);
2655     return;
2656   }
2657 
2658   // Handle different return type.
2659   if (!Context.hasSameType(FromFunction->getReturnType(),
2660                            ToFunction->getReturnType())) {
2661     PDiag << ft_return_type << ToFunction->getReturnType()
2662           << FromFunction->getReturnType();
2663     return;
2664   }
2665 
2666   unsigned FromQuals = FromFunction->getTypeQuals(),
2667            ToQuals = ToFunction->getTypeQuals();
2668   if (FromQuals != ToQuals) {
2669     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2670     return;
2671   }
2672 
2673   // Unable to find a difference, so add no extra info.
2674   PDiag << ft_default;
2675 }
2676 
2677 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2678 /// for equality of their argument types. Caller has already checked that
2679 /// they have same number of arguments.  If the parameters are different,
2680 /// ArgPos will have the parameter index of the first different parameter.
2681 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2682                                       const FunctionProtoType *NewType,
2683                                       unsigned *ArgPos) {
2684   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2685                                               N = NewType->param_type_begin(),
2686                                               E = OldType->param_type_end();
2687        O && (O != E); ++O, ++N) {
2688     if (!Context.hasSameType(O->getUnqualifiedType(),
2689                              N->getUnqualifiedType())) {
2690       if (ArgPos)
2691         *ArgPos = O - OldType->param_type_begin();
2692       return false;
2693     }
2694   }
2695   return true;
2696 }
2697 
2698 /// CheckPointerConversion - Check the pointer conversion from the
2699 /// expression From to the type ToType. This routine checks for
2700 /// ambiguous or inaccessible derived-to-base pointer
2701 /// conversions for which IsPointerConversion has already returned
2702 /// true. It returns true and produces a diagnostic if there was an
2703 /// error, or returns false otherwise.
2704 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2705                                   CastKind &Kind,
2706                                   CXXCastPath& BasePath,
2707                                   bool IgnoreBaseAccess,
2708                                   bool Diagnose) {
2709   QualType FromType = From->getType();
2710   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2711 
2712   Kind = CK_BitCast;
2713 
2714   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2715       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2716           Expr::NPCK_ZeroExpression) {
2717     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2718       DiagRuntimeBehavior(From->getExprLoc(), From,
2719                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2720                             << ToType << From->getSourceRange());
2721     else if (!isUnevaluatedContext())
2722       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2723         << ToType << From->getSourceRange();
2724   }
2725   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2726     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2727       QualType FromPointeeType = FromPtrType->getPointeeType(),
2728                ToPointeeType   = ToPtrType->getPointeeType();
2729 
2730       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2731           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2732         // We must have a derived-to-base conversion. Check an
2733         // ambiguous or inaccessible conversion.
2734         unsigned InaccessibleID = 0;
2735         unsigned AmbigiousID = 0;
2736         if (Diagnose) {
2737           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2738           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2739         }
2740         if (CheckDerivedToBaseConversion(
2741                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2742                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2743                 &BasePath, IgnoreBaseAccess))
2744           return true;
2745 
2746         // The conversion was successful.
2747         Kind = CK_DerivedToBase;
2748       }
2749 
2750       if (Diagnose && !IsCStyleOrFunctionalCast &&
2751           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2752         assert(getLangOpts().MSVCCompat &&
2753                "this should only be possible with MSVCCompat!");
2754         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2755             << From->getSourceRange();
2756       }
2757     }
2758   } else if (const ObjCObjectPointerType *ToPtrType =
2759                ToType->getAs<ObjCObjectPointerType>()) {
2760     if (const ObjCObjectPointerType *FromPtrType =
2761           FromType->getAs<ObjCObjectPointerType>()) {
2762       // Objective-C++ conversions are always okay.
2763       // FIXME: We should have a different class of conversions for the
2764       // Objective-C++ implicit conversions.
2765       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2766         return false;
2767     } else if (FromType->isBlockPointerType()) {
2768       Kind = CK_BlockPointerToObjCPointerCast;
2769     } else {
2770       Kind = CK_CPointerToObjCPointerCast;
2771     }
2772   } else if (ToType->isBlockPointerType()) {
2773     if (!FromType->isBlockPointerType())
2774       Kind = CK_AnyPointerToBlockPointerCast;
2775   }
2776 
2777   // We shouldn't fall into this case unless it's valid for other
2778   // reasons.
2779   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2780     Kind = CK_NullToPointer;
2781 
2782   return false;
2783 }
2784 
2785 /// IsMemberPointerConversion - Determines whether the conversion of the
2786 /// expression From, which has the (possibly adjusted) type FromType, can be
2787 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2788 /// If so, returns true and places the converted type (that might differ from
2789 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2790 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2791                                      QualType ToType,
2792                                      bool InOverloadResolution,
2793                                      QualType &ConvertedType) {
2794   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2795   if (!ToTypePtr)
2796     return false;
2797 
2798   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2799   if (From->isNullPointerConstant(Context,
2800                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2801                                         : Expr::NPC_ValueDependentIsNull)) {
2802     ConvertedType = ToType;
2803     return true;
2804   }
2805 
2806   // Otherwise, both types have to be member pointers.
2807   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2808   if (!FromTypePtr)
2809     return false;
2810 
2811   // A pointer to member of B can be converted to a pointer to member of D,
2812   // where D is derived from B (C++ 4.11p2).
2813   QualType FromClass(FromTypePtr->getClass(), 0);
2814   QualType ToClass(ToTypePtr->getClass(), 0);
2815 
2816   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2817       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2818     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2819                                                  ToClass.getTypePtr());
2820     return true;
2821   }
2822 
2823   return false;
2824 }
2825 
2826 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2827 /// expression From to the type ToType. This routine checks for ambiguous or
2828 /// virtual or inaccessible base-to-derived member pointer conversions
2829 /// for which IsMemberPointerConversion has already returned true. It returns
2830 /// true and produces a diagnostic if there was an error, or returns false
2831 /// otherwise.
2832 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2833                                         CastKind &Kind,
2834                                         CXXCastPath &BasePath,
2835                                         bool IgnoreBaseAccess) {
2836   QualType FromType = From->getType();
2837   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2838   if (!FromPtrType) {
2839     // This must be a null pointer to member pointer conversion
2840     assert(From->isNullPointerConstant(Context,
2841                                        Expr::NPC_ValueDependentIsNull) &&
2842            "Expr must be null pointer constant!");
2843     Kind = CK_NullToMemberPointer;
2844     return false;
2845   }
2846 
2847   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2848   assert(ToPtrType && "No member pointer cast has a target type "
2849                       "that is not a member pointer.");
2850 
2851   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2852   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2853 
2854   // FIXME: What about dependent types?
2855   assert(FromClass->isRecordType() && "Pointer into non-class.");
2856   assert(ToClass->isRecordType() && "Pointer into non-class.");
2857 
2858   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2859                      /*DetectVirtual=*/true);
2860   bool DerivationOkay =
2861       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2862   assert(DerivationOkay &&
2863          "Should not have been called if derivation isn't OK.");
2864   (void)DerivationOkay;
2865 
2866   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2867                                   getUnqualifiedType())) {
2868     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2869     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2870       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2871     return true;
2872   }
2873 
2874   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2875     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2876       << FromClass << ToClass << QualType(VBase, 0)
2877       << From->getSourceRange();
2878     return true;
2879   }
2880 
2881   if (!IgnoreBaseAccess)
2882     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2883                          Paths.front(),
2884                          diag::err_downcast_from_inaccessible_base);
2885 
2886   // Must be a base to derived member conversion.
2887   BuildBasePathArray(Paths, BasePath);
2888   Kind = CK_BaseToDerivedMemberPointer;
2889   return false;
2890 }
2891 
2892 /// Determine whether the lifetime conversion between the two given
2893 /// qualifiers sets is nontrivial.
2894 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2895                                                Qualifiers ToQuals) {
2896   // Converting anything to const __unsafe_unretained is trivial.
2897   if (ToQuals.hasConst() &&
2898       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2899     return false;
2900 
2901   return true;
2902 }
2903 
2904 /// IsQualificationConversion - Determines whether the conversion from
2905 /// an rvalue of type FromType to ToType is a qualification conversion
2906 /// (C++ 4.4).
2907 ///
2908 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2909 /// when the qualification conversion involves a change in the Objective-C
2910 /// object lifetime.
2911 bool
2912 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2913                                 bool CStyle, bool &ObjCLifetimeConversion) {
2914   FromType = Context.getCanonicalType(FromType);
2915   ToType = Context.getCanonicalType(ToType);
2916   ObjCLifetimeConversion = false;
2917 
2918   // If FromType and ToType are the same type, this is not a
2919   // qualification conversion.
2920   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2921     return false;
2922 
2923   // (C++ 4.4p4):
2924   //   A conversion can add cv-qualifiers at levels other than the first
2925   //   in multi-level pointers, subject to the following rules: [...]
2926   bool PreviousToQualsIncludeConst = true;
2927   bool UnwrappedAnyPointer = false;
2928   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2929     // Within each iteration of the loop, we check the qualifiers to
2930     // determine if this still looks like a qualification
2931     // conversion. Then, if all is well, we unwrap one more level of
2932     // pointers or pointers-to-members and do it all again
2933     // until there are no more pointers or pointers-to-members left to
2934     // unwrap.
2935     UnwrappedAnyPointer = true;
2936 
2937     Qualifiers FromQuals = FromType.getQualifiers();
2938     Qualifiers ToQuals = ToType.getQualifiers();
2939 
2940     // Objective-C ARC:
2941     //   Check Objective-C lifetime conversions.
2942     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2943         UnwrappedAnyPointer) {
2944       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2945         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2946           ObjCLifetimeConversion = true;
2947         FromQuals.removeObjCLifetime();
2948         ToQuals.removeObjCLifetime();
2949       } else {
2950         // Qualification conversions cannot cast between different
2951         // Objective-C lifetime qualifiers.
2952         return false;
2953       }
2954     }
2955 
2956     // Allow addition/removal of GC attributes but not changing GC attributes.
2957     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2958         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2959       FromQuals.removeObjCGCAttr();
2960       ToQuals.removeObjCGCAttr();
2961     }
2962 
2963     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2964     //      2,j, and similarly for volatile.
2965     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2966       return false;
2967 
2968     //   -- if the cv 1,j and cv 2,j are different, then const is in
2969     //      every cv for 0 < k < j.
2970     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2971         && !PreviousToQualsIncludeConst)
2972       return false;
2973 
2974     // Keep track of whether all prior cv-qualifiers in the "to" type
2975     // include const.
2976     PreviousToQualsIncludeConst
2977       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2978   }
2979 
2980   // We are left with FromType and ToType being the pointee types
2981   // after unwrapping the original FromType and ToType the same number
2982   // of types. If we unwrapped any pointers, and if FromType and
2983   // ToType have the same unqualified type (since we checked
2984   // qualifiers above), then this is a qualification conversion.
2985   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2986 }
2987 
2988 /// \brief - Determine whether this is a conversion from a scalar type to an
2989 /// atomic type.
2990 ///
2991 /// If successful, updates \c SCS's second and third steps in the conversion
2992 /// sequence to finish the conversion.
2993 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2994                                 bool InOverloadResolution,
2995                                 StandardConversionSequence &SCS,
2996                                 bool CStyle) {
2997   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2998   if (!ToAtomic)
2999     return false;
3000 
3001   StandardConversionSequence InnerSCS;
3002   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3003                             InOverloadResolution, InnerSCS,
3004                             CStyle, /*AllowObjCWritebackConversion=*/false))
3005     return false;
3006 
3007   SCS.Second = InnerSCS.Second;
3008   SCS.setToType(1, InnerSCS.getToType(1));
3009   SCS.Third = InnerSCS.Third;
3010   SCS.QualificationIncludesObjCLifetime
3011     = InnerSCS.QualificationIncludesObjCLifetime;
3012   SCS.setToType(2, InnerSCS.getToType(2));
3013   return true;
3014 }
3015 
3016 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3017                                               CXXConstructorDecl *Constructor,
3018                                               QualType Type) {
3019   const FunctionProtoType *CtorType =
3020       Constructor->getType()->getAs<FunctionProtoType>();
3021   if (CtorType->getNumParams() > 0) {
3022     QualType FirstArg = CtorType->getParamType(0);
3023     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3024       return true;
3025   }
3026   return false;
3027 }
3028 
3029 static OverloadingResult
3030 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3031                                        CXXRecordDecl *To,
3032                                        UserDefinedConversionSequence &User,
3033                                        OverloadCandidateSet &CandidateSet,
3034                                        bool AllowExplicit) {
3035   DeclContext::lookup_result R = S.LookupConstructors(To);
3036   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3037        Con != ConEnd; ++Con) {
3038     NamedDecl *D = *Con;
3039     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3040 
3041     // Find the constructor (which may be a template).
3042     CXXConstructorDecl *Constructor = nullptr;
3043     FunctionTemplateDecl *ConstructorTmpl
3044       = dyn_cast<FunctionTemplateDecl>(D);
3045     if (ConstructorTmpl)
3046       Constructor
3047         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3048     else
3049       Constructor = cast<CXXConstructorDecl>(D);
3050 
3051     bool Usable = !Constructor->isInvalidDecl() &&
3052                   S.isInitListConstructor(Constructor) &&
3053                   (AllowExplicit || !Constructor->isExplicit());
3054     if (Usable) {
3055       // If the first argument is (a reference to) the target type,
3056       // suppress conversions.
3057       bool SuppressUserConversions =
3058           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
3059       if (ConstructorTmpl)
3060         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3061                                        /*ExplicitArgs*/ nullptr,
3062                                        From, CandidateSet,
3063                                        SuppressUserConversions);
3064       else
3065         S.AddOverloadCandidate(Constructor, FoundDecl,
3066                                From, CandidateSet,
3067                                SuppressUserConversions);
3068     }
3069   }
3070 
3071   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3072 
3073   OverloadCandidateSet::iterator Best;
3074   switch (auto Result =
3075             CandidateSet.BestViableFunction(S, From->getLocStart(),
3076                                             Best, true)) {
3077   case OR_Deleted:
3078   case OR_Success: {
3079     // Record the standard conversion we used and the conversion function.
3080     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3081     QualType ThisType = Constructor->getThisType(S.Context);
3082     // Initializer lists don't have conversions as such.
3083     User.Before.setAsIdentityConversion();
3084     User.HadMultipleCandidates = HadMultipleCandidates;
3085     User.ConversionFunction = Constructor;
3086     User.FoundConversionFunction = Best->FoundDecl;
3087     User.After.setAsIdentityConversion();
3088     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3089     User.After.setAllToTypes(ToType);
3090     return Result;
3091   }
3092 
3093   case OR_No_Viable_Function:
3094     return OR_No_Viable_Function;
3095   case OR_Ambiguous:
3096     return OR_Ambiguous;
3097   }
3098 
3099   llvm_unreachable("Invalid OverloadResult!");
3100 }
3101 
3102 /// Determines whether there is a user-defined conversion sequence
3103 /// (C++ [over.ics.user]) that converts expression From to the type
3104 /// ToType. If such a conversion exists, User will contain the
3105 /// user-defined conversion sequence that performs such a conversion
3106 /// and this routine will return true. Otherwise, this routine returns
3107 /// false and User is unspecified.
3108 ///
3109 /// \param AllowExplicit  true if the conversion should consider C++0x
3110 /// "explicit" conversion functions as well as non-explicit conversion
3111 /// functions (C++0x [class.conv.fct]p2).
3112 ///
3113 /// \param AllowObjCConversionOnExplicit true if the conversion should
3114 /// allow an extra Objective-C pointer conversion on uses of explicit
3115 /// constructors. Requires \c AllowExplicit to also be set.
3116 static OverloadingResult
3117 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3118                         UserDefinedConversionSequence &User,
3119                         OverloadCandidateSet &CandidateSet,
3120                         bool AllowExplicit,
3121                         bool AllowObjCConversionOnExplicit) {
3122   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3123 
3124   // Whether we will only visit constructors.
3125   bool ConstructorsOnly = false;
3126 
3127   // If the type we are conversion to is a class type, enumerate its
3128   // constructors.
3129   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3130     // C++ [over.match.ctor]p1:
3131     //   When objects of class type are direct-initialized (8.5), or
3132     //   copy-initialized from an expression of the same or a
3133     //   derived class type (8.5), overload resolution selects the
3134     //   constructor. [...] For copy-initialization, the candidate
3135     //   functions are all the converting constructors (12.3.1) of
3136     //   that class. The argument list is the expression-list within
3137     //   the parentheses of the initializer.
3138     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3139         (From->getType()->getAs<RecordType>() &&
3140          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3141       ConstructorsOnly = true;
3142 
3143     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3144       // We're not going to find any constructors.
3145     } else if (CXXRecordDecl *ToRecordDecl
3146                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3147 
3148       Expr **Args = &From;
3149       unsigned NumArgs = 1;
3150       bool ListInitializing = false;
3151       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3152         // But first, see if there is an init-list-constructor that will work.
3153         OverloadingResult Result = IsInitializerListConstructorConversion(
3154             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3155         if (Result != OR_No_Viable_Function)
3156           return Result;
3157         // Never mind.
3158         CandidateSet.clear();
3159 
3160         // If we're list-initializing, we pass the individual elements as
3161         // arguments, not the entire list.
3162         Args = InitList->getInits();
3163         NumArgs = InitList->getNumInits();
3164         ListInitializing = true;
3165       }
3166 
3167       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3168       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3169            Con != ConEnd; ++Con) {
3170         NamedDecl *D = *Con;
3171         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3172 
3173         // Find the constructor (which may be a template).
3174         CXXConstructorDecl *Constructor = nullptr;
3175         FunctionTemplateDecl *ConstructorTmpl
3176           = dyn_cast<FunctionTemplateDecl>(D);
3177         if (ConstructorTmpl)
3178           Constructor
3179             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3180         else
3181           Constructor = cast<CXXConstructorDecl>(D);
3182 
3183         bool Usable = !Constructor->isInvalidDecl();
3184         if (ListInitializing)
3185           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3186         else
3187           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3188         if (Usable) {
3189           bool SuppressUserConversions = !ConstructorsOnly;
3190           if (SuppressUserConversions && ListInitializing) {
3191             SuppressUserConversions = false;
3192             if (NumArgs == 1) {
3193               // If the first argument is (a reference to) the target type,
3194               // suppress conversions.
3195               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3196                                                 S.Context, Constructor, ToType);
3197             }
3198           }
3199           if (ConstructorTmpl)
3200             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3201                                            /*ExplicitArgs*/ nullptr,
3202                                            llvm::makeArrayRef(Args, NumArgs),
3203                                            CandidateSet, SuppressUserConversions);
3204           else
3205             // Allow one user-defined conversion when user specifies a
3206             // From->ToType conversion via an static cast (c-style, etc).
3207             S.AddOverloadCandidate(Constructor, FoundDecl,
3208                                    llvm::makeArrayRef(Args, NumArgs),
3209                                    CandidateSet, SuppressUserConversions);
3210         }
3211       }
3212     }
3213   }
3214 
3215   // Enumerate conversion functions, if we're allowed to.
3216   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3217   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3218     // No conversion functions from incomplete types.
3219   } else if (const RecordType *FromRecordType
3220                                    = From->getType()->getAs<RecordType>()) {
3221     if (CXXRecordDecl *FromRecordDecl
3222          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3223       // Add all of the conversion functions as candidates.
3224       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3225       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3226         DeclAccessPair FoundDecl = I.getPair();
3227         NamedDecl *D = FoundDecl.getDecl();
3228         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3229         if (isa<UsingShadowDecl>(D))
3230           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3231 
3232         CXXConversionDecl *Conv;
3233         FunctionTemplateDecl *ConvTemplate;
3234         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3235           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3236         else
3237           Conv = cast<CXXConversionDecl>(D);
3238 
3239         if (AllowExplicit || !Conv->isExplicit()) {
3240           if (ConvTemplate)
3241             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3242                                              ActingContext, From, ToType,
3243                                              CandidateSet,
3244                                              AllowObjCConversionOnExplicit);
3245           else
3246             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3247                                      From, ToType, CandidateSet,
3248                                      AllowObjCConversionOnExplicit);
3249         }
3250       }
3251     }
3252   }
3253 
3254   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3255 
3256   OverloadCandidateSet::iterator Best;
3257   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3258                                                         Best, true)) {
3259   case OR_Success:
3260   case OR_Deleted:
3261     // Record the standard conversion we used and the conversion function.
3262     if (CXXConstructorDecl *Constructor
3263           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3264       // C++ [over.ics.user]p1:
3265       //   If the user-defined conversion is specified by a
3266       //   constructor (12.3.1), the initial standard conversion
3267       //   sequence converts the source type to the type required by
3268       //   the argument of the constructor.
3269       //
3270       QualType ThisType = Constructor->getThisType(S.Context);
3271       if (isa<InitListExpr>(From)) {
3272         // Initializer lists don't have conversions as such.
3273         User.Before.setAsIdentityConversion();
3274       } else {
3275         if (Best->Conversions[0].isEllipsis())
3276           User.EllipsisConversion = true;
3277         else {
3278           User.Before = Best->Conversions[0].Standard;
3279           User.EllipsisConversion = false;
3280         }
3281       }
3282       User.HadMultipleCandidates = HadMultipleCandidates;
3283       User.ConversionFunction = Constructor;
3284       User.FoundConversionFunction = Best->FoundDecl;
3285       User.After.setAsIdentityConversion();
3286       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3287       User.After.setAllToTypes(ToType);
3288       return Result;
3289     }
3290     if (CXXConversionDecl *Conversion
3291                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3292       // C++ [over.ics.user]p1:
3293       //
3294       //   [...] If the user-defined conversion is specified by a
3295       //   conversion function (12.3.2), the initial standard
3296       //   conversion sequence converts the source type to the
3297       //   implicit object parameter of the conversion function.
3298       User.Before = Best->Conversions[0].Standard;
3299       User.HadMultipleCandidates = HadMultipleCandidates;
3300       User.ConversionFunction = Conversion;
3301       User.FoundConversionFunction = Best->FoundDecl;
3302       User.EllipsisConversion = false;
3303 
3304       // C++ [over.ics.user]p2:
3305       //   The second standard conversion sequence converts the
3306       //   result of the user-defined conversion to the target type
3307       //   for the sequence. Since an implicit conversion sequence
3308       //   is an initialization, the special rules for
3309       //   initialization by user-defined conversion apply when
3310       //   selecting the best user-defined conversion for a
3311       //   user-defined conversion sequence (see 13.3.3 and
3312       //   13.3.3.1).
3313       User.After = Best->FinalConversion;
3314       return Result;
3315     }
3316     llvm_unreachable("Not a constructor or conversion function?");
3317 
3318   case OR_No_Viable_Function:
3319     return OR_No_Viable_Function;
3320 
3321   case OR_Ambiguous:
3322     return OR_Ambiguous;
3323   }
3324 
3325   llvm_unreachable("Invalid OverloadResult!");
3326 }
3327 
3328 bool
3329 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3330   ImplicitConversionSequence ICS;
3331   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3332                                     OverloadCandidateSet::CSK_Normal);
3333   OverloadingResult OvResult =
3334     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3335                             CandidateSet, false, false);
3336   if (OvResult == OR_Ambiguous)
3337     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3338         << From->getType() << ToType << From->getSourceRange();
3339   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3340     if (!RequireCompleteType(From->getLocStart(), ToType,
3341                              diag::err_typecheck_nonviable_condition_incomplete,
3342                              From->getType(), From->getSourceRange()))
3343       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3344           << false << From->getType() << From->getSourceRange() << ToType;
3345   } else
3346     return false;
3347   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3348   return true;
3349 }
3350 
3351 /// \brief Compare the user-defined conversion functions or constructors
3352 /// of two user-defined conversion sequences to determine whether any ordering
3353 /// is possible.
3354 static ImplicitConversionSequence::CompareKind
3355 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3356                            FunctionDecl *Function2) {
3357   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3358     return ImplicitConversionSequence::Indistinguishable;
3359 
3360   // Objective-C++:
3361   //   If both conversion functions are implicitly-declared conversions from
3362   //   a lambda closure type to a function pointer and a block pointer,
3363   //   respectively, always prefer the conversion to a function pointer,
3364   //   because the function pointer is more lightweight and is more likely
3365   //   to keep code working.
3366   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3367   if (!Conv1)
3368     return ImplicitConversionSequence::Indistinguishable;
3369 
3370   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3371   if (!Conv2)
3372     return ImplicitConversionSequence::Indistinguishable;
3373 
3374   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3375     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3376     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3377     if (Block1 != Block2)
3378       return Block1 ? ImplicitConversionSequence::Worse
3379                     : ImplicitConversionSequence::Better;
3380   }
3381 
3382   return ImplicitConversionSequence::Indistinguishable;
3383 }
3384 
3385 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3386     const ImplicitConversionSequence &ICS) {
3387   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3388          (ICS.isUserDefined() &&
3389           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3390 }
3391 
3392 /// CompareImplicitConversionSequences - Compare two implicit
3393 /// conversion sequences to determine whether one is better than the
3394 /// other or if they are indistinguishable (C++ 13.3.3.2).
3395 static ImplicitConversionSequence::CompareKind
3396 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3397                                    const ImplicitConversionSequence& ICS1,
3398                                    const ImplicitConversionSequence& ICS2)
3399 {
3400   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3401   // conversion sequences (as defined in 13.3.3.1)
3402   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3403   //      conversion sequence than a user-defined conversion sequence or
3404   //      an ellipsis conversion sequence, and
3405   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3406   //      conversion sequence than an ellipsis conversion sequence
3407   //      (13.3.3.1.3).
3408   //
3409   // C++0x [over.best.ics]p10:
3410   //   For the purpose of ranking implicit conversion sequences as
3411   //   described in 13.3.3.2, the ambiguous conversion sequence is
3412   //   treated as a user-defined sequence that is indistinguishable
3413   //   from any other user-defined conversion sequence.
3414 
3415   // String literal to 'char *' conversion has been deprecated in C++03. It has
3416   // been removed from C++11. We still accept this conversion, if it happens at
3417   // the best viable function. Otherwise, this conversion is considered worse
3418   // than ellipsis conversion. Consider this as an extension; this is not in the
3419   // standard. For example:
3420   //
3421   // int &f(...);    // #1
3422   // void f(char*);  // #2
3423   // void g() { int &r = f("foo"); }
3424   //
3425   // In C++03, we pick #2 as the best viable function.
3426   // In C++11, we pick #1 as the best viable function, because ellipsis
3427   // conversion is better than string-literal to char* conversion (since there
3428   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3429   // convert arguments, #2 would be the best viable function in C++11.
3430   // If the best viable function has this conversion, a warning will be issued
3431   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3432 
3433   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3434       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3435       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3436     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3437                ? ImplicitConversionSequence::Worse
3438                : ImplicitConversionSequence::Better;
3439 
3440   if (ICS1.getKindRank() < ICS2.getKindRank())
3441     return ImplicitConversionSequence::Better;
3442   if (ICS2.getKindRank() < ICS1.getKindRank())
3443     return ImplicitConversionSequence::Worse;
3444 
3445   // The following checks require both conversion sequences to be of
3446   // the same kind.
3447   if (ICS1.getKind() != ICS2.getKind())
3448     return ImplicitConversionSequence::Indistinguishable;
3449 
3450   ImplicitConversionSequence::CompareKind Result =
3451       ImplicitConversionSequence::Indistinguishable;
3452 
3453   // Two implicit conversion sequences of the same form are
3454   // indistinguishable conversion sequences unless one of the
3455   // following rules apply: (C++ 13.3.3.2p3):
3456 
3457   // List-initialization sequence L1 is a better conversion sequence than
3458   // list-initialization sequence L2 if:
3459   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3460   //   if not that,
3461   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3462   //   and N1 is smaller than N2.,
3463   // even if one of the other rules in this paragraph would otherwise apply.
3464   if (!ICS1.isBad()) {
3465     if (ICS1.isStdInitializerListElement() &&
3466         !ICS2.isStdInitializerListElement())
3467       return ImplicitConversionSequence::Better;
3468     if (!ICS1.isStdInitializerListElement() &&
3469         ICS2.isStdInitializerListElement())
3470       return ImplicitConversionSequence::Worse;
3471   }
3472 
3473   if (ICS1.isStandard())
3474     // Standard conversion sequence S1 is a better conversion sequence than
3475     // standard conversion sequence S2 if [...]
3476     Result = CompareStandardConversionSequences(S, Loc,
3477                                                 ICS1.Standard, ICS2.Standard);
3478   else if (ICS1.isUserDefined()) {
3479     // User-defined conversion sequence U1 is a better conversion
3480     // sequence than another user-defined conversion sequence U2 if
3481     // they contain the same user-defined conversion function or
3482     // constructor and if the second standard conversion sequence of
3483     // U1 is better than the second standard conversion sequence of
3484     // U2 (C++ 13.3.3.2p3).
3485     if (ICS1.UserDefined.ConversionFunction ==
3486           ICS2.UserDefined.ConversionFunction)
3487       Result = CompareStandardConversionSequences(S, Loc,
3488                                                   ICS1.UserDefined.After,
3489                                                   ICS2.UserDefined.After);
3490     else
3491       Result = compareConversionFunctions(S,
3492                                           ICS1.UserDefined.ConversionFunction,
3493                                           ICS2.UserDefined.ConversionFunction);
3494   }
3495 
3496   return Result;
3497 }
3498 
3499 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3500   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3501     Qualifiers Quals;
3502     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3503     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3504   }
3505 
3506   return Context.hasSameUnqualifiedType(T1, T2);
3507 }
3508 
3509 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3510 // determine if one is a proper subset of the other.
3511 static ImplicitConversionSequence::CompareKind
3512 compareStandardConversionSubsets(ASTContext &Context,
3513                                  const StandardConversionSequence& SCS1,
3514                                  const StandardConversionSequence& SCS2) {
3515   ImplicitConversionSequence::CompareKind Result
3516     = ImplicitConversionSequence::Indistinguishable;
3517 
3518   // the identity conversion sequence is considered to be a subsequence of
3519   // any non-identity conversion sequence
3520   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3521     return ImplicitConversionSequence::Better;
3522   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3523     return ImplicitConversionSequence::Worse;
3524 
3525   if (SCS1.Second != SCS2.Second) {
3526     if (SCS1.Second == ICK_Identity)
3527       Result = ImplicitConversionSequence::Better;
3528     else if (SCS2.Second == ICK_Identity)
3529       Result = ImplicitConversionSequence::Worse;
3530     else
3531       return ImplicitConversionSequence::Indistinguishable;
3532   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3533     return ImplicitConversionSequence::Indistinguishable;
3534 
3535   if (SCS1.Third == SCS2.Third) {
3536     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3537                              : ImplicitConversionSequence::Indistinguishable;
3538   }
3539 
3540   if (SCS1.Third == ICK_Identity)
3541     return Result == ImplicitConversionSequence::Worse
3542              ? ImplicitConversionSequence::Indistinguishable
3543              : ImplicitConversionSequence::Better;
3544 
3545   if (SCS2.Third == ICK_Identity)
3546     return Result == ImplicitConversionSequence::Better
3547              ? ImplicitConversionSequence::Indistinguishable
3548              : ImplicitConversionSequence::Worse;
3549 
3550   return ImplicitConversionSequence::Indistinguishable;
3551 }
3552 
3553 /// \brief Determine whether one of the given reference bindings is better
3554 /// than the other based on what kind of bindings they are.
3555 static bool
3556 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3557                              const StandardConversionSequence &SCS2) {
3558   // C++0x [over.ics.rank]p3b4:
3559   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3560   //      implicit object parameter of a non-static member function declared
3561   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3562   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3563   //      lvalue reference to a function lvalue and S2 binds an rvalue
3564   //      reference*.
3565   //
3566   // FIXME: Rvalue references. We're going rogue with the above edits,
3567   // because the semantics in the current C++0x working paper (N3225 at the
3568   // time of this writing) break the standard definition of std::forward
3569   // and std::reference_wrapper when dealing with references to functions.
3570   // Proposed wording changes submitted to CWG for consideration.
3571   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3572       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3573     return false;
3574 
3575   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3576           SCS2.IsLvalueReference) ||
3577          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3578           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3579 }
3580 
3581 /// CompareStandardConversionSequences - Compare two standard
3582 /// conversion sequences to determine whether one is better than the
3583 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3584 static ImplicitConversionSequence::CompareKind
3585 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3586                                    const StandardConversionSequence& SCS1,
3587                                    const StandardConversionSequence& SCS2)
3588 {
3589   // Standard conversion sequence S1 is a better conversion sequence
3590   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3591 
3592   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3593   //     sequences in the canonical form defined by 13.3.3.1.1,
3594   //     excluding any Lvalue Transformation; the identity conversion
3595   //     sequence is considered to be a subsequence of any
3596   //     non-identity conversion sequence) or, if not that,
3597   if (ImplicitConversionSequence::CompareKind CK
3598         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3599     return CK;
3600 
3601   //  -- the rank of S1 is better than the rank of S2 (by the rules
3602   //     defined below), or, if not that,
3603   ImplicitConversionRank Rank1 = SCS1.getRank();
3604   ImplicitConversionRank Rank2 = SCS2.getRank();
3605   if (Rank1 < Rank2)
3606     return ImplicitConversionSequence::Better;
3607   else if (Rank2 < Rank1)
3608     return ImplicitConversionSequence::Worse;
3609 
3610   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3611   // are indistinguishable unless one of the following rules
3612   // applies:
3613 
3614   //   A conversion that is not a conversion of a pointer, or
3615   //   pointer to member, to bool is better than another conversion
3616   //   that is such a conversion.
3617   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3618     return SCS2.isPointerConversionToBool()
3619              ? ImplicitConversionSequence::Better
3620              : ImplicitConversionSequence::Worse;
3621 
3622   // C++ [over.ics.rank]p4b2:
3623   //
3624   //   If class B is derived directly or indirectly from class A,
3625   //   conversion of B* to A* is better than conversion of B* to
3626   //   void*, and conversion of A* to void* is better than conversion
3627   //   of B* to void*.
3628   bool SCS1ConvertsToVoid
3629     = SCS1.isPointerConversionToVoidPointer(S.Context);
3630   bool SCS2ConvertsToVoid
3631     = SCS2.isPointerConversionToVoidPointer(S.Context);
3632   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3633     // Exactly one of the conversion sequences is a conversion to
3634     // a void pointer; it's the worse conversion.
3635     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3636                               : ImplicitConversionSequence::Worse;
3637   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3638     // Neither conversion sequence converts to a void pointer; compare
3639     // their derived-to-base conversions.
3640     if (ImplicitConversionSequence::CompareKind DerivedCK
3641           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3642       return DerivedCK;
3643   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3644              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3645     // Both conversion sequences are conversions to void
3646     // pointers. Compare the source types to determine if there's an
3647     // inheritance relationship in their sources.
3648     QualType FromType1 = SCS1.getFromType();
3649     QualType FromType2 = SCS2.getFromType();
3650 
3651     // Adjust the types we're converting from via the array-to-pointer
3652     // conversion, if we need to.
3653     if (SCS1.First == ICK_Array_To_Pointer)
3654       FromType1 = S.Context.getArrayDecayedType(FromType1);
3655     if (SCS2.First == ICK_Array_To_Pointer)
3656       FromType2 = S.Context.getArrayDecayedType(FromType2);
3657 
3658     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3659     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3660 
3661     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3662       return ImplicitConversionSequence::Better;
3663     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3664       return ImplicitConversionSequence::Worse;
3665 
3666     // Objective-C++: If one interface is more specific than the
3667     // other, it is the better one.
3668     const ObjCObjectPointerType* FromObjCPtr1
3669       = FromType1->getAs<ObjCObjectPointerType>();
3670     const ObjCObjectPointerType* FromObjCPtr2
3671       = FromType2->getAs<ObjCObjectPointerType>();
3672     if (FromObjCPtr1 && FromObjCPtr2) {
3673       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3674                                                           FromObjCPtr2);
3675       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3676                                                            FromObjCPtr1);
3677       if (AssignLeft != AssignRight) {
3678         return AssignLeft? ImplicitConversionSequence::Better
3679                          : ImplicitConversionSequence::Worse;
3680       }
3681     }
3682   }
3683 
3684   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3685   // bullet 3).
3686   if (ImplicitConversionSequence::CompareKind QualCK
3687         = CompareQualificationConversions(S, SCS1, SCS2))
3688     return QualCK;
3689 
3690   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3691     // Check for a better reference binding based on the kind of bindings.
3692     if (isBetterReferenceBindingKind(SCS1, SCS2))
3693       return ImplicitConversionSequence::Better;
3694     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3695       return ImplicitConversionSequence::Worse;
3696 
3697     // C++ [over.ics.rank]p3b4:
3698     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3699     //      which the references refer are the same type except for
3700     //      top-level cv-qualifiers, and the type to which the reference
3701     //      initialized by S2 refers is more cv-qualified than the type
3702     //      to which the reference initialized by S1 refers.
3703     QualType T1 = SCS1.getToType(2);
3704     QualType T2 = SCS2.getToType(2);
3705     T1 = S.Context.getCanonicalType(T1);
3706     T2 = S.Context.getCanonicalType(T2);
3707     Qualifiers T1Quals, T2Quals;
3708     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3709     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3710     if (UnqualT1 == UnqualT2) {
3711       // Objective-C++ ARC: If the references refer to objects with different
3712       // lifetimes, prefer bindings that don't change lifetime.
3713       if (SCS1.ObjCLifetimeConversionBinding !=
3714                                           SCS2.ObjCLifetimeConversionBinding) {
3715         return SCS1.ObjCLifetimeConversionBinding
3716                                            ? ImplicitConversionSequence::Worse
3717                                            : ImplicitConversionSequence::Better;
3718       }
3719 
3720       // If the type is an array type, promote the element qualifiers to the
3721       // type for comparison.
3722       if (isa<ArrayType>(T1) && T1Quals)
3723         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3724       if (isa<ArrayType>(T2) && T2Quals)
3725         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3726       if (T2.isMoreQualifiedThan(T1))
3727         return ImplicitConversionSequence::Better;
3728       else if (T1.isMoreQualifiedThan(T2))
3729         return ImplicitConversionSequence::Worse;
3730     }
3731   }
3732 
3733   // In Microsoft mode, prefer an integral conversion to a
3734   // floating-to-integral conversion if the integral conversion
3735   // is between types of the same size.
3736   // For example:
3737   // void f(float);
3738   // void f(int);
3739   // int main {
3740   //    long a;
3741   //    f(a);
3742   // }
3743   // Here, MSVC will call f(int) instead of generating a compile error
3744   // as clang will do in standard mode.
3745   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3746       SCS2.Second == ICK_Floating_Integral &&
3747       S.Context.getTypeSize(SCS1.getFromType()) ==
3748           S.Context.getTypeSize(SCS1.getToType(2)))
3749     return ImplicitConversionSequence::Better;
3750 
3751   return ImplicitConversionSequence::Indistinguishable;
3752 }
3753 
3754 /// CompareQualificationConversions - Compares two standard conversion
3755 /// sequences to determine whether they can be ranked based on their
3756 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3757 static ImplicitConversionSequence::CompareKind
3758 CompareQualificationConversions(Sema &S,
3759                                 const StandardConversionSequence& SCS1,
3760                                 const StandardConversionSequence& SCS2) {
3761   // C++ 13.3.3.2p3:
3762   //  -- S1 and S2 differ only in their qualification conversion and
3763   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3764   //     cv-qualification signature of type T1 is a proper subset of
3765   //     the cv-qualification signature of type T2, and S1 is not the
3766   //     deprecated string literal array-to-pointer conversion (4.2).
3767   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3768       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3769     return ImplicitConversionSequence::Indistinguishable;
3770 
3771   // FIXME: the example in the standard doesn't use a qualification
3772   // conversion (!)
3773   QualType T1 = SCS1.getToType(2);
3774   QualType T2 = SCS2.getToType(2);
3775   T1 = S.Context.getCanonicalType(T1);
3776   T2 = S.Context.getCanonicalType(T2);
3777   Qualifiers T1Quals, T2Quals;
3778   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3779   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3780 
3781   // If the types are the same, we won't learn anything by unwrapped
3782   // them.
3783   if (UnqualT1 == UnqualT2)
3784     return ImplicitConversionSequence::Indistinguishable;
3785 
3786   // If the type is an array type, promote the element qualifiers to the type
3787   // for comparison.
3788   if (isa<ArrayType>(T1) && T1Quals)
3789     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3790   if (isa<ArrayType>(T2) && T2Quals)
3791     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3792 
3793   ImplicitConversionSequence::CompareKind Result
3794     = ImplicitConversionSequence::Indistinguishable;
3795 
3796   // Objective-C++ ARC:
3797   //   Prefer qualification conversions not involving a change in lifetime
3798   //   to qualification conversions that do not change lifetime.
3799   if (SCS1.QualificationIncludesObjCLifetime !=
3800                                       SCS2.QualificationIncludesObjCLifetime) {
3801     Result = SCS1.QualificationIncludesObjCLifetime
3802                ? ImplicitConversionSequence::Worse
3803                : ImplicitConversionSequence::Better;
3804   }
3805 
3806   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3807     // Within each iteration of the loop, we check the qualifiers to
3808     // determine if this still looks like a qualification
3809     // conversion. Then, if all is well, we unwrap one more level of
3810     // pointers or pointers-to-members and do it all again
3811     // until there are no more pointers or pointers-to-members left
3812     // to unwrap. This essentially mimics what
3813     // IsQualificationConversion does, but here we're checking for a
3814     // strict subset of qualifiers.
3815     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3816       // The qualifiers are the same, so this doesn't tell us anything
3817       // about how the sequences rank.
3818       ;
3819     else if (T2.isMoreQualifiedThan(T1)) {
3820       // T1 has fewer qualifiers, so it could be the better sequence.
3821       if (Result == ImplicitConversionSequence::Worse)
3822         // Neither has qualifiers that are a subset of the other's
3823         // qualifiers.
3824         return ImplicitConversionSequence::Indistinguishable;
3825 
3826       Result = ImplicitConversionSequence::Better;
3827     } else if (T1.isMoreQualifiedThan(T2)) {
3828       // T2 has fewer qualifiers, so it could be the better sequence.
3829       if (Result == ImplicitConversionSequence::Better)
3830         // Neither has qualifiers that are a subset of the other's
3831         // qualifiers.
3832         return ImplicitConversionSequence::Indistinguishable;
3833 
3834       Result = ImplicitConversionSequence::Worse;
3835     } else {
3836       // Qualifiers are disjoint.
3837       return ImplicitConversionSequence::Indistinguishable;
3838     }
3839 
3840     // If the types after this point are equivalent, we're done.
3841     if (S.Context.hasSameUnqualifiedType(T1, T2))
3842       break;
3843   }
3844 
3845   // Check that the winning standard conversion sequence isn't using
3846   // the deprecated string literal array to pointer conversion.
3847   switch (Result) {
3848   case ImplicitConversionSequence::Better:
3849     if (SCS1.DeprecatedStringLiteralToCharPtr)
3850       Result = ImplicitConversionSequence::Indistinguishable;
3851     break;
3852 
3853   case ImplicitConversionSequence::Indistinguishable:
3854     break;
3855 
3856   case ImplicitConversionSequence::Worse:
3857     if (SCS2.DeprecatedStringLiteralToCharPtr)
3858       Result = ImplicitConversionSequence::Indistinguishable;
3859     break;
3860   }
3861 
3862   return Result;
3863 }
3864 
3865 /// CompareDerivedToBaseConversions - Compares two standard conversion
3866 /// sequences to determine whether they can be ranked based on their
3867 /// various kinds of derived-to-base conversions (C++
3868 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3869 /// conversions between Objective-C interface types.
3870 static ImplicitConversionSequence::CompareKind
3871 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3872                                 const StandardConversionSequence& SCS1,
3873                                 const StandardConversionSequence& SCS2) {
3874   QualType FromType1 = SCS1.getFromType();
3875   QualType ToType1 = SCS1.getToType(1);
3876   QualType FromType2 = SCS2.getFromType();
3877   QualType ToType2 = SCS2.getToType(1);
3878 
3879   // Adjust the types we're converting from via the array-to-pointer
3880   // conversion, if we need to.
3881   if (SCS1.First == ICK_Array_To_Pointer)
3882     FromType1 = S.Context.getArrayDecayedType(FromType1);
3883   if (SCS2.First == ICK_Array_To_Pointer)
3884     FromType2 = S.Context.getArrayDecayedType(FromType2);
3885 
3886   // Canonicalize all of the types.
3887   FromType1 = S.Context.getCanonicalType(FromType1);
3888   ToType1 = S.Context.getCanonicalType(ToType1);
3889   FromType2 = S.Context.getCanonicalType(FromType2);
3890   ToType2 = S.Context.getCanonicalType(ToType2);
3891 
3892   // C++ [over.ics.rank]p4b3:
3893   //
3894   //   If class B is derived directly or indirectly from class A and
3895   //   class C is derived directly or indirectly from B,
3896   //
3897   // Compare based on pointer conversions.
3898   if (SCS1.Second == ICK_Pointer_Conversion &&
3899       SCS2.Second == ICK_Pointer_Conversion &&
3900       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3901       FromType1->isPointerType() && FromType2->isPointerType() &&
3902       ToType1->isPointerType() && ToType2->isPointerType()) {
3903     QualType FromPointee1
3904       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3905     QualType ToPointee1
3906       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3907     QualType FromPointee2
3908       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3909     QualType ToPointee2
3910       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3911 
3912     //   -- conversion of C* to B* is better than conversion of C* to A*,
3913     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3914       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3915         return ImplicitConversionSequence::Better;
3916       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3917         return ImplicitConversionSequence::Worse;
3918     }
3919 
3920     //   -- conversion of B* to A* is better than conversion of C* to A*,
3921     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3922       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3923         return ImplicitConversionSequence::Better;
3924       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3925         return ImplicitConversionSequence::Worse;
3926     }
3927   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3928              SCS2.Second == ICK_Pointer_Conversion) {
3929     const ObjCObjectPointerType *FromPtr1
3930       = FromType1->getAs<ObjCObjectPointerType>();
3931     const ObjCObjectPointerType *FromPtr2
3932       = FromType2->getAs<ObjCObjectPointerType>();
3933     const ObjCObjectPointerType *ToPtr1
3934       = ToType1->getAs<ObjCObjectPointerType>();
3935     const ObjCObjectPointerType *ToPtr2
3936       = ToType2->getAs<ObjCObjectPointerType>();
3937 
3938     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3939       // Apply the same conversion ranking rules for Objective-C pointer types
3940       // that we do for C++ pointers to class types. However, we employ the
3941       // Objective-C pseudo-subtyping relationship used for assignment of
3942       // Objective-C pointer types.
3943       bool FromAssignLeft
3944         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3945       bool FromAssignRight
3946         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3947       bool ToAssignLeft
3948         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3949       bool ToAssignRight
3950         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3951 
3952       // A conversion to an a non-id object pointer type or qualified 'id'
3953       // type is better than a conversion to 'id'.
3954       if (ToPtr1->isObjCIdType() &&
3955           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3956         return ImplicitConversionSequence::Worse;
3957       if (ToPtr2->isObjCIdType() &&
3958           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3959         return ImplicitConversionSequence::Better;
3960 
3961       // A conversion to a non-id object pointer type is better than a
3962       // conversion to a qualified 'id' type
3963       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3964         return ImplicitConversionSequence::Worse;
3965       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3966         return ImplicitConversionSequence::Better;
3967 
3968       // A conversion to an a non-Class object pointer type or qualified 'Class'
3969       // type is better than a conversion to 'Class'.
3970       if (ToPtr1->isObjCClassType() &&
3971           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3972         return ImplicitConversionSequence::Worse;
3973       if (ToPtr2->isObjCClassType() &&
3974           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3975         return ImplicitConversionSequence::Better;
3976 
3977       // A conversion to a non-Class object pointer type is better than a
3978       // conversion to a qualified 'Class' type.
3979       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3980         return ImplicitConversionSequence::Worse;
3981       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3982         return ImplicitConversionSequence::Better;
3983 
3984       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3985       if (S.Context.hasSameType(FromType1, FromType2) &&
3986           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3987           (ToAssignLeft != ToAssignRight))
3988         return ToAssignLeft? ImplicitConversionSequence::Worse
3989                            : ImplicitConversionSequence::Better;
3990 
3991       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3992       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3993           (FromAssignLeft != FromAssignRight))
3994         return FromAssignLeft? ImplicitConversionSequence::Better
3995         : ImplicitConversionSequence::Worse;
3996     }
3997   }
3998 
3999   // Ranking of member-pointer types.
4000   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4001       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4002       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4003     const MemberPointerType * FromMemPointer1 =
4004                                         FromType1->getAs<MemberPointerType>();
4005     const MemberPointerType * ToMemPointer1 =
4006                                           ToType1->getAs<MemberPointerType>();
4007     const MemberPointerType * FromMemPointer2 =
4008                                           FromType2->getAs<MemberPointerType>();
4009     const MemberPointerType * ToMemPointer2 =
4010                                           ToType2->getAs<MemberPointerType>();
4011     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4012     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4013     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4014     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4015     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4016     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4017     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4018     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4019     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4020     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4021       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4022         return ImplicitConversionSequence::Worse;
4023       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4024         return ImplicitConversionSequence::Better;
4025     }
4026     // conversion of B::* to C::* is better than conversion of A::* to C::*
4027     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4028       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4029         return ImplicitConversionSequence::Better;
4030       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4031         return ImplicitConversionSequence::Worse;
4032     }
4033   }
4034 
4035   if (SCS1.Second == ICK_Derived_To_Base) {
4036     //   -- conversion of C to B is better than conversion of C to A,
4037     //   -- binding of an expression of type C to a reference of type
4038     //      B& is better than binding an expression of type C to a
4039     //      reference of type A&,
4040     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4041         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4042       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4043         return ImplicitConversionSequence::Better;
4044       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4045         return ImplicitConversionSequence::Worse;
4046     }
4047 
4048     //   -- conversion of B to A is better than conversion of C to A.
4049     //   -- binding of an expression of type B to a reference of type
4050     //      A& is better than binding an expression of type C to a
4051     //      reference of type A&,
4052     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4053         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4054       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4055         return ImplicitConversionSequence::Better;
4056       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4057         return ImplicitConversionSequence::Worse;
4058     }
4059   }
4060 
4061   return ImplicitConversionSequence::Indistinguishable;
4062 }
4063 
4064 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4065 /// C++ class.
4066 static bool isTypeValid(QualType T) {
4067   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4068     return !Record->isInvalidDecl();
4069 
4070   return true;
4071 }
4072 
4073 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4074 /// determine whether they are reference-related,
4075 /// reference-compatible, reference-compatible with added
4076 /// qualification, or incompatible, for use in C++ initialization by
4077 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4078 /// type, and the first type (T1) is the pointee type of the reference
4079 /// type being initialized.
4080 Sema::ReferenceCompareResult
4081 Sema::CompareReferenceRelationship(SourceLocation Loc,
4082                                    QualType OrigT1, QualType OrigT2,
4083                                    bool &DerivedToBase,
4084                                    bool &ObjCConversion,
4085                                    bool &ObjCLifetimeConversion) {
4086   assert(!OrigT1->isReferenceType() &&
4087     "T1 must be the pointee type of the reference type");
4088   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4089 
4090   QualType T1 = Context.getCanonicalType(OrigT1);
4091   QualType T2 = Context.getCanonicalType(OrigT2);
4092   Qualifiers T1Quals, T2Quals;
4093   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4094   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4095 
4096   // C++ [dcl.init.ref]p4:
4097   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4098   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4099   //   T1 is a base class of T2.
4100   DerivedToBase = false;
4101   ObjCConversion = false;
4102   ObjCLifetimeConversion = false;
4103   if (UnqualT1 == UnqualT2) {
4104     // Nothing to do.
4105   } else if (isCompleteType(Loc, OrigT2) &&
4106              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4107              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4108     DerivedToBase = true;
4109   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4110            UnqualT2->isObjCObjectOrInterfaceType() &&
4111            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4112     ObjCConversion = true;
4113   else
4114     return Ref_Incompatible;
4115 
4116   // At this point, we know that T1 and T2 are reference-related (at
4117   // least).
4118 
4119   // If the type is an array type, promote the element qualifiers to the type
4120   // for comparison.
4121   if (isa<ArrayType>(T1) && T1Quals)
4122     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4123   if (isa<ArrayType>(T2) && T2Quals)
4124     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4125 
4126   // C++ [dcl.init.ref]p4:
4127   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4128   //   reference-related to T2 and cv1 is the same cv-qualification
4129   //   as, or greater cv-qualification than, cv2. For purposes of
4130   //   overload resolution, cases for which cv1 is greater
4131   //   cv-qualification than cv2 are identified as
4132   //   reference-compatible with added qualification (see 13.3.3.2).
4133   //
4134   // Note that we also require equivalence of Objective-C GC and address-space
4135   // qualifiers when performing these computations, so that e.g., an int in
4136   // address space 1 is not reference-compatible with an int in address
4137   // space 2.
4138   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4139       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4140     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4141       ObjCLifetimeConversion = true;
4142 
4143     T1Quals.removeObjCLifetime();
4144     T2Quals.removeObjCLifetime();
4145   }
4146 
4147   if (T1Quals == T2Quals)
4148     return Ref_Compatible;
4149   else if (T1Quals.compatiblyIncludes(T2Quals))
4150     return Ref_Compatible_With_Added_Qualification;
4151   else
4152     return Ref_Related;
4153 }
4154 
4155 /// \brief Look for a user-defined conversion to an value reference-compatible
4156 ///        with DeclType. Return true if something definite is found.
4157 static bool
4158 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4159                          QualType DeclType, SourceLocation DeclLoc,
4160                          Expr *Init, QualType T2, bool AllowRvalues,
4161                          bool AllowExplicit) {
4162   assert(T2->isRecordType() && "Can only find conversions of record types.");
4163   CXXRecordDecl *T2RecordDecl
4164     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4165 
4166   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4167   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4168   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4169     NamedDecl *D = *I;
4170     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4171     if (isa<UsingShadowDecl>(D))
4172       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4173 
4174     FunctionTemplateDecl *ConvTemplate
4175       = dyn_cast<FunctionTemplateDecl>(D);
4176     CXXConversionDecl *Conv;
4177     if (ConvTemplate)
4178       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4179     else
4180       Conv = cast<CXXConversionDecl>(D);
4181 
4182     // If this is an explicit conversion, and we're not allowed to consider
4183     // explicit conversions, skip it.
4184     if (!AllowExplicit && Conv->isExplicit())
4185       continue;
4186 
4187     if (AllowRvalues) {
4188       bool DerivedToBase = false;
4189       bool ObjCConversion = false;
4190       bool ObjCLifetimeConversion = false;
4191 
4192       // If we are initializing an rvalue reference, don't permit conversion
4193       // functions that return lvalues.
4194       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4195         const ReferenceType *RefType
4196           = Conv->getConversionType()->getAs<LValueReferenceType>();
4197         if (RefType && !RefType->getPointeeType()->isFunctionType())
4198           continue;
4199       }
4200 
4201       if (!ConvTemplate &&
4202           S.CompareReferenceRelationship(
4203             DeclLoc,
4204             Conv->getConversionType().getNonReferenceType()
4205               .getUnqualifiedType(),
4206             DeclType.getNonReferenceType().getUnqualifiedType(),
4207             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4208           Sema::Ref_Incompatible)
4209         continue;
4210     } else {
4211       // If the conversion function doesn't return a reference type,
4212       // it can't be considered for this conversion. An rvalue reference
4213       // is only acceptable if its referencee is a function type.
4214 
4215       const ReferenceType *RefType =
4216         Conv->getConversionType()->getAs<ReferenceType>();
4217       if (!RefType ||
4218           (!RefType->isLValueReferenceType() &&
4219            !RefType->getPointeeType()->isFunctionType()))
4220         continue;
4221     }
4222 
4223     if (ConvTemplate)
4224       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4225                                        Init, DeclType, CandidateSet,
4226                                        /*AllowObjCConversionOnExplicit=*/false);
4227     else
4228       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4229                                DeclType, CandidateSet,
4230                                /*AllowObjCConversionOnExplicit=*/false);
4231   }
4232 
4233   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4234 
4235   OverloadCandidateSet::iterator Best;
4236   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4237   case OR_Success:
4238     // C++ [over.ics.ref]p1:
4239     //
4240     //   [...] If the parameter binds directly to the result of
4241     //   applying a conversion function to the argument
4242     //   expression, the implicit conversion sequence is a
4243     //   user-defined conversion sequence (13.3.3.1.2), with the
4244     //   second standard conversion sequence either an identity
4245     //   conversion or, if the conversion function returns an
4246     //   entity of a type that is a derived class of the parameter
4247     //   type, a derived-to-base Conversion.
4248     if (!Best->FinalConversion.DirectBinding)
4249       return false;
4250 
4251     ICS.setUserDefined();
4252     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4253     ICS.UserDefined.After = Best->FinalConversion;
4254     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4255     ICS.UserDefined.ConversionFunction = Best->Function;
4256     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4257     ICS.UserDefined.EllipsisConversion = false;
4258     assert(ICS.UserDefined.After.ReferenceBinding &&
4259            ICS.UserDefined.After.DirectBinding &&
4260            "Expected a direct reference binding!");
4261     return true;
4262 
4263   case OR_Ambiguous:
4264     ICS.setAmbiguous();
4265     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4266          Cand != CandidateSet.end(); ++Cand)
4267       if (Cand->Viable)
4268         ICS.Ambiguous.addConversion(Cand->Function);
4269     return true;
4270 
4271   case OR_No_Viable_Function:
4272   case OR_Deleted:
4273     // There was no suitable conversion, or we found a deleted
4274     // conversion; continue with other checks.
4275     return false;
4276   }
4277 
4278   llvm_unreachable("Invalid OverloadResult!");
4279 }
4280 
4281 /// \brief Compute an implicit conversion sequence for reference
4282 /// initialization.
4283 static ImplicitConversionSequence
4284 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4285                  SourceLocation DeclLoc,
4286                  bool SuppressUserConversions,
4287                  bool AllowExplicit) {
4288   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4289 
4290   // Most paths end in a failed conversion.
4291   ImplicitConversionSequence ICS;
4292   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4293 
4294   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4295   QualType T2 = Init->getType();
4296 
4297   // If the initializer is the address of an overloaded function, try
4298   // to resolve the overloaded function. If all goes well, T2 is the
4299   // type of the resulting function.
4300   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4301     DeclAccessPair Found;
4302     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4303                                                                 false, Found))
4304       T2 = Fn->getType();
4305   }
4306 
4307   // Compute some basic properties of the types and the initializer.
4308   bool isRValRef = DeclType->isRValueReferenceType();
4309   bool DerivedToBase = false;
4310   bool ObjCConversion = false;
4311   bool ObjCLifetimeConversion = false;
4312   Expr::Classification InitCategory = Init->Classify(S.Context);
4313   Sema::ReferenceCompareResult RefRelationship
4314     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4315                                      ObjCConversion, ObjCLifetimeConversion);
4316 
4317 
4318   // C++0x [dcl.init.ref]p5:
4319   //   A reference to type "cv1 T1" is initialized by an expression
4320   //   of type "cv2 T2" as follows:
4321 
4322   //     -- If reference is an lvalue reference and the initializer expression
4323   if (!isRValRef) {
4324     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4325     //        reference-compatible with "cv2 T2," or
4326     //
4327     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4328     if (InitCategory.isLValue() &&
4329         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4330       // C++ [over.ics.ref]p1:
4331       //   When a parameter of reference type binds directly (8.5.3)
4332       //   to an argument expression, the implicit conversion sequence
4333       //   is the identity conversion, unless the argument expression
4334       //   has a type that is a derived class of the parameter type,
4335       //   in which case the implicit conversion sequence is a
4336       //   derived-to-base Conversion (13.3.3.1).
4337       ICS.setStandard();
4338       ICS.Standard.First = ICK_Identity;
4339       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4340                          : ObjCConversion? ICK_Compatible_Conversion
4341                          : ICK_Identity;
4342       ICS.Standard.Third = ICK_Identity;
4343       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4344       ICS.Standard.setToType(0, T2);
4345       ICS.Standard.setToType(1, T1);
4346       ICS.Standard.setToType(2, T1);
4347       ICS.Standard.ReferenceBinding = true;
4348       ICS.Standard.DirectBinding = true;
4349       ICS.Standard.IsLvalueReference = !isRValRef;
4350       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4351       ICS.Standard.BindsToRvalue = false;
4352       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4353       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4354       ICS.Standard.CopyConstructor = nullptr;
4355       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4356 
4357       // Nothing more to do: the inaccessibility/ambiguity check for
4358       // derived-to-base conversions is suppressed when we're
4359       // computing the implicit conversion sequence (C++
4360       // [over.best.ics]p2).
4361       return ICS;
4362     }
4363 
4364     //       -- has a class type (i.e., T2 is a class type), where T1 is
4365     //          not reference-related to T2, and can be implicitly
4366     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4367     //          is reference-compatible with "cv3 T3" 92) (this
4368     //          conversion is selected by enumerating the applicable
4369     //          conversion functions (13.3.1.6) and choosing the best
4370     //          one through overload resolution (13.3)),
4371     if (!SuppressUserConversions && T2->isRecordType() &&
4372         S.isCompleteType(DeclLoc, T2) &&
4373         RefRelationship == Sema::Ref_Incompatible) {
4374       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4375                                    Init, T2, /*AllowRvalues=*/false,
4376                                    AllowExplicit))
4377         return ICS;
4378     }
4379   }
4380 
4381   //     -- Otherwise, the reference shall be an lvalue reference to a
4382   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4383   //        shall be an rvalue reference.
4384   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4385     return ICS;
4386 
4387   //       -- If the initializer expression
4388   //
4389   //            -- is an xvalue, class prvalue, array prvalue or function
4390   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4391   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4392       (InitCategory.isXValue() ||
4393       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4394       (InitCategory.isLValue() && T2->isFunctionType()))) {
4395     ICS.setStandard();
4396     ICS.Standard.First = ICK_Identity;
4397     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4398                       : ObjCConversion? ICK_Compatible_Conversion
4399                       : ICK_Identity;
4400     ICS.Standard.Third = ICK_Identity;
4401     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4402     ICS.Standard.setToType(0, T2);
4403     ICS.Standard.setToType(1, T1);
4404     ICS.Standard.setToType(2, T1);
4405     ICS.Standard.ReferenceBinding = true;
4406     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4407     // binding unless we're binding to a class prvalue.
4408     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4409     // allow the use of rvalue references in C++98/03 for the benefit of
4410     // standard library implementors; therefore, we need the xvalue check here.
4411     ICS.Standard.DirectBinding =
4412       S.getLangOpts().CPlusPlus11 ||
4413       !(InitCategory.isPRValue() || T2->isRecordType());
4414     ICS.Standard.IsLvalueReference = !isRValRef;
4415     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4416     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4417     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4418     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4419     ICS.Standard.CopyConstructor = nullptr;
4420     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4421     return ICS;
4422   }
4423 
4424   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4425   //               reference-related to T2, and can be implicitly converted to
4426   //               an xvalue, class prvalue, or function lvalue of type
4427   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4428   //               "cv3 T3",
4429   //
4430   //          then the reference is bound to the value of the initializer
4431   //          expression in the first case and to the result of the conversion
4432   //          in the second case (or, in either case, to an appropriate base
4433   //          class subobject).
4434   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4435       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4436       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4437                                Init, T2, /*AllowRvalues=*/true,
4438                                AllowExplicit)) {
4439     // In the second case, if the reference is an rvalue reference
4440     // and the second standard conversion sequence of the
4441     // user-defined conversion sequence includes an lvalue-to-rvalue
4442     // conversion, the program is ill-formed.
4443     if (ICS.isUserDefined() && isRValRef &&
4444         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4445       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4446 
4447     return ICS;
4448   }
4449 
4450   // A temporary of function type cannot be created; don't even try.
4451   if (T1->isFunctionType())
4452     return ICS;
4453 
4454   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4455   //          initialized from the initializer expression using the
4456   //          rules for a non-reference copy initialization (8.5). The
4457   //          reference is then bound to the temporary. If T1 is
4458   //          reference-related to T2, cv1 must be the same
4459   //          cv-qualification as, or greater cv-qualification than,
4460   //          cv2; otherwise, the program is ill-formed.
4461   if (RefRelationship == Sema::Ref_Related) {
4462     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4463     // we would be reference-compatible or reference-compatible with
4464     // added qualification. But that wasn't the case, so the reference
4465     // initialization fails.
4466     //
4467     // Note that we only want to check address spaces and cvr-qualifiers here.
4468     // ObjC GC and lifetime qualifiers aren't important.
4469     Qualifiers T1Quals = T1.getQualifiers();
4470     Qualifiers T2Quals = T2.getQualifiers();
4471     T1Quals.removeObjCGCAttr();
4472     T1Quals.removeObjCLifetime();
4473     T2Quals.removeObjCGCAttr();
4474     T2Quals.removeObjCLifetime();
4475     if (!T1Quals.compatiblyIncludes(T2Quals))
4476       return ICS;
4477   }
4478 
4479   // If at least one of the types is a class type, the types are not
4480   // related, and we aren't allowed any user conversions, the
4481   // reference binding fails. This case is important for breaking
4482   // recursion, since TryImplicitConversion below will attempt to
4483   // create a temporary through the use of a copy constructor.
4484   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4485       (T1->isRecordType() || T2->isRecordType()))
4486     return ICS;
4487 
4488   // If T1 is reference-related to T2 and the reference is an rvalue
4489   // reference, the initializer expression shall not be an lvalue.
4490   if (RefRelationship >= Sema::Ref_Related &&
4491       isRValRef && Init->Classify(S.Context).isLValue())
4492     return ICS;
4493 
4494   // C++ [over.ics.ref]p2:
4495   //   When a parameter of reference type is not bound directly to
4496   //   an argument expression, the conversion sequence is the one
4497   //   required to convert the argument expression to the
4498   //   underlying type of the reference according to
4499   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4500   //   to copy-initializing a temporary of the underlying type with
4501   //   the argument expression. Any difference in top-level
4502   //   cv-qualification is subsumed by the initialization itself
4503   //   and does not constitute a conversion.
4504   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4505                               /*AllowExplicit=*/false,
4506                               /*InOverloadResolution=*/false,
4507                               /*CStyle=*/false,
4508                               /*AllowObjCWritebackConversion=*/false,
4509                               /*AllowObjCConversionOnExplicit=*/false);
4510 
4511   // Of course, that's still a reference binding.
4512   if (ICS.isStandard()) {
4513     ICS.Standard.ReferenceBinding = true;
4514     ICS.Standard.IsLvalueReference = !isRValRef;
4515     ICS.Standard.BindsToFunctionLvalue = false;
4516     ICS.Standard.BindsToRvalue = true;
4517     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4518     ICS.Standard.ObjCLifetimeConversionBinding = false;
4519   } else if (ICS.isUserDefined()) {
4520     const ReferenceType *LValRefType =
4521         ICS.UserDefined.ConversionFunction->getReturnType()
4522             ->getAs<LValueReferenceType>();
4523 
4524     // C++ [over.ics.ref]p3:
4525     //   Except for an implicit object parameter, for which see 13.3.1, a
4526     //   standard conversion sequence cannot be formed if it requires [...]
4527     //   binding an rvalue reference to an lvalue other than a function
4528     //   lvalue.
4529     // Note that the function case is not possible here.
4530     if (DeclType->isRValueReferenceType() && LValRefType) {
4531       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4532       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4533       // reference to an rvalue!
4534       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4535       return ICS;
4536     }
4537 
4538     ICS.UserDefined.Before.setAsIdentityConversion();
4539     ICS.UserDefined.After.ReferenceBinding = true;
4540     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4541     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4542     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4543     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4544     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4545   }
4546 
4547   return ICS;
4548 }
4549 
4550 static ImplicitConversionSequence
4551 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4552                       bool SuppressUserConversions,
4553                       bool InOverloadResolution,
4554                       bool AllowObjCWritebackConversion,
4555                       bool AllowExplicit = false);
4556 
4557 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4558 /// initializer list From.
4559 static ImplicitConversionSequence
4560 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4561                   bool SuppressUserConversions,
4562                   bool InOverloadResolution,
4563                   bool AllowObjCWritebackConversion) {
4564   // C++11 [over.ics.list]p1:
4565   //   When an argument is an initializer list, it is not an expression and
4566   //   special rules apply for converting it to a parameter type.
4567 
4568   ImplicitConversionSequence Result;
4569   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4570 
4571   // We need a complete type for what follows. Incomplete types can never be
4572   // initialized from init lists.
4573   if (!S.isCompleteType(From->getLocStart(), ToType))
4574     return Result;
4575 
4576   // Per DR1467:
4577   //   If the parameter type is a class X and the initializer list has a single
4578   //   element of type cv U, where U is X or a class derived from X, the
4579   //   implicit conversion sequence is the one required to convert the element
4580   //   to the parameter type.
4581   //
4582   //   Otherwise, if the parameter type is a character array [... ]
4583   //   and the initializer list has a single element that is an
4584   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4585   //   implicit conversion sequence is the identity conversion.
4586   if (From->getNumInits() == 1) {
4587     if (ToType->isRecordType()) {
4588       QualType InitType = From->getInit(0)->getType();
4589       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4590           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4591         return TryCopyInitialization(S, From->getInit(0), ToType,
4592                                      SuppressUserConversions,
4593                                      InOverloadResolution,
4594                                      AllowObjCWritebackConversion);
4595     }
4596     // FIXME: Check the other conditions here: array of character type,
4597     // initializer is a string literal.
4598     if (ToType->isArrayType()) {
4599       InitializedEntity Entity =
4600         InitializedEntity::InitializeParameter(S.Context, ToType,
4601                                                /*Consumed=*/false);
4602       if (S.CanPerformCopyInitialization(Entity, From)) {
4603         Result.setStandard();
4604         Result.Standard.setAsIdentityConversion();
4605         Result.Standard.setFromType(ToType);
4606         Result.Standard.setAllToTypes(ToType);
4607         return Result;
4608       }
4609     }
4610   }
4611 
4612   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4613   // C++11 [over.ics.list]p2:
4614   //   If the parameter type is std::initializer_list<X> or "array of X" and
4615   //   all the elements can be implicitly converted to X, the implicit
4616   //   conversion sequence is the worst conversion necessary to convert an
4617   //   element of the list to X.
4618   //
4619   // C++14 [over.ics.list]p3:
4620   //   Otherwise, if the parameter type is "array of N X", if the initializer
4621   //   list has exactly N elements or if it has fewer than N elements and X is
4622   //   default-constructible, and if all the elements of the initializer list
4623   //   can be implicitly converted to X, the implicit conversion sequence is
4624   //   the worst conversion necessary to convert an element of the list to X.
4625   //
4626   // FIXME: We're missing a lot of these checks.
4627   bool toStdInitializerList = false;
4628   QualType X;
4629   if (ToType->isArrayType())
4630     X = S.Context.getAsArrayType(ToType)->getElementType();
4631   else
4632     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4633   if (!X.isNull()) {
4634     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4635       Expr *Init = From->getInit(i);
4636       ImplicitConversionSequence ICS =
4637           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4638                                 InOverloadResolution,
4639                                 AllowObjCWritebackConversion);
4640       // If a single element isn't convertible, fail.
4641       if (ICS.isBad()) {
4642         Result = ICS;
4643         break;
4644       }
4645       // Otherwise, look for the worst conversion.
4646       if (Result.isBad() ||
4647           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4648                                              Result) ==
4649               ImplicitConversionSequence::Worse)
4650         Result = ICS;
4651     }
4652 
4653     // For an empty list, we won't have computed any conversion sequence.
4654     // Introduce the identity conversion sequence.
4655     if (From->getNumInits() == 0) {
4656       Result.setStandard();
4657       Result.Standard.setAsIdentityConversion();
4658       Result.Standard.setFromType(ToType);
4659       Result.Standard.setAllToTypes(ToType);
4660     }
4661 
4662     Result.setStdInitializerListElement(toStdInitializerList);
4663     return Result;
4664   }
4665 
4666   // C++14 [over.ics.list]p4:
4667   // C++11 [over.ics.list]p3:
4668   //   Otherwise, if the parameter is a non-aggregate class X and overload
4669   //   resolution chooses a single best constructor [...] the implicit
4670   //   conversion sequence is a user-defined conversion sequence. If multiple
4671   //   constructors are viable but none is better than the others, the
4672   //   implicit conversion sequence is a user-defined conversion sequence.
4673   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4674     // This function can deal with initializer lists.
4675     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4676                                     /*AllowExplicit=*/false,
4677                                     InOverloadResolution, /*CStyle=*/false,
4678                                     AllowObjCWritebackConversion,
4679                                     /*AllowObjCConversionOnExplicit=*/false);
4680   }
4681 
4682   // C++14 [over.ics.list]p5:
4683   // C++11 [over.ics.list]p4:
4684   //   Otherwise, if the parameter has an aggregate type which can be
4685   //   initialized from the initializer list [...] the implicit conversion
4686   //   sequence is a user-defined conversion sequence.
4687   if (ToType->isAggregateType()) {
4688     // Type is an aggregate, argument is an init list. At this point it comes
4689     // down to checking whether the initialization works.
4690     // FIXME: Find out whether this parameter is consumed or not.
4691     InitializedEntity Entity =
4692         InitializedEntity::InitializeParameter(S.Context, ToType,
4693                                                /*Consumed=*/false);
4694     if (S.CanPerformCopyInitialization(Entity, From)) {
4695       Result.setUserDefined();
4696       Result.UserDefined.Before.setAsIdentityConversion();
4697       // Initializer lists don't have a type.
4698       Result.UserDefined.Before.setFromType(QualType());
4699       Result.UserDefined.Before.setAllToTypes(QualType());
4700 
4701       Result.UserDefined.After.setAsIdentityConversion();
4702       Result.UserDefined.After.setFromType(ToType);
4703       Result.UserDefined.After.setAllToTypes(ToType);
4704       Result.UserDefined.ConversionFunction = nullptr;
4705     }
4706     return Result;
4707   }
4708 
4709   // C++14 [over.ics.list]p6:
4710   // C++11 [over.ics.list]p5:
4711   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4712   if (ToType->isReferenceType()) {
4713     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4714     // mention initializer lists in any way. So we go by what list-
4715     // initialization would do and try to extrapolate from that.
4716 
4717     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4718 
4719     // If the initializer list has a single element that is reference-related
4720     // to the parameter type, we initialize the reference from that.
4721     if (From->getNumInits() == 1) {
4722       Expr *Init = From->getInit(0);
4723 
4724       QualType T2 = Init->getType();
4725 
4726       // If the initializer is the address of an overloaded function, try
4727       // to resolve the overloaded function. If all goes well, T2 is the
4728       // type of the resulting function.
4729       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4730         DeclAccessPair Found;
4731         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4732                                    Init, ToType, false, Found))
4733           T2 = Fn->getType();
4734       }
4735 
4736       // Compute some basic properties of the types and the initializer.
4737       bool dummy1 = false;
4738       bool dummy2 = false;
4739       bool dummy3 = false;
4740       Sema::ReferenceCompareResult RefRelationship
4741         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4742                                          dummy2, dummy3);
4743 
4744       if (RefRelationship >= Sema::Ref_Related) {
4745         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4746                                 SuppressUserConversions,
4747                                 /*AllowExplicit=*/false);
4748       }
4749     }
4750 
4751     // Otherwise, we bind the reference to a temporary created from the
4752     // initializer list.
4753     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4754                                InOverloadResolution,
4755                                AllowObjCWritebackConversion);
4756     if (Result.isFailure())
4757       return Result;
4758     assert(!Result.isEllipsis() &&
4759            "Sub-initialization cannot result in ellipsis conversion.");
4760 
4761     // Can we even bind to a temporary?
4762     if (ToType->isRValueReferenceType() ||
4763         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4764       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4765                                             Result.UserDefined.After;
4766       SCS.ReferenceBinding = true;
4767       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4768       SCS.BindsToRvalue = true;
4769       SCS.BindsToFunctionLvalue = false;
4770       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4771       SCS.ObjCLifetimeConversionBinding = false;
4772     } else
4773       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4774                     From, ToType);
4775     return Result;
4776   }
4777 
4778   // C++14 [over.ics.list]p7:
4779   // C++11 [over.ics.list]p6:
4780   //   Otherwise, if the parameter type is not a class:
4781   if (!ToType->isRecordType()) {
4782     //    - if the initializer list has one element that is not itself an
4783     //      initializer list, the implicit conversion sequence is the one
4784     //      required to convert the element to the parameter type.
4785     unsigned NumInits = From->getNumInits();
4786     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4787       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4788                                      SuppressUserConversions,
4789                                      InOverloadResolution,
4790                                      AllowObjCWritebackConversion);
4791     //    - if the initializer list has no elements, the implicit conversion
4792     //      sequence is the identity conversion.
4793     else if (NumInits == 0) {
4794       Result.setStandard();
4795       Result.Standard.setAsIdentityConversion();
4796       Result.Standard.setFromType(ToType);
4797       Result.Standard.setAllToTypes(ToType);
4798     }
4799     return Result;
4800   }
4801 
4802   // C++14 [over.ics.list]p8:
4803   // C++11 [over.ics.list]p7:
4804   //   In all cases other than those enumerated above, no conversion is possible
4805   return Result;
4806 }
4807 
4808 /// TryCopyInitialization - Try to copy-initialize a value of type
4809 /// ToType from the expression From. Return the implicit conversion
4810 /// sequence required to pass this argument, which may be a bad
4811 /// conversion sequence (meaning that the argument cannot be passed to
4812 /// a parameter of this type). If @p SuppressUserConversions, then we
4813 /// do not permit any user-defined conversion sequences.
4814 static ImplicitConversionSequence
4815 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4816                       bool SuppressUserConversions,
4817                       bool InOverloadResolution,
4818                       bool AllowObjCWritebackConversion,
4819                       bool AllowExplicit) {
4820   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4821     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4822                              InOverloadResolution,AllowObjCWritebackConversion);
4823 
4824   if (ToType->isReferenceType())
4825     return TryReferenceInit(S, From, ToType,
4826                             /*FIXME:*/From->getLocStart(),
4827                             SuppressUserConversions,
4828                             AllowExplicit);
4829 
4830   return TryImplicitConversion(S, From, ToType,
4831                                SuppressUserConversions,
4832                                /*AllowExplicit=*/false,
4833                                InOverloadResolution,
4834                                /*CStyle=*/false,
4835                                AllowObjCWritebackConversion,
4836                                /*AllowObjCConversionOnExplicit=*/false);
4837 }
4838 
4839 static bool TryCopyInitialization(const CanQualType FromQTy,
4840                                   const CanQualType ToQTy,
4841                                   Sema &S,
4842                                   SourceLocation Loc,
4843                                   ExprValueKind FromVK) {
4844   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4845   ImplicitConversionSequence ICS =
4846     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4847 
4848   return !ICS.isBad();
4849 }
4850 
4851 /// TryObjectArgumentInitialization - Try to initialize the object
4852 /// parameter of the given member function (@c Method) from the
4853 /// expression @p From.
4854 static ImplicitConversionSequence
4855 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4856                                 Expr::Classification FromClassification,
4857                                 CXXMethodDecl *Method,
4858                                 CXXRecordDecl *ActingContext) {
4859   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4860   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4861   //                 const volatile object.
4862   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4863     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4864   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4865 
4866   // Set up the conversion sequence as a "bad" conversion, to allow us
4867   // to exit early.
4868   ImplicitConversionSequence ICS;
4869 
4870   // We need to have an object of class type.
4871   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4872     FromType = PT->getPointeeType();
4873 
4874     // When we had a pointer, it's implicitly dereferenced, so we
4875     // better have an lvalue.
4876     assert(FromClassification.isLValue());
4877   }
4878 
4879   assert(FromType->isRecordType());
4880 
4881   // C++0x [over.match.funcs]p4:
4882   //   For non-static member functions, the type of the implicit object
4883   //   parameter is
4884   //
4885   //     - "lvalue reference to cv X" for functions declared without a
4886   //        ref-qualifier or with the & ref-qualifier
4887   //     - "rvalue reference to cv X" for functions declared with the &&
4888   //        ref-qualifier
4889   //
4890   // where X is the class of which the function is a member and cv is the
4891   // cv-qualification on the member function declaration.
4892   //
4893   // However, when finding an implicit conversion sequence for the argument, we
4894   // are not allowed to create temporaries or perform user-defined conversions
4895   // (C++ [over.match.funcs]p5). We perform a simplified version of
4896   // reference binding here, that allows class rvalues to bind to
4897   // non-constant references.
4898 
4899   // First check the qualifiers.
4900   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4901   if (ImplicitParamType.getCVRQualifiers()
4902                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4903       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4904     ICS.setBad(BadConversionSequence::bad_qualifiers,
4905                FromType, ImplicitParamType);
4906     return ICS;
4907   }
4908 
4909   // Check that we have either the same type or a derived type. It
4910   // affects the conversion rank.
4911   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4912   ImplicitConversionKind SecondKind;
4913   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4914     SecondKind = ICK_Identity;
4915   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4916     SecondKind = ICK_Derived_To_Base;
4917   else {
4918     ICS.setBad(BadConversionSequence::unrelated_class,
4919                FromType, ImplicitParamType);
4920     return ICS;
4921   }
4922 
4923   // Check the ref-qualifier.
4924   switch (Method->getRefQualifier()) {
4925   case RQ_None:
4926     // Do nothing; we don't care about lvalueness or rvalueness.
4927     break;
4928 
4929   case RQ_LValue:
4930     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4931       // non-const lvalue reference cannot bind to an rvalue
4932       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4933                  ImplicitParamType);
4934       return ICS;
4935     }
4936     break;
4937 
4938   case RQ_RValue:
4939     if (!FromClassification.isRValue()) {
4940       // rvalue reference cannot bind to an lvalue
4941       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4942                  ImplicitParamType);
4943       return ICS;
4944     }
4945     break;
4946   }
4947 
4948   // Success. Mark this as a reference binding.
4949   ICS.setStandard();
4950   ICS.Standard.setAsIdentityConversion();
4951   ICS.Standard.Second = SecondKind;
4952   ICS.Standard.setFromType(FromType);
4953   ICS.Standard.setAllToTypes(ImplicitParamType);
4954   ICS.Standard.ReferenceBinding = true;
4955   ICS.Standard.DirectBinding = true;
4956   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4957   ICS.Standard.BindsToFunctionLvalue = false;
4958   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4959   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4960     = (Method->getRefQualifier() == RQ_None);
4961   return ICS;
4962 }
4963 
4964 /// PerformObjectArgumentInitialization - Perform initialization of
4965 /// the implicit object parameter for the given Method with the given
4966 /// expression.
4967 ExprResult
4968 Sema::PerformObjectArgumentInitialization(Expr *From,
4969                                           NestedNameSpecifier *Qualifier,
4970                                           NamedDecl *FoundDecl,
4971                                           CXXMethodDecl *Method) {
4972   QualType FromRecordType, DestType;
4973   QualType ImplicitParamRecordType  =
4974     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4975 
4976   Expr::Classification FromClassification;
4977   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4978     FromRecordType = PT->getPointeeType();
4979     DestType = Method->getThisType(Context);
4980     FromClassification = Expr::Classification::makeSimpleLValue();
4981   } else {
4982     FromRecordType = From->getType();
4983     DestType = ImplicitParamRecordType;
4984     FromClassification = From->Classify(Context);
4985   }
4986 
4987   // Note that we always use the true parent context when performing
4988   // the actual argument initialization.
4989   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4990       *this, From->getLocStart(), From->getType(), FromClassification, Method,
4991       Method->getParent());
4992   if (ICS.isBad()) {
4993     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4994       Qualifiers FromQs = FromRecordType.getQualifiers();
4995       Qualifiers ToQs = DestType.getQualifiers();
4996       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4997       if (CVR) {
4998         Diag(From->getLocStart(),
4999              diag::err_member_function_call_bad_cvr)
5000           << Method->getDeclName() << FromRecordType << (CVR - 1)
5001           << From->getSourceRange();
5002         Diag(Method->getLocation(), diag::note_previous_decl)
5003           << Method->getDeclName();
5004         return ExprError();
5005       }
5006     }
5007 
5008     return Diag(From->getLocStart(),
5009                 diag::err_implicit_object_parameter_init)
5010        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5011   }
5012 
5013   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5014     ExprResult FromRes =
5015       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5016     if (FromRes.isInvalid())
5017       return ExprError();
5018     From = FromRes.get();
5019   }
5020 
5021   if (!Context.hasSameType(From->getType(), DestType))
5022     From = ImpCastExprToType(From, DestType, CK_NoOp,
5023                              From->getValueKind()).get();
5024   return From;
5025 }
5026 
5027 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5028 /// expression From to bool (C++0x [conv]p3).
5029 static ImplicitConversionSequence
5030 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5031   return TryImplicitConversion(S, From, S.Context.BoolTy,
5032                                /*SuppressUserConversions=*/false,
5033                                /*AllowExplicit=*/true,
5034                                /*InOverloadResolution=*/false,
5035                                /*CStyle=*/false,
5036                                /*AllowObjCWritebackConversion=*/false,
5037                                /*AllowObjCConversionOnExplicit=*/false);
5038 }
5039 
5040 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5041 /// of the expression From to bool (C++0x [conv]p3).
5042 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5043   if (checkPlaceholderForOverload(*this, From))
5044     return ExprError();
5045 
5046   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5047   if (!ICS.isBad())
5048     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5049 
5050   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5051     return Diag(From->getLocStart(),
5052                 diag::err_typecheck_bool_condition)
5053                   << From->getType() << From->getSourceRange();
5054   return ExprError();
5055 }
5056 
5057 /// Check that the specified conversion is permitted in a converted constant
5058 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5059 /// is acceptable.
5060 static bool CheckConvertedConstantConversions(Sema &S,
5061                                               StandardConversionSequence &SCS) {
5062   // Since we know that the target type is an integral or unscoped enumeration
5063   // type, most conversion kinds are impossible. All possible First and Third
5064   // conversions are fine.
5065   switch (SCS.Second) {
5066   case ICK_Identity:
5067   case ICK_NoReturn_Adjustment:
5068   case ICK_Integral_Promotion:
5069   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5070     return true;
5071 
5072   case ICK_Boolean_Conversion:
5073     // Conversion from an integral or unscoped enumeration type to bool is
5074     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5075     // conversion, so we allow it in a converted constant expression.
5076     //
5077     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5078     // a lot of popular code. We should at least add a warning for this
5079     // (non-conforming) extension.
5080     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5081            SCS.getToType(2)->isBooleanType();
5082 
5083   case ICK_Pointer_Conversion:
5084   case ICK_Pointer_Member:
5085     // C++1z: null pointer conversions and null member pointer conversions are
5086     // only permitted if the source type is std::nullptr_t.
5087     return SCS.getFromType()->isNullPtrType();
5088 
5089   case ICK_Floating_Promotion:
5090   case ICK_Complex_Promotion:
5091   case ICK_Floating_Conversion:
5092   case ICK_Complex_Conversion:
5093   case ICK_Floating_Integral:
5094   case ICK_Compatible_Conversion:
5095   case ICK_Derived_To_Base:
5096   case ICK_Vector_Conversion:
5097   case ICK_Vector_Splat:
5098   case ICK_Complex_Real:
5099   case ICK_Block_Pointer_Conversion:
5100   case ICK_TransparentUnionConversion:
5101   case ICK_Writeback_Conversion:
5102   case ICK_Zero_Event_Conversion:
5103   case ICK_C_Only_Conversion:
5104     return false;
5105 
5106   case ICK_Lvalue_To_Rvalue:
5107   case ICK_Array_To_Pointer:
5108   case ICK_Function_To_Pointer:
5109     llvm_unreachable("found a first conversion kind in Second");
5110 
5111   case ICK_Qualification:
5112     llvm_unreachable("found a third conversion kind in Second");
5113 
5114   case ICK_Num_Conversion_Kinds:
5115     break;
5116   }
5117 
5118   llvm_unreachable("unknown conversion kind");
5119 }
5120 
5121 /// CheckConvertedConstantExpression - Check that the expression From is a
5122 /// converted constant expression of type T, perform the conversion and produce
5123 /// the converted expression, per C++11 [expr.const]p3.
5124 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5125                                                    QualType T, APValue &Value,
5126                                                    Sema::CCEKind CCE,
5127                                                    bool RequireInt) {
5128   assert(S.getLangOpts().CPlusPlus11 &&
5129          "converted constant expression outside C++11");
5130 
5131   if (checkPlaceholderForOverload(S, From))
5132     return ExprError();
5133 
5134   // C++1z [expr.const]p3:
5135   //  A converted constant expression of type T is an expression,
5136   //  implicitly converted to type T, where the converted
5137   //  expression is a constant expression and the implicit conversion
5138   //  sequence contains only [... list of conversions ...].
5139   ImplicitConversionSequence ICS =
5140     TryCopyInitialization(S, From, T,
5141                           /*SuppressUserConversions=*/false,
5142                           /*InOverloadResolution=*/false,
5143                           /*AllowObjcWritebackConversion=*/false,
5144                           /*AllowExplicit=*/false);
5145   StandardConversionSequence *SCS = nullptr;
5146   switch (ICS.getKind()) {
5147   case ImplicitConversionSequence::StandardConversion:
5148     SCS = &ICS.Standard;
5149     break;
5150   case ImplicitConversionSequence::UserDefinedConversion:
5151     // We are converting to a non-class type, so the Before sequence
5152     // must be trivial.
5153     SCS = &ICS.UserDefined.After;
5154     break;
5155   case ImplicitConversionSequence::AmbiguousConversion:
5156   case ImplicitConversionSequence::BadConversion:
5157     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5158       return S.Diag(From->getLocStart(),
5159                     diag::err_typecheck_converted_constant_expression)
5160                 << From->getType() << From->getSourceRange() << T;
5161     return ExprError();
5162 
5163   case ImplicitConversionSequence::EllipsisConversion:
5164     llvm_unreachable("ellipsis conversion in converted constant expression");
5165   }
5166 
5167   // Check that we would only use permitted conversions.
5168   if (!CheckConvertedConstantConversions(S, *SCS)) {
5169     return S.Diag(From->getLocStart(),
5170                   diag::err_typecheck_converted_constant_expression_disallowed)
5171              << From->getType() << From->getSourceRange() << T;
5172   }
5173   // [...] and where the reference binding (if any) binds directly.
5174   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5175     return S.Diag(From->getLocStart(),
5176                   diag::err_typecheck_converted_constant_expression_indirect)
5177              << From->getType() << From->getSourceRange() << T;
5178   }
5179 
5180   ExprResult Result =
5181       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5182   if (Result.isInvalid())
5183     return Result;
5184 
5185   // Check for a narrowing implicit conversion.
5186   APValue PreNarrowingValue;
5187   QualType PreNarrowingType;
5188   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5189                                 PreNarrowingType)) {
5190   case NK_Variable_Narrowing:
5191     // Implicit conversion to a narrower type, and the value is not a constant
5192     // expression. We'll diagnose this in a moment.
5193   case NK_Not_Narrowing:
5194     break;
5195 
5196   case NK_Constant_Narrowing:
5197     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5198       << CCE << /*Constant*/1
5199       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5200     break;
5201 
5202   case NK_Type_Narrowing:
5203     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5204       << CCE << /*Constant*/0 << From->getType() << T;
5205     break;
5206   }
5207 
5208   // Check the expression is a constant expression.
5209   SmallVector<PartialDiagnosticAt, 8> Notes;
5210   Expr::EvalResult Eval;
5211   Eval.Diag = &Notes;
5212 
5213   if ((T->isReferenceType()
5214            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5215            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5216       (RequireInt && !Eval.Val.isInt())) {
5217     // The expression can't be folded, so we can't keep it at this position in
5218     // the AST.
5219     Result = ExprError();
5220   } else {
5221     Value = Eval.Val;
5222 
5223     if (Notes.empty()) {
5224       // It's a constant expression.
5225       return Result;
5226     }
5227   }
5228 
5229   // It's not a constant expression. Produce an appropriate diagnostic.
5230   if (Notes.size() == 1 &&
5231       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5232     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5233   else {
5234     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5235       << CCE << From->getSourceRange();
5236     for (unsigned I = 0; I < Notes.size(); ++I)
5237       S.Diag(Notes[I].first, Notes[I].second);
5238   }
5239   return ExprError();
5240 }
5241 
5242 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5243                                                   APValue &Value, CCEKind CCE) {
5244   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5245 }
5246 
5247 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5248                                                   llvm::APSInt &Value,
5249                                                   CCEKind CCE) {
5250   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5251 
5252   APValue V;
5253   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5254   if (!R.isInvalid())
5255     Value = V.getInt();
5256   return R;
5257 }
5258 
5259 
5260 /// dropPointerConversions - If the given standard conversion sequence
5261 /// involves any pointer conversions, remove them.  This may change
5262 /// the result type of the conversion sequence.
5263 static void dropPointerConversion(StandardConversionSequence &SCS) {
5264   if (SCS.Second == ICK_Pointer_Conversion) {
5265     SCS.Second = ICK_Identity;
5266     SCS.Third = ICK_Identity;
5267     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5268   }
5269 }
5270 
5271 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5272 /// convert the expression From to an Objective-C pointer type.
5273 static ImplicitConversionSequence
5274 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5275   // Do an implicit conversion to 'id'.
5276   QualType Ty = S.Context.getObjCIdType();
5277   ImplicitConversionSequence ICS
5278     = TryImplicitConversion(S, From, Ty,
5279                             // FIXME: Are these flags correct?
5280                             /*SuppressUserConversions=*/false,
5281                             /*AllowExplicit=*/true,
5282                             /*InOverloadResolution=*/false,
5283                             /*CStyle=*/false,
5284                             /*AllowObjCWritebackConversion=*/false,
5285                             /*AllowObjCConversionOnExplicit=*/true);
5286 
5287   // Strip off any final conversions to 'id'.
5288   switch (ICS.getKind()) {
5289   case ImplicitConversionSequence::BadConversion:
5290   case ImplicitConversionSequence::AmbiguousConversion:
5291   case ImplicitConversionSequence::EllipsisConversion:
5292     break;
5293 
5294   case ImplicitConversionSequence::UserDefinedConversion:
5295     dropPointerConversion(ICS.UserDefined.After);
5296     break;
5297 
5298   case ImplicitConversionSequence::StandardConversion:
5299     dropPointerConversion(ICS.Standard);
5300     break;
5301   }
5302 
5303   return ICS;
5304 }
5305 
5306 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5307 /// conversion of the expression From to an Objective-C pointer type.
5308 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5309   if (checkPlaceholderForOverload(*this, From))
5310     return ExprError();
5311 
5312   QualType Ty = Context.getObjCIdType();
5313   ImplicitConversionSequence ICS =
5314     TryContextuallyConvertToObjCPointer(*this, From);
5315   if (!ICS.isBad())
5316     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5317   return ExprError();
5318 }
5319 
5320 /// Determine whether the provided type is an integral type, or an enumeration
5321 /// type of a permitted flavor.
5322 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5323   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5324                                  : T->isIntegralOrUnscopedEnumerationType();
5325 }
5326 
5327 static ExprResult
5328 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5329                             Sema::ContextualImplicitConverter &Converter,
5330                             QualType T, UnresolvedSetImpl &ViableConversions) {
5331 
5332   if (Converter.Suppress)
5333     return ExprError();
5334 
5335   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5336   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5337     CXXConversionDecl *Conv =
5338         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5339     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5340     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5341   }
5342   return From;
5343 }
5344 
5345 static bool
5346 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5347                            Sema::ContextualImplicitConverter &Converter,
5348                            QualType T, bool HadMultipleCandidates,
5349                            UnresolvedSetImpl &ExplicitConversions) {
5350   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5351     DeclAccessPair Found = ExplicitConversions[0];
5352     CXXConversionDecl *Conversion =
5353         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5354 
5355     // The user probably meant to invoke the given explicit
5356     // conversion; use it.
5357     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5358     std::string TypeStr;
5359     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5360 
5361     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5362         << FixItHint::CreateInsertion(From->getLocStart(),
5363                                       "static_cast<" + TypeStr + ">(")
5364         << FixItHint::CreateInsertion(
5365                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5366     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5367 
5368     // If we aren't in a SFINAE context, build a call to the
5369     // explicit conversion function.
5370     if (SemaRef.isSFINAEContext())
5371       return true;
5372 
5373     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5374     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5375                                                        HadMultipleCandidates);
5376     if (Result.isInvalid())
5377       return true;
5378     // Record usage of conversion in an implicit cast.
5379     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5380                                     CK_UserDefinedConversion, Result.get(),
5381                                     nullptr, Result.get()->getValueKind());
5382   }
5383   return false;
5384 }
5385 
5386 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5387                              Sema::ContextualImplicitConverter &Converter,
5388                              QualType T, bool HadMultipleCandidates,
5389                              DeclAccessPair &Found) {
5390   CXXConversionDecl *Conversion =
5391       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5392   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5393 
5394   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5395   if (!Converter.SuppressConversion) {
5396     if (SemaRef.isSFINAEContext())
5397       return true;
5398 
5399     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5400         << From->getSourceRange();
5401   }
5402 
5403   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5404                                                      HadMultipleCandidates);
5405   if (Result.isInvalid())
5406     return true;
5407   // Record usage of conversion in an implicit cast.
5408   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5409                                   CK_UserDefinedConversion, Result.get(),
5410                                   nullptr, Result.get()->getValueKind());
5411   return false;
5412 }
5413 
5414 static ExprResult finishContextualImplicitConversion(
5415     Sema &SemaRef, SourceLocation Loc, Expr *From,
5416     Sema::ContextualImplicitConverter &Converter) {
5417   if (!Converter.match(From->getType()) && !Converter.Suppress)
5418     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5419         << From->getSourceRange();
5420 
5421   return SemaRef.DefaultLvalueConversion(From);
5422 }
5423 
5424 static void
5425 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5426                                   UnresolvedSetImpl &ViableConversions,
5427                                   OverloadCandidateSet &CandidateSet) {
5428   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5429     DeclAccessPair FoundDecl = ViableConversions[I];
5430     NamedDecl *D = FoundDecl.getDecl();
5431     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5432     if (isa<UsingShadowDecl>(D))
5433       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5434 
5435     CXXConversionDecl *Conv;
5436     FunctionTemplateDecl *ConvTemplate;
5437     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5438       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5439     else
5440       Conv = cast<CXXConversionDecl>(D);
5441 
5442     if (ConvTemplate)
5443       SemaRef.AddTemplateConversionCandidate(
5444         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5445         /*AllowObjCConversionOnExplicit=*/false);
5446     else
5447       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5448                                      ToType, CandidateSet,
5449                                      /*AllowObjCConversionOnExplicit=*/false);
5450   }
5451 }
5452 
5453 /// \brief Attempt to convert the given expression to a type which is accepted
5454 /// by the given converter.
5455 ///
5456 /// This routine will attempt to convert an expression of class type to a
5457 /// type accepted by the specified converter. In C++11 and before, the class
5458 /// must have a single non-explicit conversion function converting to a matching
5459 /// type. In C++1y, there can be multiple such conversion functions, but only
5460 /// one target type.
5461 ///
5462 /// \param Loc The source location of the construct that requires the
5463 /// conversion.
5464 ///
5465 /// \param From The expression we're converting from.
5466 ///
5467 /// \param Converter Used to control and diagnose the conversion process.
5468 ///
5469 /// \returns The expression, converted to an integral or enumeration type if
5470 /// successful.
5471 ExprResult Sema::PerformContextualImplicitConversion(
5472     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5473   // We can't perform any more checking for type-dependent expressions.
5474   if (From->isTypeDependent())
5475     return From;
5476 
5477   // Process placeholders immediately.
5478   if (From->hasPlaceholderType()) {
5479     ExprResult result = CheckPlaceholderExpr(From);
5480     if (result.isInvalid())
5481       return result;
5482     From = result.get();
5483   }
5484 
5485   // If the expression already has a matching type, we're golden.
5486   QualType T = From->getType();
5487   if (Converter.match(T))
5488     return DefaultLvalueConversion(From);
5489 
5490   // FIXME: Check for missing '()' if T is a function type?
5491 
5492   // We can only perform contextual implicit conversions on objects of class
5493   // type.
5494   const RecordType *RecordTy = T->getAs<RecordType>();
5495   if (!RecordTy || !getLangOpts().CPlusPlus) {
5496     if (!Converter.Suppress)
5497       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5498     return From;
5499   }
5500 
5501   // We must have a complete class type.
5502   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5503     ContextualImplicitConverter &Converter;
5504     Expr *From;
5505 
5506     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5507         : Converter(Converter), From(From) {}
5508 
5509     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5510       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5511     }
5512   } IncompleteDiagnoser(Converter, From);
5513 
5514   if (Converter.Suppress ? !isCompleteType(Loc, T)
5515                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5516     return From;
5517 
5518   // Look for a conversion to an integral or enumeration type.
5519   UnresolvedSet<4>
5520       ViableConversions; // These are *potentially* viable in C++1y.
5521   UnresolvedSet<4> ExplicitConversions;
5522   const auto &Conversions =
5523       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5524 
5525   bool HadMultipleCandidates =
5526       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5527 
5528   // To check that there is only one target type, in C++1y:
5529   QualType ToType;
5530   bool HasUniqueTargetType = true;
5531 
5532   // Collect explicit or viable (potentially in C++1y) conversions.
5533   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5534     NamedDecl *D = (*I)->getUnderlyingDecl();
5535     CXXConversionDecl *Conversion;
5536     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5537     if (ConvTemplate) {
5538       if (getLangOpts().CPlusPlus14)
5539         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5540       else
5541         continue; // C++11 does not consider conversion operator templates(?).
5542     } else
5543       Conversion = cast<CXXConversionDecl>(D);
5544 
5545     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5546            "Conversion operator templates are considered potentially "
5547            "viable in C++1y");
5548 
5549     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5550     if (Converter.match(CurToType) || ConvTemplate) {
5551 
5552       if (Conversion->isExplicit()) {
5553         // FIXME: For C++1y, do we need this restriction?
5554         // cf. diagnoseNoViableConversion()
5555         if (!ConvTemplate)
5556           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5557       } else {
5558         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5559           if (ToType.isNull())
5560             ToType = CurToType.getUnqualifiedType();
5561           else if (HasUniqueTargetType &&
5562                    (CurToType.getUnqualifiedType() != ToType))
5563             HasUniqueTargetType = false;
5564         }
5565         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5566       }
5567     }
5568   }
5569 
5570   if (getLangOpts().CPlusPlus14) {
5571     // C++1y [conv]p6:
5572     // ... An expression e of class type E appearing in such a context
5573     // is said to be contextually implicitly converted to a specified
5574     // type T and is well-formed if and only if e can be implicitly
5575     // converted to a type T that is determined as follows: E is searched
5576     // for conversion functions whose return type is cv T or reference to
5577     // cv T such that T is allowed by the context. There shall be
5578     // exactly one such T.
5579 
5580     // If no unique T is found:
5581     if (ToType.isNull()) {
5582       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5583                                      HadMultipleCandidates,
5584                                      ExplicitConversions))
5585         return ExprError();
5586       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5587     }
5588 
5589     // If more than one unique Ts are found:
5590     if (!HasUniqueTargetType)
5591       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5592                                          ViableConversions);
5593 
5594     // If one unique T is found:
5595     // First, build a candidate set from the previously recorded
5596     // potentially viable conversions.
5597     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5598     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5599                                       CandidateSet);
5600 
5601     // Then, perform overload resolution over the candidate set.
5602     OverloadCandidateSet::iterator Best;
5603     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5604     case OR_Success: {
5605       // Apply this conversion.
5606       DeclAccessPair Found =
5607           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5608       if (recordConversion(*this, Loc, From, Converter, T,
5609                            HadMultipleCandidates, Found))
5610         return ExprError();
5611       break;
5612     }
5613     case OR_Ambiguous:
5614       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5615                                          ViableConversions);
5616     case OR_No_Viable_Function:
5617       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5618                                      HadMultipleCandidates,
5619                                      ExplicitConversions))
5620         return ExprError();
5621     // fall through 'OR_Deleted' case.
5622     case OR_Deleted:
5623       // We'll complain below about a non-integral condition type.
5624       break;
5625     }
5626   } else {
5627     switch (ViableConversions.size()) {
5628     case 0: {
5629       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5630                                      HadMultipleCandidates,
5631                                      ExplicitConversions))
5632         return ExprError();
5633 
5634       // We'll complain below about a non-integral condition type.
5635       break;
5636     }
5637     case 1: {
5638       // Apply this conversion.
5639       DeclAccessPair Found = ViableConversions[0];
5640       if (recordConversion(*this, Loc, From, Converter, T,
5641                            HadMultipleCandidates, Found))
5642         return ExprError();
5643       break;
5644     }
5645     default:
5646       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5647                                          ViableConversions);
5648     }
5649   }
5650 
5651   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5652 }
5653 
5654 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5655 /// an acceptable non-member overloaded operator for a call whose
5656 /// arguments have types T1 (and, if non-empty, T2). This routine
5657 /// implements the check in C++ [over.match.oper]p3b2 concerning
5658 /// enumeration types.
5659 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5660                                                    FunctionDecl *Fn,
5661                                                    ArrayRef<Expr *> Args) {
5662   QualType T1 = Args[0]->getType();
5663   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5664 
5665   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5666     return true;
5667 
5668   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5669     return true;
5670 
5671   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5672   if (Proto->getNumParams() < 1)
5673     return false;
5674 
5675   if (T1->isEnumeralType()) {
5676     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5677     if (Context.hasSameUnqualifiedType(T1, ArgType))
5678       return true;
5679   }
5680 
5681   if (Proto->getNumParams() < 2)
5682     return false;
5683 
5684   if (!T2.isNull() && T2->isEnumeralType()) {
5685     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5686     if (Context.hasSameUnqualifiedType(T2, ArgType))
5687       return true;
5688   }
5689 
5690   return false;
5691 }
5692 
5693 /// AddOverloadCandidate - Adds the given function to the set of
5694 /// candidate functions, using the given function call arguments.  If
5695 /// @p SuppressUserConversions, then don't allow user-defined
5696 /// conversions via constructors or conversion operators.
5697 ///
5698 /// \param PartialOverloading true if we are performing "partial" overloading
5699 /// based on an incomplete set of function arguments. This feature is used by
5700 /// code completion.
5701 void
5702 Sema::AddOverloadCandidate(FunctionDecl *Function,
5703                            DeclAccessPair FoundDecl,
5704                            ArrayRef<Expr *> Args,
5705                            OverloadCandidateSet &CandidateSet,
5706                            bool SuppressUserConversions,
5707                            bool PartialOverloading,
5708                            bool AllowExplicit) {
5709   const FunctionProtoType *Proto
5710     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5711   assert(Proto && "Functions without a prototype cannot be overloaded");
5712   assert(!Function->getDescribedFunctionTemplate() &&
5713          "Use AddTemplateOverloadCandidate for function templates");
5714 
5715   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5716     if (!isa<CXXConstructorDecl>(Method)) {
5717       // If we get here, it's because we're calling a member function
5718       // that is named without a member access expression (e.g.,
5719       // "this->f") that was either written explicitly or created
5720       // implicitly. This can happen with a qualified call to a member
5721       // function, e.g., X::f(). We use an empty type for the implied
5722       // object argument (C++ [over.call.func]p3), and the acting context
5723       // is irrelevant.
5724       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5725                          QualType(), Expr::Classification::makeSimpleLValue(),
5726                          Args, CandidateSet, SuppressUserConversions,
5727                          PartialOverloading);
5728       return;
5729     }
5730     // We treat a constructor like a non-member function, since its object
5731     // argument doesn't participate in overload resolution.
5732   }
5733 
5734   if (!CandidateSet.isNewCandidate(Function))
5735     return;
5736 
5737   // C++ [over.match.oper]p3:
5738   //   if no operand has a class type, only those non-member functions in the
5739   //   lookup set that have a first parameter of type T1 or "reference to
5740   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5741   //   is a right operand) a second parameter of type T2 or "reference to
5742   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5743   //   candidate functions.
5744   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5745       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5746     return;
5747 
5748   // C++11 [class.copy]p11: [DR1402]
5749   //   A defaulted move constructor that is defined as deleted is ignored by
5750   //   overload resolution.
5751   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5752   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5753       Constructor->isMoveConstructor())
5754     return;
5755 
5756   // Overload resolution is always an unevaluated context.
5757   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5758 
5759   // Add this candidate
5760   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5761   Candidate.FoundDecl = FoundDecl;
5762   Candidate.Function = Function;
5763   Candidate.Viable = true;
5764   Candidate.IsSurrogate = false;
5765   Candidate.IgnoreObjectArgument = false;
5766   Candidate.ExplicitCallArguments = Args.size();
5767 
5768   if (Constructor) {
5769     // C++ [class.copy]p3:
5770     //   A member function template is never instantiated to perform the copy
5771     //   of a class object to an object of its class type.
5772     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5773     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5774         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5775          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5776                        ClassType))) {
5777       Candidate.Viable = false;
5778       Candidate.FailureKind = ovl_fail_illegal_constructor;
5779       return;
5780     }
5781   }
5782 
5783   unsigned NumParams = Proto->getNumParams();
5784 
5785   // (C++ 13.3.2p2): A candidate function having fewer than m
5786   // parameters is viable only if it has an ellipsis in its parameter
5787   // list (8.3.5).
5788   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5789       !Proto->isVariadic()) {
5790     Candidate.Viable = false;
5791     Candidate.FailureKind = ovl_fail_too_many_arguments;
5792     return;
5793   }
5794 
5795   // (C++ 13.3.2p2): A candidate function having more than m parameters
5796   // is viable only if the (m+1)st parameter has a default argument
5797   // (8.3.6). For the purposes of overload resolution, the
5798   // parameter list is truncated on the right, so that there are
5799   // exactly m parameters.
5800   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5801   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5802     // Not enough arguments.
5803     Candidate.Viable = false;
5804     Candidate.FailureKind = ovl_fail_too_few_arguments;
5805     return;
5806   }
5807 
5808   // (CUDA B.1): Check for invalid calls between targets.
5809   if (getLangOpts().CUDA)
5810     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5811       // Skip the check for callers that are implicit members, because in this
5812       // case we may not yet know what the member's target is; the target is
5813       // inferred for the member automatically, based on the bases and fields of
5814       // the class.
5815       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5816         Candidate.Viable = false;
5817         Candidate.FailureKind = ovl_fail_bad_target;
5818         return;
5819       }
5820 
5821   // Determine the implicit conversion sequences for each of the
5822   // arguments.
5823   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5824     if (ArgIdx < NumParams) {
5825       // (C++ 13.3.2p3): for F to be a viable function, there shall
5826       // exist for each argument an implicit conversion sequence
5827       // (13.3.3.1) that converts that argument to the corresponding
5828       // parameter of F.
5829       QualType ParamType = Proto->getParamType(ArgIdx);
5830       Candidate.Conversions[ArgIdx]
5831         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5832                                 SuppressUserConversions,
5833                                 /*InOverloadResolution=*/true,
5834                                 /*AllowObjCWritebackConversion=*/
5835                                   getLangOpts().ObjCAutoRefCount,
5836                                 AllowExplicit);
5837       if (Candidate.Conversions[ArgIdx].isBad()) {
5838         Candidate.Viable = false;
5839         Candidate.FailureKind = ovl_fail_bad_conversion;
5840         return;
5841       }
5842     } else {
5843       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5844       // argument for which there is no corresponding parameter is
5845       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5846       Candidate.Conversions[ArgIdx].setEllipsis();
5847     }
5848   }
5849 
5850   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5851     Candidate.Viable = false;
5852     Candidate.FailureKind = ovl_fail_enable_if;
5853     Candidate.DeductionFailure.Data = FailedAttr;
5854     return;
5855   }
5856 }
5857 
5858 ObjCMethodDecl *
5859 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5860                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5861   if (Methods.size() <= 1)
5862     return nullptr;
5863 
5864   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5865     bool Match = true;
5866     ObjCMethodDecl *Method = Methods[b];
5867     unsigned NumNamedArgs = Sel.getNumArgs();
5868     // Method might have more arguments than selector indicates. This is due
5869     // to addition of c-style arguments in method.
5870     if (Method->param_size() > NumNamedArgs)
5871       NumNamedArgs = Method->param_size();
5872     if (Args.size() < NumNamedArgs)
5873       continue;
5874 
5875     for (unsigned i = 0; i < NumNamedArgs; i++) {
5876       // We can't do any type-checking on a type-dependent argument.
5877       if (Args[i]->isTypeDependent()) {
5878         Match = false;
5879         break;
5880       }
5881 
5882       ParmVarDecl *param = Method->parameters()[i];
5883       Expr *argExpr = Args[i];
5884       assert(argExpr && "SelectBestMethod(): missing expression");
5885 
5886       // Strip the unbridged-cast placeholder expression off unless it's
5887       // a consumed argument.
5888       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5889           !param->hasAttr<CFConsumedAttr>())
5890         argExpr = stripARCUnbridgedCast(argExpr);
5891 
5892       // If the parameter is __unknown_anytype, move on to the next method.
5893       if (param->getType() == Context.UnknownAnyTy) {
5894         Match = false;
5895         break;
5896       }
5897 
5898       ImplicitConversionSequence ConversionState
5899         = TryCopyInitialization(*this, argExpr, param->getType(),
5900                                 /*SuppressUserConversions*/false,
5901                                 /*InOverloadResolution=*/true,
5902                                 /*AllowObjCWritebackConversion=*/
5903                                 getLangOpts().ObjCAutoRefCount,
5904                                 /*AllowExplicit*/false);
5905         if (ConversionState.isBad()) {
5906           Match = false;
5907           break;
5908         }
5909     }
5910     // Promote additional arguments to variadic methods.
5911     if (Match && Method->isVariadic()) {
5912       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5913         if (Args[i]->isTypeDependent()) {
5914           Match = false;
5915           break;
5916         }
5917         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5918                                                           nullptr);
5919         if (Arg.isInvalid()) {
5920           Match = false;
5921           break;
5922         }
5923       }
5924     } else {
5925       // Check for extra arguments to non-variadic methods.
5926       if (Args.size() != NumNamedArgs)
5927         Match = false;
5928       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5929         // Special case when selectors have no argument. In this case, select
5930         // one with the most general result type of 'id'.
5931         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5932           QualType ReturnT = Methods[b]->getReturnType();
5933           if (ReturnT->isObjCIdType())
5934             return Methods[b];
5935         }
5936       }
5937     }
5938 
5939     if (Match)
5940       return Method;
5941   }
5942   return nullptr;
5943 }
5944 
5945 // specific_attr_iterator iterates over enable_if attributes in reverse, and
5946 // enable_if is order-sensitive. As a result, we need to reverse things
5947 // sometimes. Size of 4 elements is arbitrary.
5948 static SmallVector<EnableIfAttr *, 4>
5949 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5950   SmallVector<EnableIfAttr *, 4> Result;
5951   if (!Function->hasAttrs())
5952     return Result;
5953 
5954   const auto &FuncAttrs = Function->getAttrs();
5955   for (Attr *Attr : FuncAttrs)
5956     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5957       Result.push_back(EnableIf);
5958 
5959   std::reverse(Result.begin(), Result.end());
5960   return Result;
5961 }
5962 
5963 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5964                                   bool MissingImplicitThis) {
5965   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5966   if (EnableIfAttrs.empty())
5967     return nullptr;
5968 
5969   SFINAETrap Trap(*this);
5970   SmallVector<Expr *, 16> ConvertedArgs;
5971   bool InitializationFailed = false;
5972   bool ContainsValueDependentExpr = false;
5973 
5974   // Convert the arguments.
5975   for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5976     ExprResult R;
5977     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5978         !cast<CXXMethodDecl>(Function)->isStatic() &&
5979         !isa<CXXConstructorDecl>(Function)) {
5980       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5981       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5982                                               Method, Method);
5983     } else {
5984       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5985                                         Context, Function->getParamDecl(I)),
5986                                     SourceLocation(), Args[I]);
5987     }
5988 
5989     if (R.isInvalid()) {
5990       InitializationFailed = true;
5991       break;
5992     }
5993 
5994     ContainsValueDependentExpr |= R.get()->isValueDependent();
5995     ConvertedArgs.push_back(R.get());
5996   }
5997 
5998   if (InitializationFailed || Trap.hasErrorOccurred())
5999     return EnableIfAttrs[0];
6000 
6001   // Push default arguments if needed.
6002   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6003     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6004       ParmVarDecl *P = Function->getParamDecl(i);
6005       ExprResult R = PerformCopyInitialization(
6006           InitializedEntity::InitializeParameter(Context,
6007                                                  Function->getParamDecl(i)),
6008           SourceLocation(),
6009           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6010                                            : P->getDefaultArg());
6011       if (R.isInvalid()) {
6012         InitializationFailed = true;
6013         break;
6014       }
6015       ContainsValueDependentExpr |= R.get()->isValueDependent();
6016       ConvertedArgs.push_back(R.get());
6017     }
6018 
6019     if (InitializationFailed || Trap.hasErrorOccurred())
6020       return EnableIfAttrs[0];
6021   }
6022 
6023   for (auto *EIA : EnableIfAttrs) {
6024     APValue Result;
6025     if (EIA->getCond()->isValueDependent()) {
6026       // Don't even try now, we'll examine it after instantiation.
6027       continue;
6028     }
6029 
6030     if (!EIA->getCond()->EvaluateWithSubstitution(
6031             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6032       if (!ContainsValueDependentExpr)
6033         return EIA;
6034     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
6035       return EIA;
6036     }
6037   }
6038   return nullptr;
6039 }
6040 
6041 /// \brief Add all of the function declarations in the given function set to
6042 /// the overload candidate set.
6043 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6044                                  ArrayRef<Expr *> Args,
6045                                  OverloadCandidateSet& CandidateSet,
6046                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6047                                  bool SuppressUserConversions,
6048                                  bool PartialOverloading) {
6049   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6050     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6051     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6052       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6053         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6054                            cast<CXXMethodDecl>(FD)->getParent(),
6055                            Args[0]->getType(), Args[0]->Classify(Context),
6056                            Args.slice(1), CandidateSet,
6057                            SuppressUserConversions, PartialOverloading);
6058       else
6059         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6060                              SuppressUserConversions, PartialOverloading);
6061     } else {
6062       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6063       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6064           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6065         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6066                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6067                                    ExplicitTemplateArgs,
6068                                    Args[0]->getType(),
6069                                    Args[0]->Classify(Context), Args.slice(1),
6070                                    CandidateSet, SuppressUserConversions,
6071                                    PartialOverloading);
6072       else
6073         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6074                                      ExplicitTemplateArgs, Args,
6075                                      CandidateSet, SuppressUserConversions,
6076                                      PartialOverloading);
6077     }
6078   }
6079 }
6080 
6081 /// AddMethodCandidate - Adds a named decl (which is some kind of
6082 /// method) as a method candidate to the given overload set.
6083 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6084                               QualType ObjectType,
6085                               Expr::Classification ObjectClassification,
6086                               ArrayRef<Expr *> Args,
6087                               OverloadCandidateSet& CandidateSet,
6088                               bool SuppressUserConversions) {
6089   NamedDecl *Decl = FoundDecl.getDecl();
6090   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6091 
6092   if (isa<UsingShadowDecl>(Decl))
6093     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6094 
6095   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6096     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6097            "Expected a member function template");
6098     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6099                                /*ExplicitArgs*/ nullptr,
6100                                ObjectType, ObjectClassification,
6101                                Args, CandidateSet,
6102                                SuppressUserConversions);
6103   } else {
6104     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6105                        ObjectType, ObjectClassification,
6106                        Args,
6107                        CandidateSet, SuppressUserConversions);
6108   }
6109 }
6110 
6111 /// AddMethodCandidate - Adds the given C++ member function to the set
6112 /// of candidate functions, using the given function call arguments
6113 /// and the object argument (@c Object). For example, in a call
6114 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6115 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6116 /// allow user-defined conversions via constructors or conversion
6117 /// operators.
6118 void
6119 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6120                          CXXRecordDecl *ActingContext, QualType ObjectType,
6121                          Expr::Classification ObjectClassification,
6122                          ArrayRef<Expr *> Args,
6123                          OverloadCandidateSet &CandidateSet,
6124                          bool SuppressUserConversions,
6125                          bool PartialOverloading) {
6126   const FunctionProtoType *Proto
6127     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6128   assert(Proto && "Methods without a prototype cannot be overloaded");
6129   assert(!isa<CXXConstructorDecl>(Method) &&
6130          "Use AddOverloadCandidate for constructors");
6131 
6132   if (!CandidateSet.isNewCandidate(Method))
6133     return;
6134 
6135   // C++11 [class.copy]p23: [DR1402]
6136   //   A defaulted move assignment operator that is defined as deleted is
6137   //   ignored by overload resolution.
6138   if (Method->isDefaulted() && Method->isDeleted() &&
6139       Method->isMoveAssignmentOperator())
6140     return;
6141 
6142   // Overload resolution is always an unevaluated context.
6143   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6144 
6145   // Add this candidate
6146   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6147   Candidate.FoundDecl = FoundDecl;
6148   Candidate.Function = Method;
6149   Candidate.IsSurrogate = false;
6150   Candidate.IgnoreObjectArgument = false;
6151   Candidate.ExplicitCallArguments = Args.size();
6152 
6153   unsigned NumParams = Proto->getNumParams();
6154 
6155   // (C++ 13.3.2p2): A candidate function having fewer than m
6156   // parameters is viable only if it has an ellipsis in its parameter
6157   // list (8.3.5).
6158   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6159       !Proto->isVariadic()) {
6160     Candidate.Viable = false;
6161     Candidate.FailureKind = ovl_fail_too_many_arguments;
6162     return;
6163   }
6164 
6165   // (C++ 13.3.2p2): A candidate function having more than m parameters
6166   // is viable only if the (m+1)st parameter has a default argument
6167   // (8.3.6). For the purposes of overload resolution, the
6168   // parameter list is truncated on the right, so that there are
6169   // exactly m parameters.
6170   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6171   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6172     // Not enough arguments.
6173     Candidate.Viable = false;
6174     Candidate.FailureKind = ovl_fail_too_few_arguments;
6175     return;
6176   }
6177 
6178   Candidate.Viable = true;
6179 
6180   if (Method->isStatic() || ObjectType.isNull())
6181     // The implicit object argument is ignored.
6182     Candidate.IgnoreObjectArgument = true;
6183   else {
6184     // Determine the implicit conversion sequence for the object
6185     // parameter.
6186     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6187         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6188         Method, ActingContext);
6189     if (Candidate.Conversions[0].isBad()) {
6190       Candidate.Viable = false;
6191       Candidate.FailureKind = ovl_fail_bad_conversion;
6192       return;
6193     }
6194   }
6195 
6196   // (CUDA B.1): Check for invalid calls between targets.
6197   if (getLangOpts().CUDA)
6198     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6199       if (CheckCUDATarget(Caller, Method)) {
6200         Candidate.Viable = false;
6201         Candidate.FailureKind = ovl_fail_bad_target;
6202         return;
6203       }
6204 
6205   // Determine the implicit conversion sequences for each of the
6206   // arguments.
6207   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6208     if (ArgIdx < NumParams) {
6209       // (C++ 13.3.2p3): for F to be a viable function, there shall
6210       // exist for each argument an implicit conversion sequence
6211       // (13.3.3.1) that converts that argument to the corresponding
6212       // parameter of F.
6213       QualType ParamType = Proto->getParamType(ArgIdx);
6214       Candidate.Conversions[ArgIdx + 1]
6215         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6216                                 SuppressUserConversions,
6217                                 /*InOverloadResolution=*/true,
6218                                 /*AllowObjCWritebackConversion=*/
6219                                   getLangOpts().ObjCAutoRefCount);
6220       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6221         Candidate.Viable = false;
6222         Candidate.FailureKind = ovl_fail_bad_conversion;
6223         return;
6224       }
6225     } else {
6226       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6227       // argument for which there is no corresponding parameter is
6228       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6229       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6230     }
6231   }
6232 
6233   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6234     Candidate.Viable = false;
6235     Candidate.FailureKind = ovl_fail_enable_if;
6236     Candidate.DeductionFailure.Data = FailedAttr;
6237     return;
6238   }
6239 }
6240 
6241 /// \brief Add a C++ member function template as a candidate to the candidate
6242 /// set, using template argument deduction to produce an appropriate member
6243 /// function template specialization.
6244 void
6245 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6246                                  DeclAccessPair FoundDecl,
6247                                  CXXRecordDecl *ActingContext,
6248                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6249                                  QualType ObjectType,
6250                                  Expr::Classification ObjectClassification,
6251                                  ArrayRef<Expr *> Args,
6252                                  OverloadCandidateSet& CandidateSet,
6253                                  bool SuppressUserConversions,
6254                                  bool PartialOverloading) {
6255   if (!CandidateSet.isNewCandidate(MethodTmpl))
6256     return;
6257 
6258   // C++ [over.match.funcs]p7:
6259   //   In each case where a candidate is a function template, candidate
6260   //   function template specializations are generated using template argument
6261   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6262   //   candidate functions in the usual way.113) A given name can refer to one
6263   //   or more function templates and also to a set of overloaded non-template
6264   //   functions. In such a case, the candidate functions generated from each
6265   //   function template are combined with the set of non-template candidate
6266   //   functions.
6267   TemplateDeductionInfo Info(CandidateSet.getLocation());
6268   FunctionDecl *Specialization = nullptr;
6269   if (TemplateDeductionResult Result
6270       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6271                                 Specialization, Info, PartialOverloading)) {
6272     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6273     Candidate.FoundDecl = FoundDecl;
6274     Candidate.Function = MethodTmpl->getTemplatedDecl();
6275     Candidate.Viable = false;
6276     Candidate.FailureKind = ovl_fail_bad_deduction;
6277     Candidate.IsSurrogate = false;
6278     Candidate.IgnoreObjectArgument = false;
6279     Candidate.ExplicitCallArguments = Args.size();
6280     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6281                                                           Info);
6282     return;
6283   }
6284 
6285   // Add the function template specialization produced by template argument
6286   // deduction as a candidate.
6287   assert(Specialization && "Missing member function template specialization?");
6288   assert(isa<CXXMethodDecl>(Specialization) &&
6289          "Specialization is not a member function?");
6290   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6291                      ActingContext, ObjectType, ObjectClassification, Args,
6292                      CandidateSet, SuppressUserConversions, PartialOverloading);
6293 }
6294 
6295 /// \brief Add a C++ function template specialization as a candidate
6296 /// in the candidate set, using template argument deduction to produce
6297 /// an appropriate function template specialization.
6298 void
6299 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6300                                    DeclAccessPair FoundDecl,
6301                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6302                                    ArrayRef<Expr *> Args,
6303                                    OverloadCandidateSet& CandidateSet,
6304                                    bool SuppressUserConversions,
6305                                    bool PartialOverloading) {
6306   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6307     return;
6308 
6309   // C++ [over.match.funcs]p7:
6310   //   In each case where a candidate is a function template, candidate
6311   //   function template specializations are generated using template argument
6312   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6313   //   candidate functions in the usual way.113) A given name can refer to one
6314   //   or more function templates and also to a set of overloaded non-template
6315   //   functions. In such a case, the candidate functions generated from each
6316   //   function template are combined with the set of non-template candidate
6317   //   functions.
6318   TemplateDeductionInfo Info(CandidateSet.getLocation());
6319   FunctionDecl *Specialization = nullptr;
6320   if (TemplateDeductionResult Result
6321         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6322                                   Specialization, Info, PartialOverloading)) {
6323     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6324     Candidate.FoundDecl = FoundDecl;
6325     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6326     Candidate.Viable = false;
6327     Candidate.FailureKind = ovl_fail_bad_deduction;
6328     Candidate.IsSurrogate = false;
6329     Candidate.IgnoreObjectArgument = false;
6330     Candidate.ExplicitCallArguments = Args.size();
6331     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6332                                                           Info);
6333     return;
6334   }
6335 
6336   // Add the function template specialization produced by template argument
6337   // deduction as a candidate.
6338   assert(Specialization && "Missing function template specialization?");
6339   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6340                        SuppressUserConversions, PartialOverloading);
6341 }
6342 
6343 /// Determine whether this is an allowable conversion from the result
6344 /// of an explicit conversion operator to the expected type, per C++
6345 /// [over.match.conv]p1 and [over.match.ref]p1.
6346 ///
6347 /// \param ConvType The return type of the conversion function.
6348 ///
6349 /// \param ToType The type we are converting to.
6350 ///
6351 /// \param AllowObjCPointerConversion Allow a conversion from one
6352 /// Objective-C pointer to another.
6353 ///
6354 /// \returns true if the conversion is allowable, false otherwise.
6355 static bool isAllowableExplicitConversion(Sema &S,
6356                                           QualType ConvType, QualType ToType,
6357                                           bool AllowObjCPointerConversion) {
6358   QualType ToNonRefType = ToType.getNonReferenceType();
6359 
6360   // Easy case: the types are the same.
6361   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6362     return true;
6363 
6364   // Allow qualification conversions.
6365   bool ObjCLifetimeConversion;
6366   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6367                                   ObjCLifetimeConversion))
6368     return true;
6369 
6370   // If we're not allowed to consider Objective-C pointer conversions,
6371   // we're done.
6372   if (!AllowObjCPointerConversion)
6373     return false;
6374 
6375   // Is this an Objective-C pointer conversion?
6376   bool IncompatibleObjC = false;
6377   QualType ConvertedType;
6378   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6379                                    IncompatibleObjC);
6380 }
6381 
6382 /// AddConversionCandidate - Add a C++ conversion function as a
6383 /// candidate in the candidate set (C++ [over.match.conv],
6384 /// C++ [over.match.copy]). From is the expression we're converting from,
6385 /// and ToType is the type that we're eventually trying to convert to
6386 /// (which may or may not be the same type as the type that the
6387 /// conversion function produces).
6388 void
6389 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6390                              DeclAccessPair FoundDecl,
6391                              CXXRecordDecl *ActingContext,
6392                              Expr *From, QualType ToType,
6393                              OverloadCandidateSet& CandidateSet,
6394                              bool AllowObjCConversionOnExplicit) {
6395   assert(!Conversion->getDescribedFunctionTemplate() &&
6396          "Conversion function templates use AddTemplateConversionCandidate");
6397   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6398   if (!CandidateSet.isNewCandidate(Conversion))
6399     return;
6400 
6401   // If the conversion function has an undeduced return type, trigger its
6402   // deduction now.
6403   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6404     if (DeduceReturnType(Conversion, From->getExprLoc()))
6405       return;
6406     ConvType = Conversion->getConversionType().getNonReferenceType();
6407   }
6408 
6409   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6410   // operator is only a candidate if its return type is the target type or
6411   // can be converted to the target type with a qualification conversion.
6412   if (Conversion->isExplicit() &&
6413       !isAllowableExplicitConversion(*this, ConvType, ToType,
6414                                      AllowObjCConversionOnExplicit))
6415     return;
6416 
6417   // Overload resolution is always an unevaluated context.
6418   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6419 
6420   // Add this candidate
6421   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6422   Candidate.FoundDecl = FoundDecl;
6423   Candidate.Function = Conversion;
6424   Candidate.IsSurrogate = false;
6425   Candidate.IgnoreObjectArgument = false;
6426   Candidate.FinalConversion.setAsIdentityConversion();
6427   Candidate.FinalConversion.setFromType(ConvType);
6428   Candidate.FinalConversion.setAllToTypes(ToType);
6429   Candidate.Viable = true;
6430   Candidate.ExplicitCallArguments = 1;
6431 
6432   // C++ [over.match.funcs]p4:
6433   //   For conversion functions, the function is considered to be a member of
6434   //   the class of the implicit implied object argument for the purpose of
6435   //   defining the type of the implicit object parameter.
6436   //
6437   // Determine the implicit conversion sequence for the implicit
6438   // object parameter.
6439   QualType ImplicitParamType = From->getType();
6440   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6441     ImplicitParamType = FromPtrType->getPointeeType();
6442   CXXRecordDecl *ConversionContext
6443     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6444 
6445   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6446       *this, CandidateSet.getLocation(), From->getType(),
6447       From->Classify(Context), Conversion, ConversionContext);
6448 
6449   if (Candidate.Conversions[0].isBad()) {
6450     Candidate.Viable = false;
6451     Candidate.FailureKind = ovl_fail_bad_conversion;
6452     return;
6453   }
6454 
6455   // We won't go through a user-defined type conversion function to convert a
6456   // derived to base as such conversions are given Conversion Rank. They only
6457   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6458   QualType FromCanon
6459     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6460   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6461   if (FromCanon == ToCanon ||
6462       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6463     Candidate.Viable = false;
6464     Candidate.FailureKind = ovl_fail_trivial_conversion;
6465     return;
6466   }
6467 
6468   // To determine what the conversion from the result of calling the
6469   // conversion function to the type we're eventually trying to
6470   // convert to (ToType), we need to synthesize a call to the
6471   // conversion function and attempt copy initialization from it. This
6472   // makes sure that we get the right semantics with respect to
6473   // lvalues/rvalues and the type. Fortunately, we can allocate this
6474   // call on the stack and we don't need its arguments to be
6475   // well-formed.
6476   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6477                             VK_LValue, From->getLocStart());
6478   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6479                                 Context.getPointerType(Conversion->getType()),
6480                                 CK_FunctionToPointerDecay,
6481                                 &ConversionRef, VK_RValue);
6482 
6483   QualType ConversionType = Conversion->getConversionType();
6484   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6485     Candidate.Viable = false;
6486     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6487     return;
6488   }
6489 
6490   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6491 
6492   // Note that it is safe to allocate CallExpr on the stack here because
6493   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6494   // allocator).
6495   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6496   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6497                 From->getLocStart());
6498   ImplicitConversionSequence ICS =
6499     TryCopyInitialization(*this, &Call, ToType,
6500                           /*SuppressUserConversions=*/true,
6501                           /*InOverloadResolution=*/false,
6502                           /*AllowObjCWritebackConversion=*/false);
6503 
6504   switch (ICS.getKind()) {
6505   case ImplicitConversionSequence::StandardConversion:
6506     Candidate.FinalConversion = ICS.Standard;
6507 
6508     // C++ [over.ics.user]p3:
6509     //   If the user-defined conversion is specified by a specialization of a
6510     //   conversion function template, the second standard conversion sequence
6511     //   shall have exact match rank.
6512     if (Conversion->getPrimaryTemplate() &&
6513         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6514       Candidate.Viable = false;
6515       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6516       return;
6517     }
6518 
6519     // C++0x [dcl.init.ref]p5:
6520     //    In the second case, if the reference is an rvalue reference and
6521     //    the second standard conversion sequence of the user-defined
6522     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6523     //    program is ill-formed.
6524     if (ToType->isRValueReferenceType() &&
6525         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6526       Candidate.Viable = false;
6527       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6528       return;
6529     }
6530     break;
6531 
6532   case ImplicitConversionSequence::BadConversion:
6533     Candidate.Viable = false;
6534     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6535     return;
6536 
6537   default:
6538     llvm_unreachable(
6539            "Can only end up with a standard conversion sequence or failure");
6540   }
6541 
6542   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6543     Candidate.Viable = false;
6544     Candidate.FailureKind = ovl_fail_enable_if;
6545     Candidate.DeductionFailure.Data = FailedAttr;
6546     return;
6547   }
6548 }
6549 
6550 /// \brief Adds a conversion function template specialization
6551 /// candidate to the overload set, using template argument deduction
6552 /// to deduce the template arguments of the conversion function
6553 /// template from the type that we are converting to (C++
6554 /// [temp.deduct.conv]).
6555 void
6556 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6557                                      DeclAccessPair FoundDecl,
6558                                      CXXRecordDecl *ActingDC,
6559                                      Expr *From, QualType ToType,
6560                                      OverloadCandidateSet &CandidateSet,
6561                                      bool AllowObjCConversionOnExplicit) {
6562   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6563          "Only conversion function templates permitted here");
6564 
6565   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6566     return;
6567 
6568   TemplateDeductionInfo Info(CandidateSet.getLocation());
6569   CXXConversionDecl *Specialization = nullptr;
6570   if (TemplateDeductionResult Result
6571         = DeduceTemplateArguments(FunctionTemplate, ToType,
6572                                   Specialization, Info)) {
6573     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6574     Candidate.FoundDecl = FoundDecl;
6575     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6576     Candidate.Viable = false;
6577     Candidate.FailureKind = ovl_fail_bad_deduction;
6578     Candidate.IsSurrogate = false;
6579     Candidate.IgnoreObjectArgument = false;
6580     Candidate.ExplicitCallArguments = 1;
6581     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6582                                                           Info);
6583     return;
6584   }
6585 
6586   // Add the conversion function template specialization produced by
6587   // template argument deduction as a candidate.
6588   assert(Specialization && "Missing function template specialization?");
6589   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6590                          CandidateSet, AllowObjCConversionOnExplicit);
6591 }
6592 
6593 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6594 /// converts the given @c Object to a function pointer via the
6595 /// conversion function @c Conversion, and then attempts to call it
6596 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6597 /// the type of function that we'll eventually be calling.
6598 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6599                                  DeclAccessPair FoundDecl,
6600                                  CXXRecordDecl *ActingContext,
6601                                  const FunctionProtoType *Proto,
6602                                  Expr *Object,
6603                                  ArrayRef<Expr *> Args,
6604                                  OverloadCandidateSet& CandidateSet) {
6605   if (!CandidateSet.isNewCandidate(Conversion))
6606     return;
6607 
6608   // Overload resolution is always an unevaluated context.
6609   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6610 
6611   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6612   Candidate.FoundDecl = FoundDecl;
6613   Candidate.Function = nullptr;
6614   Candidate.Surrogate = Conversion;
6615   Candidate.Viable = true;
6616   Candidate.IsSurrogate = true;
6617   Candidate.IgnoreObjectArgument = false;
6618   Candidate.ExplicitCallArguments = Args.size();
6619 
6620   // Determine the implicit conversion sequence for the implicit
6621   // object parameter.
6622   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6623       *this, CandidateSet.getLocation(), Object->getType(),
6624       Object->Classify(Context), Conversion, ActingContext);
6625   if (ObjectInit.isBad()) {
6626     Candidate.Viable = false;
6627     Candidate.FailureKind = ovl_fail_bad_conversion;
6628     Candidate.Conversions[0] = ObjectInit;
6629     return;
6630   }
6631 
6632   // The first conversion is actually a user-defined conversion whose
6633   // first conversion is ObjectInit's standard conversion (which is
6634   // effectively a reference binding). Record it as such.
6635   Candidate.Conversions[0].setUserDefined();
6636   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6637   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6638   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6639   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6640   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6641   Candidate.Conversions[0].UserDefined.After
6642     = Candidate.Conversions[0].UserDefined.Before;
6643   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6644 
6645   // Find the
6646   unsigned NumParams = Proto->getNumParams();
6647 
6648   // (C++ 13.3.2p2): A candidate function having fewer than m
6649   // parameters is viable only if it has an ellipsis in its parameter
6650   // list (8.3.5).
6651   if (Args.size() > NumParams && !Proto->isVariadic()) {
6652     Candidate.Viable = false;
6653     Candidate.FailureKind = ovl_fail_too_many_arguments;
6654     return;
6655   }
6656 
6657   // Function types don't have any default arguments, so just check if
6658   // we have enough arguments.
6659   if (Args.size() < NumParams) {
6660     // Not enough arguments.
6661     Candidate.Viable = false;
6662     Candidate.FailureKind = ovl_fail_too_few_arguments;
6663     return;
6664   }
6665 
6666   // Determine the implicit conversion sequences for each of the
6667   // arguments.
6668   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6669     if (ArgIdx < NumParams) {
6670       // (C++ 13.3.2p3): for F to be a viable function, there shall
6671       // exist for each argument an implicit conversion sequence
6672       // (13.3.3.1) that converts that argument to the corresponding
6673       // parameter of F.
6674       QualType ParamType = Proto->getParamType(ArgIdx);
6675       Candidate.Conversions[ArgIdx + 1]
6676         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6677                                 /*SuppressUserConversions=*/false,
6678                                 /*InOverloadResolution=*/false,
6679                                 /*AllowObjCWritebackConversion=*/
6680                                   getLangOpts().ObjCAutoRefCount);
6681       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6682         Candidate.Viable = false;
6683         Candidate.FailureKind = ovl_fail_bad_conversion;
6684         return;
6685       }
6686     } else {
6687       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6688       // argument for which there is no corresponding parameter is
6689       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6690       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6691     }
6692   }
6693 
6694   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6695     Candidate.Viable = false;
6696     Candidate.FailureKind = ovl_fail_enable_if;
6697     Candidate.DeductionFailure.Data = FailedAttr;
6698     return;
6699   }
6700 }
6701 
6702 /// \brief Add overload candidates for overloaded operators that are
6703 /// member functions.
6704 ///
6705 /// Add the overloaded operator candidates that are member functions
6706 /// for the operator Op that was used in an operator expression such
6707 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6708 /// CandidateSet will store the added overload candidates. (C++
6709 /// [over.match.oper]).
6710 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6711                                        SourceLocation OpLoc,
6712                                        ArrayRef<Expr *> Args,
6713                                        OverloadCandidateSet& CandidateSet,
6714                                        SourceRange OpRange) {
6715   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6716 
6717   // C++ [over.match.oper]p3:
6718   //   For a unary operator @ with an operand of a type whose
6719   //   cv-unqualified version is T1, and for a binary operator @ with
6720   //   a left operand of a type whose cv-unqualified version is T1 and
6721   //   a right operand of a type whose cv-unqualified version is T2,
6722   //   three sets of candidate functions, designated member
6723   //   candidates, non-member candidates and built-in candidates, are
6724   //   constructed as follows:
6725   QualType T1 = Args[0]->getType();
6726 
6727   //     -- If T1 is a complete class type or a class currently being
6728   //        defined, the set of member candidates is the result of the
6729   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6730   //        the set of member candidates is empty.
6731   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6732     // Complete the type if it can be completed.
6733     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6734       return;
6735     // If the type is neither complete nor being defined, bail out now.
6736     if (!T1Rec->getDecl()->getDefinition())
6737       return;
6738 
6739     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6740     LookupQualifiedName(Operators, T1Rec->getDecl());
6741     Operators.suppressDiagnostics();
6742 
6743     for (LookupResult::iterator Oper = Operators.begin(),
6744                              OperEnd = Operators.end();
6745          Oper != OperEnd;
6746          ++Oper)
6747       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6748                          Args[0]->Classify(Context),
6749                          Args.slice(1),
6750                          CandidateSet,
6751                          /* SuppressUserConversions = */ false);
6752   }
6753 }
6754 
6755 /// AddBuiltinCandidate - Add a candidate for a built-in
6756 /// operator. ResultTy and ParamTys are the result and parameter types
6757 /// of the built-in candidate, respectively. Args and NumArgs are the
6758 /// arguments being passed to the candidate. IsAssignmentOperator
6759 /// should be true when this built-in candidate is an assignment
6760 /// operator. NumContextualBoolArguments is the number of arguments
6761 /// (at the beginning of the argument list) that will be contextually
6762 /// converted to bool.
6763 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6764                                ArrayRef<Expr *> Args,
6765                                OverloadCandidateSet& CandidateSet,
6766                                bool IsAssignmentOperator,
6767                                unsigned NumContextualBoolArguments) {
6768   // Overload resolution is always an unevaluated context.
6769   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6770 
6771   // Add this candidate
6772   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6773   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6774   Candidate.Function = nullptr;
6775   Candidate.IsSurrogate = false;
6776   Candidate.IgnoreObjectArgument = false;
6777   Candidate.BuiltinTypes.ResultTy = ResultTy;
6778   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6779     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6780 
6781   // Determine the implicit conversion sequences for each of the
6782   // arguments.
6783   Candidate.Viable = true;
6784   Candidate.ExplicitCallArguments = Args.size();
6785   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6786     // C++ [over.match.oper]p4:
6787     //   For the built-in assignment operators, conversions of the
6788     //   left operand are restricted as follows:
6789     //     -- no temporaries are introduced to hold the left operand, and
6790     //     -- no user-defined conversions are applied to the left
6791     //        operand to achieve a type match with the left-most
6792     //        parameter of a built-in candidate.
6793     //
6794     // We block these conversions by turning off user-defined
6795     // conversions, since that is the only way that initialization of
6796     // a reference to a non-class type can occur from something that
6797     // is not of the same type.
6798     if (ArgIdx < NumContextualBoolArguments) {
6799       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6800              "Contextual conversion to bool requires bool type");
6801       Candidate.Conversions[ArgIdx]
6802         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6803     } else {
6804       Candidate.Conversions[ArgIdx]
6805         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6806                                 ArgIdx == 0 && IsAssignmentOperator,
6807                                 /*InOverloadResolution=*/false,
6808                                 /*AllowObjCWritebackConversion=*/
6809                                   getLangOpts().ObjCAutoRefCount);
6810     }
6811     if (Candidate.Conversions[ArgIdx].isBad()) {
6812       Candidate.Viable = false;
6813       Candidate.FailureKind = ovl_fail_bad_conversion;
6814       break;
6815     }
6816   }
6817 }
6818 
6819 namespace {
6820 
6821 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6822 /// candidate operator functions for built-in operators (C++
6823 /// [over.built]). The types are separated into pointer types and
6824 /// enumeration types.
6825 class BuiltinCandidateTypeSet  {
6826   /// TypeSet - A set of types.
6827   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6828                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6829 
6830   /// PointerTypes - The set of pointer types that will be used in the
6831   /// built-in candidates.
6832   TypeSet PointerTypes;
6833 
6834   /// MemberPointerTypes - The set of member pointer types that will be
6835   /// used in the built-in candidates.
6836   TypeSet MemberPointerTypes;
6837 
6838   /// EnumerationTypes - The set of enumeration types that will be
6839   /// used in the built-in candidates.
6840   TypeSet EnumerationTypes;
6841 
6842   /// \brief The set of vector types that will be used in the built-in
6843   /// candidates.
6844   TypeSet VectorTypes;
6845 
6846   /// \brief A flag indicating non-record types are viable candidates
6847   bool HasNonRecordTypes;
6848 
6849   /// \brief A flag indicating whether either arithmetic or enumeration types
6850   /// were present in the candidate set.
6851   bool HasArithmeticOrEnumeralTypes;
6852 
6853   /// \brief A flag indicating whether the nullptr type was present in the
6854   /// candidate set.
6855   bool HasNullPtrType;
6856 
6857   /// Sema - The semantic analysis instance where we are building the
6858   /// candidate type set.
6859   Sema &SemaRef;
6860 
6861   /// Context - The AST context in which we will build the type sets.
6862   ASTContext &Context;
6863 
6864   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6865                                                const Qualifiers &VisibleQuals);
6866   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6867 
6868 public:
6869   /// iterator - Iterates through the types that are part of the set.
6870   typedef TypeSet::iterator iterator;
6871 
6872   BuiltinCandidateTypeSet(Sema &SemaRef)
6873     : HasNonRecordTypes(false),
6874       HasArithmeticOrEnumeralTypes(false),
6875       HasNullPtrType(false),
6876       SemaRef(SemaRef),
6877       Context(SemaRef.Context) { }
6878 
6879   void AddTypesConvertedFrom(QualType Ty,
6880                              SourceLocation Loc,
6881                              bool AllowUserConversions,
6882                              bool AllowExplicitConversions,
6883                              const Qualifiers &VisibleTypeConversionsQuals);
6884 
6885   /// pointer_begin - First pointer type found;
6886   iterator pointer_begin() { return PointerTypes.begin(); }
6887 
6888   /// pointer_end - Past the last pointer type found;
6889   iterator pointer_end() { return PointerTypes.end(); }
6890 
6891   /// member_pointer_begin - First member pointer type found;
6892   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6893 
6894   /// member_pointer_end - Past the last member pointer type found;
6895   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6896 
6897   /// enumeration_begin - First enumeration type found;
6898   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6899 
6900   /// enumeration_end - Past the last enumeration type found;
6901   iterator enumeration_end() { return EnumerationTypes.end(); }
6902 
6903   iterator vector_begin() { return VectorTypes.begin(); }
6904   iterator vector_end() { return VectorTypes.end(); }
6905 
6906   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6907   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6908   bool hasNullPtrType() const { return HasNullPtrType; }
6909 };
6910 
6911 } // end anonymous namespace
6912 
6913 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6914 /// the set of pointer types along with any more-qualified variants of
6915 /// that type. For example, if @p Ty is "int const *", this routine
6916 /// will add "int const *", "int const volatile *", "int const
6917 /// restrict *", and "int const volatile restrict *" to the set of
6918 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6919 /// false otherwise.
6920 ///
6921 /// FIXME: what to do about extended qualifiers?
6922 bool
6923 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6924                                              const Qualifiers &VisibleQuals) {
6925 
6926   // Insert this type.
6927   if (!PointerTypes.insert(Ty))
6928     return false;
6929 
6930   QualType PointeeTy;
6931   const PointerType *PointerTy = Ty->getAs<PointerType>();
6932   bool buildObjCPtr = false;
6933   if (!PointerTy) {
6934     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6935     PointeeTy = PTy->getPointeeType();
6936     buildObjCPtr = true;
6937   } else {
6938     PointeeTy = PointerTy->getPointeeType();
6939   }
6940 
6941   // Don't add qualified variants of arrays. For one, they're not allowed
6942   // (the qualifier would sink to the element type), and for another, the
6943   // only overload situation where it matters is subscript or pointer +- int,
6944   // and those shouldn't have qualifier variants anyway.
6945   if (PointeeTy->isArrayType())
6946     return true;
6947 
6948   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6949   bool hasVolatile = VisibleQuals.hasVolatile();
6950   bool hasRestrict = VisibleQuals.hasRestrict();
6951 
6952   // Iterate through all strict supersets of BaseCVR.
6953   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6954     if ((CVR | BaseCVR) != CVR) continue;
6955     // Skip over volatile if no volatile found anywhere in the types.
6956     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6957 
6958     // Skip over restrict if no restrict found anywhere in the types, or if
6959     // the type cannot be restrict-qualified.
6960     if ((CVR & Qualifiers::Restrict) &&
6961         (!hasRestrict ||
6962          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6963       continue;
6964 
6965     // Build qualified pointee type.
6966     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6967 
6968     // Build qualified pointer type.
6969     QualType QPointerTy;
6970     if (!buildObjCPtr)
6971       QPointerTy = Context.getPointerType(QPointeeTy);
6972     else
6973       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6974 
6975     // Insert qualified pointer type.
6976     PointerTypes.insert(QPointerTy);
6977   }
6978 
6979   return true;
6980 }
6981 
6982 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6983 /// to the set of pointer types along with any more-qualified variants of
6984 /// that type. For example, if @p Ty is "int const *", this routine
6985 /// will add "int const *", "int const volatile *", "int const
6986 /// restrict *", and "int const volatile restrict *" to the set of
6987 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6988 /// false otherwise.
6989 ///
6990 /// FIXME: what to do about extended qualifiers?
6991 bool
6992 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6993     QualType Ty) {
6994   // Insert this type.
6995   if (!MemberPointerTypes.insert(Ty))
6996     return false;
6997 
6998   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6999   assert(PointerTy && "type was not a member pointer type!");
7000 
7001   QualType PointeeTy = PointerTy->getPointeeType();
7002   // Don't add qualified variants of arrays. For one, they're not allowed
7003   // (the qualifier would sink to the element type), and for another, the
7004   // only overload situation where it matters is subscript or pointer +- int,
7005   // and those shouldn't have qualifier variants anyway.
7006   if (PointeeTy->isArrayType())
7007     return true;
7008   const Type *ClassTy = PointerTy->getClass();
7009 
7010   // Iterate through all strict supersets of the pointee type's CVR
7011   // qualifiers.
7012   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7013   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7014     if ((CVR | BaseCVR) != CVR) continue;
7015 
7016     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7017     MemberPointerTypes.insert(
7018       Context.getMemberPointerType(QPointeeTy, ClassTy));
7019   }
7020 
7021   return true;
7022 }
7023 
7024 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7025 /// Ty can be implicit converted to the given set of @p Types. We're
7026 /// primarily interested in pointer types and enumeration types. We also
7027 /// take member pointer types, for the conditional operator.
7028 /// AllowUserConversions is true if we should look at the conversion
7029 /// functions of a class type, and AllowExplicitConversions if we
7030 /// should also include the explicit conversion functions of a class
7031 /// type.
7032 void
7033 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7034                                                SourceLocation Loc,
7035                                                bool AllowUserConversions,
7036                                                bool AllowExplicitConversions,
7037                                                const Qualifiers &VisibleQuals) {
7038   // Only deal with canonical types.
7039   Ty = Context.getCanonicalType(Ty);
7040 
7041   // Look through reference types; they aren't part of the type of an
7042   // expression for the purposes of conversions.
7043   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7044     Ty = RefTy->getPointeeType();
7045 
7046   // If we're dealing with an array type, decay to the pointer.
7047   if (Ty->isArrayType())
7048     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7049 
7050   // Otherwise, we don't care about qualifiers on the type.
7051   Ty = Ty.getLocalUnqualifiedType();
7052 
7053   // Flag if we ever add a non-record type.
7054   const RecordType *TyRec = Ty->getAs<RecordType>();
7055   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7056 
7057   // Flag if we encounter an arithmetic type.
7058   HasArithmeticOrEnumeralTypes =
7059     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7060 
7061   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7062     PointerTypes.insert(Ty);
7063   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7064     // Insert our type, and its more-qualified variants, into the set
7065     // of types.
7066     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7067       return;
7068   } else if (Ty->isMemberPointerType()) {
7069     // Member pointers are far easier, since the pointee can't be converted.
7070     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7071       return;
7072   } else if (Ty->isEnumeralType()) {
7073     HasArithmeticOrEnumeralTypes = true;
7074     EnumerationTypes.insert(Ty);
7075   } else if (Ty->isVectorType()) {
7076     // We treat vector types as arithmetic types in many contexts as an
7077     // extension.
7078     HasArithmeticOrEnumeralTypes = true;
7079     VectorTypes.insert(Ty);
7080   } else if (Ty->isNullPtrType()) {
7081     HasNullPtrType = true;
7082   } else if (AllowUserConversions && TyRec) {
7083     // No conversion functions in incomplete types.
7084     if (!SemaRef.isCompleteType(Loc, Ty))
7085       return;
7086 
7087     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7088     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7089       if (isa<UsingShadowDecl>(D))
7090         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7091 
7092       // Skip conversion function templates; they don't tell us anything
7093       // about which builtin types we can convert to.
7094       if (isa<FunctionTemplateDecl>(D))
7095         continue;
7096 
7097       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7098       if (AllowExplicitConversions || !Conv->isExplicit()) {
7099         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7100                               VisibleQuals);
7101       }
7102     }
7103   }
7104 }
7105 
7106 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7107 /// the volatile- and non-volatile-qualified assignment operators for the
7108 /// given type to the candidate set.
7109 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7110                                                    QualType T,
7111                                                    ArrayRef<Expr *> Args,
7112                                     OverloadCandidateSet &CandidateSet) {
7113   QualType ParamTypes[2];
7114 
7115   // T& operator=(T&, T)
7116   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7117   ParamTypes[1] = T;
7118   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7119                         /*IsAssignmentOperator=*/true);
7120 
7121   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7122     // volatile T& operator=(volatile T&, T)
7123     ParamTypes[0]
7124       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7125     ParamTypes[1] = T;
7126     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7127                           /*IsAssignmentOperator=*/true);
7128   }
7129 }
7130 
7131 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7132 /// if any, found in visible type conversion functions found in ArgExpr's type.
7133 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7134     Qualifiers VRQuals;
7135     const RecordType *TyRec;
7136     if (const MemberPointerType *RHSMPType =
7137         ArgExpr->getType()->getAs<MemberPointerType>())
7138       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7139     else
7140       TyRec = ArgExpr->getType()->getAs<RecordType>();
7141     if (!TyRec) {
7142       // Just to be safe, assume the worst case.
7143       VRQuals.addVolatile();
7144       VRQuals.addRestrict();
7145       return VRQuals;
7146     }
7147 
7148     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7149     if (!ClassDecl->hasDefinition())
7150       return VRQuals;
7151 
7152     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7153       if (isa<UsingShadowDecl>(D))
7154         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7155       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7156         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7157         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7158           CanTy = ResTypeRef->getPointeeType();
7159         // Need to go down the pointer/mempointer chain and add qualifiers
7160         // as see them.
7161         bool done = false;
7162         while (!done) {
7163           if (CanTy.isRestrictQualified())
7164             VRQuals.addRestrict();
7165           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7166             CanTy = ResTypePtr->getPointeeType();
7167           else if (const MemberPointerType *ResTypeMPtr =
7168                 CanTy->getAs<MemberPointerType>())
7169             CanTy = ResTypeMPtr->getPointeeType();
7170           else
7171             done = true;
7172           if (CanTy.isVolatileQualified())
7173             VRQuals.addVolatile();
7174           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7175             return VRQuals;
7176         }
7177       }
7178     }
7179     return VRQuals;
7180 }
7181 
7182 namespace {
7183 
7184 /// \brief Helper class to manage the addition of builtin operator overload
7185 /// candidates. It provides shared state and utility methods used throughout
7186 /// the process, as well as a helper method to add each group of builtin
7187 /// operator overloads from the standard to a candidate set.
7188 class BuiltinOperatorOverloadBuilder {
7189   // Common instance state available to all overload candidate addition methods.
7190   Sema &S;
7191   ArrayRef<Expr *> Args;
7192   Qualifiers VisibleTypeConversionsQuals;
7193   bool HasArithmeticOrEnumeralCandidateType;
7194   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7195   OverloadCandidateSet &CandidateSet;
7196 
7197   // Define some constants used to index and iterate over the arithemetic types
7198   // provided via the getArithmeticType() method below.
7199   // The "promoted arithmetic types" are the arithmetic
7200   // types are that preserved by promotion (C++ [over.built]p2).
7201   static const unsigned FirstIntegralType = 3;
7202   static const unsigned LastIntegralType = 20;
7203   static const unsigned FirstPromotedIntegralType = 3,
7204                         LastPromotedIntegralType = 11;
7205   static const unsigned FirstPromotedArithmeticType = 0,
7206                         LastPromotedArithmeticType = 11;
7207   static const unsigned NumArithmeticTypes = 20;
7208 
7209   /// \brief Get the canonical type for a given arithmetic type index.
7210   CanQualType getArithmeticType(unsigned index) {
7211     assert(index < NumArithmeticTypes);
7212     static CanQualType ASTContext::* const
7213       ArithmeticTypes[NumArithmeticTypes] = {
7214       // Start of promoted types.
7215       &ASTContext::FloatTy,
7216       &ASTContext::DoubleTy,
7217       &ASTContext::LongDoubleTy,
7218 
7219       // Start of integral types.
7220       &ASTContext::IntTy,
7221       &ASTContext::LongTy,
7222       &ASTContext::LongLongTy,
7223       &ASTContext::Int128Ty,
7224       &ASTContext::UnsignedIntTy,
7225       &ASTContext::UnsignedLongTy,
7226       &ASTContext::UnsignedLongLongTy,
7227       &ASTContext::UnsignedInt128Ty,
7228       // End of promoted types.
7229 
7230       &ASTContext::BoolTy,
7231       &ASTContext::CharTy,
7232       &ASTContext::WCharTy,
7233       &ASTContext::Char16Ty,
7234       &ASTContext::Char32Ty,
7235       &ASTContext::SignedCharTy,
7236       &ASTContext::ShortTy,
7237       &ASTContext::UnsignedCharTy,
7238       &ASTContext::UnsignedShortTy,
7239       // End of integral types.
7240       // FIXME: What about complex? What about half?
7241     };
7242     return S.Context.*ArithmeticTypes[index];
7243   }
7244 
7245   /// \brief Gets the canonical type resulting from the usual arithemetic
7246   /// converions for the given arithmetic types.
7247   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7248     // Accelerator table for performing the usual arithmetic conversions.
7249     // The rules are basically:
7250     //   - if either is floating-point, use the wider floating-point
7251     //   - if same signedness, use the higher rank
7252     //   - if same size, use unsigned of the higher rank
7253     //   - use the larger type
7254     // These rules, together with the axiom that higher ranks are
7255     // never smaller, are sufficient to precompute all of these results
7256     // *except* when dealing with signed types of higher rank.
7257     // (we could precompute SLL x UI for all known platforms, but it's
7258     // better not to make any assumptions).
7259     // We assume that int128 has a higher rank than long long on all platforms.
7260     enum PromotedType {
7261             Dep=-1,
7262             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7263     };
7264     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7265                                         [LastPromotedArithmeticType] = {
7266 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7267 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7268 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7269 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7270 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7271 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7272 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7273 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7274 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7275 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7276 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7277     };
7278 
7279     assert(L < LastPromotedArithmeticType);
7280     assert(R < LastPromotedArithmeticType);
7281     int Idx = ConversionsTable[L][R];
7282 
7283     // Fast path: the table gives us a concrete answer.
7284     if (Idx != Dep) return getArithmeticType(Idx);
7285 
7286     // Slow path: we need to compare widths.
7287     // An invariant is that the signed type has higher rank.
7288     CanQualType LT = getArithmeticType(L),
7289                 RT = getArithmeticType(R);
7290     unsigned LW = S.Context.getIntWidth(LT),
7291              RW = S.Context.getIntWidth(RT);
7292 
7293     // If they're different widths, use the signed type.
7294     if (LW > RW) return LT;
7295     else if (LW < RW) return RT;
7296 
7297     // Otherwise, use the unsigned type of the signed type's rank.
7298     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7299     assert(L == SLL || R == SLL);
7300     return S.Context.UnsignedLongLongTy;
7301   }
7302 
7303   /// \brief Helper method to factor out the common pattern of adding overloads
7304   /// for '++' and '--' builtin operators.
7305   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7306                                            bool HasVolatile,
7307                                            bool HasRestrict) {
7308     QualType ParamTypes[2] = {
7309       S.Context.getLValueReferenceType(CandidateTy),
7310       S.Context.IntTy
7311     };
7312 
7313     // Non-volatile version.
7314     if (Args.size() == 1)
7315       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7316     else
7317       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7318 
7319     // Use a heuristic to reduce number of builtin candidates in the set:
7320     // add volatile version only if there are conversions to a volatile type.
7321     if (HasVolatile) {
7322       ParamTypes[0] =
7323         S.Context.getLValueReferenceType(
7324           S.Context.getVolatileType(CandidateTy));
7325       if (Args.size() == 1)
7326         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7327       else
7328         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7329     }
7330 
7331     // Add restrict version only if there are conversions to a restrict type
7332     // and our candidate type is a non-restrict-qualified pointer.
7333     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7334         !CandidateTy.isRestrictQualified()) {
7335       ParamTypes[0]
7336         = S.Context.getLValueReferenceType(
7337             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7338       if (Args.size() == 1)
7339         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7340       else
7341         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7342 
7343       if (HasVolatile) {
7344         ParamTypes[0]
7345           = S.Context.getLValueReferenceType(
7346               S.Context.getCVRQualifiedType(CandidateTy,
7347                                             (Qualifiers::Volatile |
7348                                              Qualifiers::Restrict)));
7349         if (Args.size() == 1)
7350           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7351         else
7352           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7353       }
7354     }
7355 
7356   }
7357 
7358 public:
7359   BuiltinOperatorOverloadBuilder(
7360     Sema &S, ArrayRef<Expr *> Args,
7361     Qualifiers VisibleTypeConversionsQuals,
7362     bool HasArithmeticOrEnumeralCandidateType,
7363     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7364     OverloadCandidateSet &CandidateSet)
7365     : S(S), Args(Args),
7366       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7367       HasArithmeticOrEnumeralCandidateType(
7368         HasArithmeticOrEnumeralCandidateType),
7369       CandidateTypes(CandidateTypes),
7370       CandidateSet(CandidateSet) {
7371     // Validate some of our static helper constants in debug builds.
7372     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7373            "Invalid first promoted integral type");
7374     assert(getArithmeticType(LastPromotedIntegralType - 1)
7375              == S.Context.UnsignedInt128Ty &&
7376            "Invalid last promoted integral type");
7377     assert(getArithmeticType(FirstPromotedArithmeticType)
7378              == S.Context.FloatTy &&
7379            "Invalid first promoted arithmetic type");
7380     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7381              == S.Context.UnsignedInt128Ty &&
7382            "Invalid last promoted arithmetic type");
7383   }
7384 
7385   // C++ [over.built]p3:
7386   //
7387   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7388   //   is either volatile or empty, there exist candidate operator
7389   //   functions of the form
7390   //
7391   //       VQ T&      operator++(VQ T&);
7392   //       T          operator++(VQ T&, int);
7393   //
7394   // C++ [over.built]p4:
7395   //
7396   //   For every pair (T, VQ), where T is an arithmetic type other
7397   //   than bool, and VQ is either volatile or empty, there exist
7398   //   candidate operator functions of the form
7399   //
7400   //       VQ T&      operator--(VQ T&);
7401   //       T          operator--(VQ T&, int);
7402   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7403     if (!HasArithmeticOrEnumeralCandidateType)
7404       return;
7405 
7406     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7407          Arith < NumArithmeticTypes; ++Arith) {
7408       addPlusPlusMinusMinusStyleOverloads(
7409         getArithmeticType(Arith),
7410         VisibleTypeConversionsQuals.hasVolatile(),
7411         VisibleTypeConversionsQuals.hasRestrict());
7412     }
7413   }
7414 
7415   // C++ [over.built]p5:
7416   //
7417   //   For every pair (T, VQ), where T is a cv-qualified or
7418   //   cv-unqualified object type, and VQ is either volatile or
7419   //   empty, there exist candidate operator functions of the form
7420   //
7421   //       T*VQ&      operator++(T*VQ&);
7422   //       T*VQ&      operator--(T*VQ&);
7423   //       T*         operator++(T*VQ&, int);
7424   //       T*         operator--(T*VQ&, int);
7425   void addPlusPlusMinusMinusPointerOverloads() {
7426     for (BuiltinCandidateTypeSet::iterator
7427               Ptr = CandidateTypes[0].pointer_begin(),
7428            PtrEnd = CandidateTypes[0].pointer_end();
7429          Ptr != PtrEnd; ++Ptr) {
7430       // Skip pointer types that aren't pointers to object types.
7431       if (!(*Ptr)->getPointeeType()->isObjectType())
7432         continue;
7433 
7434       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7435         (!(*Ptr).isVolatileQualified() &&
7436          VisibleTypeConversionsQuals.hasVolatile()),
7437         (!(*Ptr).isRestrictQualified() &&
7438          VisibleTypeConversionsQuals.hasRestrict()));
7439     }
7440   }
7441 
7442   // C++ [over.built]p6:
7443   //   For every cv-qualified or cv-unqualified object type T, there
7444   //   exist candidate operator functions of the form
7445   //
7446   //       T&         operator*(T*);
7447   //
7448   // C++ [over.built]p7:
7449   //   For every function type T that does not have cv-qualifiers or a
7450   //   ref-qualifier, there exist candidate operator functions of the form
7451   //       T&         operator*(T*);
7452   void addUnaryStarPointerOverloads() {
7453     for (BuiltinCandidateTypeSet::iterator
7454               Ptr = CandidateTypes[0].pointer_begin(),
7455            PtrEnd = CandidateTypes[0].pointer_end();
7456          Ptr != PtrEnd; ++Ptr) {
7457       QualType ParamTy = *Ptr;
7458       QualType PointeeTy = ParamTy->getPointeeType();
7459       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7460         continue;
7461 
7462       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7463         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7464           continue;
7465 
7466       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7467                             &ParamTy, Args, CandidateSet);
7468     }
7469   }
7470 
7471   // C++ [over.built]p9:
7472   //  For every promoted arithmetic type T, there exist candidate
7473   //  operator functions of the form
7474   //
7475   //       T         operator+(T);
7476   //       T         operator-(T);
7477   void addUnaryPlusOrMinusArithmeticOverloads() {
7478     if (!HasArithmeticOrEnumeralCandidateType)
7479       return;
7480 
7481     for (unsigned Arith = FirstPromotedArithmeticType;
7482          Arith < LastPromotedArithmeticType; ++Arith) {
7483       QualType ArithTy = getArithmeticType(Arith);
7484       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7485     }
7486 
7487     // Extension: We also add these operators for vector types.
7488     for (BuiltinCandidateTypeSet::iterator
7489               Vec = CandidateTypes[0].vector_begin(),
7490            VecEnd = CandidateTypes[0].vector_end();
7491          Vec != VecEnd; ++Vec) {
7492       QualType VecTy = *Vec;
7493       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7494     }
7495   }
7496 
7497   // C++ [over.built]p8:
7498   //   For every type T, there exist candidate operator functions of
7499   //   the form
7500   //
7501   //       T*         operator+(T*);
7502   void addUnaryPlusPointerOverloads() {
7503     for (BuiltinCandidateTypeSet::iterator
7504               Ptr = CandidateTypes[0].pointer_begin(),
7505            PtrEnd = CandidateTypes[0].pointer_end();
7506          Ptr != PtrEnd; ++Ptr) {
7507       QualType ParamTy = *Ptr;
7508       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7509     }
7510   }
7511 
7512   // C++ [over.built]p10:
7513   //   For every promoted integral type T, there exist candidate
7514   //   operator functions of the form
7515   //
7516   //        T         operator~(T);
7517   void addUnaryTildePromotedIntegralOverloads() {
7518     if (!HasArithmeticOrEnumeralCandidateType)
7519       return;
7520 
7521     for (unsigned Int = FirstPromotedIntegralType;
7522          Int < LastPromotedIntegralType; ++Int) {
7523       QualType IntTy = getArithmeticType(Int);
7524       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7525     }
7526 
7527     // Extension: We also add this operator for vector types.
7528     for (BuiltinCandidateTypeSet::iterator
7529               Vec = CandidateTypes[0].vector_begin(),
7530            VecEnd = CandidateTypes[0].vector_end();
7531          Vec != VecEnd; ++Vec) {
7532       QualType VecTy = *Vec;
7533       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7534     }
7535   }
7536 
7537   // C++ [over.match.oper]p16:
7538   //   For every pointer to member type T, there exist candidate operator
7539   //   functions of the form
7540   //
7541   //        bool operator==(T,T);
7542   //        bool operator!=(T,T);
7543   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7544     /// Set of (canonical) types that we've already handled.
7545     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7546 
7547     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7548       for (BuiltinCandidateTypeSet::iterator
7549                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7550              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7551            MemPtr != MemPtrEnd;
7552            ++MemPtr) {
7553         // Don't add the same builtin candidate twice.
7554         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7555           continue;
7556 
7557         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7558         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7559       }
7560     }
7561   }
7562 
7563   // C++ [over.built]p15:
7564   //
7565   //   For every T, where T is an enumeration type, a pointer type, or
7566   //   std::nullptr_t, there exist candidate operator functions of the form
7567   //
7568   //        bool       operator<(T, T);
7569   //        bool       operator>(T, T);
7570   //        bool       operator<=(T, T);
7571   //        bool       operator>=(T, T);
7572   //        bool       operator==(T, T);
7573   //        bool       operator!=(T, T);
7574   void addRelationalPointerOrEnumeralOverloads() {
7575     // C++ [over.match.oper]p3:
7576     //   [...]the built-in candidates include all of the candidate operator
7577     //   functions defined in 13.6 that, compared to the given operator, [...]
7578     //   do not have the same parameter-type-list as any non-template non-member
7579     //   candidate.
7580     //
7581     // Note that in practice, this only affects enumeration types because there
7582     // aren't any built-in candidates of record type, and a user-defined operator
7583     // must have an operand of record or enumeration type. Also, the only other
7584     // overloaded operator with enumeration arguments, operator=,
7585     // cannot be overloaded for enumeration types, so this is the only place
7586     // where we must suppress candidates like this.
7587     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7588       UserDefinedBinaryOperators;
7589 
7590     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7591       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7592           CandidateTypes[ArgIdx].enumeration_end()) {
7593         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7594                                          CEnd = CandidateSet.end();
7595              C != CEnd; ++C) {
7596           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7597             continue;
7598 
7599           if (C->Function->isFunctionTemplateSpecialization())
7600             continue;
7601 
7602           QualType FirstParamType =
7603             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7604           QualType SecondParamType =
7605             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7606 
7607           // Skip if either parameter isn't of enumeral type.
7608           if (!FirstParamType->isEnumeralType() ||
7609               !SecondParamType->isEnumeralType())
7610             continue;
7611 
7612           // Add this operator to the set of known user-defined operators.
7613           UserDefinedBinaryOperators.insert(
7614             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7615                            S.Context.getCanonicalType(SecondParamType)));
7616         }
7617       }
7618     }
7619 
7620     /// Set of (canonical) types that we've already handled.
7621     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7622 
7623     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7624       for (BuiltinCandidateTypeSet::iterator
7625                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7626              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7627            Ptr != PtrEnd; ++Ptr) {
7628         // Don't add the same builtin candidate twice.
7629         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7630           continue;
7631 
7632         QualType ParamTypes[2] = { *Ptr, *Ptr };
7633         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7634       }
7635       for (BuiltinCandidateTypeSet::iterator
7636                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7637              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7638            Enum != EnumEnd; ++Enum) {
7639         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7640 
7641         // Don't add the same builtin candidate twice, or if a user defined
7642         // candidate exists.
7643         if (!AddedTypes.insert(CanonType).second ||
7644             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7645                                                             CanonType)))
7646           continue;
7647 
7648         QualType ParamTypes[2] = { *Enum, *Enum };
7649         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7650       }
7651 
7652       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7653         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7654         if (AddedTypes.insert(NullPtrTy).second &&
7655             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7656                                                              NullPtrTy))) {
7657           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7658           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7659                                 CandidateSet);
7660         }
7661       }
7662     }
7663   }
7664 
7665   // C++ [over.built]p13:
7666   //
7667   //   For every cv-qualified or cv-unqualified object type T
7668   //   there exist candidate operator functions of the form
7669   //
7670   //      T*         operator+(T*, ptrdiff_t);
7671   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7672   //      T*         operator-(T*, ptrdiff_t);
7673   //      T*         operator+(ptrdiff_t, T*);
7674   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7675   //
7676   // C++ [over.built]p14:
7677   //
7678   //   For every T, where T is a pointer to object type, there
7679   //   exist candidate operator functions of the form
7680   //
7681   //      ptrdiff_t  operator-(T, T);
7682   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7683     /// Set of (canonical) types that we've already handled.
7684     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7685 
7686     for (int Arg = 0; Arg < 2; ++Arg) {
7687       QualType AsymmetricParamTypes[2] = {
7688         S.Context.getPointerDiffType(),
7689         S.Context.getPointerDiffType(),
7690       };
7691       for (BuiltinCandidateTypeSet::iterator
7692                 Ptr = CandidateTypes[Arg].pointer_begin(),
7693              PtrEnd = CandidateTypes[Arg].pointer_end();
7694            Ptr != PtrEnd; ++Ptr) {
7695         QualType PointeeTy = (*Ptr)->getPointeeType();
7696         if (!PointeeTy->isObjectType())
7697           continue;
7698 
7699         AsymmetricParamTypes[Arg] = *Ptr;
7700         if (Arg == 0 || Op == OO_Plus) {
7701           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7702           // T* operator+(ptrdiff_t, T*);
7703           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7704         }
7705         if (Op == OO_Minus) {
7706           // ptrdiff_t operator-(T, T);
7707           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7708             continue;
7709 
7710           QualType ParamTypes[2] = { *Ptr, *Ptr };
7711           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7712                                 Args, CandidateSet);
7713         }
7714       }
7715     }
7716   }
7717 
7718   // C++ [over.built]p12:
7719   //
7720   //   For every pair of promoted arithmetic types L and R, there
7721   //   exist candidate operator functions of the form
7722   //
7723   //        LR         operator*(L, R);
7724   //        LR         operator/(L, R);
7725   //        LR         operator+(L, R);
7726   //        LR         operator-(L, R);
7727   //        bool       operator<(L, R);
7728   //        bool       operator>(L, R);
7729   //        bool       operator<=(L, R);
7730   //        bool       operator>=(L, R);
7731   //        bool       operator==(L, R);
7732   //        bool       operator!=(L, R);
7733   //
7734   //   where LR is the result of the usual arithmetic conversions
7735   //   between types L and R.
7736   //
7737   // C++ [over.built]p24:
7738   //
7739   //   For every pair of promoted arithmetic types L and R, there exist
7740   //   candidate operator functions of the form
7741   //
7742   //        LR       operator?(bool, L, R);
7743   //
7744   //   where LR is the result of the usual arithmetic conversions
7745   //   between types L and R.
7746   // Our candidates ignore the first parameter.
7747   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7748     if (!HasArithmeticOrEnumeralCandidateType)
7749       return;
7750 
7751     for (unsigned Left = FirstPromotedArithmeticType;
7752          Left < LastPromotedArithmeticType; ++Left) {
7753       for (unsigned Right = FirstPromotedArithmeticType;
7754            Right < LastPromotedArithmeticType; ++Right) {
7755         QualType LandR[2] = { getArithmeticType(Left),
7756                               getArithmeticType(Right) };
7757         QualType Result =
7758           isComparison ? S.Context.BoolTy
7759                        : getUsualArithmeticConversions(Left, Right);
7760         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7761       }
7762     }
7763 
7764     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7765     // conditional operator for vector types.
7766     for (BuiltinCandidateTypeSet::iterator
7767               Vec1 = CandidateTypes[0].vector_begin(),
7768            Vec1End = CandidateTypes[0].vector_end();
7769          Vec1 != Vec1End; ++Vec1) {
7770       for (BuiltinCandidateTypeSet::iterator
7771                 Vec2 = CandidateTypes[1].vector_begin(),
7772              Vec2End = CandidateTypes[1].vector_end();
7773            Vec2 != Vec2End; ++Vec2) {
7774         QualType LandR[2] = { *Vec1, *Vec2 };
7775         QualType Result = S.Context.BoolTy;
7776         if (!isComparison) {
7777           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7778             Result = *Vec1;
7779           else
7780             Result = *Vec2;
7781         }
7782 
7783         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7784       }
7785     }
7786   }
7787 
7788   // C++ [over.built]p17:
7789   //
7790   //   For every pair of promoted integral types L and R, there
7791   //   exist candidate operator functions of the form
7792   //
7793   //      LR         operator%(L, R);
7794   //      LR         operator&(L, R);
7795   //      LR         operator^(L, R);
7796   //      LR         operator|(L, R);
7797   //      L          operator<<(L, R);
7798   //      L          operator>>(L, R);
7799   //
7800   //   where LR is the result of the usual arithmetic conversions
7801   //   between types L and R.
7802   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7803     if (!HasArithmeticOrEnumeralCandidateType)
7804       return;
7805 
7806     for (unsigned Left = FirstPromotedIntegralType;
7807          Left < LastPromotedIntegralType; ++Left) {
7808       for (unsigned Right = FirstPromotedIntegralType;
7809            Right < LastPromotedIntegralType; ++Right) {
7810         QualType LandR[2] = { getArithmeticType(Left),
7811                               getArithmeticType(Right) };
7812         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7813             ? LandR[0]
7814             : getUsualArithmeticConversions(Left, Right);
7815         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7816       }
7817     }
7818   }
7819 
7820   // C++ [over.built]p20:
7821   //
7822   //   For every pair (T, VQ), where T is an enumeration or
7823   //   pointer to member type and VQ is either volatile or
7824   //   empty, there exist candidate operator functions of the form
7825   //
7826   //        VQ T&      operator=(VQ T&, T);
7827   void addAssignmentMemberPointerOrEnumeralOverloads() {
7828     /// Set of (canonical) types that we've already handled.
7829     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7830 
7831     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7832       for (BuiltinCandidateTypeSet::iterator
7833                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7834              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7835            Enum != EnumEnd; ++Enum) {
7836         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7837           continue;
7838 
7839         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7840       }
7841 
7842       for (BuiltinCandidateTypeSet::iterator
7843                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7844              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7845            MemPtr != MemPtrEnd; ++MemPtr) {
7846         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7847           continue;
7848 
7849         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7850       }
7851     }
7852   }
7853 
7854   // C++ [over.built]p19:
7855   //
7856   //   For every pair (T, VQ), where T is any type and VQ is either
7857   //   volatile or empty, there exist candidate operator functions
7858   //   of the form
7859   //
7860   //        T*VQ&      operator=(T*VQ&, T*);
7861   //
7862   // C++ [over.built]p21:
7863   //
7864   //   For every pair (T, VQ), where T is a cv-qualified or
7865   //   cv-unqualified object type and VQ is either volatile or
7866   //   empty, there exist candidate operator functions of the form
7867   //
7868   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7869   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7870   void addAssignmentPointerOverloads(bool isEqualOp) {
7871     /// Set of (canonical) types that we've already handled.
7872     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7873 
7874     for (BuiltinCandidateTypeSet::iterator
7875               Ptr = CandidateTypes[0].pointer_begin(),
7876            PtrEnd = CandidateTypes[0].pointer_end();
7877          Ptr != PtrEnd; ++Ptr) {
7878       // If this is operator=, keep track of the builtin candidates we added.
7879       if (isEqualOp)
7880         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7881       else if (!(*Ptr)->getPointeeType()->isObjectType())
7882         continue;
7883 
7884       // non-volatile version
7885       QualType ParamTypes[2] = {
7886         S.Context.getLValueReferenceType(*Ptr),
7887         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7888       };
7889       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7890                             /*IsAssigmentOperator=*/ isEqualOp);
7891 
7892       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7893                           VisibleTypeConversionsQuals.hasVolatile();
7894       if (NeedVolatile) {
7895         // volatile version
7896         ParamTypes[0] =
7897           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7898         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7899                               /*IsAssigmentOperator=*/isEqualOp);
7900       }
7901 
7902       if (!(*Ptr).isRestrictQualified() &&
7903           VisibleTypeConversionsQuals.hasRestrict()) {
7904         // restrict version
7905         ParamTypes[0]
7906           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7907         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7908                               /*IsAssigmentOperator=*/isEqualOp);
7909 
7910         if (NeedVolatile) {
7911           // volatile restrict version
7912           ParamTypes[0]
7913             = S.Context.getLValueReferenceType(
7914                 S.Context.getCVRQualifiedType(*Ptr,
7915                                               (Qualifiers::Volatile |
7916                                                Qualifiers::Restrict)));
7917           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7918                                 /*IsAssigmentOperator=*/isEqualOp);
7919         }
7920       }
7921     }
7922 
7923     if (isEqualOp) {
7924       for (BuiltinCandidateTypeSet::iterator
7925                 Ptr = CandidateTypes[1].pointer_begin(),
7926              PtrEnd = CandidateTypes[1].pointer_end();
7927            Ptr != PtrEnd; ++Ptr) {
7928         // Make sure we don't add the same candidate twice.
7929         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7930           continue;
7931 
7932         QualType ParamTypes[2] = {
7933           S.Context.getLValueReferenceType(*Ptr),
7934           *Ptr,
7935         };
7936 
7937         // non-volatile version
7938         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7939                               /*IsAssigmentOperator=*/true);
7940 
7941         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7942                            VisibleTypeConversionsQuals.hasVolatile();
7943         if (NeedVolatile) {
7944           // volatile version
7945           ParamTypes[0] =
7946             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7947           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7948                                 /*IsAssigmentOperator=*/true);
7949         }
7950 
7951         if (!(*Ptr).isRestrictQualified() &&
7952             VisibleTypeConversionsQuals.hasRestrict()) {
7953           // restrict version
7954           ParamTypes[0]
7955             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7956           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7957                                 /*IsAssigmentOperator=*/true);
7958 
7959           if (NeedVolatile) {
7960             // volatile restrict version
7961             ParamTypes[0]
7962               = S.Context.getLValueReferenceType(
7963                   S.Context.getCVRQualifiedType(*Ptr,
7964                                                 (Qualifiers::Volatile |
7965                                                  Qualifiers::Restrict)));
7966             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7967                                   /*IsAssigmentOperator=*/true);
7968           }
7969         }
7970       }
7971     }
7972   }
7973 
7974   // C++ [over.built]p18:
7975   //
7976   //   For every triple (L, VQ, R), where L is an arithmetic type,
7977   //   VQ is either volatile or empty, and R is a promoted
7978   //   arithmetic type, there exist candidate operator functions of
7979   //   the form
7980   //
7981   //        VQ L&      operator=(VQ L&, R);
7982   //        VQ L&      operator*=(VQ L&, R);
7983   //        VQ L&      operator/=(VQ L&, R);
7984   //        VQ L&      operator+=(VQ L&, R);
7985   //        VQ L&      operator-=(VQ L&, R);
7986   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7987     if (!HasArithmeticOrEnumeralCandidateType)
7988       return;
7989 
7990     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7991       for (unsigned Right = FirstPromotedArithmeticType;
7992            Right < LastPromotedArithmeticType; ++Right) {
7993         QualType ParamTypes[2];
7994         ParamTypes[1] = getArithmeticType(Right);
7995 
7996         // Add this built-in operator as a candidate (VQ is empty).
7997         ParamTypes[0] =
7998           S.Context.getLValueReferenceType(getArithmeticType(Left));
7999         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8000                               /*IsAssigmentOperator=*/isEqualOp);
8001 
8002         // Add this built-in operator as a candidate (VQ is 'volatile').
8003         if (VisibleTypeConversionsQuals.hasVolatile()) {
8004           ParamTypes[0] =
8005             S.Context.getVolatileType(getArithmeticType(Left));
8006           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8007           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8008                                 /*IsAssigmentOperator=*/isEqualOp);
8009         }
8010       }
8011     }
8012 
8013     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8014     for (BuiltinCandidateTypeSet::iterator
8015               Vec1 = CandidateTypes[0].vector_begin(),
8016            Vec1End = CandidateTypes[0].vector_end();
8017          Vec1 != Vec1End; ++Vec1) {
8018       for (BuiltinCandidateTypeSet::iterator
8019                 Vec2 = CandidateTypes[1].vector_begin(),
8020              Vec2End = CandidateTypes[1].vector_end();
8021            Vec2 != Vec2End; ++Vec2) {
8022         QualType ParamTypes[2];
8023         ParamTypes[1] = *Vec2;
8024         // Add this built-in operator as a candidate (VQ is empty).
8025         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8026         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8027                               /*IsAssigmentOperator=*/isEqualOp);
8028 
8029         // Add this built-in operator as a candidate (VQ is 'volatile').
8030         if (VisibleTypeConversionsQuals.hasVolatile()) {
8031           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8032           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8033           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8034                                 /*IsAssigmentOperator=*/isEqualOp);
8035         }
8036       }
8037     }
8038   }
8039 
8040   // C++ [over.built]p22:
8041   //
8042   //   For every triple (L, VQ, R), where L is an integral type, VQ
8043   //   is either volatile or empty, and R is a promoted integral
8044   //   type, there exist candidate operator functions of the form
8045   //
8046   //        VQ L&       operator%=(VQ L&, R);
8047   //        VQ L&       operator<<=(VQ L&, R);
8048   //        VQ L&       operator>>=(VQ L&, R);
8049   //        VQ L&       operator&=(VQ L&, R);
8050   //        VQ L&       operator^=(VQ L&, R);
8051   //        VQ L&       operator|=(VQ L&, R);
8052   void addAssignmentIntegralOverloads() {
8053     if (!HasArithmeticOrEnumeralCandidateType)
8054       return;
8055 
8056     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8057       for (unsigned Right = FirstPromotedIntegralType;
8058            Right < LastPromotedIntegralType; ++Right) {
8059         QualType ParamTypes[2];
8060         ParamTypes[1] = getArithmeticType(Right);
8061 
8062         // Add this built-in operator as a candidate (VQ is empty).
8063         ParamTypes[0] =
8064           S.Context.getLValueReferenceType(getArithmeticType(Left));
8065         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8066         if (VisibleTypeConversionsQuals.hasVolatile()) {
8067           // Add this built-in operator as a candidate (VQ is 'volatile').
8068           ParamTypes[0] = getArithmeticType(Left);
8069           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8070           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8071           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8072         }
8073       }
8074     }
8075   }
8076 
8077   // C++ [over.operator]p23:
8078   //
8079   //   There also exist candidate operator functions of the form
8080   //
8081   //        bool        operator!(bool);
8082   //        bool        operator&&(bool, bool);
8083   //        bool        operator||(bool, bool);
8084   void addExclaimOverload() {
8085     QualType ParamTy = S.Context.BoolTy;
8086     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8087                           /*IsAssignmentOperator=*/false,
8088                           /*NumContextualBoolArguments=*/1);
8089   }
8090   void addAmpAmpOrPipePipeOverload() {
8091     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8092     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8093                           /*IsAssignmentOperator=*/false,
8094                           /*NumContextualBoolArguments=*/2);
8095   }
8096 
8097   // C++ [over.built]p13:
8098   //
8099   //   For every cv-qualified or cv-unqualified object type T there
8100   //   exist candidate operator functions of the form
8101   //
8102   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8103   //        T&         operator[](T*, ptrdiff_t);
8104   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8105   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8106   //        T&         operator[](ptrdiff_t, T*);
8107   void addSubscriptOverloads() {
8108     for (BuiltinCandidateTypeSet::iterator
8109               Ptr = CandidateTypes[0].pointer_begin(),
8110            PtrEnd = CandidateTypes[0].pointer_end();
8111          Ptr != PtrEnd; ++Ptr) {
8112       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8113       QualType PointeeType = (*Ptr)->getPointeeType();
8114       if (!PointeeType->isObjectType())
8115         continue;
8116 
8117       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8118 
8119       // T& operator[](T*, ptrdiff_t)
8120       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8121     }
8122 
8123     for (BuiltinCandidateTypeSet::iterator
8124               Ptr = CandidateTypes[1].pointer_begin(),
8125            PtrEnd = CandidateTypes[1].pointer_end();
8126          Ptr != PtrEnd; ++Ptr) {
8127       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8128       QualType PointeeType = (*Ptr)->getPointeeType();
8129       if (!PointeeType->isObjectType())
8130         continue;
8131 
8132       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8133 
8134       // T& operator[](ptrdiff_t, T*)
8135       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8136     }
8137   }
8138 
8139   // C++ [over.built]p11:
8140   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8141   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8142   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8143   //    there exist candidate operator functions of the form
8144   //
8145   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8146   //
8147   //    where CV12 is the union of CV1 and CV2.
8148   void addArrowStarOverloads() {
8149     for (BuiltinCandidateTypeSet::iterator
8150              Ptr = CandidateTypes[0].pointer_begin(),
8151            PtrEnd = CandidateTypes[0].pointer_end();
8152          Ptr != PtrEnd; ++Ptr) {
8153       QualType C1Ty = (*Ptr);
8154       QualType C1;
8155       QualifierCollector Q1;
8156       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8157       if (!isa<RecordType>(C1))
8158         continue;
8159       // heuristic to reduce number of builtin candidates in the set.
8160       // Add volatile/restrict version only if there are conversions to a
8161       // volatile/restrict type.
8162       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8163         continue;
8164       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8165         continue;
8166       for (BuiltinCandidateTypeSet::iterator
8167                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8168              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8169            MemPtr != MemPtrEnd; ++MemPtr) {
8170         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8171         QualType C2 = QualType(mptr->getClass(), 0);
8172         C2 = C2.getUnqualifiedType();
8173         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8174           break;
8175         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8176         // build CV12 T&
8177         QualType T = mptr->getPointeeType();
8178         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8179             T.isVolatileQualified())
8180           continue;
8181         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8182             T.isRestrictQualified())
8183           continue;
8184         T = Q1.apply(S.Context, T);
8185         QualType ResultTy = S.Context.getLValueReferenceType(T);
8186         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8187       }
8188     }
8189   }
8190 
8191   // Note that we don't consider the first argument, since it has been
8192   // contextually converted to bool long ago. The candidates below are
8193   // therefore added as binary.
8194   //
8195   // C++ [over.built]p25:
8196   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8197   //   enumeration type, there exist candidate operator functions of the form
8198   //
8199   //        T        operator?(bool, T, T);
8200   //
8201   void addConditionalOperatorOverloads() {
8202     /// Set of (canonical) types that we've already handled.
8203     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8204 
8205     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8206       for (BuiltinCandidateTypeSet::iterator
8207                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8208              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8209            Ptr != PtrEnd; ++Ptr) {
8210         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8211           continue;
8212 
8213         QualType ParamTypes[2] = { *Ptr, *Ptr };
8214         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8215       }
8216 
8217       for (BuiltinCandidateTypeSet::iterator
8218                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8219              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8220            MemPtr != MemPtrEnd; ++MemPtr) {
8221         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8222           continue;
8223 
8224         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8225         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8226       }
8227 
8228       if (S.getLangOpts().CPlusPlus11) {
8229         for (BuiltinCandidateTypeSet::iterator
8230                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8231                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8232              Enum != EnumEnd; ++Enum) {
8233           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8234             continue;
8235 
8236           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8237             continue;
8238 
8239           QualType ParamTypes[2] = { *Enum, *Enum };
8240           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8241         }
8242       }
8243     }
8244   }
8245 };
8246 
8247 } // end anonymous namespace
8248 
8249 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8250 /// operator overloads to the candidate set (C++ [over.built]), based
8251 /// on the operator @p Op and the arguments given. For example, if the
8252 /// operator is a binary '+', this routine might add "int
8253 /// operator+(int, int)" to cover integer addition.
8254 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8255                                         SourceLocation OpLoc,
8256                                         ArrayRef<Expr *> Args,
8257                                         OverloadCandidateSet &CandidateSet) {
8258   // Find all of the types that the arguments can convert to, but only
8259   // if the operator we're looking at has built-in operator candidates
8260   // that make use of these types. Also record whether we encounter non-record
8261   // candidate types or either arithmetic or enumeral candidate types.
8262   Qualifiers VisibleTypeConversionsQuals;
8263   VisibleTypeConversionsQuals.addConst();
8264   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8265     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8266 
8267   bool HasNonRecordCandidateType = false;
8268   bool HasArithmeticOrEnumeralCandidateType = false;
8269   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8270   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8271     CandidateTypes.emplace_back(*this);
8272     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8273                                                  OpLoc,
8274                                                  true,
8275                                                  (Op == OO_Exclaim ||
8276                                                   Op == OO_AmpAmp ||
8277                                                   Op == OO_PipePipe),
8278                                                  VisibleTypeConversionsQuals);
8279     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8280         CandidateTypes[ArgIdx].hasNonRecordTypes();
8281     HasArithmeticOrEnumeralCandidateType =
8282         HasArithmeticOrEnumeralCandidateType ||
8283         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8284   }
8285 
8286   // Exit early when no non-record types have been added to the candidate set
8287   // for any of the arguments to the operator.
8288   //
8289   // We can't exit early for !, ||, or &&, since there we have always have
8290   // 'bool' overloads.
8291   if (!HasNonRecordCandidateType &&
8292       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8293     return;
8294 
8295   // Setup an object to manage the common state for building overloads.
8296   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8297                                            VisibleTypeConversionsQuals,
8298                                            HasArithmeticOrEnumeralCandidateType,
8299                                            CandidateTypes, CandidateSet);
8300 
8301   // Dispatch over the operation to add in only those overloads which apply.
8302   switch (Op) {
8303   case OO_None:
8304   case NUM_OVERLOADED_OPERATORS:
8305     llvm_unreachable("Expected an overloaded operator");
8306 
8307   case OO_New:
8308   case OO_Delete:
8309   case OO_Array_New:
8310   case OO_Array_Delete:
8311   case OO_Call:
8312     llvm_unreachable(
8313                     "Special operators don't use AddBuiltinOperatorCandidates");
8314 
8315   case OO_Comma:
8316   case OO_Arrow:
8317   case OO_Coawait:
8318     // C++ [over.match.oper]p3:
8319     //   -- For the operator ',', the unary operator '&', the
8320     //      operator '->', or the operator 'co_await', the
8321     //      built-in candidates set is empty.
8322     break;
8323 
8324   case OO_Plus: // '+' is either unary or binary
8325     if (Args.size() == 1)
8326       OpBuilder.addUnaryPlusPointerOverloads();
8327     // Fall through.
8328 
8329   case OO_Minus: // '-' is either unary or binary
8330     if (Args.size() == 1) {
8331       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8332     } else {
8333       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8334       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8335     }
8336     break;
8337 
8338   case OO_Star: // '*' is either unary or binary
8339     if (Args.size() == 1)
8340       OpBuilder.addUnaryStarPointerOverloads();
8341     else
8342       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8343     break;
8344 
8345   case OO_Slash:
8346     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8347     break;
8348 
8349   case OO_PlusPlus:
8350   case OO_MinusMinus:
8351     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8352     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8353     break;
8354 
8355   case OO_EqualEqual:
8356   case OO_ExclaimEqual:
8357     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8358     // Fall through.
8359 
8360   case OO_Less:
8361   case OO_Greater:
8362   case OO_LessEqual:
8363   case OO_GreaterEqual:
8364     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8365     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8366     break;
8367 
8368   case OO_Percent:
8369   case OO_Caret:
8370   case OO_Pipe:
8371   case OO_LessLess:
8372   case OO_GreaterGreater:
8373     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8374     break;
8375 
8376   case OO_Amp: // '&' is either unary or binary
8377     if (Args.size() == 1)
8378       // C++ [over.match.oper]p3:
8379       //   -- For the operator ',', the unary operator '&', or the
8380       //      operator '->', the built-in candidates set is empty.
8381       break;
8382 
8383     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8384     break;
8385 
8386   case OO_Tilde:
8387     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8388     break;
8389 
8390   case OO_Equal:
8391     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8392     // Fall through.
8393 
8394   case OO_PlusEqual:
8395   case OO_MinusEqual:
8396     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8397     // Fall through.
8398 
8399   case OO_StarEqual:
8400   case OO_SlashEqual:
8401     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8402     break;
8403 
8404   case OO_PercentEqual:
8405   case OO_LessLessEqual:
8406   case OO_GreaterGreaterEqual:
8407   case OO_AmpEqual:
8408   case OO_CaretEqual:
8409   case OO_PipeEqual:
8410     OpBuilder.addAssignmentIntegralOverloads();
8411     break;
8412 
8413   case OO_Exclaim:
8414     OpBuilder.addExclaimOverload();
8415     break;
8416 
8417   case OO_AmpAmp:
8418   case OO_PipePipe:
8419     OpBuilder.addAmpAmpOrPipePipeOverload();
8420     break;
8421 
8422   case OO_Subscript:
8423     OpBuilder.addSubscriptOverloads();
8424     break;
8425 
8426   case OO_ArrowStar:
8427     OpBuilder.addArrowStarOverloads();
8428     break;
8429 
8430   case OO_Conditional:
8431     OpBuilder.addConditionalOperatorOverloads();
8432     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8433     break;
8434   }
8435 }
8436 
8437 /// \brief Add function candidates found via argument-dependent lookup
8438 /// to the set of overloading candidates.
8439 ///
8440 /// This routine performs argument-dependent name lookup based on the
8441 /// given function name (which may also be an operator name) and adds
8442 /// all of the overload candidates found by ADL to the overload
8443 /// candidate set (C++ [basic.lookup.argdep]).
8444 void
8445 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8446                                            SourceLocation Loc,
8447                                            ArrayRef<Expr *> Args,
8448                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8449                                            OverloadCandidateSet& CandidateSet,
8450                                            bool PartialOverloading) {
8451   ADLResult Fns;
8452 
8453   // FIXME: This approach for uniquing ADL results (and removing
8454   // redundant candidates from the set) relies on pointer-equality,
8455   // which means we need to key off the canonical decl.  However,
8456   // always going back to the canonical decl might not get us the
8457   // right set of default arguments.  What default arguments are
8458   // we supposed to consider on ADL candidates, anyway?
8459 
8460   // FIXME: Pass in the explicit template arguments?
8461   ArgumentDependentLookup(Name, Loc, Args, Fns);
8462 
8463   // Erase all of the candidates we already knew about.
8464   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8465                                    CandEnd = CandidateSet.end();
8466        Cand != CandEnd; ++Cand)
8467     if (Cand->Function) {
8468       Fns.erase(Cand->Function);
8469       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8470         Fns.erase(FunTmpl);
8471     }
8472 
8473   // For each of the ADL candidates we found, add it to the overload
8474   // set.
8475   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8476     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8477     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8478       if (ExplicitTemplateArgs)
8479         continue;
8480 
8481       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8482                            PartialOverloading);
8483     } else
8484       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8485                                    FoundDecl, ExplicitTemplateArgs,
8486                                    Args, CandidateSet, PartialOverloading);
8487   }
8488 }
8489 
8490 // Determines whether Cand1 is "better" in terms of its enable_if attrs than
8491 // Cand2 for overloading. This function assumes that all of the enable_if attrs
8492 // on Cand1 and Cand2 have conditions that evaluate to true.
8493 //
8494 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8495 // Cand1's first N enable_if attributes have precisely the same conditions as
8496 // Cand2's first N enable_if attributes (where N = the number of enable_if
8497 // attributes on Cand2), and Cand1 has more than N enable_if attributes.
8498 static bool hasBetterEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8499                                    const FunctionDecl *Cand2) {
8500 
8501   // FIXME: The next several lines are just
8502   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8503   // instead of reverse order which is how they're stored in the AST.
8504   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8505   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8506 
8507   // Candidate 1 is better if it has strictly more attributes and
8508   // the common sequence is identical.
8509   if (Cand1Attrs.size() <= Cand2Attrs.size())
8510     return false;
8511 
8512   auto Cand1I = Cand1Attrs.begin();
8513   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8514   for (auto &Cand2A : Cand2Attrs) {
8515     Cand1ID.clear();
8516     Cand2ID.clear();
8517 
8518     auto &Cand1A = *Cand1I++;
8519     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8520     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8521     if (Cand1ID != Cand2ID)
8522       return false;
8523   }
8524 
8525   return true;
8526 }
8527 
8528 /// isBetterOverloadCandidate - Determines whether the first overload
8529 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8530 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8531                                       const OverloadCandidate &Cand2,
8532                                       SourceLocation Loc,
8533                                       bool UserDefinedConversion) {
8534   // Define viable functions to be better candidates than non-viable
8535   // functions.
8536   if (!Cand2.Viable)
8537     return Cand1.Viable;
8538   else if (!Cand1.Viable)
8539     return false;
8540 
8541   // C++ [over.match.best]p1:
8542   //
8543   //   -- if F is a static member function, ICS1(F) is defined such
8544   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8545   //      any function G, and, symmetrically, ICS1(G) is neither
8546   //      better nor worse than ICS1(F).
8547   unsigned StartArg = 0;
8548   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8549     StartArg = 1;
8550 
8551   // C++ [over.match.best]p1:
8552   //   A viable function F1 is defined to be a better function than another
8553   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8554   //   conversion sequence than ICSi(F2), and then...
8555   unsigned NumArgs = Cand1.NumConversions;
8556   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8557   bool HasBetterConversion = false;
8558   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8559     switch (CompareImplicitConversionSequences(S, Loc,
8560                                                Cand1.Conversions[ArgIdx],
8561                                                Cand2.Conversions[ArgIdx])) {
8562     case ImplicitConversionSequence::Better:
8563       // Cand1 has a better conversion sequence.
8564       HasBetterConversion = true;
8565       break;
8566 
8567     case ImplicitConversionSequence::Worse:
8568       // Cand1 can't be better than Cand2.
8569       return false;
8570 
8571     case ImplicitConversionSequence::Indistinguishable:
8572       // Do nothing.
8573       break;
8574     }
8575   }
8576 
8577   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8578   //       ICSj(F2), or, if not that,
8579   if (HasBetterConversion)
8580     return true;
8581 
8582   //   -- the context is an initialization by user-defined conversion
8583   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8584   //      from the return type of F1 to the destination type (i.e.,
8585   //      the type of the entity being initialized) is a better
8586   //      conversion sequence than the standard conversion sequence
8587   //      from the return type of F2 to the destination type.
8588   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8589       isa<CXXConversionDecl>(Cand1.Function) &&
8590       isa<CXXConversionDecl>(Cand2.Function)) {
8591     // First check whether we prefer one of the conversion functions over the
8592     // other. This only distinguishes the results in non-standard, extension
8593     // cases such as the conversion from a lambda closure type to a function
8594     // pointer or block.
8595     ImplicitConversionSequence::CompareKind Result =
8596         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8597     if (Result == ImplicitConversionSequence::Indistinguishable)
8598       Result = CompareStandardConversionSequences(S, Loc,
8599                                                   Cand1.FinalConversion,
8600                                                   Cand2.FinalConversion);
8601 
8602     if (Result != ImplicitConversionSequence::Indistinguishable)
8603       return Result == ImplicitConversionSequence::Better;
8604 
8605     // FIXME: Compare kind of reference binding if conversion functions
8606     // convert to a reference type used in direct reference binding, per
8607     // C++14 [over.match.best]p1 section 2 bullet 3.
8608   }
8609 
8610   //    -- F1 is a non-template function and F2 is a function template
8611   //       specialization, or, if not that,
8612   bool Cand1IsSpecialization = Cand1.Function &&
8613                                Cand1.Function->getPrimaryTemplate();
8614   bool Cand2IsSpecialization = Cand2.Function &&
8615                                Cand2.Function->getPrimaryTemplate();
8616   if (Cand1IsSpecialization != Cand2IsSpecialization)
8617     return Cand2IsSpecialization;
8618 
8619   //   -- F1 and F2 are function template specializations, and the function
8620   //      template for F1 is more specialized than the template for F2
8621   //      according to the partial ordering rules described in 14.5.5.2, or,
8622   //      if not that,
8623   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8624     if (FunctionTemplateDecl *BetterTemplate
8625           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8626                                          Cand2.Function->getPrimaryTemplate(),
8627                                          Loc,
8628                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8629                                                              : TPOC_Call,
8630                                          Cand1.ExplicitCallArguments,
8631                                          Cand2.ExplicitCallArguments))
8632       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8633   }
8634 
8635   // Check for enable_if value-based overload resolution.
8636   if (Cand1.Function && Cand2.Function &&
8637       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8638        Cand2.Function->hasAttr<EnableIfAttr>()))
8639     return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8640 
8641   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8642     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8643     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8644            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8645   }
8646 
8647   bool HasPS1 = Cand1.Function != nullptr &&
8648                 functionHasPassObjectSizeParams(Cand1.Function);
8649   bool HasPS2 = Cand2.Function != nullptr &&
8650                 functionHasPassObjectSizeParams(Cand2.Function);
8651   return HasPS1 != HasPS2 && HasPS1;
8652 }
8653 
8654 /// Determine whether two declarations are "equivalent" for the purposes of
8655 /// name lookup and overload resolution. This applies when the same internal/no
8656 /// linkage entity is defined by two modules (probably by textually including
8657 /// the same header). In such a case, we don't consider the declarations to
8658 /// declare the same entity, but we also don't want lookups with both
8659 /// declarations visible to be ambiguous in some cases (this happens when using
8660 /// a modularized libstdc++).
8661 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8662                                                   const NamedDecl *B) {
8663   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8664   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8665   if (!VA || !VB)
8666     return false;
8667 
8668   // The declarations must be declaring the same name as an internal linkage
8669   // entity in different modules.
8670   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8671           VB->getDeclContext()->getRedeclContext()) ||
8672       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8673           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8674       VA->isExternallyVisible() || VB->isExternallyVisible())
8675     return false;
8676 
8677   // Check that the declarations appear to be equivalent.
8678   //
8679   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8680   // For constants and functions, we should check the initializer or body is
8681   // the same. For non-constant variables, we shouldn't allow it at all.
8682   if (Context.hasSameType(VA->getType(), VB->getType()))
8683     return true;
8684 
8685   // Enum constants within unnamed enumerations will have different types, but
8686   // may still be similar enough to be interchangeable for our purposes.
8687   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8688     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8689       // Only handle anonymous enums. If the enumerations were named and
8690       // equivalent, they would have been merged to the same type.
8691       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8692       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8693       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8694           !Context.hasSameType(EnumA->getIntegerType(),
8695                                EnumB->getIntegerType()))
8696         return false;
8697       // Allow this only if the value is the same for both enumerators.
8698       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8699     }
8700   }
8701 
8702   // Nothing else is sufficiently similar.
8703   return false;
8704 }
8705 
8706 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8707     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8708   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8709 
8710   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8711   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8712       << !M << (M ? M->getFullModuleName() : "");
8713 
8714   for (auto *E : Equiv) {
8715     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8716     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8717         << !M << (M ? M->getFullModuleName() : "");
8718   }
8719 }
8720 
8721 /// \brief Computes the best viable function (C++ 13.3.3)
8722 /// within an overload candidate set.
8723 ///
8724 /// \param Loc The location of the function name (or operator symbol) for
8725 /// which overload resolution occurs.
8726 ///
8727 /// \param Best If overload resolution was successful or found a deleted
8728 /// function, \p Best points to the candidate function found.
8729 ///
8730 /// \returns The result of overload resolution.
8731 OverloadingResult
8732 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8733                                          iterator &Best,
8734                                          bool UserDefinedConversion) {
8735   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8736   std::transform(begin(), end(), std::back_inserter(Candidates),
8737                  [](OverloadCandidate &Cand) { return &Cand; });
8738 
8739   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8740   // but accepted by both clang and NVCC. However during a particular
8741   // compilation mode only one call variant is viable. We need to
8742   // exclude non-viable overload candidates from consideration based
8743   // only on their host/device attributes. Specifically, if one
8744   // candidate call is WrongSide and the other is SameSide, we ignore
8745   // the WrongSide candidate.
8746   if (S.getLangOpts().CUDA) {
8747     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8748     bool ContainsSameSideCandidate =
8749         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8750           return Cand->Function &&
8751                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8752                      Sema::CFP_SameSide;
8753         });
8754     if (ContainsSameSideCandidate) {
8755       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8756         return Cand->Function &&
8757                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8758                    Sema::CFP_WrongSide;
8759       };
8760       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8761                                       IsWrongSideCandidate),
8762                        Candidates.end());
8763     }
8764   }
8765 
8766   // Find the best viable function.
8767   Best = end();
8768   for (auto *Cand : Candidates)
8769     if (Cand->Viable)
8770       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8771                                                      UserDefinedConversion))
8772         Best = Cand;
8773 
8774   // If we didn't find any viable functions, abort.
8775   if (Best == end())
8776     return OR_No_Viable_Function;
8777 
8778   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8779 
8780   // Make sure that this function is better than every other viable
8781   // function. If not, we have an ambiguity.
8782   for (auto *Cand : Candidates) {
8783     if (Cand->Viable &&
8784         Cand != Best &&
8785         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8786                                    UserDefinedConversion)) {
8787       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8788                                                    Cand->Function)) {
8789         EquivalentCands.push_back(Cand->Function);
8790         continue;
8791       }
8792 
8793       Best = end();
8794       return OR_Ambiguous;
8795     }
8796   }
8797 
8798   // Best is the best viable function.
8799   if (Best->Function &&
8800       (Best->Function->isDeleted() ||
8801        S.isFunctionConsideredUnavailable(Best->Function)))
8802     return OR_Deleted;
8803 
8804   if (!EquivalentCands.empty())
8805     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8806                                                     EquivalentCands);
8807 
8808   return OR_Success;
8809 }
8810 
8811 namespace {
8812 
8813 enum OverloadCandidateKind {
8814   oc_function,
8815   oc_method,
8816   oc_constructor,
8817   oc_function_template,
8818   oc_method_template,
8819   oc_constructor_template,
8820   oc_implicit_default_constructor,
8821   oc_implicit_copy_constructor,
8822   oc_implicit_move_constructor,
8823   oc_implicit_copy_assignment,
8824   oc_implicit_move_assignment,
8825   oc_implicit_inherited_constructor
8826 };
8827 
8828 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8829                                                 FunctionDecl *Fn,
8830                                                 std::string &Description) {
8831   bool isTemplate = false;
8832 
8833   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8834     isTemplate = true;
8835     Description = S.getTemplateArgumentBindingsText(
8836       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8837   }
8838 
8839   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8840     if (!Ctor->isImplicit())
8841       return isTemplate ? oc_constructor_template : oc_constructor;
8842 
8843     if (Ctor->getInheritedConstructor())
8844       return oc_implicit_inherited_constructor;
8845 
8846     if (Ctor->isDefaultConstructor())
8847       return oc_implicit_default_constructor;
8848 
8849     if (Ctor->isMoveConstructor())
8850       return oc_implicit_move_constructor;
8851 
8852     assert(Ctor->isCopyConstructor() &&
8853            "unexpected sort of implicit constructor");
8854     return oc_implicit_copy_constructor;
8855   }
8856 
8857   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8858     // This actually gets spelled 'candidate function' for now, but
8859     // it doesn't hurt to split it out.
8860     if (!Meth->isImplicit())
8861       return isTemplate ? oc_method_template : oc_method;
8862 
8863     if (Meth->isMoveAssignmentOperator())
8864       return oc_implicit_move_assignment;
8865 
8866     if (Meth->isCopyAssignmentOperator())
8867       return oc_implicit_copy_assignment;
8868 
8869     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8870     return oc_method;
8871   }
8872 
8873   return isTemplate ? oc_function_template : oc_function;
8874 }
8875 
8876 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8877   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8878   if (!Ctor) return;
8879 
8880   Ctor = Ctor->getInheritedConstructor();
8881   if (!Ctor) return;
8882 
8883   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8884 }
8885 
8886 } // end anonymous namespace
8887 
8888 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8889                                     const FunctionDecl *FD) {
8890   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8891     bool AlwaysTrue;
8892     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8893       return false;
8894     if (!AlwaysTrue)
8895       return false;
8896   }
8897   return true;
8898 }
8899 
8900 /// \brief Returns true if we can take the address of the function.
8901 ///
8902 /// \param Complain - If true, we'll emit a diagnostic
8903 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8904 ///   we in overload resolution?
8905 /// \param Loc - The location of the statement we're complaining about. Ignored
8906 ///   if we're not complaining, or if we're in overload resolution.
8907 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8908                                               bool Complain,
8909                                               bool InOverloadResolution,
8910                                               SourceLocation Loc) {
8911   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8912     if (Complain) {
8913       if (InOverloadResolution)
8914         S.Diag(FD->getLocStart(),
8915                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8916       else
8917         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8918     }
8919     return false;
8920   }
8921 
8922   auto I = std::find_if(FD->param_begin(), FD->param_end(),
8923                         std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8924   if (I == FD->param_end())
8925     return true;
8926 
8927   if (Complain) {
8928     // Add one to ParamNo because it's user-facing
8929     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8930     if (InOverloadResolution)
8931       S.Diag(FD->getLocation(),
8932              diag::note_ovl_candidate_has_pass_object_size_params)
8933           << ParamNo;
8934     else
8935       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8936           << FD << ParamNo;
8937   }
8938   return false;
8939 }
8940 
8941 static bool checkAddressOfCandidateIsAvailable(Sema &S,
8942                                                const FunctionDecl *FD) {
8943   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8944                                            /*InOverloadResolution=*/true,
8945                                            /*Loc=*/SourceLocation());
8946 }
8947 
8948 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8949                                              bool Complain,
8950                                              SourceLocation Loc) {
8951   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8952                                              /*InOverloadResolution=*/false,
8953                                              Loc);
8954 }
8955 
8956 // Notes the location of an overload candidate.
8957 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8958                                  bool TakingAddress) {
8959   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8960     return;
8961 
8962   std::string FnDesc;
8963   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8964   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8965                              << (unsigned) K << FnDesc;
8966 
8967   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8968   Diag(Fn->getLocation(), PD);
8969   MaybeEmitInheritedConstructorNote(*this, Fn);
8970 }
8971 
8972 // Notes the location of all overload candidates designated through
8973 // OverloadedExpr
8974 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8975                                      bool TakingAddress) {
8976   assert(OverloadedExpr->getType() == Context.OverloadTy);
8977 
8978   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8979   OverloadExpr *OvlExpr = Ovl.Expression;
8980 
8981   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8982                             IEnd = OvlExpr->decls_end();
8983        I != IEnd; ++I) {
8984     if (FunctionTemplateDecl *FunTmpl =
8985                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8986       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8987                             TakingAddress);
8988     } else if (FunctionDecl *Fun
8989                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8990       NoteOverloadCandidate(Fun, DestType, TakingAddress);
8991     }
8992   }
8993 }
8994 
8995 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8996 /// "lead" diagnostic; it will be given two arguments, the source and
8997 /// target types of the conversion.
8998 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8999                                  Sema &S,
9000                                  SourceLocation CaretLoc,
9001                                  const PartialDiagnostic &PDiag) const {
9002   S.Diag(CaretLoc, PDiag)
9003     << Ambiguous.getFromType() << Ambiguous.getToType();
9004   // FIXME: The note limiting machinery is borrowed from
9005   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9006   // refactoring here.
9007   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9008   unsigned CandsShown = 0;
9009   AmbiguousConversionSequence::const_iterator I, E;
9010   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9011     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9012       break;
9013     ++CandsShown;
9014     S.NoteOverloadCandidate(*I);
9015   }
9016   if (I != E)
9017     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9018 }
9019 
9020 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9021                                   unsigned I, bool TakingCandidateAddress) {
9022   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9023   assert(Conv.isBad());
9024   assert(Cand->Function && "for now, candidate must be a function");
9025   FunctionDecl *Fn = Cand->Function;
9026 
9027   // There's a conversion slot for the object argument if this is a
9028   // non-constructor method.  Note that 'I' corresponds the
9029   // conversion-slot index.
9030   bool isObjectArgument = false;
9031   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9032     if (I == 0)
9033       isObjectArgument = true;
9034     else
9035       I--;
9036   }
9037 
9038   std::string FnDesc;
9039   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9040 
9041   Expr *FromExpr = Conv.Bad.FromExpr;
9042   QualType FromTy = Conv.Bad.getFromType();
9043   QualType ToTy = Conv.Bad.getToType();
9044 
9045   if (FromTy == S.Context.OverloadTy) {
9046     assert(FromExpr && "overload set argument came from implicit argument?");
9047     Expr *E = FromExpr->IgnoreParens();
9048     if (isa<UnaryOperator>(E))
9049       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9050     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9051 
9052     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9053       << (unsigned) FnKind << FnDesc
9054       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9055       << ToTy << Name << I+1;
9056     MaybeEmitInheritedConstructorNote(S, Fn);
9057     return;
9058   }
9059 
9060   // Do some hand-waving analysis to see if the non-viability is due
9061   // to a qualifier mismatch.
9062   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9063   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9064   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9065     CToTy = RT->getPointeeType();
9066   else {
9067     // TODO: detect and diagnose the full richness of const mismatches.
9068     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9069       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9070         CFromTy = FromPT->getPointeeType();
9071         CToTy = ToPT->getPointeeType();
9072       }
9073   }
9074 
9075   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9076       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9077     Qualifiers FromQs = CFromTy.getQualifiers();
9078     Qualifiers ToQs = CToTy.getQualifiers();
9079 
9080     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9081       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9082         << (unsigned) FnKind << FnDesc
9083         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9084         << FromTy
9085         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9086         << (unsigned) isObjectArgument << I+1;
9087       MaybeEmitInheritedConstructorNote(S, Fn);
9088       return;
9089     }
9090 
9091     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9092       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9093         << (unsigned) FnKind << FnDesc
9094         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9095         << FromTy
9096         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9097         << (unsigned) isObjectArgument << I+1;
9098       MaybeEmitInheritedConstructorNote(S, Fn);
9099       return;
9100     }
9101 
9102     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9103       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9104       << (unsigned) FnKind << FnDesc
9105       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9106       << FromTy
9107       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9108       << (unsigned) isObjectArgument << I+1;
9109       MaybeEmitInheritedConstructorNote(S, Fn);
9110       return;
9111     }
9112 
9113     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9114     assert(CVR && "unexpected qualifiers mismatch");
9115 
9116     if (isObjectArgument) {
9117       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9118         << (unsigned) FnKind << FnDesc
9119         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9120         << FromTy << (CVR - 1);
9121     } else {
9122       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9123         << (unsigned) FnKind << FnDesc
9124         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9125         << FromTy << (CVR - 1) << I+1;
9126     }
9127     MaybeEmitInheritedConstructorNote(S, Fn);
9128     return;
9129   }
9130 
9131   // Special diagnostic for failure to convert an initializer list, since
9132   // telling the user that it has type void is not useful.
9133   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9134     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9135       << (unsigned) FnKind << FnDesc
9136       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9137       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9138     MaybeEmitInheritedConstructorNote(S, Fn);
9139     return;
9140   }
9141 
9142   // Diagnose references or pointers to incomplete types differently,
9143   // since it's far from impossible that the incompleteness triggered
9144   // the failure.
9145   QualType TempFromTy = FromTy.getNonReferenceType();
9146   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9147     TempFromTy = PTy->getPointeeType();
9148   if (TempFromTy->isIncompleteType()) {
9149     // Emit the generic diagnostic and, optionally, add the hints to it.
9150     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9151       << (unsigned) FnKind << FnDesc
9152       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9153       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9154       << (unsigned) (Cand->Fix.Kind);
9155 
9156     MaybeEmitInheritedConstructorNote(S, Fn);
9157     return;
9158   }
9159 
9160   // Diagnose base -> derived pointer conversions.
9161   unsigned BaseToDerivedConversion = 0;
9162   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9163     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9164       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9165                                                FromPtrTy->getPointeeType()) &&
9166           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9167           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9168           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9169                           FromPtrTy->getPointeeType()))
9170         BaseToDerivedConversion = 1;
9171     }
9172   } else if (const ObjCObjectPointerType *FromPtrTy
9173                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9174     if (const ObjCObjectPointerType *ToPtrTy
9175                                         = ToTy->getAs<ObjCObjectPointerType>())
9176       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9177         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9178           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9179                                                 FromPtrTy->getPointeeType()) &&
9180               FromIface->isSuperClassOf(ToIface))
9181             BaseToDerivedConversion = 2;
9182   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9183     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9184         !FromTy->isIncompleteType() &&
9185         !ToRefTy->getPointeeType()->isIncompleteType() &&
9186         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9187       BaseToDerivedConversion = 3;
9188     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9189                ToTy.getNonReferenceType().getCanonicalType() ==
9190                FromTy.getNonReferenceType().getCanonicalType()) {
9191       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9192         << (unsigned) FnKind << FnDesc
9193         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9194         << (unsigned) isObjectArgument << I + 1;
9195       MaybeEmitInheritedConstructorNote(S, Fn);
9196       return;
9197     }
9198   }
9199 
9200   if (BaseToDerivedConversion) {
9201     S.Diag(Fn->getLocation(),
9202            diag::note_ovl_candidate_bad_base_to_derived_conv)
9203       << (unsigned) FnKind << FnDesc
9204       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9205       << (BaseToDerivedConversion - 1)
9206       << FromTy << ToTy << I+1;
9207     MaybeEmitInheritedConstructorNote(S, Fn);
9208     return;
9209   }
9210 
9211   if (isa<ObjCObjectPointerType>(CFromTy) &&
9212       isa<PointerType>(CToTy)) {
9213       Qualifiers FromQs = CFromTy.getQualifiers();
9214       Qualifiers ToQs = CToTy.getQualifiers();
9215       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9216         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9217         << (unsigned) FnKind << FnDesc
9218         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9219         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9220         MaybeEmitInheritedConstructorNote(S, Fn);
9221         return;
9222       }
9223   }
9224 
9225   if (TakingCandidateAddress &&
9226       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9227     return;
9228 
9229   // Emit the generic diagnostic and, optionally, add the hints to it.
9230   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9231   FDiag << (unsigned) FnKind << FnDesc
9232     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9233     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9234     << (unsigned) (Cand->Fix.Kind);
9235 
9236   // If we can fix the conversion, suggest the FixIts.
9237   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9238        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9239     FDiag << *HI;
9240   S.Diag(Fn->getLocation(), FDiag);
9241 
9242   MaybeEmitInheritedConstructorNote(S, Fn);
9243 }
9244 
9245 /// Additional arity mismatch diagnosis specific to a function overload
9246 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9247 /// over a candidate in any candidate set.
9248 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9249                                unsigned NumArgs) {
9250   FunctionDecl *Fn = Cand->Function;
9251   unsigned MinParams = Fn->getMinRequiredArguments();
9252 
9253   // With invalid overloaded operators, it's possible that we think we
9254   // have an arity mismatch when in fact it looks like we have the
9255   // right number of arguments, because only overloaded operators have
9256   // the weird behavior of overloading member and non-member functions.
9257   // Just don't report anything.
9258   if (Fn->isInvalidDecl() &&
9259       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9260     return true;
9261 
9262   if (NumArgs < MinParams) {
9263     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9264            (Cand->FailureKind == ovl_fail_bad_deduction &&
9265             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9266   } else {
9267     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9268            (Cand->FailureKind == ovl_fail_bad_deduction &&
9269             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9270   }
9271 
9272   return false;
9273 }
9274 
9275 /// General arity mismatch diagnosis over a candidate in a candidate set.
9276 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
9277   assert(isa<FunctionDecl>(D) &&
9278       "The templated declaration should at least be a function"
9279       " when diagnosing bad template argument deduction due to too many"
9280       " or too few arguments");
9281 
9282   FunctionDecl *Fn = cast<FunctionDecl>(D);
9283 
9284   // TODO: treat calls to a missing default constructor as a special case
9285   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9286   unsigned MinParams = Fn->getMinRequiredArguments();
9287 
9288   // at least / at most / exactly
9289   unsigned mode, modeCount;
9290   if (NumFormalArgs < MinParams) {
9291     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9292         FnTy->isTemplateVariadic())
9293       mode = 0; // "at least"
9294     else
9295       mode = 2; // "exactly"
9296     modeCount = MinParams;
9297   } else {
9298     if (MinParams != FnTy->getNumParams())
9299       mode = 1; // "at most"
9300     else
9301       mode = 2; // "exactly"
9302     modeCount = FnTy->getNumParams();
9303   }
9304 
9305   std::string Description;
9306   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9307 
9308   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9309     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9310       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9311       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9312   else
9313     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9314       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9315       << mode << modeCount << NumFormalArgs;
9316   MaybeEmitInheritedConstructorNote(S, Fn);
9317 }
9318 
9319 /// Arity mismatch diagnosis specific to a function overload candidate.
9320 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9321                                   unsigned NumFormalArgs) {
9322   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9323     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9324 }
9325 
9326 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9327   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9328     return FD->getDescribedFunctionTemplate();
9329   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9330     return RD->getDescribedClassTemplate();
9331 
9332   llvm_unreachable("Unsupported: Getting the described template declaration"
9333                    " for bad deduction diagnosis");
9334 }
9335 
9336 /// Diagnose a failed template-argument deduction.
9337 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9338                                  DeductionFailureInfo &DeductionFailure,
9339                                  unsigned NumArgs,
9340                                  bool TakingCandidateAddress) {
9341   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9342   NamedDecl *ParamD;
9343   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9344   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9345   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9346   switch (DeductionFailure.Result) {
9347   case Sema::TDK_Success:
9348     llvm_unreachable("TDK_success while diagnosing bad deduction");
9349 
9350   case Sema::TDK_Incomplete: {
9351     assert(ParamD && "no parameter found for incomplete deduction result");
9352     S.Diag(Templated->getLocation(),
9353            diag::note_ovl_candidate_incomplete_deduction)
9354         << ParamD->getDeclName();
9355     MaybeEmitInheritedConstructorNote(S, Templated);
9356     return;
9357   }
9358 
9359   case Sema::TDK_Underqualified: {
9360     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9361     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9362 
9363     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9364 
9365     // Param will have been canonicalized, but it should just be a
9366     // qualified version of ParamD, so move the qualifiers to that.
9367     QualifierCollector Qs;
9368     Qs.strip(Param);
9369     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9370     assert(S.Context.hasSameType(Param, NonCanonParam));
9371 
9372     // Arg has also been canonicalized, but there's nothing we can do
9373     // about that.  It also doesn't matter as much, because it won't
9374     // have any template parameters in it (because deduction isn't
9375     // done on dependent types).
9376     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9377 
9378     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9379         << ParamD->getDeclName() << Arg << NonCanonParam;
9380     MaybeEmitInheritedConstructorNote(S, Templated);
9381     return;
9382   }
9383 
9384   case Sema::TDK_Inconsistent: {
9385     assert(ParamD && "no parameter found for inconsistent deduction result");
9386     int which = 0;
9387     if (isa<TemplateTypeParmDecl>(ParamD))
9388       which = 0;
9389     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9390       which = 1;
9391     else {
9392       which = 2;
9393     }
9394 
9395     S.Diag(Templated->getLocation(),
9396            diag::note_ovl_candidate_inconsistent_deduction)
9397         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9398         << *DeductionFailure.getSecondArg();
9399     MaybeEmitInheritedConstructorNote(S, Templated);
9400     return;
9401   }
9402 
9403   case Sema::TDK_InvalidExplicitArguments:
9404     assert(ParamD && "no parameter found for invalid explicit arguments");
9405     if (ParamD->getDeclName())
9406       S.Diag(Templated->getLocation(),
9407              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9408           << ParamD->getDeclName();
9409     else {
9410       int index = 0;
9411       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9412         index = TTP->getIndex();
9413       else if (NonTypeTemplateParmDecl *NTTP
9414                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9415         index = NTTP->getIndex();
9416       else
9417         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9418       S.Diag(Templated->getLocation(),
9419              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9420           << (index + 1);
9421     }
9422     MaybeEmitInheritedConstructorNote(S, Templated);
9423     return;
9424 
9425   case Sema::TDK_TooManyArguments:
9426   case Sema::TDK_TooFewArguments:
9427     DiagnoseArityMismatch(S, Templated, NumArgs);
9428     return;
9429 
9430   case Sema::TDK_InstantiationDepth:
9431     S.Diag(Templated->getLocation(),
9432            diag::note_ovl_candidate_instantiation_depth);
9433     MaybeEmitInheritedConstructorNote(S, Templated);
9434     return;
9435 
9436   case Sema::TDK_SubstitutionFailure: {
9437     // Format the template argument list into the argument string.
9438     SmallString<128> TemplateArgString;
9439     if (TemplateArgumentList *Args =
9440             DeductionFailure.getTemplateArgumentList()) {
9441       TemplateArgString = " ";
9442       TemplateArgString += S.getTemplateArgumentBindingsText(
9443           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9444     }
9445 
9446     // If this candidate was disabled by enable_if, say so.
9447     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9448     if (PDiag && PDiag->second.getDiagID() ==
9449           diag::err_typename_nested_not_found_enable_if) {
9450       // FIXME: Use the source range of the condition, and the fully-qualified
9451       //        name of the enable_if template. These are both present in PDiag.
9452       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9453         << "'enable_if'" << TemplateArgString;
9454       return;
9455     }
9456 
9457     // Format the SFINAE diagnostic into the argument string.
9458     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9459     //        formatted message in another diagnostic.
9460     SmallString<128> SFINAEArgString;
9461     SourceRange R;
9462     if (PDiag) {
9463       SFINAEArgString = ": ";
9464       R = SourceRange(PDiag->first, PDiag->first);
9465       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9466     }
9467 
9468     S.Diag(Templated->getLocation(),
9469            diag::note_ovl_candidate_substitution_failure)
9470         << TemplateArgString << SFINAEArgString << R;
9471     MaybeEmitInheritedConstructorNote(S, Templated);
9472     return;
9473   }
9474 
9475   case Sema::TDK_FailedOverloadResolution: {
9476     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9477     S.Diag(Templated->getLocation(),
9478            diag::note_ovl_candidate_failed_overload_resolution)
9479         << R.Expression->getName();
9480     return;
9481   }
9482 
9483   case Sema::TDK_DeducedMismatch: {
9484     // Format the template argument list into the argument string.
9485     SmallString<128> TemplateArgString;
9486     if (TemplateArgumentList *Args =
9487             DeductionFailure.getTemplateArgumentList()) {
9488       TemplateArgString = " ";
9489       TemplateArgString += S.getTemplateArgumentBindingsText(
9490           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9491     }
9492 
9493     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9494         << (*DeductionFailure.getCallArgIndex() + 1)
9495         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9496         << TemplateArgString;
9497     break;
9498   }
9499 
9500   case Sema::TDK_NonDeducedMismatch: {
9501     // FIXME: Provide a source location to indicate what we couldn't match.
9502     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9503     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9504     if (FirstTA.getKind() == TemplateArgument::Template &&
9505         SecondTA.getKind() == TemplateArgument::Template) {
9506       TemplateName FirstTN = FirstTA.getAsTemplate();
9507       TemplateName SecondTN = SecondTA.getAsTemplate();
9508       if (FirstTN.getKind() == TemplateName::Template &&
9509           SecondTN.getKind() == TemplateName::Template) {
9510         if (FirstTN.getAsTemplateDecl()->getName() ==
9511             SecondTN.getAsTemplateDecl()->getName()) {
9512           // FIXME: This fixes a bad diagnostic where both templates are named
9513           // the same.  This particular case is a bit difficult since:
9514           // 1) It is passed as a string to the diagnostic printer.
9515           // 2) The diagnostic printer only attempts to find a better
9516           //    name for types, not decls.
9517           // Ideally, this should folded into the diagnostic printer.
9518           S.Diag(Templated->getLocation(),
9519                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9520               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9521           return;
9522         }
9523       }
9524     }
9525 
9526     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9527         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9528       return;
9529 
9530     // FIXME: For generic lambda parameters, check if the function is a lambda
9531     // call operator, and if so, emit a prettier and more informative
9532     // diagnostic that mentions 'auto' and lambda in addition to
9533     // (or instead of?) the canonical template type parameters.
9534     S.Diag(Templated->getLocation(),
9535            diag::note_ovl_candidate_non_deduced_mismatch)
9536         << FirstTA << SecondTA;
9537     return;
9538   }
9539   // TODO: diagnose these individually, then kill off
9540   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9541   case Sema::TDK_MiscellaneousDeductionFailure:
9542     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9543     MaybeEmitInheritedConstructorNote(S, Templated);
9544     return;
9545   }
9546 }
9547 
9548 /// Diagnose a failed template-argument deduction, for function calls.
9549 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9550                                  unsigned NumArgs,
9551                                  bool TakingCandidateAddress) {
9552   unsigned TDK = Cand->DeductionFailure.Result;
9553   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9554     if (CheckArityMismatch(S, Cand, NumArgs))
9555       return;
9556   }
9557   DiagnoseBadDeduction(S, Cand->Function, // pattern
9558                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9559 }
9560 
9561 /// CUDA: diagnose an invalid call across targets.
9562 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9563   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9564   FunctionDecl *Callee = Cand->Function;
9565 
9566   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9567                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9568 
9569   std::string FnDesc;
9570   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9571 
9572   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9573       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9574 
9575   // This could be an implicit constructor for which we could not infer the
9576   // target due to a collsion. Diagnose that case.
9577   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9578   if (Meth != nullptr && Meth->isImplicit()) {
9579     CXXRecordDecl *ParentClass = Meth->getParent();
9580     Sema::CXXSpecialMember CSM;
9581 
9582     switch (FnKind) {
9583     default:
9584       return;
9585     case oc_implicit_default_constructor:
9586       CSM = Sema::CXXDefaultConstructor;
9587       break;
9588     case oc_implicit_copy_constructor:
9589       CSM = Sema::CXXCopyConstructor;
9590       break;
9591     case oc_implicit_move_constructor:
9592       CSM = Sema::CXXMoveConstructor;
9593       break;
9594     case oc_implicit_copy_assignment:
9595       CSM = Sema::CXXCopyAssignment;
9596       break;
9597     case oc_implicit_move_assignment:
9598       CSM = Sema::CXXMoveAssignment;
9599       break;
9600     };
9601 
9602     bool ConstRHS = false;
9603     if (Meth->getNumParams()) {
9604       if (const ReferenceType *RT =
9605               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9606         ConstRHS = RT->getPointeeType().isConstQualified();
9607       }
9608     }
9609 
9610     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9611                                               /* ConstRHS */ ConstRHS,
9612                                               /* Diagnose */ true);
9613   }
9614 }
9615 
9616 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9617   FunctionDecl *Callee = Cand->Function;
9618   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9619 
9620   S.Diag(Callee->getLocation(),
9621          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9622       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9623 }
9624 
9625 /// Generates a 'note' diagnostic for an overload candidate.  We've
9626 /// already generated a primary error at the call site.
9627 ///
9628 /// It really does need to be a single diagnostic with its caret
9629 /// pointed at the candidate declaration.  Yes, this creates some
9630 /// major challenges of technical writing.  Yes, this makes pointing
9631 /// out problems with specific arguments quite awkward.  It's still
9632 /// better than generating twenty screens of text for every failed
9633 /// overload.
9634 ///
9635 /// It would be great to be able to express per-candidate problems
9636 /// more richly for those diagnostic clients that cared, but we'd
9637 /// still have to be just as careful with the default diagnostics.
9638 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9639                                   unsigned NumArgs,
9640                                   bool TakingCandidateAddress) {
9641   FunctionDecl *Fn = Cand->Function;
9642 
9643   // Note deleted candidates, but only if they're viable.
9644   if (Cand->Viable && (Fn->isDeleted() ||
9645       S.isFunctionConsideredUnavailable(Fn))) {
9646     std::string FnDesc;
9647     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9648 
9649     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9650       << FnKind << FnDesc
9651       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9652     MaybeEmitInheritedConstructorNote(S, Fn);
9653     return;
9654   }
9655 
9656   // We don't really have anything else to say about viable candidates.
9657   if (Cand->Viable) {
9658     S.NoteOverloadCandidate(Fn);
9659     return;
9660   }
9661 
9662   switch (Cand->FailureKind) {
9663   case ovl_fail_too_many_arguments:
9664   case ovl_fail_too_few_arguments:
9665     return DiagnoseArityMismatch(S, Cand, NumArgs);
9666 
9667   case ovl_fail_bad_deduction:
9668     return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
9669 
9670   case ovl_fail_illegal_constructor: {
9671     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9672       << (Fn->getPrimaryTemplate() ? 1 : 0);
9673     MaybeEmitInheritedConstructorNote(S, Fn);
9674     return;
9675   }
9676 
9677   case ovl_fail_trivial_conversion:
9678   case ovl_fail_bad_final_conversion:
9679   case ovl_fail_final_conversion_not_exact:
9680     return S.NoteOverloadCandidate(Fn);
9681 
9682   case ovl_fail_bad_conversion: {
9683     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9684     for (unsigned N = Cand->NumConversions; I != N; ++I)
9685       if (Cand->Conversions[I].isBad())
9686         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9687 
9688     // FIXME: this currently happens when we're called from SemaInit
9689     // when user-conversion overload fails.  Figure out how to handle
9690     // those conditions and diagnose them well.
9691     return S.NoteOverloadCandidate(Fn);
9692   }
9693 
9694   case ovl_fail_bad_target:
9695     return DiagnoseBadTarget(S, Cand);
9696 
9697   case ovl_fail_enable_if:
9698     return DiagnoseFailedEnableIfAttr(S, Cand);
9699 
9700   case ovl_fail_addr_not_available: {
9701     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9702     (void)Available;
9703     assert(!Available);
9704     break;
9705   }
9706   }
9707 }
9708 
9709 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9710   // Desugar the type of the surrogate down to a function type,
9711   // retaining as many typedefs as possible while still showing
9712   // the function type (and, therefore, its parameter types).
9713   QualType FnType = Cand->Surrogate->getConversionType();
9714   bool isLValueReference = false;
9715   bool isRValueReference = false;
9716   bool isPointer = false;
9717   if (const LValueReferenceType *FnTypeRef =
9718         FnType->getAs<LValueReferenceType>()) {
9719     FnType = FnTypeRef->getPointeeType();
9720     isLValueReference = true;
9721   } else if (const RValueReferenceType *FnTypeRef =
9722                FnType->getAs<RValueReferenceType>()) {
9723     FnType = FnTypeRef->getPointeeType();
9724     isRValueReference = true;
9725   }
9726   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9727     FnType = FnTypePtr->getPointeeType();
9728     isPointer = true;
9729   }
9730   // Desugar down to a function type.
9731   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9732   // Reconstruct the pointer/reference as appropriate.
9733   if (isPointer) FnType = S.Context.getPointerType(FnType);
9734   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9735   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9736 
9737   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9738     << FnType;
9739   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9740 }
9741 
9742 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9743                                          SourceLocation OpLoc,
9744                                          OverloadCandidate *Cand) {
9745   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9746   std::string TypeStr("operator");
9747   TypeStr += Opc;
9748   TypeStr += "(";
9749   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9750   if (Cand->NumConversions == 1) {
9751     TypeStr += ")";
9752     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9753   } else {
9754     TypeStr += ", ";
9755     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9756     TypeStr += ")";
9757     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9758   }
9759 }
9760 
9761 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9762                                          OverloadCandidate *Cand) {
9763   unsigned NoOperands = Cand->NumConversions;
9764   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9765     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9766     if (ICS.isBad()) break; // all meaningless after first invalid
9767     if (!ICS.isAmbiguous()) continue;
9768 
9769     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9770                               S.PDiag(diag::note_ambiguous_type_conversion));
9771   }
9772 }
9773 
9774 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9775   if (Cand->Function)
9776     return Cand->Function->getLocation();
9777   if (Cand->IsSurrogate)
9778     return Cand->Surrogate->getLocation();
9779   return SourceLocation();
9780 }
9781 
9782 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9783   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9784   case Sema::TDK_Success:
9785     llvm_unreachable("TDK_success while diagnosing bad deduction");
9786 
9787   case Sema::TDK_Invalid:
9788   case Sema::TDK_Incomplete:
9789     return 1;
9790 
9791   case Sema::TDK_Underqualified:
9792   case Sema::TDK_Inconsistent:
9793     return 2;
9794 
9795   case Sema::TDK_SubstitutionFailure:
9796   case Sema::TDK_DeducedMismatch:
9797   case Sema::TDK_NonDeducedMismatch:
9798   case Sema::TDK_MiscellaneousDeductionFailure:
9799     return 3;
9800 
9801   case Sema::TDK_InstantiationDepth:
9802   case Sema::TDK_FailedOverloadResolution:
9803     return 4;
9804 
9805   case Sema::TDK_InvalidExplicitArguments:
9806     return 5;
9807 
9808   case Sema::TDK_TooManyArguments:
9809   case Sema::TDK_TooFewArguments:
9810     return 6;
9811   }
9812   llvm_unreachable("Unhandled deduction result");
9813 }
9814 
9815 namespace {
9816 struct CompareOverloadCandidatesForDisplay {
9817   Sema &S;
9818   SourceLocation Loc;
9819   size_t NumArgs;
9820 
9821   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9822       : S(S), NumArgs(nArgs) {}
9823 
9824   bool operator()(const OverloadCandidate *L,
9825                   const OverloadCandidate *R) {
9826     // Fast-path this check.
9827     if (L == R) return false;
9828 
9829     // Order first by viability.
9830     if (L->Viable) {
9831       if (!R->Viable) return true;
9832 
9833       // TODO: introduce a tri-valued comparison for overload
9834       // candidates.  Would be more worthwhile if we had a sort
9835       // that could exploit it.
9836       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9837       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9838     } else if (R->Viable)
9839       return false;
9840 
9841     assert(L->Viable == R->Viable);
9842 
9843     // Criteria by which we can sort non-viable candidates:
9844     if (!L->Viable) {
9845       // 1. Arity mismatches come after other candidates.
9846       if (L->FailureKind == ovl_fail_too_many_arguments ||
9847           L->FailureKind == ovl_fail_too_few_arguments) {
9848         if (R->FailureKind == ovl_fail_too_many_arguments ||
9849             R->FailureKind == ovl_fail_too_few_arguments) {
9850           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9851           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9852           if (LDist == RDist) {
9853             if (L->FailureKind == R->FailureKind)
9854               // Sort non-surrogates before surrogates.
9855               return !L->IsSurrogate && R->IsSurrogate;
9856             // Sort candidates requiring fewer parameters than there were
9857             // arguments given after candidates requiring more parameters
9858             // than there were arguments given.
9859             return L->FailureKind == ovl_fail_too_many_arguments;
9860           }
9861           return LDist < RDist;
9862         }
9863         return false;
9864       }
9865       if (R->FailureKind == ovl_fail_too_many_arguments ||
9866           R->FailureKind == ovl_fail_too_few_arguments)
9867         return true;
9868 
9869       // 2. Bad conversions come first and are ordered by the number
9870       // of bad conversions and quality of good conversions.
9871       if (L->FailureKind == ovl_fail_bad_conversion) {
9872         if (R->FailureKind != ovl_fail_bad_conversion)
9873           return true;
9874 
9875         // The conversion that can be fixed with a smaller number of changes,
9876         // comes first.
9877         unsigned numLFixes = L->Fix.NumConversionsFixed;
9878         unsigned numRFixes = R->Fix.NumConversionsFixed;
9879         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9880         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9881         if (numLFixes != numRFixes) {
9882           return numLFixes < numRFixes;
9883         }
9884 
9885         // If there's any ordering between the defined conversions...
9886         // FIXME: this might not be transitive.
9887         assert(L->NumConversions == R->NumConversions);
9888 
9889         int leftBetter = 0;
9890         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9891         for (unsigned E = L->NumConversions; I != E; ++I) {
9892           switch (CompareImplicitConversionSequences(S, Loc,
9893                                                      L->Conversions[I],
9894                                                      R->Conversions[I])) {
9895           case ImplicitConversionSequence::Better:
9896             leftBetter++;
9897             break;
9898 
9899           case ImplicitConversionSequence::Worse:
9900             leftBetter--;
9901             break;
9902 
9903           case ImplicitConversionSequence::Indistinguishable:
9904             break;
9905           }
9906         }
9907         if (leftBetter > 0) return true;
9908         if (leftBetter < 0) return false;
9909 
9910       } else if (R->FailureKind == ovl_fail_bad_conversion)
9911         return false;
9912 
9913       if (L->FailureKind == ovl_fail_bad_deduction) {
9914         if (R->FailureKind != ovl_fail_bad_deduction)
9915           return true;
9916 
9917         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9918           return RankDeductionFailure(L->DeductionFailure)
9919                < RankDeductionFailure(R->DeductionFailure);
9920       } else if (R->FailureKind == ovl_fail_bad_deduction)
9921         return false;
9922 
9923       // TODO: others?
9924     }
9925 
9926     // Sort everything else by location.
9927     SourceLocation LLoc = GetLocationForCandidate(L);
9928     SourceLocation RLoc = GetLocationForCandidate(R);
9929 
9930     // Put candidates without locations (e.g. builtins) at the end.
9931     if (LLoc.isInvalid()) return false;
9932     if (RLoc.isInvalid()) return true;
9933 
9934     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9935   }
9936 };
9937 }
9938 
9939 /// CompleteNonViableCandidate - Normally, overload resolution only
9940 /// computes up to the first. Produces the FixIt set if possible.
9941 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9942                                        ArrayRef<Expr *> Args) {
9943   assert(!Cand->Viable);
9944 
9945   // Don't do anything on failures other than bad conversion.
9946   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9947 
9948   // We only want the FixIts if all the arguments can be corrected.
9949   bool Unfixable = false;
9950   // Use a implicit copy initialization to check conversion fixes.
9951   Cand->Fix.setConversionChecker(TryCopyInitialization);
9952 
9953   // Skip forward to the first bad conversion.
9954   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9955   unsigned ConvCount = Cand->NumConversions;
9956   while (true) {
9957     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9958     ConvIdx++;
9959     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9960       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9961       break;
9962     }
9963   }
9964 
9965   if (ConvIdx == ConvCount)
9966     return;
9967 
9968   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9969          "remaining conversion is initialized?");
9970 
9971   // FIXME: this should probably be preserved from the overload
9972   // operation somehow.
9973   bool SuppressUserConversions = false;
9974 
9975   const FunctionProtoType* Proto;
9976   unsigned ArgIdx = ConvIdx;
9977 
9978   if (Cand->IsSurrogate) {
9979     QualType ConvType
9980       = Cand->Surrogate->getConversionType().getNonReferenceType();
9981     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9982       ConvType = ConvPtrType->getPointeeType();
9983     Proto = ConvType->getAs<FunctionProtoType>();
9984     ArgIdx--;
9985   } else if (Cand->Function) {
9986     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9987     if (isa<CXXMethodDecl>(Cand->Function) &&
9988         !isa<CXXConstructorDecl>(Cand->Function))
9989       ArgIdx--;
9990   } else {
9991     // Builtin binary operator with a bad first conversion.
9992     assert(ConvCount <= 3);
9993     for (; ConvIdx != ConvCount; ++ConvIdx)
9994       Cand->Conversions[ConvIdx]
9995         = TryCopyInitialization(S, Args[ConvIdx],
9996                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9997                                 SuppressUserConversions,
9998                                 /*InOverloadResolution*/ true,
9999                                 /*AllowObjCWritebackConversion=*/
10000                                   S.getLangOpts().ObjCAutoRefCount);
10001     return;
10002   }
10003 
10004   // Fill in the rest of the conversions.
10005   unsigned NumParams = Proto->getNumParams();
10006   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10007     if (ArgIdx < NumParams) {
10008       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10009           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10010           /*InOverloadResolution=*/true,
10011           /*AllowObjCWritebackConversion=*/
10012           S.getLangOpts().ObjCAutoRefCount);
10013       // Store the FixIt in the candidate if it exists.
10014       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10015         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10016     }
10017     else
10018       Cand->Conversions[ConvIdx].setEllipsis();
10019   }
10020 }
10021 
10022 /// PrintOverloadCandidates - When overload resolution fails, prints
10023 /// diagnostic messages containing the candidates in the candidate
10024 /// set.
10025 void OverloadCandidateSet::NoteCandidates(Sema &S,
10026                                           OverloadCandidateDisplayKind OCD,
10027                                           ArrayRef<Expr *> Args,
10028                                           StringRef Opc,
10029                                           SourceLocation OpLoc) {
10030   // Sort the candidates by viability and position.  Sorting directly would
10031   // be prohibitive, so we make a set of pointers and sort those.
10032   SmallVector<OverloadCandidate*, 32> Cands;
10033   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10034   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10035     if (Cand->Viable)
10036       Cands.push_back(Cand);
10037     else if (OCD == OCD_AllCandidates) {
10038       CompleteNonViableCandidate(S, Cand, Args);
10039       if (Cand->Function || Cand->IsSurrogate)
10040         Cands.push_back(Cand);
10041       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10042       // want to list every possible builtin candidate.
10043     }
10044   }
10045 
10046   std::sort(Cands.begin(), Cands.end(),
10047             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10048 
10049   bool ReportedAmbiguousConversions = false;
10050 
10051   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10052   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10053   unsigned CandsShown = 0;
10054   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10055     OverloadCandidate *Cand = *I;
10056 
10057     // Set an arbitrary limit on the number of candidate functions we'll spam
10058     // the user with.  FIXME: This limit should depend on details of the
10059     // candidate list.
10060     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10061       break;
10062     }
10063     ++CandsShown;
10064 
10065     if (Cand->Function)
10066       NoteFunctionCandidate(S, Cand, Args.size(),
10067                             /*TakingCandidateAddress=*/false);
10068     else if (Cand->IsSurrogate)
10069       NoteSurrogateCandidate(S, Cand);
10070     else {
10071       assert(Cand->Viable &&
10072              "Non-viable built-in candidates are not added to Cands.");
10073       // Generally we only see ambiguities including viable builtin
10074       // operators if overload resolution got screwed up by an
10075       // ambiguous user-defined conversion.
10076       //
10077       // FIXME: It's quite possible for different conversions to see
10078       // different ambiguities, though.
10079       if (!ReportedAmbiguousConversions) {
10080         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10081         ReportedAmbiguousConversions = true;
10082       }
10083 
10084       // If this is a viable builtin, print it.
10085       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10086     }
10087   }
10088 
10089   if (I != E)
10090     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10091 }
10092 
10093 static SourceLocation
10094 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10095   return Cand->Specialization ? Cand->Specialization->getLocation()
10096                               : SourceLocation();
10097 }
10098 
10099 namespace {
10100 struct CompareTemplateSpecCandidatesForDisplay {
10101   Sema &S;
10102   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10103 
10104   bool operator()(const TemplateSpecCandidate *L,
10105                   const TemplateSpecCandidate *R) {
10106     // Fast-path this check.
10107     if (L == R)
10108       return false;
10109 
10110     // Assuming that both candidates are not matches...
10111 
10112     // Sort by the ranking of deduction failures.
10113     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10114       return RankDeductionFailure(L->DeductionFailure) <
10115              RankDeductionFailure(R->DeductionFailure);
10116 
10117     // Sort everything else by location.
10118     SourceLocation LLoc = GetLocationForCandidate(L);
10119     SourceLocation RLoc = GetLocationForCandidate(R);
10120 
10121     // Put candidates without locations (e.g. builtins) at the end.
10122     if (LLoc.isInvalid())
10123       return false;
10124     if (RLoc.isInvalid())
10125       return true;
10126 
10127     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10128   }
10129 };
10130 }
10131 
10132 /// Diagnose a template argument deduction failure.
10133 /// We are treating these failures as overload failures due to bad
10134 /// deductions.
10135 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10136                                                  bool ForTakingAddress) {
10137   DiagnoseBadDeduction(S, Specialization, // pattern
10138                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10139 }
10140 
10141 void TemplateSpecCandidateSet::destroyCandidates() {
10142   for (iterator i = begin(), e = end(); i != e; ++i) {
10143     i->DeductionFailure.Destroy();
10144   }
10145 }
10146 
10147 void TemplateSpecCandidateSet::clear() {
10148   destroyCandidates();
10149   Candidates.clear();
10150 }
10151 
10152 /// NoteCandidates - When no template specialization match is found, prints
10153 /// diagnostic messages containing the non-matching specializations that form
10154 /// the candidate set.
10155 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10156 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10157 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10158   // Sort the candidates by position (assuming no candidate is a match).
10159   // Sorting directly would be prohibitive, so we make a set of pointers
10160   // and sort those.
10161   SmallVector<TemplateSpecCandidate *, 32> Cands;
10162   Cands.reserve(size());
10163   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10164     if (Cand->Specialization)
10165       Cands.push_back(Cand);
10166     // Otherwise, this is a non-matching builtin candidate.  We do not,
10167     // in general, want to list every possible builtin candidate.
10168   }
10169 
10170   std::sort(Cands.begin(), Cands.end(),
10171             CompareTemplateSpecCandidatesForDisplay(S));
10172 
10173   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10174   // for generalization purposes (?).
10175   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10176 
10177   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10178   unsigned CandsShown = 0;
10179   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10180     TemplateSpecCandidate *Cand = *I;
10181 
10182     // Set an arbitrary limit on the number of candidates we'll spam
10183     // the user with.  FIXME: This limit should depend on details of the
10184     // candidate list.
10185     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10186       break;
10187     ++CandsShown;
10188 
10189     assert(Cand->Specialization &&
10190            "Non-matching built-in candidates are not added to Cands.");
10191     Cand->NoteDeductionFailure(S, ForTakingAddress);
10192   }
10193 
10194   if (I != E)
10195     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10196 }
10197 
10198 // [PossiblyAFunctionType]  -->   [Return]
10199 // NonFunctionType --> NonFunctionType
10200 // R (A) --> R(A)
10201 // R (*)(A) --> R (A)
10202 // R (&)(A) --> R (A)
10203 // R (S::*)(A) --> R (A)
10204 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10205   QualType Ret = PossiblyAFunctionType;
10206   if (const PointerType *ToTypePtr =
10207     PossiblyAFunctionType->getAs<PointerType>())
10208     Ret = ToTypePtr->getPointeeType();
10209   else if (const ReferenceType *ToTypeRef =
10210     PossiblyAFunctionType->getAs<ReferenceType>())
10211     Ret = ToTypeRef->getPointeeType();
10212   else if (const MemberPointerType *MemTypePtr =
10213     PossiblyAFunctionType->getAs<MemberPointerType>())
10214     Ret = MemTypePtr->getPointeeType();
10215   Ret =
10216     Context.getCanonicalType(Ret).getUnqualifiedType();
10217   return Ret;
10218 }
10219 
10220 namespace {
10221 // A helper class to help with address of function resolution
10222 // - allows us to avoid passing around all those ugly parameters
10223 class AddressOfFunctionResolver {
10224   Sema& S;
10225   Expr* SourceExpr;
10226   const QualType& TargetType;
10227   QualType TargetFunctionType; // Extracted function type from target type
10228 
10229   bool Complain;
10230   //DeclAccessPair& ResultFunctionAccessPair;
10231   ASTContext& Context;
10232 
10233   bool TargetTypeIsNonStaticMemberFunction;
10234   bool FoundNonTemplateFunction;
10235   bool StaticMemberFunctionFromBoundPointer;
10236   bool HasComplained;
10237 
10238   OverloadExpr::FindResult OvlExprInfo;
10239   OverloadExpr *OvlExpr;
10240   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10241   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10242   TemplateSpecCandidateSet FailedCandidates;
10243 
10244 public:
10245   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10246                             const QualType &TargetType, bool Complain)
10247       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10248         Complain(Complain), Context(S.getASTContext()),
10249         TargetTypeIsNonStaticMemberFunction(
10250             !!TargetType->getAs<MemberPointerType>()),
10251         FoundNonTemplateFunction(false),
10252         StaticMemberFunctionFromBoundPointer(false),
10253         HasComplained(false),
10254         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10255         OvlExpr(OvlExprInfo.Expression),
10256         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10257     ExtractUnqualifiedFunctionTypeFromTargetType();
10258 
10259     if (TargetFunctionType->isFunctionType()) {
10260       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10261         if (!UME->isImplicitAccess() &&
10262             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10263           StaticMemberFunctionFromBoundPointer = true;
10264     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10265       DeclAccessPair dap;
10266       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10267               OvlExpr, false, &dap)) {
10268         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10269           if (!Method->isStatic()) {
10270             // If the target type is a non-function type and the function found
10271             // is a non-static member function, pretend as if that was the
10272             // target, it's the only possible type to end up with.
10273             TargetTypeIsNonStaticMemberFunction = true;
10274 
10275             // And skip adding the function if its not in the proper form.
10276             // We'll diagnose this due to an empty set of functions.
10277             if (!OvlExprInfo.HasFormOfMemberPointer)
10278               return;
10279           }
10280 
10281         Matches.push_back(std::make_pair(dap, Fn));
10282       }
10283       return;
10284     }
10285 
10286     if (OvlExpr->hasExplicitTemplateArgs())
10287       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10288 
10289     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10290       // C++ [over.over]p4:
10291       //   If more than one function is selected, [...]
10292       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10293         if (FoundNonTemplateFunction)
10294           EliminateAllTemplateMatches();
10295         else
10296           EliminateAllExceptMostSpecializedTemplate();
10297       }
10298     }
10299 
10300     if (S.getLangOpts().CUDA && Matches.size() > 1)
10301       EliminateSuboptimalCudaMatches();
10302   }
10303 
10304   bool hasComplained() const { return HasComplained; }
10305 
10306 private:
10307   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10308     QualType Discard;
10309     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10310            S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10311   }
10312 
10313   /// \return true if A is considered a better overload candidate for the
10314   /// desired type than B.
10315   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10316     // If A doesn't have exactly the correct type, we don't want to classify it
10317     // as "better" than anything else. This way, the user is required to
10318     // disambiguate for us if there are multiple candidates and no exact match.
10319     return candidateHasExactlyCorrectType(A) &&
10320            (!candidateHasExactlyCorrectType(B) ||
10321             hasBetterEnableIfAttrs(S, A, B));
10322   }
10323 
10324   /// \return true if we were able to eliminate all but one overload candidate,
10325   /// false otherwise.
10326   bool eliminiateSuboptimalOverloadCandidates() {
10327     // Same algorithm as overload resolution -- one pass to pick the "best",
10328     // another pass to be sure that nothing is better than the best.
10329     auto Best = Matches.begin();
10330     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10331       if (isBetterCandidate(I->second, Best->second))
10332         Best = I;
10333 
10334     const FunctionDecl *BestFn = Best->second;
10335     auto IsBestOrInferiorToBest = [this, BestFn](
10336         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10337       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10338     };
10339 
10340     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10341     // option, so we can potentially give the user a better error
10342     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10343       return false;
10344     Matches[0] = *Best;
10345     Matches.resize(1);
10346     return true;
10347   }
10348 
10349   bool isTargetTypeAFunction() const {
10350     return TargetFunctionType->isFunctionType();
10351   }
10352 
10353   // [ToType]     [Return]
10354 
10355   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10356   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10357   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10358   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10359     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10360   }
10361 
10362   // return true if any matching specializations were found
10363   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10364                                    const DeclAccessPair& CurAccessFunPair) {
10365     if (CXXMethodDecl *Method
10366               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10367       // Skip non-static function templates when converting to pointer, and
10368       // static when converting to member pointer.
10369       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10370         return false;
10371     }
10372     else if (TargetTypeIsNonStaticMemberFunction)
10373       return false;
10374 
10375     // C++ [over.over]p2:
10376     //   If the name is a function template, template argument deduction is
10377     //   done (14.8.2.2), and if the argument deduction succeeds, the
10378     //   resulting template argument list is used to generate a single
10379     //   function template specialization, which is added to the set of
10380     //   overloaded functions considered.
10381     FunctionDecl *Specialization = nullptr;
10382     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10383     if (Sema::TemplateDeductionResult Result
10384           = S.DeduceTemplateArguments(FunctionTemplate,
10385                                       &OvlExplicitTemplateArgs,
10386                                       TargetFunctionType, Specialization,
10387                                       Info, /*InOverloadResolution=*/true)) {
10388       // Make a note of the failed deduction for diagnostics.
10389       FailedCandidates.addCandidate()
10390           .set(FunctionTemplate->getTemplatedDecl(),
10391                MakeDeductionFailureInfo(Context, Result, Info));
10392       return false;
10393     }
10394 
10395     // Template argument deduction ensures that we have an exact match or
10396     // compatible pointer-to-function arguments that would be adjusted by ICS.
10397     // This function template specicalization works.
10398     assert(S.isSameOrCompatibleFunctionType(
10399               Context.getCanonicalType(Specialization->getType()),
10400               Context.getCanonicalType(TargetFunctionType)));
10401 
10402     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10403       return false;
10404 
10405     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10406     return true;
10407   }
10408 
10409   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10410                                       const DeclAccessPair& CurAccessFunPair) {
10411     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10412       // Skip non-static functions when converting to pointer, and static
10413       // when converting to member pointer.
10414       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10415         return false;
10416     }
10417     else if (TargetTypeIsNonStaticMemberFunction)
10418       return false;
10419 
10420     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10421       if (S.getLangOpts().CUDA)
10422         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10423           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10424             return false;
10425 
10426       // If any candidate has a placeholder return type, trigger its deduction
10427       // now.
10428       if (S.getLangOpts().CPlusPlus14 &&
10429           FunDecl->getReturnType()->isUndeducedType() &&
10430           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10431         HasComplained |= Complain;
10432         return false;
10433       }
10434 
10435       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10436         return false;
10437 
10438       // If we're in C, we need to support types that aren't exactly identical.
10439       if (!S.getLangOpts().CPlusPlus ||
10440           candidateHasExactlyCorrectType(FunDecl)) {
10441         Matches.push_back(std::make_pair(
10442             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10443         FoundNonTemplateFunction = true;
10444         return true;
10445       }
10446     }
10447 
10448     return false;
10449   }
10450 
10451   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10452     bool Ret = false;
10453 
10454     // If the overload expression doesn't have the form of a pointer to
10455     // member, don't try to convert it to a pointer-to-member type.
10456     if (IsInvalidFormOfPointerToMemberFunction())
10457       return false;
10458 
10459     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10460                                E = OvlExpr->decls_end();
10461          I != E; ++I) {
10462       // Look through any using declarations to find the underlying function.
10463       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10464 
10465       // C++ [over.over]p3:
10466       //   Non-member functions and static member functions match
10467       //   targets of type "pointer-to-function" or "reference-to-function."
10468       //   Nonstatic member functions match targets of
10469       //   type "pointer-to-member-function."
10470       // Note that according to DR 247, the containing class does not matter.
10471       if (FunctionTemplateDecl *FunctionTemplate
10472                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10473         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10474           Ret = true;
10475       }
10476       // If we have explicit template arguments supplied, skip non-templates.
10477       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10478                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10479         Ret = true;
10480     }
10481     assert(Ret || Matches.empty());
10482     return Ret;
10483   }
10484 
10485   void EliminateAllExceptMostSpecializedTemplate() {
10486     //   [...] and any given function template specialization F1 is
10487     //   eliminated if the set contains a second function template
10488     //   specialization whose function template is more specialized
10489     //   than the function template of F1 according to the partial
10490     //   ordering rules of 14.5.5.2.
10491 
10492     // The algorithm specified above is quadratic. We instead use a
10493     // two-pass algorithm (similar to the one used to identify the
10494     // best viable function in an overload set) that identifies the
10495     // best function template (if it exists).
10496 
10497     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10498     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10499       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10500 
10501     // TODO: It looks like FailedCandidates does not serve much purpose
10502     // here, since the no_viable diagnostic has index 0.
10503     UnresolvedSetIterator Result = S.getMostSpecialized(
10504         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10505         SourceExpr->getLocStart(), S.PDiag(),
10506         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10507                                                      .second->getDeclName(),
10508         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10509         Complain, TargetFunctionType);
10510 
10511     if (Result != MatchesCopy.end()) {
10512       // Make it the first and only element
10513       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10514       Matches[0].second = cast<FunctionDecl>(*Result);
10515       Matches.resize(1);
10516     } else
10517       HasComplained |= Complain;
10518   }
10519 
10520   void EliminateAllTemplateMatches() {
10521     //   [...] any function template specializations in the set are
10522     //   eliminated if the set also contains a non-template function, [...]
10523     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10524       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10525         ++I;
10526       else {
10527         Matches[I] = Matches[--N];
10528         Matches.resize(N);
10529       }
10530     }
10531   }
10532 
10533   void EliminateSuboptimalCudaMatches() {
10534     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10535   }
10536 
10537 public:
10538   void ComplainNoMatchesFound() const {
10539     assert(Matches.empty());
10540     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10541         << OvlExpr->getName() << TargetFunctionType
10542         << OvlExpr->getSourceRange();
10543     if (FailedCandidates.empty())
10544       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10545                                   /*TakingAddress=*/true);
10546     else {
10547       // We have some deduction failure messages. Use them to diagnose
10548       // the function templates, and diagnose the non-template candidates
10549       // normally.
10550       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10551                                  IEnd = OvlExpr->decls_end();
10552            I != IEnd; ++I)
10553         if (FunctionDecl *Fun =
10554                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10555           if (!functionHasPassObjectSizeParams(Fun))
10556             S.NoteOverloadCandidate(Fun, TargetFunctionType,
10557                                     /*TakingAddress=*/true);
10558       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10559     }
10560   }
10561 
10562   bool IsInvalidFormOfPointerToMemberFunction() const {
10563     return TargetTypeIsNonStaticMemberFunction &&
10564       !OvlExprInfo.HasFormOfMemberPointer;
10565   }
10566 
10567   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10568       // TODO: Should we condition this on whether any functions might
10569       // have matched, or is it more appropriate to do that in callers?
10570       // TODO: a fixit wouldn't hurt.
10571       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10572         << TargetType << OvlExpr->getSourceRange();
10573   }
10574 
10575   bool IsStaticMemberFunctionFromBoundPointer() const {
10576     return StaticMemberFunctionFromBoundPointer;
10577   }
10578 
10579   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10580     S.Diag(OvlExpr->getLocStart(),
10581            diag::err_invalid_form_pointer_member_function)
10582       << OvlExpr->getSourceRange();
10583   }
10584 
10585   void ComplainOfInvalidConversion() const {
10586     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10587       << OvlExpr->getName() << TargetType;
10588   }
10589 
10590   void ComplainMultipleMatchesFound() const {
10591     assert(Matches.size() > 1);
10592     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10593       << OvlExpr->getName()
10594       << OvlExpr->getSourceRange();
10595     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10596                                 /*TakingAddress=*/true);
10597   }
10598 
10599   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10600 
10601   int getNumMatches() const { return Matches.size(); }
10602 
10603   FunctionDecl* getMatchingFunctionDecl() const {
10604     if (Matches.size() != 1) return nullptr;
10605     return Matches[0].second;
10606   }
10607 
10608   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10609     if (Matches.size() != 1) return nullptr;
10610     return &Matches[0].first;
10611   }
10612 };
10613 }
10614 
10615 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10616 /// an overloaded function (C++ [over.over]), where @p From is an
10617 /// expression with overloaded function type and @p ToType is the type
10618 /// we're trying to resolve to. For example:
10619 ///
10620 /// @code
10621 /// int f(double);
10622 /// int f(int);
10623 ///
10624 /// int (*pfd)(double) = f; // selects f(double)
10625 /// @endcode
10626 ///
10627 /// This routine returns the resulting FunctionDecl if it could be
10628 /// resolved, and NULL otherwise. When @p Complain is true, this
10629 /// routine will emit diagnostics if there is an error.
10630 FunctionDecl *
10631 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10632                                          QualType TargetType,
10633                                          bool Complain,
10634                                          DeclAccessPair &FoundResult,
10635                                          bool *pHadMultipleCandidates) {
10636   assert(AddressOfExpr->getType() == Context.OverloadTy);
10637 
10638   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10639                                      Complain);
10640   int NumMatches = Resolver.getNumMatches();
10641   FunctionDecl *Fn = nullptr;
10642   bool ShouldComplain = Complain && !Resolver.hasComplained();
10643   if (NumMatches == 0 && ShouldComplain) {
10644     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10645       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10646     else
10647       Resolver.ComplainNoMatchesFound();
10648   }
10649   else if (NumMatches > 1 && ShouldComplain)
10650     Resolver.ComplainMultipleMatchesFound();
10651   else if (NumMatches == 1) {
10652     Fn = Resolver.getMatchingFunctionDecl();
10653     assert(Fn);
10654     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10655     if (Complain) {
10656       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10657         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10658       else
10659         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10660     }
10661   }
10662 
10663   if (pHadMultipleCandidates)
10664     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10665   return Fn;
10666 }
10667 
10668 /// \brief Given an expression that refers to an overloaded function, try to
10669 /// resolve that function to a single function that can have its address taken.
10670 /// This will modify `Pair` iff it returns non-null.
10671 ///
10672 /// This routine can only realistically succeed if all but one candidates in the
10673 /// overload set for SrcExpr cannot have their addresses taken.
10674 FunctionDecl *
10675 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10676                                                   DeclAccessPair &Pair) {
10677   OverloadExpr::FindResult R = OverloadExpr::find(E);
10678   OverloadExpr *Ovl = R.Expression;
10679   FunctionDecl *Result = nullptr;
10680   DeclAccessPair DAP;
10681   // Don't use the AddressOfResolver because we're specifically looking for
10682   // cases where we have one overload candidate that lacks
10683   // enable_if/pass_object_size/...
10684   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10685     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10686     if (!FD)
10687       return nullptr;
10688 
10689     if (!checkAddressOfFunctionIsAvailable(FD))
10690       continue;
10691 
10692     // We have more than one result; quit.
10693     if (Result)
10694       return nullptr;
10695     DAP = I.getPair();
10696     Result = FD;
10697   }
10698 
10699   if (Result)
10700     Pair = DAP;
10701   return Result;
10702 }
10703 
10704 /// \brief Given an expression that refers to an overloaded function, try to
10705 /// resolve that overloaded function expression down to a single function.
10706 ///
10707 /// This routine can only resolve template-ids that refer to a single function
10708 /// template, where that template-id refers to a single template whose template
10709 /// arguments are either provided by the template-id or have defaults,
10710 /// as described in C++0x [temp.arg.explicit]p3.
10711 ///
10712 /// If no template-ids are found, no diagnostics are emitted and NULL is
10713 /// returned.
10714 FunctionDecl *
10715 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10716                                                   bool Complain,
10717                                                   DeclAccessPair *FoundResult) {
10718   // C++ [over.over]p1:
10719   //   [...] [Note: any redundant set of parentheses surrounding the
10720   //   overloaded function name is ignored (5.1). ]
10721   // C++ [over.over]p1:
10722   //   [...] The overloaded function name can be preceded by the &
10723   //   operator.
10724 
10725   // If we didn't actually find any template-ids, we're done.
10726   if (!ovl->hasExplicitTemplateArgs())
10727     return nullptr;
10728 
10729   TemplateArgumentListInfo ExplicitTemplateArgs;
10730   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10731   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10732 
10733   // Look through all of the overloaded functions, searching for one
10734   // whose type matches exactly.
10735   FunctionDecl *Matched = nullptr;
10736   for (UnresolvedSetIterator I = ovl->decls_begin(),
10737          E = ovl->decls_end(); I != E; ++I) {
10738     // C++0x [temp.arg.explicit]p3:
10739     //   [...] In contexts where deduction is done and fails, or in contexts
10740     //   where deduction is not done, if a template argument list is
10741     //   specified and it, along with any default template arguments,
10742     //   identifies a single function template specialization, then the
10743     //   template-id is an lvalue for the function template specialization.
10744     FunctionTemplateDecl *FunctionTemplate
10745       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10746 
10747     // C++ [over.over]p2:
10748     //   If the name is a function template, template argument deduction is
10749     //   done (14.8.2.2), and if the argument deduction succeeds, the
10750     //   resulting template argument list is used to generate a single
10751     //   function template specialization, which is added to the set of
10752     //   overloaded functions considered.
10753     FunctionDecl *Specialization = nullptr;
10754     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10755     if (TemplateDeductionResult Result
10756           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10757                                     Specialization, Info,
10758                                     /*InOverloadResolution=*/true)) {
10759       // Make a note of the failed deduction for diagnostics.
10760       // TODO: Actually use the failed-deduction info?
10761       FailedCandidates.addCandidate()
10762           .set(FunctionTemplate->getTemplatedDecl(),
10763                MakeDeductionFailureInfo(Context, Result, Info));
10764       continue;
10765     }
10766 
10767     assert(Specialization && "no specialization and no error?");
10768 
10769     // Multiple matches; we can't resolve to a single declaration.
10770     if (Matched) {
10771       if (Complain) {
10772         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10773           << ovl->getName();
10774         NoteAllOverloadCandidates(ovl);
10775       }
10776       return nullptr;
10777     }
10778 
10779     Matched = Specialization;
10780     if (FoundResult) *FoundResult = I.getPair();
10781   }
10782 
10783   if (Matched && getLangOpts().CPlusPlus14 &&
10784       Matched->getReturnType()->isUndeducedType() &&
10785       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10786     return nullptr;
10787 
10788   return Matched;
10789 }
10790 
10791 
10792 
10793 
10794 // Resolve and fix an overloaded expression that can be resolved
10795 // because it identifies a single function template specialization.
10796 //
10797 // Last three arguments should only be supplied if Complain = true
10798 //
10799 // Return true if it was logically possible to so resolve the
10800 // expression, regardless of whether or not it succeeded.  Always
10801 // returns true if 'complain' is set.
10802 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10803                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10804                       bool complain, SourceRange OpRangeForComplaining,
10805                                            QualType DestTypeForComplaining,
10806                                             unsigned DiagIDForComplaining) {
10807   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10808 
10809   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10810 
10811   DeclAccessPair found;
10812   ExprResult SingleFunctionExpression;
10813   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10814                            ovl.Expression, /*complain*/ false, &found)) {
10815     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10816       SrcExpr = ExprError();
10817       return true;
10818     }
10819 
10820     // It is only correct to resolve to an instance method if we're
10821     // resolving a form that's permitted to be a pointer to member.
10822     // Otherwise we'll end up making a bound member expression, which
10823     // is illegal in all the contexts we resolve like this.
10824     if (!ovl.HasFormOfMemberPointer &&
10825         isa<CXXMethodDecl>(fn) &&
10826         cast<CXXMethodDecl>(fn)->isInstance()) {
10827       if (!complain) return false;
10828 
10829       Diag(ovl.Expression->getExprLoc(),
10830            diag::err_bound_member_function)
10831         << 0 << ovl.Expression->getSourceRange();
10832 
10833       // TODO: I believe we only end up here if there's a mix of
10834       // static and non-static candidates (otherwise the expression
10835       // would have 'bound member' type, not 'overload' type).
10836       // Ideally we would note which candidate was chosen and why
10837       // the static candidates were rejected.
10838       SrcExpr = ExprError();
10839       return true;
10840     }
10841 
10842     // Fix the expression to refer to 'fn'.
10843     SingleFunctionExpression =
10844         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10845 
10846     // If desired, do function-to-pointer decay.
10847     if (doFunctionPointerConverion) {
10848       SingleFunctionExpression =
10849         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10850       if (SingleFunctionExpression.isInvalid()) {
10851         SrcExpr = ExprError();
10852         return true;
10853       }
10854     }
10855   }
10856 
10857   if (!SingleFunctionExpression.isUsable()) {
10858     if (complain) {
10859       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10860         << ovl.Expression->getName()
10861         << DestTypeForComplaining
10862         << OpRangeForComplaining
10863         << ovl.Expression->getQualifierLoc().getSourceRange();
10864       NoteAllOverloadCandidates(SrcExpr.get());
10865 
10866       SrcExpr = ExprError();
10867       return true;
10868     }
10869 
10870     return false;
10871   }
10872 
10873   SrcExpr = SingleFunctionExpression;
10874   return true;
10875 }
10876 
10877 /// \brief Add a single candidate to the overload set.
10878 static void AddOverloadedCallCandidate(Sema &S,
10879                                        DeclAccessPair FoundDecl,
10880                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10881                                        ArrayRef<Expr *> Args,
10882                                        OverloadCandidateSet &CandidateSet,
10883                                        bool PartialOverloading,
10884                                        bool KnownValid) {
10885   NamedDecl *Callee = FoundDecl.getDecl();
10886   if (isa<UsingShadowDecl>(Callee))
10887     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10888 
10889   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10890     if (ExplicitTemplateArgs) {
10891       assert(!KnownValid && "Explicit template arguments?");
10892       return;
10893     }
10894     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10895                            /*SuppressUsedConversions=*/false,
10896                            PartialOverloading);
10897     return;
10898   }
10899 
10900   if (FunctionTemplateDecl *FuncTemplate
10901       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10902     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10903                                    ExplicitTemplateArgs, Args, CandidateSet,
10904                                    /*SuppressUsedConversions=*/false,
10905                                    PartialOverloading);
10906     return;
10907   }
10908 
10909   assert(!KnownValid && "unhandled case in overloaded call candidate");
10910 }
10911 
10912 /// \brief Add the overload candidates named by callee and/or found by argument
10913 /// dependent lookup to the given overload set.
10914 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10915                                        ArrayRef<Expr *> Args,
10916                                        OverloadCandidateSet &CandidateSet,
10917                                        bool PartialOverloading) {
10918 
10919 #ifndef NDEBUG
10920   // Verify that ArgumentDependentLookup is consistent with the rules
10921   // in C++0x [basic.lookup.argdep]p3:
10922   //
10923   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10924   //   and let Y be the lookup set produced by argument dependent
10925   //   lookup (defined as follows). If X contains
10926   //
10927   //     -- a declaration of a class member, or
10928   //
10929   //     -- a block-scope function declaration that is not a
10930   //        using-declaration, or
10931   //
10932   //     -- a declaration that is neither a function or a function
10933   //        template
10934   //
10935   //   then Y is empty.
10936 
10937   if (ULE->requiresADL()) {
10938     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10939            E = ULE->decls_end(); I != E; ++I) {
10940       assert(!(*I)->getDeclContext()->isRecord());
10941       assert(isa<UsingShadowDecl>(*I) ||
10942              !(*I)->getDeclContext()->isFunctionOrMethod());
10943       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10944     }
10945   }
10946 #endif
10947 
10948   // It would be nice to avoid this copy.
10949   TemplateArgumentListInfo TABuffer;
10950   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10951   if (ULE->hasExplicitTemplateArgs()) {
10952     ULE->copyTemplateArgumentsInto(TABuffer);
10953     ExplicitTemplateArgs = &TABuffer;
10954   }
10955 
10956   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10957          E = ULE->decls_end(); I != E; ++I)
10958     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10959                                CandidateSet, PartialOverloading,
10960                                /*KnownValid*/ true);
10961 
10962   if (ULE->requiresADL())
10963     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10964                                          Args, ExplicitTemplateArgs,
10965                                          CandidateSet, PartialOverloading);
10966 }
10967 
10968 /// Determine whether a declaration with the specified name could be moved into
10969 /// a different namespace.
10970 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10971   switch (Name.getCXXOverloadedOperator()) {
10972   case OO_New: case OO_Array_New:
10973   case OO_Delete: case OO_Array_Delete:
10974     return false;
10975 
10976   default:
10977     return true;
10978   }
10979 }
10980 
10981 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10982 /// template, where the non-dependent name was declared after the template
10983 /// was defined. This is common in code written for a compilers which do not
10984 /// correctly implement two-stage name lookup.
10985 ///
10986 /// Returns true if a viable candidate was found and a diagnostic was issued.
10987 static bool
10988 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10989                        const CXXScopeSpec &SS, LookupResult &R,
10990                        OverloadCandidateSet::CandidateSetKind CSK,
10991                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10992                        ArrayRef<Expr *> Args,
10993                        bool *DoDiagnoseEmptyLookup = nullptr) {
10994   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10995     return false;
10996 
10997   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10998     if (DC->isTransparentContext())
10999       continue;
11000 
11001     SemaRef.LookupQualifiedName(R, DC);
11002 
11003     if (!R.empty()) {
11004       R.suppressDiagnostics();
11005 
11006       if (isa<CXXRecordDecl>(DC)) {
11007         // Don't diagnose names we find in classes; we get much better
11008         // diagnostics for these from DiagnoseEmptyLookup.
11009         R.clear();
11010         if (DoDiagnoseEmptyLookup)
11011           *DoDiagnoseEmptyLookup = true;
11012         return false;
11013       }
11014 
11015       OverloadCandidateSet Candidates(FnLoc, CSK);
11016       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11017         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11018                                    ExplicitTemplateArgs, Args,
11019                                    Candidates, false, /*KnownValid*/ false);
11020 
11021       OverloadCandidateSet::iterator Best;
11022       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11023         // No viable functions. Don't bother the user with notes for functions
11024         // which don't work and shouldn't be found anyway.
11025         R.clear();
11026         return false;
11027       }
11028 
11029       // Find the namespaces where ADL would have looked, and suggest
11030       // declaring the function there instead.
11031       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11032       Sema::AssociatedClassSet AssociatedClasses;
11033       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11034                                                  AssociatedNamespaces,
11035                                                  AssociatedClasses);
11036       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11037       if (canBeDeclaredInNamespace(R.getLookupName())) {
11038         DeclContext *Std = SemaRef.getStdNamespace();
11039         for (Sema::AssociatedNamespaceSet::iterator
11040                it = AssociatedNamespaces.begin(),
11041                end = AssociatedNamespaces.end(); it != end; ++it) {
11042           // Never suggest declaring a function within namespace 'std'.
11043           if (Std && Std->Encloses(*it))
11044             continue;
11045 
11046           // Never suggest declaring a function within a namespace with a
11047           // reserved name, like __gnu_cxx.
11048           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11049           if (NS &&
11050               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11051             continue;
11052 
11053           SuggestedNamespaces.insert(*it);
11054         }
11055       }
11056 
11057       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11058         << R.getLookupName();
11059       if (SuggestedNamespaces.empty()) {
11060         SemaRef.Diag(Best->Function->getLocation(),
11061                      diag::note_not_found_by_two_phase_lookup)
11062           << R.getLookupName() << 0;
11063       } else if (SuggestedNamespaces.size() == 1) {
11064         SemaRef.Diag(Best->Function->getLocation(),
11065                      diag::note_not_found_by_two_phase_lookup)
11066           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11067       } else {
11068         // FIXME: It would be useful to list the associated namespaces here,
11069         // but the diagnostics infrastructure doesn't provide a way to produce
11070         // a localized representation of a list of items.
11071         SemaRef.Diag(Best->Function->getLocation(),
11072                      diag::note_not_found_by_two_phase_lookup)
11073           << R.getLookupName() << 2;
11074       }
11075 
11076       // Try to recover by calling this function.
11077       return true;
11078     }
11079 
11080     R.clear();
11081   }
11082 
11083   return false;
11084 }
11085 
11086 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11087 /// template, where the non-dependent operator was declared after the template
11088 /// was defined.
11089 ///
11090 /// Returns true if a viable candidate was found and a diagnostic was issued.
11091 static bool
11092 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11093                                SourceLocation OpLoc,
11094                                ArrayRef<Expr *> Args) {
11095   DeclarationName OpName =
11096     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11097   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11098   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11099                                 OverloadCandidateSet::CSK_Operator,
11100                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11101 }
11102 
11103 namespace {
11104 class BuildRecoveryCallExprRAII {
11105   Sema &SemaRef;
11106 public:
11107   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11108     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11109     SemaRef.IsBuildingRecoveryCallExpr = true;
11110   }
11111 
11112   ~BuildRecoveryCallExprRAII() {
11113     SemaRef.IsBuildingRecoveryCallExpr = false;
11114   }
11115 };
11116 
11117 }
11118 
11119 static std::unique_ptr<CorrectionCandidateCallback>
11120 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11121               bool HasTemplateArgs, bool AllowTypoCorrection) {
11122   if (!AllowTypoCorrection)
11123     return llvm::make_unique<NoTypoCorrectionCCC>();
11124   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11125                                                   HasTemplateArgs, ME);
11126 }
11127 
11128 /// Attempts to recover from a call where no functions were found.
11129 ///
11130 /// Returns true if new candidates were found.
11131 static ExprResult
11132 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11133                       UnresolvedLookupExpr *ULE,
11134                       SourceLocation LParenLoc,
11135                       MutableArrayRef<Expr *> Args,
11136                       SourceLocation RParenLoc,
11137                       bool EmptyLookup, bool AllowTypoCorrection) {
11138   // Do not try to recover if it is already building a recovery call.
11139   // This stops infinite loops for template instantiations like
11140   //
11141   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11142   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11143   //
11144   if (SemaRef.IsBuildingRecoveryCallExpr)
11145     return ExprError();
11146   BuildRecoveryCallExprRAII RCE(SemaRef);
11147 
11148   CXXScopeSpec SS;
11149   SS.Adopt(ULE->getQualifierLoc());
11150   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11151 
11152   TemplateArgumentListInfo TABuffer;
11153   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11154   if (ULE->hasExplicitTemplateArgs()) {
11155     ULE->copyTemplateArgumentsInto(TABuffer);
11156     ExplicitTemplateArgs = &TABuffer;
11157   }
11158 
11159   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11160                  Sema::LookupOrdinaryName);
11161   bool DoDiagnoseEmptyLookup = EmptyLookup;
11162   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11163                               OverloadCandidateSet::CSK_Normal,
11164                               ExplicitTemplateArgs, Args,
11165                               &DoDiagnoseEmptyLookup) &&
11166     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11167         S, SS, R,
11168         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11169                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11170         ExplicitTemplateArgs, Args)))
11171     return ExprError();
11172 
11173   assert(!R.empty() && "lookup results empty despite recovery");
11174 
11175   // Build an implicit member call if appropriate.  Just drop the
11176   // casts and such from the call, we don't really care.
11177   ExprResult NewFn = ExprError();
11178   if ((*R.begin())->isCXXClassMember())
11179     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11180                                                     ExplicitTemplateArgs, S);
11181   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11182     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11183                                         ExplicitTemplateArgs);
11184   else
11185     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11186 
11187   if (NewFn.isInvalid())
11188     return ExprError();
11189 
11190   // This shouldn't cause an infinite loop because we're giving it
11191   // an expression with viable lookup results, which should never
11192   // end up here.
11193   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11194                                MultiExprArg(Args.data(), Args.size()),
11195                                RParenLoc);
11196 }
11197 
11198 /// \brief Constructs and populates an OverloadedCandidateSet from
11199 /// the given function.
11200 /// \returns true when an the ExprResult output parameter has been set.
11201 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11202                                   UnresolvedLookupExpr *ULE,
11203                                   MultiExprArg Args,
11204                                   SourceLocation RParenLoc,
11205                                   OverloadCandidateSet *CandidateSet,
11206                                   ExprResult *Result) {
11207 #ifndef NDEBUG
11208   if (ULE->requiresADL()) {
11209     // To do ADL, we must have found an unqualified name.
11210     assert(!ULE->getQualifier() && "qualified name with ADL");
11211 
11212     // We don't perform ADL for implicit declarations of builtins.
11213     // Verify that this was correctly set up.
11214     FunctionDecl *F;
11215     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11216         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11217         F->getBuiltinID() && F->isImplicit())
11218       llvm_unreachable("performing ADL for builtin");
11219 
11220     // We don't perform ADL in C.
11221     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11222   }
11223 #endif
11224 
11225   UnbridgedCastsSet UnbridgedCasts;
11226   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11227     *Result = ExprError();
11228     return true;
11229   }
11230 
11231   // Add the functions denoted by the callee to the set of candidate
11232   // functions, including those from argument-dependent lookup.
11233   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11234 
11235   if (getLangOpts().MSVCCompat &&
11236       CurContext->isDependentContext() && !isSFINAEContext() &&
11237       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11238 
11239     OverloadCandidateSet::iterator Best;
11240     if (CandidateSet->empty() ||
11241         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11242             OR_No_Viable_Function) {
11243       // In Microsoft mode, if we are inside a template class member function then
11244       // create a type dependent CallExpr. The goal is to postpone name lookup
11245       // to instantiation time to be able to search into type dependent base
11246       // classes.
11247       CallExpr *CE = new (Context) CallExpr(
11248           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11249       CE->setTypeDependent(true);
11250       CE->setValueDependent(true);
11251       CE->setInstantiationDependent(true);
11252       *Result = CE;
11253       return true;
11254     }
11255   }
11256 
11257   if (CandidateSet->empty())
11258     return false;
11259 
11260   UnbridgedCasts.restore();
11261   return false;
11262 }
11263 
11264 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11265 /// the completed call expression. If overload resolution fails, emits
11266 /// diagnostics and returns ExprError()
11267 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11268                                            UnresolvedLookupExpr *ULE,
11269                                            SourceLocation LParenLoc,
11270                                            MultiExprArg Args,
11271                                            SourceLocation RParenLoc,
11272                                            Expr *ExecConfig,
11273                                            OverloadCandidateSet *CandidateSet,
11274                                            OverloadCandidateSet::iterator *Best,
11275                                            OverloadingResult OverloadResult,
11276                                            bool AllowTypoCorrection) {
11277   if (CandidateSet->empty())
11278     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11279                                  RParenLoc, /*EmptyLookup=*/true,
11280                                  AllowTypoCorrection);
11281 
11282   switch (OverloadResult) {
11283   case OR_Success: {
11284     FunctionDecl *FDecl = (*Best)->Function;
11285     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11286     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11287       return ExprError();
11288     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11289     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11290                                          ExecConfig);
11291   }
11292 
11293   case OR_No_Viable_Function: {
11294     // Try to recover by looking for viable functions which the user might
11295     // have meant to call.
11296     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11297                                                 Args, RParenLoc,
11298                                                 /*EmptyLookup=*/false,
11299                                                 AllowTypoCorrection);
11300     if (!Recovery.isInvalid())
11301       return Recovery;
11302 
11303     // If the user passes in a function that we can't take the address of, we
11304     // generally end up emitting really bad error messages. Here, we attempt to
11305     // emit better ones.
11306     for (const Expr *Arg : Args) {
11307       if (!Arg->getType()->isFunctionType())
11308         continue;
11309       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11310         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11311         if (FD &&
11312             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11313                                                        Arg->getExprLoc()))
11314           return ExprError();
11315       }
11316     }
11317 
11318     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11319         << ULE->getName() << Fn->getSourceRange();
11320     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11321     break;
11322   }
11323 
11324   case OR_Ambiguous:
11325     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11326       << ULE->getName() << Fn->getSourceRange();
11327     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11328     break;
11329 
11330   case OR_Deleted: {
11331     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11332       << (*Best)->Function->isDeleted()
11333       << ULE->getName()
11334       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11335       << Fn->getSourceRange();
11336     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11337 
11338     // We emitted an error for the unvailable/deleted function call but keep
11339     // the call in the AST.
11340     FunctionDecl *FDecl = (*Best)->Function;
11341     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11342     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11343                                          ExecConfig);
11344   }
11345   }
11346 
11347   // Overload resolution failed.
11348   return ExprError();
11349 }
11350 
11351 static void markUnaddressableCandidatesUnviable(Sema &S,
11352                                                 OverloadCandidateSet &CS) {
11353   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11354     if (I->Viable &&
11355         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11356       I->Viable = false;
11357       I->FailureKind = ovl_fail_addr_not_available;
11358     }
11359   }
11360 }
11361 
11362 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11363 /// (which eventually refers to the declaration Func) and the call
11364 /// arguments Args/NumArgs, attempt to resolve the function call down
11365 /// to a specific function. If overload resolution succeeds, returns
11366 /// the call expression produced by overload resolution.
11367 /// Otherwise, emits diagnostics and returns ExprError.
11368 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11369                                          UnresolvedLookupExpr *ULE,
11370                                          SourceLocation LParenLoc,
11371                                          MultiExprArg Args,
11372                                          SourceLocation RParenLoc,
11373                                          Expr *ExecConfig,
11374                                          bool AllowTypoCorrection,
11375                                          bool CalleesAddressIsTaken) {
11376   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11377                                     OverloadCandidateSet::CSK_Normal);
11378   ExprResult result;
11379 
11380   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11381                              &result))
11382     return result;
11383 
11384   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11385   // functions that aren't addressible are considered unviable.
11386   if (CalleesAddressIsTaken)
11387     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11388 
11389   OverloadCandidateSet::iterator Best;
11390   OverloadingResult OverloadResult =
11391       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11392 
11393   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11394                                   RParenLoc, ExecConfig, &CandidateSet,
11395                                   &Best, OverloadResult,
11396                                   AllowTypoCorrection);
11397 }
11398 
11399 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11400   return Functions.size() > 1 ||
11401     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11402 }
11403 
11404 /// \brief Create a unary operation that may resolve to an overloaded
11405 /// operator.
11406 ///
11407 /// \param OpLoc The location of the operator itself (e.g., '*').
11408 ///
11409 /// \param Opc The UnaryOperatorKind that describes this operator.
11410 ///
11411 /// \param Fns The set of non-member functions that will be
11412 /// considered by overload resolution. The caller needs to build this
11413 /// set based on the context using, e.g.,
11414 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11415 /// set should not contain any member functions; those will be added
11416 /// by CreateOverloadedUnaryOp().
11417 ///
11418 /// \param Input The input argument.
11419 ExprResult
11420 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11421                               const UnresolvedSetImpl &Fns,
11422                               Expr *Input) {
11423   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11424   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11425   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11426   // TODO: provide better source location info.
11427   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11428 
11429   if (checkPlaceholderForOverload(*this, Input))
11430     return ExprError();
11431 
11432   Expr *Args[2] = { Input, nullptr };
11433   unsigned NumArgs = 1;
11434 
11435   // For post-increment and post-decrement, add the implicit '0' as
11436   // the second argument, so that we know this is a post-increment or
11437   // post-decrement.
11438   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11439     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11440     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11441                                      SourceLocation());
11442     NumArgs = 2;
11443   }
11444 
11445   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11446 
11447   if (Input->isTypeDependent()) {
11448     if (Fns.empty())
11449       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11450                                          VK_RValue, OK_Ordinary, OpLoc);
11451 
11452     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11453     UnresolvedLookupExpr *Fn
11454       = UnresolvedLookupExpr::Create(Context, NamingClass,
11455                                      NestedNameSpecifierLoc(), OpNameInfo,
11456                                      /*ADL*/ true, IsOverloaded(Fns),
11457                                      Fns.begin(), Fns.end());
11458     return new (Context)
11459         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11460                             VK_RValue, OpLoc, false);
11461   }
11462 
11463   // Build an empty overload set.
11464   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11465 
11466   // Add the candidates from the given function set.
11467   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11468 
11469   // Add operator candidates that are member functions.
11470   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11471 
11472   // Add candidates from ADL.
11473   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11474                                        /*ExplicitTemplateArgs*/nullptr,
11475                                        CandidateSet);
11476 
11477   // Add builtin operator candidates.
11478   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11479 
11480   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11481 
11482   // Perform overload resolution.
11483   OverloadCandidateSet::iterator Best;
11484   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11485   case OR_Success: {
11486     // We found a built-in operator or an overloaded operator.
11487     FunctionDecl *FnDecl = Best->Function;
11488 
11489     if (FnDecl) {
11490       // We matched an overloaded operator. Build a call to that
11491       // operator.
11492 
11493       // Convert the arguments.
11494       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11495         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11496 
11497         ExprResult InputRes =
11498           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11499                                               Best->FoundDecl, Method);
11500         if (InputRes.isInvalid())
11501           return ExprError();
11502         Input = InputRes.get();
11503       } else {
11504         // Convert the arguments.
11505         ExprResult InputInit
11506           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11507                                                       Context,
11508                                                       FnDecl->getParamDecl(0)),
11509                                       SourceLocation(),
11510                                       Input);
11511         if (InputInit.isInvalid())
11512           return ExprError();
11513         Input = InputInit.get();
11514       }
11515 
11516       // Build the actual expression node.
11517       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11518                                                 HadMultipleCandidates, OpLoc);
11519       if (FnExpr.isInvalid())
11520         return ExprError();
11521 
11522       // Determine the result type.
11523       QualType ResultTy = FnDecl->getReturnType();
11524       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11525       ResultTy = ResultTy.getNonLValueExprType(Context);
11526 
11527       Args[0] = Input;
11528       CallExpr *TheCall =
11529         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11530                                           ResultTy, VK, OpLoc, false);
11531 
11532       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11533         return ExprError();
11534 
11535       return MaybeBindToTemporary(TheCall);
11536     } else {
11537       // We matched a built-in operator. Convert the arguments, then
11538       // break out so that we will build the appropriate built-in
11539       // operator node.
11540       ExprResult InputRes =
11541         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11542                                   Best->Conversions[0], AA_Passing);
11543       if (InputRes.isInvalid())
11544         return ExprError();
11545       Input = InputRes.get();
11546       break;
11547     }
11548   }
11549 
11550   case OR_No_Viable_Function:
11551     // This is an erroneous use of an operator which can be overloaded by
11552     // a non-member function. Check for non-member operators which were
11553     // defined too late to be candidates.
11554     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11555       // FIXME: Recover by calling the found function.
11556       return ExprError();
11557 
11558     // No viable function; fall through to handling this as a
11559     // built-in operator, which will produce an error message for us.
11560     break;
11561 
11562   case OR_Ambiguous:
11563     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11564         << UnaryOperator::getOpcodeStr(Opc)
11565         << Input->getType()
11566         << Input->getSourceRange();
11567     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11568                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11569     return ExprError();
11570 
11571   case OR_Deleted:
11572     Diag(OpLoc, diag::err_ovl_deleted_oper)
11573       << Best->Function->isDeleted()
11574       << UnaryOperator::getOpcodeStr(Opc)
11575       << getDeletedOrUnavailableSuffix(Best->Function)
11576       << Input->getSourceRange();
11577     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11578                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11579     return ExprError();
11580   }
11581 
11582   // Either we found no viable overloaded operator or we matched a
11583   // built-in operator. In either case, fall through to trying to
11584   // build a built-in operation.
11585   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11586 }
11587 
11588 /// \brief Create a binary operation that may resolve to an overloaded
11589 /// operator.
11590 ///
11591 /// \param OpLoc The location of the operator itself (e.g., '+').
11592 ///
11593 /// \param Opc The BinaryOperatorKind that describes this operator.
11594 ///
11595 /// \param Fns The set of non-member functions that will be
11596 /// considered by overload resolution. The caller needs to build this
11597 /// set based on the context using, e.g.,
11598 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11599 /// set should not contain any member functions; those will be added
11600 /// by CreateOverloadedBinOp().
11601 ///
11602 /// \param LHS Left-hand argument.
11603 /// \param RHS Right-hand argument.
11604 ExprResult
11605 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11606                             BinaryOperatorKind Opc,
11607                             const UnresolvedSetImpl &Fns,
11608                             Expr *LHS, Expr *RHS) {
11609   Expr *Args[2] = { LHS, RHS };
11610   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11611 
11612   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11613   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11614 
11615   // If either side is type-dependent, create an appropriate dependent
11616   // expression.
11617   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11618     if (Fns.empty()) {
11619       // If there are no functions to store, just build a dependent
11620       // BinaryOperator or CompoundAssignment.
11621       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11622         return new (Context) BinaryOperator(
11623             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11624             OpLoc, FPFeatures.fp_contract);
11625 
11626       return new (Context) CompoundAssignOperator(
11627           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11628           Context.DependentTy, Context.DependentTy, OpLoc,
11629           FPFeatures.fp_contract);
11630     }
11631 
11632     // FIXME: save results of ADL from here?
11633     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11634     // TODO: provide better source location info in DNLoc component.
11635     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11636     UnresolvedLookupExpr *Fn
11637       = UnresolvedLookupExpr::Create(Context, NamingClass,
11638                                      NestedNameSpecifierLoc(), OpNameInfo,
11639                                      /*ADL*/ true, IsOverloaded(Fns),
11640                                      Fns.begin(), Fns.end());
11641     return new (Context)
11642         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11643                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11644   }
11645 
11646   // Always do placeholder-like conversions on the RHS.
11647   if (checkPlaceholderForOverload(*this, Args[1]))
11648     return ExprError();
11649 
11650   // Do placeholder-like conversion on the LHS; note that we should
11651   // not get here with a PseudoObject LHS.
11652   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11653   if (checkPlaceholderForOverload(*this, Args[0]))
11654     return ExprError();
11655 
11656   // If this is the assignment operator, we only perform overload resolution
11657   // if the left-hand side is a class or enumeration type. This is actually
11658   // a hack. The standard requires that we do overload resolution between the
11659   // various built-in candidates, but as DR507 points out, this can lead to
11660   // problems. So we do it this way, which pretty much follows what GCC does.
11661   // Note that we go the traditional code path for compound assignment forms.
11662   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11663     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11664 
11665   // If this is the .* operator, which is not overloadable, just
11666   // create a built-in binary operator.
11667   if (Opc == BO_PtrMemD)
11668     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11669 
11670   // Build an empty overload set.
11671   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11672 
11673   // Add the candidates from the given function set.
11674   AddFunctionCandidates(Fns, Args, CandidateSet);
11675 
11676   // Add operator candidates that are member functions.
11677   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11678 
11679   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11680   // performed for an assignment operator (nor for operator[] nor operator->,
11681   // which don't get here).
11682   if (Opc != BO_Assign)
11683     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11684                                          /*ExplicitTemplateArgs*/ nullptr,
11685                                          CandidateSet);
11686 
11687   // Add builtin operator candidates.
11688   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11689 
11690   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11691 
11692   // Perform overload resolution.
11693   OverloadCandidateSet::iterator Best;
11694   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11695     case OR_Success: {
11696       // We found a built-in operator or an overloaded operator.
11697       FunctionDecl *FnDecl = Best->Function;
11698 
11699       if (FnDecl) {
11700         // We matched an overloaded operator. Build a call to that
11701         // operator.
11702 
11703         // Convert the arguments.
11704         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11705           // Best->Access is only meaningful for class members.
11706           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11707 
11708           ExprResult Arg1 =
11709             PerformCopyInitialization(
11710               InitializedEntity::InitializeParameter(Context,
11711                                                      FnDecl->getParamDecl(0)),
11712               SourceLocation(), Args[1]);
11713           if (Arg1.isInvalid())
11714             return ExprError();
11715 
11716           ExprResult Arg0 =
11717             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11718                                                 Best->FoundDecl, Method);
11719           if (Arg0.isInvalid())
11720             return ExprError();
11721           Args[0] = Arg0.getAs<Expr>();
11722           Args[1] = RHS = Arg1.getAs<Expr>();
11723         } else {
11724           // Convert the arguments.
11725           ExprResult Arg0 = PerformCopyInitialization(
11726             InitializedEntity::InitializeParameter(Context,
11727                                                    FnDecl->getParamDecl(0)),
11728             SourceLocation(), Args[0]);
11729           if (Arg0.isInvalid())
11730             return ExprError();
11731 
11732           ExprResult Arg1 =
11733             PerformCopyInitialization(
11734               InitializedEntity::InitializeParameter(Context,
11735                                                      FnDecl->getParamDecl(1)),
11736               SourceLocation(), Args[1]);
11737           if (Arg1.isInvalid())
11738             return ExprError();
11739           Args[0] = LHS = Arg0.getAs<Expr>();
11740           Args[1] = RHS = Arg1.getAs<Expr>();
11741         }
11742 
11743         // Build the actual expression node.
11744         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11745                                                   Best->FoundDecl,
11746                                                   HadMultipleCandidates, OpLoc);
11747         if (FnExpr.isInvalid())
11748           return ExprError();
11749 
11750         // Determine the result type.
11751         QualType ResultTy = FnDecl->getReturnType();
11752         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11753         ResultTy = ResultTy.getNonLValueExprType(Context);
11754 
11755         CXXOperatorCallExpr *TheCall =
11756           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11757                                             Args, ResultTy, VK, OpLoc,
11758                                             FPFeatures.fp_contract);
11759 
11760         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11761                                 FnDecl))
11762           return ExprError();
11763 
11764         ArrayRef<const Expr *> ArgsArray(Args, 2);
11765         // Cut off the implicit 'this'.
11766         if (isa<CXXMethodDecl>(FnDecl))
11767           ArgsArray = ArgsArray.slice(1);
11768 
11769         // Check for a self move.
11770         if (Op == OO_Equal)
11771           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11772 
11773         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11774                   TheCall->getSourceRange(), VariadicDoesNotApply);
11775 
11776         return MaybeBindToTemporary(TheCall);
11777       } else {
11778         // We matched a built-in operator. Convert the arguments, then
11779         // break out so that we will build the appropriate built-in
11780         // operator node.
11781         ExprResult ArgsRes0 =
11782           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11783                                     Best->Conversions[0], AA_Passing);
11784         if (ArgsRes0.isInvalid())
11785           return ExprError();
11786         Args[0] = ArgsRes0.get();
11787 
11788         ExprResult ArgsRes1 =
11789           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11790                                     Best->Conversions[1], AA_Passing);
11791         if (ArgsRes1.isInvalid())
11792           return ExprError();
11793         Args[1] = ArgsRes1.get();
11794         break;
11795       }
11796     }
11797 
11798     case OR_No_Viable_Function: {
11799       // C++ [over.match.oper]p9:
11800       //   If the operator is the operator , [...] and there are no
11801       //   viable functions, then the operator is assumed to be the
11802       //   built-in operator and interpreted according to clause 5.
11803       if (Opc == BO_Comma)
11804         break;
11805 
11806       // For class as left operand for assignment or compound assigment
11807       // operator do not fall through to handling in built-in, but report that
11808       // no overloaded assignment operator found
11809       ExprResult Result = ExprError();
11810       if (Args[0]->getType()->isRecordType() &&
11811           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11812         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11813              << BinaryOperator::getOpcodeStr(Opc)
11814              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11815         if (Args[0]->getType()->isIncompleteType()) {
11816           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11817             << Args[0]->getType()
11818             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11819         }
11820       } else {
11821         // This is an erroneous use of an operator which can be overloaded by
11822         // a non-member function. Check for non-member operators which were
11823         // defined too late to be candidates.
11824         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11825           // FIXME: Recover by calling the found function.
11826           return ExprError();
11827 
11828         // No viable function; try to create a built-in operation, which will
11829         // produce an error. Then, show the non-viable candidates.
11830         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11831       }
11832       assert(Result.isInvalid() &&
11833              "C++ binary operator overloading is missing candidates!");
11834       if (Result.isInvalid())
11835         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11836                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11837       return Result;
11838     }
11839 
11840     case OR_Ambiguous:
11841       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11842           << BinaryOperator::getOpcodeStr(Opc)
11843           << Args[0]->getType() << Args[1]->getType()
11844           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11845       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11846                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11847       return ExprError();
11848 
11849     case OR_Deleted:
11850       if (isImplicitlyDeleted(Best->Function)) {
11851         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11852         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11853           << Context.getRecordType(Method->getParent())
11854           << getSpecialMember(Method);
11855 
11856         // The user probably meant to call this special member. Just
11857         // explain why it's deleted.
11858         NoteDeletedFunction(Method);
11859         return ExprError();
11860       } else {
11861         Diag(OpLoc, diag::err_ovl_deleted_oper)
11862           << Best->Function->isDeleted()
11863           << BinaryOperator::getOpcodeStr(Opc)
11864           << getDeletedOrUnavailableSuffix(Best->Function)
11865           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11866       }
11867       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11868                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11869       return ExprError();
11870   }
11871 
11872   // We matched a built-in operator; build it.
11873   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11874 }
11875 
11876 ExprResult
11877 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11878                                          SourceLocation RLoc,
11879                                          Expr *Base, Expr *Idx) {
11880   Expr *Args[2] = { Base, Idx };
11881   DeclarationName OpName =
11882       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11883 
11884   // If either side is type-dependent, create an appropriate dependent
11885   // expression.
11886   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11887 
11888     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11889     // CHECKME: no 'operator' keyword?
11890     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11891     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11892     UnresolvedLookupExpr *Fn
11893       = UnresolvedLookupExpr::Create(Context, NamingClass,
11894                                      NestedNameSpecifierLoc(), OpNameInfo,
11895                                      /*ADL*/ true, /*Overloaded*/ false,
11896                                      UnresolvedSetIterator(),
11897                                      UnresolvedSetIterator());
11898     // Can't add any actual overloads yet
11899 
11900     return new (Context)
11901         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11902                             Context.DependentTy, VK_RValue, RLoc, false);
11903   }
11904 
11905   // Handle placeholders on both operands.
11906   if (checkPlaceholderForOverload(*this, Args[0]))
11907     return ExprError();
11908   if (checkPlaceholderForOverload(*this, Args[1]))
11909     return ExprError();
11910 
11911   // Build an empty overload set.
11912   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11913 
11914   // Subscript can only be overloaded as a member function.
11915 
11916   // Add operator candidates that are member functions.
11917   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11918 
11919   // Add builtin operator candidates.
11920   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11921 
11922   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11923 
11924   // Perform overload resolution.
11925   OverloadCandidateSet::iterator Best;
11926   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11927     case OR_Success: {
11928       // We found a built-in operator or an overloaded operator.
11929       FunctionDecl *FnDecl = Best->Function;
11930 
11931       if (FnDecl) {
11932         // We matched an overloaded operator. Build a call to that
11933         // operator.
11934 
11935         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11936 
11937         // Convert the arguments.
11938         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11939         ExprResult Arg0 =
11940           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11941                                               Best->FoundDecl, Method);
11942         if (Arg0.isInvalid())
11943           return ExprError();
11944         Args[0] = Arg0.get();
11945 
11946         // Convert the arguments.
11947         ExprResult InputInit
11948           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11949                                                       Context,
11950                                                       FnDecl->getParamDecl(0)),
11951                                       SourceLocation(),
11952                                       Args[1]);
11953         if (InputInit.isInvalid())
11954           return ExprError();
11955 
11956         Args[1] = InputInit.getAs<Expr>();
11957 
11958         // Build the actual expression node.
11959         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11960         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11961         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11962                                                   Best->FoundDecl,
11963                                                   HadMultipleCandidates,
11964                                                   OpLocInfo.getLoc(),
11965                                                   OpLocInfo.getInfo());
11966         if (FnExpr.isInvalid())
11967           return ExprError();
11968 
11969         // Determine the result type
11970         QualType ResultTy = FnDecl->getReturnType();
11971         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11972         ResultTy = ResultTy.getNonLValueExprType(Context);
11973 
11974         CXXOperatorCallExpr *TheCall =
11975           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11976                                             FnExpr.get(), Args,
11977                                             ResultTy, VK, RLoc,
11978                                             false);
11979 
11980         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11981           return ExprError();
11982 
11983         return MaybeBindToTemporary(TheCall);
11984       } else {
11985         // We matched a built-in operator. Convert the arguments, then
11986         // break out so that we will build the appropriate built-in
11987         // operator node.
11988         ExprResult ArgsRes0 =
11989           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11990                                     Best->Conversions[0], AA_Passing);
11991         if (ArgsRes0.isInvalid())
11992           return ExprError();
11993         Args[0] = ArgsRes0.get();
11994 
11995         ExprResult ArgsRes1 =
11996           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11997                                     Best->Conversions[1], AA_Passing);
11998         if (ArgsRes1.isInvalid())
11999           return ExprError();
12000         Args[1] = ArgsRes1.get();
12001 
12002         break;
12003       }
12004     }
12005 
12006     case OR_No_Viable_Function: {
12007       if (CandidateSet.empty())
12008         Diag(LLoc, diag::err_ovl_no_oper)
12009           << Args[0]->getType() << /*subscript*/ 0
12010           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12011       else
12012         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12013           << Args[0]->getType()
12014           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12015       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12016                                   "[]", LLoc);
12017       return ExprError();
12018     }
12019 
12020     case OR_Ambiguous:
12021       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12022           << "[]"
12023           << Args[0]->getType() << Args[1]->getType()
12024           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12025       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12026                                   "[]", LLoc);
12027       return ExprError();
12028 
12029     case OR_Deleted:
12030       Diag(LLoc, diag::err_ovl_deleted_oper)
12031         << Best->Function->isDeleted() << "[]"
12032         << getDeletedOrUnavailableSuffix(Best->Function)
12033         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12034       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12035                                   "[]", LLoc);
12036       return ExprError();
12037     }
12038 
12039   // We matched a built-in operator; build it.
12040   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12041 }
12042 
12043 /// BuildCallToMemberFunction - Build a call to a member
12044 /// function. MemExpr is the expression that refers to the member
12045 /// function (and includes the object parameter), Args/NumArgs are the
12046 /// arguments to the function call (not including the object
12047 /// parameter). The caller needs to validate that the member
12048 /// expression refers to a non-static member function or an overloaded
12049 /// member function.
12050 ExprResult
12051 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12052                                 SourceLocation LParenLoc,
12053                                 MultiExprArg Args,
12054                                 SourceLocation RParenLoc) {
12055   assert(MemExprE->getType() == Context.BoundMemberTy ||
12056          MemExprE->getType() == Context.OverloadTy);
12057 
12058   // Dig out the member expression. This holds both the object
12059   // argument and the member function we're referring to.
12060   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12061 
12062   // Determine whether this is a call to a pointer-to-member function.
12063   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12064     assert(op->getType() == Context.BoundMemberTy);
12065     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12066 
12067     QualType fnType =
12068       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12069 
12070     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12071     QualType resultType = proto->getCallResultType(Context);
12072     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12073 
12074     // Check that the object type isn't more qualified than the
12075     // member function we're calling.
12076     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12077 
12078     QualType objectType = op->getLHS()->getType();
12079     if (op->getOpcode() == BO_PtrMemI)
12080       objectType = objectType->castAs<PointerType>()->getPointeeType();
12081     Qualifiers objectQuals = objectType.getQualifiers();
12082 
12083     Qualifiers difference = objectQuals - funcQuals;
12084     difference.removeObjCGCAttr();
12085     difference.removeAddressSpace();
12086     if (difference) {
12087       std::string qualsString = difference.getAsString();
12088       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12089         << fnType.getUnqualifiedType()
12090         << qualsString
12091         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12092     }
12093 
12094     CXXMemberCallExpr *call
12095       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12096                                         resultType, valueKind, RParenLoc);
12097 
12098     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12099                             call, nullptr))
12100       return ExprError();
12101 
12102     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12103       return ExprError();
12104 
12105     if (CheckOtherCall(call, proto))
12106       return ExprError();
12107 
12108     return MaybeBindToTemporary(call);
12109   }
12110 
12111   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12112     return new (Context)
12113         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12114 
12115   UnbridgedCastsSet UnbridgedCasts;
12116   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12117     return ExprError();
12118 
12119   MemberExpr *MemExpr;
12120   CXXMethodDecl *Method = nullptr;
12121   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12122   NestedNameSpecifier *Qualifier = nullptr;
12123   if (isa<MemberExpr>(NakedMemExpr)) {
12124     MemExpr = cast<MemberExpr>(NakedMemExpr);
12125     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12126     FoundDecl = MemExpr->getFoundDecl();
12127     Qualifier = MemExpr->getQualifier();
12128     UnbridgedCasts.restore();
12129   } else {
12130     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12131     Qualifier = UnresExpr->getQualifier();
12132 
12133     QualType ObjectType = UnresExpr->getBaseType();
12134     Expr::Classification ObjectClassification
12135       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12136                             : UnresExpr->getBase()->Classify(Context);
12137 
12138     // Add overload candidates
12139     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12140                                       OverloadCandidateSet::CSK_Normal);
12141 
12142     // FIXME: avoid copy.
12143     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12144     if (UnresExpr->hasExplicitTemplateArgs()) {
12145       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12146       TemplateArgs = &TemplateArgsBuffer;
12147     }
12148 
12149     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12150            E = UnresExpr->decls_end(); I != E; ++I) {
12151 
12152       NamedDecl *Func = *I;
12153       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12154       if (isa<UsingShadowDecl>(Func))
12155         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12156 
12157 
12158       // Microsoft supports direct constructor calls.
12159       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12160         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12161                              Args, CandidateSet);
12162       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12163         // If explicit template arguments were provided, we can't call a
12164         // non-template member function.
12165         if (TemplateArgs)
12166           continue;
12167 
12168         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12169                            ObjectClassification, Args, CandidateSet,
12170                            /*SuppressUserConversions=*/false);
12171       } else {
12172         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12173                                    I.getPair(), ActingDC, TemplateArgs,
12174                                    ObjectType,  ObjectClassification,
12175                                    Args, CandidateSet,
12176                                    /*SuppressUsedConversions=*/false);
12177       }
12178     }
12179 
12180     DeclarationName DeclName = UnresExpr->getMemberName();
12181 
12182     UnbridgedCasts.restore();
12183 
12184     OverloadCandidateSet::iterator Best;
12185     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12186                                             Best)) {
12187     case OR_Success:
12188       Method = cast<CXXMethodDecl>(Best->Function);
12189       FoundDecl = Best->FoundDecl;
12190       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12191       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12192         return ExprError();
12193       // If FoundDecl is different from Method (such as if one is a template
12194       // and the other a specialization), make sure DiagnoseUseOfDecl is
12195       // called on both.
12196       // FIXME: This would be more comprehensively addressed by modifying
12197       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12198       // being used.
12199       if (Method != FoundDecl.getDecl() &&
12200                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12201         return ExprError();
12202       break;
12203 
12204     case OR_No_Viable_Function:
12205       Diag(UnresExpr->getMemberLoc(),
12206            diag::err_ovl_no_viable_member_function_in_call)
12207         << DeclName << MemExprE->getSourceRange();
12208       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12209       // FIXME: Leaking incoming expressions!
12210       return ExprError();
12211 
12212     case OR_Ambiguous:
12213       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12214         << DeclName << MemExprE->getSourceRange();
12215       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12216       // FIXME: Leaking incoming expressions!
12217       return ExprError();
12218 
12219     case OR_Deleted:
12220       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12221         << Best->Function->isDeleted()
12222         << DeclName
12223         << getDeletedOrUnavailableSuffix(Best->Function)
12224         << MemExprE->getSourceRange();
12225       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12226       // FIXME: Leaking incoming expressions!
12227       return ExprError();
12228     }
12229 
12230     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12231 
12232     // If overload resolution picked a static member, build a
12233     // non-member call based on that function.
12234     if (Method->isStatic()) {
12235       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12236                                    RParenLoc);
12237     }
12238 
12239     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12240   }
12241 
12242   QualType ResultType = Method->getReturnType();
12243   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12244   ResultType = ResultType.getNonLValueExprType(Context);
12245 
12246   assert(Method && "Member call to something that isn't a method?");
12247   CXXMemberCallExpr *TheCall =
12248     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12249                                     ResultType, VK, RParenLoc);
12250 
12251   // (CUDA B.1): Check for invalid calls between targets.
12252   if (getLangOpts().CUDA) {
12253     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12254       if (CheckCUDATarget(Caller, Method)) {
12255         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12256             << IdentifyCUDATarget(Method) << Method->getIdentifier()
12257             << IdentifyCUDATarget(Caller);
12258         return ExprError();
12259       }
12260     }
12261   }
12262 
12263   // Check for a valid return type.
12264   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12265                           TheCall, Method))
12266     return ExprError();
12267 
12268   // Convert the object argument (for a non-static member function call).
12269   // We only need to do this if there was actually an overload; otherwise
12270   // it was done at lookup.
12271   if (!Method->isStatic()) {
12272     ExprResult ObjectArg =
12273       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12274                                           FoundDecl, Method);
12275     if (ObjectArg.isInvalid())
12276       return ExprError();
12277     MemExpr->setBase(ObjectArg.get());
12278   }
12279 
12280   // Convert the rest of the arguments
12281   const FunctionProtoType *Proto =
12282     Method->getType()->getAs<FunctionProtoType>();
12283   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12284                               RParenLoc))
12285     return ExprError();
12286 
12287   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12288 
12289   if (CheckFunctionCall(Method, TheCall, Proto))
12290     return ExprError();
12291 
12292   // In the case the method to call was not selected by the overloading
12293   // resolution process, we still need to handle the enable_if attribute. Do
12294   // that here, so it will not hide previous -- and more relevant -- errors
12295   if (isa<MemberExpr>(NakedMemExpr)) {
12296     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12297       Diag(MemExprE->getLocStart(),
12298            diag::err_ovl_no_viable_member_function_in_call)
12299           << Method << Method->getSourceRange();
12300       Diag(Method->getLocation(),
12301            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12302           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12303       return ExprError();
12304     }
12305   }
12306 
12307   if ((isa<CXXConstructorDecl>(CurContext) ||
12308        isa<CXXDestructorDecl>(CurContext)) &&
12309       TheCall->getMethodDecl()->isPure()) {
12310     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12311 
12312     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12313         MemExpr->performsVirtualDispatch(getLangOpts())) {
12314       Diag(MemExpr->getLocStart(),
12315            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12316         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12317         << MD->getParent()->getDeclName();
12318 
12319       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12320       if (getLangOpts().AppleKext)
12321         Diag(MemExpr->getLocStart(),
12322              diag::note_pure_qualified_call_kext)
12323              << MD->getParent()->getDeclName()
12324              << MD->getDeclName();
12325     }
12326   }
12327 
12328   if (CXXDestructorDecl *DD =
12329           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12330     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12331     bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() ||
12332                             getLangOpts().AppleKext;
12333     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12334                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12335                          MemExpr->getMemberLoc());
12336   }
12337 
12338   return MaybeBindToTemporary(TheCall);
12339 }
12340 
12341 /// BuildCallToObjectOfClassType - Build a call to an object of class
12342 /// type (C++ [over.call.object]), which can end up invoking an
12343 /// overloaded function call operator (@c operator()) or performing a
12344 /// user-defined conversion on the object argument.
12345 ExprResult
12346 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12347                                    SourceLocation LParenLoc,
12348                                    MultiExprArg Args,
12349                                    SourceLocation RParenLoc) {
12350   if (checkPlaceholderForOverload(*this, Obj))
12351     return ExprError();
12352   ExprResult Object = Obj;
12353 
12354   UnbridgedCastsSet UnbridgedCasts;
12355   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12356     return ExprError();
12357 
12358   assert(Object.get()->getType()->isRecordType() &&
12359          "Requires object type argument");
12360   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12361 
12362   // C++ [over.call.object]p1:
12363   //  If the primary-expression E in the function call syntax
12364   //  evaluates to a class object of type "cv T", then the set of
12365   //  candidate functions includes at least the function call
12366   //  operators of T. The function call operators of T are obtained by
12367   //  ordinary lookup of the name operator() in the context of
12368   //  (E).operator().
12369   OverloadCandidateSet CandidateSet(LParenLoc,
12370                                     OverloadCandidateSet::CSK_Operator);
12371   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12372 
12373   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12374                           diag::err_incomplete_object_call, Object.get()))
12375     return true;
12376 
12377   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12378   LookupQualifiedName(R, Record->getDecl());
12379   R.suppressDiagnostics();
12380 
12381   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12382        Oper != OperEnd; ++Oper) {
12383     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12384                        Object.get()->Classify(Context),
12385                        Args, CandidateSet,
12386                        /*SuppressUserConversions=*/ false);
12387   }
12388 
12389   // C++ [over.call.object]p2:
12390   //   In addition, for each (non-explicit in C++0x) conversion function
12391   //   declared in T of the form
12392   //
12393   //        operator conversion-type-id () cv-qualifier;
12394   //
12395   //   where cv-qualifier is the same cv-qualification as, or a
12396   //   greater cv-qualification than, cv, and where conversion-type-id
12397   //   denotes the type "pointer to function of (P1,...,Pn) returning
12398   //   R", or the type "reference to pointer to function of
12399   //   (P1,...,Pn) returning R", or the type "reference to function
12400   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12401   //   is also considered as a candidate function. Similarly,
12402   //   surrogate call functions are added to the set of candidate
12403   //   functions for each conversion function declared in an
12404   //   accessible base class provided the function is not hidden
12405   //   within T by another intervening declaration.
12406   const auto &Conversions =
12407       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12408   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12409     NamedDecl *D = *I;
12410     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12411     if (isa<UsingShadowDecl>(D))
12412       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12413 
12414     // Skip over templated conversion functions; they aren't
12415     // surrogates.
12416     if (isa<FunctionTemplateDecl>(D))
12417       continue;
12418 
12419     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12420     if (!Conv->isExplicit()) {
12421       // Strip the reference type (if any) and then the pointer type (if
12422       // any) to get down to what might be a function type.
12423       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12424       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12425         ConvType = ConvPtrType->getPointeeType();
12426 
12427       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12428       {
12429         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12430                               Object.get(), Args, CandidateSet);
12431       }
12432     }
12433   }
12434 
12435   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12436 
12437   // Perform overload resolution.
12438   OverloadCandidateSet::iterator Best;
12439   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12440                              Best)) {
12441   case OR_Success:
12442     // Overload resolution succeeded; we'll build the appropriate call
12443     // below.
12444     break;
12445 
12446   case OR_No_Viable_Function:
12447     if (CandidateSet.empty())
12448       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12449         << Object.get()->getType() << /*call*/ 1
12450         << Object.get()->getSourceRange();
12451     else
12452       Diag(Object.get()->getLocStart(),
12453            diag::err_ovl_no_viable_object_call)
12454         << Object.get()->getType() << Object.get()->getSourceRange();
12455     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12456     break;
12457 
12458   case OR_Ambiguous:
12459     Diag(Object.get()->getLocStart(),
12460          diag::err_ovl_ambiguous_object_call)
12461       << Object.get()->getType() << Object.get()->getSourceRange();
12462     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12463     break;
12464 
12465   case OR_Deleted:
12466     Diag(Object.get()->getLocStart(),
12467          diag::err_ovl_deleted_object_call)
12468       << Best->Function->isDeleted()
12469       << Object.get()->getType()
12470       << getDeletedOrUnavailableSuffix(Best->Function)
12471       << Object.get()->getSourceRange();
12472     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12473     break;
12474   }
12475 
12476   if (Best == CandidateSet.end())
12477     return true;
12478 
12479   UnbridgedCasts.restore();
12480 
12481   if (Best->Function == nullptr) {
12482     // Since there is no function declaration, this is one of the
12483     // surrogate candidates. Dig out the conversion function.
12484     CXXConversionDecl *Conv
12485       = cast<CXXConversionDecl>(
12486                          Best->Conversions[0].UserDefined.ConversionFunction);
12487 
12488     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12489                               Best->FoundDecl);
12490     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12491       return ExprError();
12492     assert(Conv == Best->FoundDecl.getDecl() &&
12493              "Found Decl & conversion-to-functionptr should be same, right?!");
12494     // We selected one of the surrogate functions that converts the
12495     // object parameter to a function pointer. Perform the conversion
12496     // on the object argument, then let ActOnCallExpr finish the job.
12497 
12498     // Create an implicit member expr to refer to the conversion operator.
12499     // and then call it.
12500     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12501                                              Conv, HadMultipleCandidates);
12502     if (Call.isInvalid())
12503       return ExprError();
12504     // Record usage of conversion in an implicit cast.
12505     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12506                                     CK_UserDefinedConversion, Call.get(),
12507                                     nullptr, VK_RValue);
12508 
12509     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12510   }
12511 
12512   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12513 
12514   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12515   // that calls this method, using Object for the implicit object
12516   // parameter and passing along the remaining arguments.
12517   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12518 
12519   // An error diagnostic has already been printed when parsing the declaration.
12520   if (Method->isInvalidDecl())
12521     return ExprError();
12522 
12523   const FunctionProtoType *Proto =
12524     Method->getType()->getAs<FunctionProtoType>();
12525 
12526   unsigned NumParams = Proto->getNumParams();
12527 
12528   DeclarationNameInfo OpLocInfo(
12529                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12530   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12531   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12532                                            HadMultipleCandidates,
12533                                            OpLocInfo.getLoc(),
12534                                            OpLocInfo.getInfo());
12535   if (NewFn.isInvalid())
12536     return true;
12537 
12538   // Build the full argument list for the method call (the implicit object
12539   // parameter is placed at the beginning of the list).
12540   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12541   MethodArgs[0] = Object.get();
12542   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12543 
12544   // Once we've built TheCall, all of the expressions are properly
12545   // owned.
12546   QualType ResultTy = Method->getReturnType();
12547   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12548   ResultTy = ResultTy.getNonLValueExprType(Context);
12549 
12550   CXXOperatorCallExpr *TheCall = new (Context)
12551       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12552                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12553                           ResultTy, VK, RParenLoc, false);
12554   MethodArgs.reset();
12555 
12556   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12557     return true;
12558 
12559   // We may have default arguments. If so, we need to allocate more
12560   // slots in the call for them.
12561   if (Args.size() < NumParams)
12562     TheCall->setNumArgs(Context, NumParams + 1);
12563 
12564   bool IsError = false;
12565 
12566   // Initialize the implicit object parameter.
12567   ExprResult ObjRes =
12568     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12569                                         Best->FoundDecl, Method);
12570   if (ObjRes.isInvalid())
12571     IsError = true;
12572   else
12573     Object = ObjRes;
12574   TheCall->setArg(0, Object.get());
12575 
12576   // Check the argument types.
12577   for (unsigned i = 0; i != NumParams; i++) {
12578     Expr *Arg;
12579     if (i < Args.size()) {
12580       Arg = Args[i];
12581 
12582       // Pass the argument.
12583 
12584       ExprResult InputInit
12585         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12586                                                     Context,
12587                                                     Method->getParamDecl(i)),
12588                                     SourceLocation(), Arg);
12589 
12590       IsError |= InputInit.isInvalid();
12591       Arg = InputInit.getAs<Expr>();
12592     } else {
12593       ExprResult DefArg
12594         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12595       if (DefArg.isInvalid()) {
12596         IsError = true;
12597         break;
12598       }
12599 
12600       Arg = DefArg.getAs<Expr>();
12601     }
12602 
12603     TheCall->setArg(i + 1, Arg);
12604   }
12605 
12606   // If this is a variadic call, handle args passed through "...".
12607   if (Proto->isVariadic()) {
12608     // Promote the arguments (C99 6.5.2.2p7).
12609     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12610       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12611                                                         nullptr);
12612       IsError |= Arg.isInvalid();
12613       TheCall->setArg(i + 1, Arg.get());
12614     }
12615   }
12616 
12617   if (IsError) return true;
12618 
12619   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12620 
12621   if (CheckFunctionCall(Method, TheCall, Proto))
12622     return true;
12623 
12624   return MaybeBindToTemporary(TheCall);
12625 }
12626 
12627 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12628 ///  (if one exists), where @c Base is an expression of class type and
12629 /// @c Member is the name of the member we're trying to find.
12630 ExprResult
12631 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12632                                bool *NoArrowOperatorFound) {
12633   assert(Base->getType()->isRecordType() &&
12634          "left-hand side must have class type");
12635 
12636   if (checkPlaceholderForOverload(*this, Base))
12637     return ExprError();
12638 
12639   SourceLocation Loc = Base->getExprLoc();
12640 
12641   // C++ [over.ref]p1:
12642   //
12643   //   [...] An expression x->m is interpreted as (x.operator->())->m
12644   //   for a class object x of type T if T::operator->() exists and if
12645   //   the operator is selected as the best match function by the
12646   //   overload resolution mechanism (13.3).
12647   DeclarationName OpName =
12648     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12649   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12650   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12651 
12652   if (RequireCompleteType(Loc, Base->getType(),
12653                           diag::err_typecheck_incomplete_tag, Base))
12654     return ExprError();
12655 
12656   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12657   LookupQualifiedName(R, BaseRecord->getDecl());
12658   R.suppressDiagnostics();
12659 
12660   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12661        Oper != OperEnd; ++Oper) {
12662     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12663                        None, CandidateSet, /*SuppressUserConversions=*/false);
12664   }
12665 
12666   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12667 
12668   // Perform overload resolution.
12669   OverloadCandidateSet::iterator Best;
12670   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12671   case OR_Success:
12672     // Overload resolution succeeded; we'll build the call below.
12673     break;
12674 
12675   case OR_No_Viable_Function:
12676     if (CandidateSet.empty()) {
12677       QualType BaseType = Base->getType();
12678       if (NoArrowOperatorFound) {
12679         // Report this specific error to the caller instead of emitting a
12680         // diagnostic, as requested.
12681         *NoArrowOperatorFound = true;
12682         return ExprError();
12683       }
12684       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12685         << BaseType << Base->getSourceRange();
12686       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12687         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12688           << FixItHint::CreateReplacement(OpLoc, ".");
12689       }
12690     } else
12691       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12692         << "operator->" << Base->getSourceRange();
12693     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12694     return ExprError();
12695 
12696   case OR_Ambiguous:
12697     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12698       << "->" << Base->getType() << Base->getSourceRange();
12699     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12700     return ExprError();
12701 
12702   case OR_Deleted:
12703     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12704       << Best->Function->isDeleted()
12705       << "->"
12706       << getDeletedOrUnavailableSuffix(Best->Function)
12707       << Base->getSourceRange();
12708     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12709     return ExprError();
12710   }
12711 
12712   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12713 
12714   // Convert the object parameter.
12715   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12716   ExprResult BaseResult =
12717     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12718                                         Best->FoundDecl, Method);
12719   if (BaseResult.isInvalid())
12720     return ExprError();
12721   Base = BaseResult.get();
12722 
12723   // Build the operator call.
12724   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12725                                             HadMultipleCandidates, OpLoc);
12726   if (FnExpr.isInvalid())
12727     return ExprError();
12728 
12729   QualType ResultTy = Method->getReturnType();
12730   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12731   ResultTy = ResultTy.getNonLValueExprType(Context);
12732   CXXOperatorCallExpr *TheCall =
12733     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12734                                       Base, ResultTy, VK, OpLoc, false);
12735 
12736   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12737           return ExprError();
12738 
12739   return MaybeBindToTemporary(TheCall);
12740 }
12741 
12742 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12743 /// a literal operator described by the provided lookup results.
12744 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12745                                           DeclarationNameInfo &SuffixInfo,
12746                                           ArrayRef<Expr*> Args,
12747                                           SourceLocation LitEndLoc,
12748                                        TemplateArgumentListInfo *TemplateArgs) {
12749   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12750 
12751   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12752                                     OverloadCandidateSet::CSK_Normal);
12753   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12754                         /*SuppressUserConversions=*/true);
12755 
12756   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12757 
12758   // Perform overload resolution. This will usually be trivial, but might need
12759   // to perform substitutions for a literal operator template.
12760   OverloadCandidateSet::iterator Best;
12761   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12762   case OR_Success:
12763   case OR_Deleted:
12764     break;
12765 
12766   case OR_No_Viable_Function:
12767     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12768       << R.getLookupName();
12769     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12770     return ExprError();
12771 
12772   case OR_Ambiguous:
12773     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12774     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12775     return ExprError();
12776   }
12777 
12778   FunctionDecl *FD = Best->Function;
12779   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12780                                         HadMultipleCandidates,
12781                                         SuffixInfo.getLoc(),
12782                                         SuffixInfo.getInfo());
12783   if (Fn.isInvalid())
12784     return true;
12785 
12786   // Check the argument types. This should almost always be a no-op, except
12787   // that array-to-pointer decay is applied to string literals.
12788   Expr *ConvArgs[2];
12789   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12790     ExprResult InputInit = PerformCopyInitialization(
12791       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12792       SourceLocation(), Args[ArgIdx]);
12793     if (InputInit.isInvalid())
12794       return true;
12795     ConvArgs[ArgIdx] = InputInit.get();
12796   }
12797 
12798   QualType ResultTy = FD->getReturnType();
12799   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12800   ResultTy = ResultTy.getNonLValueExprType(Context);
12801 
12802   UserDefinedLiteral *UDL =
12803     new (Context) UserDefinedLiteral(Context, Fn.get(),
12804                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12805                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12806 
12807   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12808     return ExprError();
12809 
12810   if (CheckFunctionCall(FD, UDL, nullptr))
12811     return ExprError();
12812 
12813   return MaybeBindToTemporary(UDL);
12814 }
12815 
12816 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12817 /// given LookupResult is non-empty, it is assumed to describe a member which
12818 /// will be invoked. Otherwise, the function will be found via argument
12819 /// dependent lookup.
12820 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12821 /// otherwise CallExpr is set to ExprError() and some non-success value
12822 /// is returned.
12823 Sema::ForRangeStatus
12824 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12825                                 SourceLocation RangeLoc,
12826                                 const DeclarationNameInfo &NameInfo,
12827                                 LookupResult &MemberLookup,
12828                                 OverloadCandidateSet *CandidateSet,
12829                                 Expr *Range, ExprResult *CallExpr) {
12830   Scope *S = nullptr;
12831 
12832   CandidateSet->clear();
12833   if (!MemberLookup.empty()) {
12834     ExprResult MemberRef =
12835         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12836                                  /*IsPtr=*/false, CXXScopeSpec(),
12837                                  /*TemplateKWLoc=*/SourceLocation(),
12838                                  /*FirstQualifierInScope=*/nullptr,
12839                                  MemberLookup,
12840                                  /*TemplateArgs=*/nullptr, S);
12841     if (MemberRef.isInvalid()) {
12842       *CallExpr = ExprError();
12843       return FRS_DiagnosticIssued;
12844     }
12845     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12846     if (CallExpr->isInvalid()) {
12847       *CallExpr = ExprError();
12848       return FRS_DiagnosticIssued;
12849     }
12850   } else {
12851     UnresolvedSet<0> FoundNames;
12852     UnresolvedLookupExpr *Fn =
12853       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12854                                    NestedNameSpecifierLoc(), NameInfo,
12855                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12856                                    FoundNames.begin(), FoundNames.end());
12857 
12858     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12859                                                     CandidateSet, CallExpr);
12860     if (CandidateSet->empty() || CandidateSetError) {
12861       *CallExpr = ExprError();
12862       return FRS_NoViableFunction;
12863     }
12864     OverloadCandidateSet::iterator Best;
12865     OverloadingResult OverloadResult =
12866         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12867 
12868     if (OverloadResult == OR_No_Viable_Function) {
12869       *CallExpr = ExprError();
12870       return FRS_NoViableFunction;
12871     }
12872     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12873                                          Loc, nullptr, CandidateSet, &Best,
12874                                          OverloadResult,
12875                                          /*AllowTypoCorrection=*/false);
12876     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12877       *CallExpr = ExprError();
12878       return FRS_DiagnosticIssued;
12879     }
12880   }
12881   return FRS_Success;
12882 }
12883 
12884 
12885 /// FixOverloadedFunctionReference - E is an expression that refers to
12886 /// a C++ overloaded function (possibly with some parentheses and
12887 /// perhaps a '&' around it). We have resolved the overloaded function
12888 /// to the function declaration Fn, so patch up the expression E to
12889 /// refer (possibly indirectly) to Fn. Returns the new expr.
12890 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12891                                            FunctionDecl *Fn) {
12892   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12893     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12894                                                    Found, Fn);
12895     if (SubExpr == PE->getSubExpr())
12896       return PE;
12897 
12898     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12899   }
12900 
12901   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12902     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12903                                                    Found, Fn);
12904     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12905                                SubExpr->getType()) &&
12906            "Implicit cast type cannot be determined from overload");
12907     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12908     if (SubExpr == ICE->getSubExpr())
12909       return ICE;
12910 
12911     return ImplicitCastExpr::Create(Context, ICE->getType(),
12912                                     ICE->getCastKind(),
12913                                     SubExpr, nullptr,
12914                                     ICE->getValueKind());
12915   }
12916 
12917   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12918     assert(UnOp->getOpcode() == UO_AddrOf &&
12919            "Can only take the address of an overloaded function");
12920     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12921       if (Method->isStatic()) {
12922         // Do nothing: static member functions aren't any different
12923         // from non-member functions.
12924       } else {
12925         // Fix the subexpression, which really has to be an
12926         // UnresolvedLookupExpr holding an overloaded member function
12927         // or template.
12928         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12929                                                        Found, Fn);
12930         if (SubExpr == UnOp->getSubExpr())
12931           return UnOp;
12932 
12933         assert(isa<DeclRefExpr>(SubExpr)
12934                && "fixed to something other than a decl ref");
12935         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12936                && "fixed to a member ref with no nested name qualifier");
12937 
12938         // We have taken the address of a pointer to member
12939         // function. Perform the computation here so that we get the
12940         // appropriate pointer to member type.
12941         QualType ClassType
12942           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12943         QualType MemPtrType
12944           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12945 
12946         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12947                                            VK_RValue, OK_Ordinary,
12948                                            UnOp->getOperatorLoc());
12949       }
12950     }
12951     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12952                                                    Found, Fn);
12953     if (SubExpr == UnOp->getSubExpr())
12954       return UnOp;
12955 
12956     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12957                                      Context.getPointerType(SubExpr->getType()),
12958                                        VK_RValue, OK_Ordinary,
12959                                        UnOp->getOperatorLoc());
12960   }
12961 
12962   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12963     // FIXME: avoid copy.
12964     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12965     if (ULE->hasExplicitTemplateArgs()) {
12966       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12967       TemplateArgs = &TemplateArgsBuffer;
12968     }
12969 
12970     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12971                                            ULE->getQualifierLoc(),
12972                                            ULE->getTemplateKeywordLoc(),
12973                                            Fn,
12974                                            /*enclosing*/ false, // FIXME?
12975                                            ULE->getNameLoc(),
12976                                            Fn->getType(),
12977                                            VK_LValue,
12978                                            Found.getDecl(),
12979                                            TemplateArgs);
12980     MarkDeclRefReferenced(DRE);
12981     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12982     return DRE;
12983   }
12984 
12985   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12986     // FIXME: avoid copy.
12987     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12988     if (MemExpr->hasExplicitTemplateArgs()) {
12989       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12990       TemplateArgs = &TemplateArgsBuffer;
12991     }
12992 
12993     Expr *Base;
12994 
12995     // If we're filling in a static method where we used to have an
12996     // implicit member access, rewrite to a simple decl ref.
12997     if (MemExpr->isImplicitAccess()) {
12998       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12999         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13000                                                MemExpr->getQualifierLoc(),
13001                                                MemExpr->getTemplateKeywordLoc(),
13002                                                Fn,
13003                                                /*enclosing*/ false,
13004                                                MemExpr->getMemberLoc(),
13005                                                Fn->getType(),
13006                                                VK_LValue,
13007                                                Found.getDecl(),
13008                                                TemplateArgs);
13009         MarkDeclRefReferenced(DRE);
13010         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13011         return DRE;
13012       } else {
13013         SourceLocation Loc = MemExpr->getMemberLoc();
13014         if (MemExpr->getQualifier())
13015           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13016         CheckCXXThisCapture(Loc);
13017         Base = new (Context) CXXThisExpr(Loc,
13018                                          MemExpr->getBaseType(),
13019                                          /*isImplicit=*/true);
13020       }
13021     } else
13022       Base = MemExpr->getBase();
13023 
13024     ExprValueKind valueKind;
13025     QualType type;
13026     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13027       valueKind = VK_LValue;
13028       type = Fn->getType();
13029     } else {
13030       valueKind = VK_RValue;
13031       type = Context.BoundMemberTy;
13032     }
13033 
13034     MemberExpr *ME = MemberExpr::Create(
13035         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13036         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13037         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13038         OK_Ordinary);
13039     ME->setHadMultipleCandidates(true);
13040     MarkMemberReferenced(ME);
13041     return ME;
13042   }
13043 
13044   llvm_unreachable("Invalid reference to overloaded function");
13045 }
13046 
13047 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13048                                                 DeclAccessPair Found,
13049                                                 FunctionDecl *Fn) {
13050   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13051 }
13052