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 /// A convenience routine for creating a decayed reference to a function.
42 static ExprResult
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44                       bool HadMultipleCandidates,
45                       SourceLocation Loc = SourceLocation(),
46                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
48     return ExprError();
49   // If FoundDecl is different from Fn (such as if one is a template
50   // and the other a specialization), make sure DiagnoseUseOfDecl is
51   // called on both.
52   // FIXME: This would be more comprehensively addressed by modifying
53   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54   // being used.
55   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
56     return ExprError();
57   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58                                                  VK_LValue, Loc, LocInfo);
59   if (HadMultipleCandidates)
60     DRE->setHadMultipleCandidates(true);
61 
62   S.MarkDeclRefReferenced(DRE);
63 
64   ExprResult E = DRE;
65   E = S.DefaultFunctionArrayConversion(E.get());
66   if (E.isInvalid())
67     return ExprError();
68   return E;
69 }
70 
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72                                  bool InOverloadResolution,
73                                  StandardConversionSequence &SCS,
74                                  bool CStyle,
75                                  bool AllowObjCWritebackConversion);
76 
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78                                                  QualType &ToType,
79                                                  bool InOverloadResolution,
80                                                  StandardConversionSequence &SCS,
81                                                  bool CStyle);
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84                         UserDefinedConversionSequence& User,
85                         OverloadCandidateSet& Conversions,
86                         bool AllowExplicit,
87                         bool AllowObjCConversionOnExplicit);
88 
89 
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92                                    const StandardConversionSequence& SCS1,
93                                    const StandardConversionSequence& SCS2);
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97                                 const StandardConversionSequence& SCS1,
98                                 const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 /// GetConversionRank - Retrieve the implicit conversion rank
106 /// corresponding to the given implicit conversion kind.
107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
108   static const ImplicitConversionRank
109     Rank[(int)ICK_Num_Conversion_Kinds] = {
110     ICR_Exact_Match,
111     ICR_Exact_Match,
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Promotion,
117     ICR_Promotion,
118     ICR_Promotion,
119     ICR_Conversion,
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_Complex_Real_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Writeback_Conversion
134   };
135   return Rank[(int)Kind];
136 }
137 
138 /// GetImplicitConversionName - Return the name of this kind of
139 /// implicit conversion.
140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
141   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
142     "No conversion",
143     "Lvalue-to-rvalue",
144     "Array-to-pointer",
145     "Function-to-pointer",
146     "Noreturn adjustment",
147     "Qualification",
148     "Integral promotion",
149     "Floating point promotion",
150     "Complex promotion",
151     "Integral conversion",
152     "Floating conversion",
153     "Complex conversion",
154     "Floating-integral conversion",
155     "Pointer conversion",
156     "Pointer-to-member conversion",
157     "Boolean conversion",
158     "Compatible-types conversion",
159     "Derived-to-base conversion",
160     "Vector conversion",
161     "Vector splat",
162     "Complex-real conversion",
163     "Block Pointer conversion",
164     "Transparent Union Conversion",
165     "Writeback conversion"
166   };
167   return Name[Kind];
168 }
169 
170 /// StandardConversionSequence - Set the standard conversion
171 /// sequence to the identity conversion.
172 void StandardConversionSequence::setAsIdentityConversion() {
173   First = ICK_Identity;
174   Second = ICK_Identity;
175   Third = ICK_Identity;
176   DeprecatedStringLiteralToCharPtr = false;
177   QualificationIncludesObjCLifetime = false;
178   ReferenceBinding = false;
179   DirectBinding = false;
180   IsLvalueReference = true;
181   BindsToFunctionLvalue = false;
182   BindsToRvalue = false;
183   BindsImplicitObjectArgumentWithoutRefQualifier = false;
184   ObjCLifetimeConversionBinding = false;
185   CopyConstructor = nullptr;
186 }
187 
188 /// getRank - Retrieve the rank of this standard conversion sequence
189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190 /// implicit conversions.
191 ImplicitConversionRank StandardConversionSequence::getRank() const {
192   ImplicitConversionRank Rank = ICR_Exact_Match;
193   if  (GetConversionRank(First) > Rank)
194     Rank = GetConversionRank(First);
195   if  (GetConversionRank(Second) > Rank)
196     Rank = GetConversionRank(Second);
197   if  (GetConversionRank(Third) > Rank)
198     Rank = GetConversionRank(Third);
199   return Rank;
200 }
201 
202 /// isPointerConversionToBool - Determines whether this conversion is
203 /// a conversion of a pointer or pointer-to-member to bool. This is
204 /// used as part of the ranking of standard conversion sequences
205 /// (C++ 13.3.3.2p4).
206 bool StandardConversionSequence::isPointerConversionToBool() const {
207   // Note that FromType has not necessarily been transformed by the
208   // array-to-pointer or function-to-pointer implicit conversions, so
209   // check for their presence as well as checking whether FromType is
210   // a pointer.
211   if (getToType(1)->isBooleanType() &&
212       (getFromType()->isPointerType() ||
213        getFromType()->isObjCObjectPointerType() ||
214        getFromType()->isBlockPointerType() ||
215        getFromType()->isNullPtrType() ||
216        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217     return true;
218 
219   return false;
220 }
221 
222 /// isPointerConversionToVoidPointer - Determines whether this
223 /// conversion is a conversion of a pointer to a void pointer. This is
224 /// used as part of the ranking of standard conversion sequences (C++
225 /// 13.3.3.2p4).
226 bool
227 StandardConversionSequence::
228 isPointerConversionToVoidPointer(ASTContext& Context) const {
229   QualType FromType = getFromType();
230   QualType ToType = getToType(1);
231 
232   // Note that FromType has not necessarily been transformed by the
233   // array-to-pointer implicit conversion, so check for its presence
234   // and redo the conversion to get a pointer.
235   if (First == ICK_Array_To_Pointer)
236     FromType = Context.getArrayDecayedType(FromType);
237 
238   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
239     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
240       return ToPtrType->getPointeeType()->isVoidType();
241 
242   return false;
243 }
244 
245 /// Skip any implicit casts which could be either part of a narrowing conversion
246 /// or after one in an implicit conversion.
247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249     switch (ICE->getCastKind()) {
250     case CK_NoOp:
251     case CK_IntegralCast:
252     case CK_IntegralToBoolean:
253     case CK_IntegralToFloating:
254     case CK_FloatingToIntegral:
255     case CK_FloatingToBoolean:
256     case CK_FloatingCast:
257       Converted = ICE->getSubExpr();
258       continue;
259 
260     default:
261       return Converted;
262     }
263   }
264 
265   return Converted;
266 }
267 
268 /// Check if this standard conversion sequence represents a narrowing
269 /// conversion, according to C++11 [dcl.init.list]p7.
270 ///
271 /// \param Ctx  The AST context.
272 /// \param Converted  The result of applying this standard conversion sequence.
273 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
274 ///        value of the expression prior to the narrowing conversion.
275 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
276 ///        type of the expression prior to the narrowing conversion.
277 NarrowingKind
278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279                                              const Expr *Converted,
280                                              APValue &ConstantValue,
281                                              QualType &ConstantType) const {
282   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
283 
284   // C++11 [dcl.init.list]p7:
285   //   A narrowing conversion is an implicit conversion ...
286   QualType FromType = getToType(0);
287   QualType ToType = getToType(1);
288   switch (Second) {
289   // 'bool' is an integral type; dispatch to the right place to handle it.
290   case ICK_Boolean_Conversion:
291     if (FromType->isRealFloatingType())
292       goto FloatingIntegralConversion;
293     if (FromType->isIntegralOrUnscopedEnumerationType())
294       goto IntegralConversion;
295     // Boolean conversions can be from pointers and pointers to members
296     // [conv.bool], and those aren't considered narrowing conversions.
297     return NK_Not_Narrowing;
298 
299   // -- from a floating-point type to an integer type, or
300   //
301   // -- from an integer type or unscoped enumeration type to a floating-point
302   //    type, except where the source is a constant expression and the actual
303   //    value after conversion will fit into the target type and will produce
304   //    the original value when converted back to the original type, or
305   case ICK_Floating_Integral:
306   FloatingIntegralConversion:
307     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308       return NK_Type_Narrowing;
309     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310       llvm::APSInt IntConstantValue;
311       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
312       if (Initializer &&
313           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314         // Convert the integer to the floating type.
315         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317                                 llvm::APFloat::rmNearestTiesToEven);
318         // And back.
319         llvm::APSInt ConvertedValue = IntConstantValue;
320         bool ignored;
321         Result.convertToInteger(ConvertedValue,
322                                 llvm::APFloat::rmTowardZero, &ignored);
323         // If the resulting value is different, this was a narrowing conversion.
324         if (IntConstantValue != ConvertedValue) {
325           ConstantValue = APValue(IntConstantValue);
326           ConstantType = Initializer->getType();
327           return NK_Constant_Narrowing;
328         }
329       } else {
330         // Variables are always narrowings.
331         return NK_Variable_Narrowing;
332       }
333     }
334     return NK_Not_Narrowing;
335 
336   // -- from long double to double or float, or from double to float, except
337   //    where the source is a constant expression and the actual value after
338   //    conversion is within the range of values that can be represented (even
339   //    if it cannot be represented exactly), or
340   case ICK_Floating_Conversion:
341     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343       // FromType is larger than ToType.
344       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346         // Constant!
347         assert(ConstantValue.isFloat());
348         llvm::APFloat FloatVal = ConstantValue.getFloat();
349         // Convert the source value into the target type.
350         bool ignored;
351         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352           Ctx.getFloatTypeSemantics(ToType),
353           llvm::APFloat::rmNearestTiesToEven, &ignored);
354         // If there was no overflow, the source value is within the range of
355         // values that can be represented.
356         if (ConvertStatus & llvm::APFloat::opOverflow) {
357           ConstantType = Initializer->getType();
358           return NK_Constant_Narrowing;
359         }
360       } else {
361         return NK_Variable_Narrowing;
362       }
363     }
364     return NK_Not_Narrowing;
365 
366   // -- from an integer type or unscoped enumeration type to an integer type
367   //    that cannot represent all the values of the original type, except where
368   //    the source is a constant expression and the actual value after
369   //    conversion will fit into the target type and will produce the original
370   //    value when converted back to the original type.
371   case ICK_Integral_Conversion:
372   IntegralConversion: {
373     assert(FromType->isIntegralOrUnscopedEnumerationType());
374     assert(ToType->isIntegralOrUnscopedEnumerationType());
375     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376     const unsigned FromWidth = Ctx.getIntWidth(FromType);
377     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378     const unsigned ToWidth = Ctx.getIntWidth(ToType);
379 
380     if (FromWidth > ToWidth ||
381         (FromWidth == ToWidth && FromSigned != ToSigned) ||
382         (FromSigned && !ToSigned)) {
383       // Not all values of FromType can be represented in ToType.
384       llvm::APSInt InitializerValue;
385       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
386       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387         // Such conversions on variables are always narrowing.
388         return NK_Variable_Narrowing;
389       }
390       bool Narrowing = false;
391       if (FromWidth < ToWidth) {
392         // Negative -> unsigned is narrowing. Otherwise, more bits is never
393         // narrowing.
394         if (InitializerValue.isSigned() && InitializerValue.isNegative())
395           Narrowing = true;
396       } else {
397         // Add a bit to the InitializerValue so we don't have to worry about
398         // signed vs. unsigned comparisons.
399         InitializerValue = InitializerValue.extend(
400           InitializerValue.getBitWidth() + 1);
401         // Convert the initializer to and from the target width and signed-ness.
402         llvm::APSInt ConvertedValue = InitializerValue;
403         ConvertedValue = ConvertedValue.trunc(ToWidth);
404         ConvertedValue.setIsSigned(ToSigned);
405         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406         ConvertedValue.setIsSigned(InitializerValue.isSigned());
407         // If the result is different, this was a narrowing conversion.
408         if (ConvertedValue != InitializerValue)
409           Narrowing = true;
410       }
411       if (Narrowing) {
412         ConstantType = Initializer->getType();
413         ConstantValue = APValue(InitializerValue);
414         return NK_Constant_Narrowing;
415       }
416     }
417     return NK_Not_Narrowing;
418   }
419 
420   default:
421     // Other kinds of conversions are not narrowings.
422     return NK_Not_Narrowing;
423   }
424 }
425 
426 /// dump - Print this standard conversion sequence to standard
427 /// error. Useful for debugging overloading issues.
428 void StandardConversionSequence::dump() const {
429   raw_ostream &OS = llvm::errs();
430   bool PrintedSomething = false;
431   if (First != ICK_Identity) {
432     OS << GetImplicitConversionName(First);
433     PrintedSomething = true;
434   }
435 
436   if (Second != ICK_Identity) {
437     if (PrintedSomething) {
438       OS << " -> ";
439     }
440     OS << GetImplicitConversionName(Second);
441 
442     if (CopyConstructor) {
443       OS << " (by copy constructor)";
444     } else if (DirectBinding) {
445       OS << " (direct reference binding)";
446     } else if (ReferenceBinding) {
447       OS << " (reference binding)";
448     }
449     PrintedSomething = true;
450   }
451 
452   if (Third != ICK_Identity) {
453     if (PrintedSomething) {
454       OS << " -> ";
455     }
456     OS << GetImplicitConversionName(Third);
457     PrintedSomething = true;
458   }
459 
460   if (!PrintedSomething) {
461     OS << "No conversions required";
462   }
463 }
464 
465 /// dump - Print this user-defined conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 void UserDefinedConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   if (Before.First || Before.Second || Before.Third) {
470     Before.dump();
471     OS << " -> ";
472   }
473   if (ConversionFunction)
474     OS << '\'' << *ConversionFunction << '\'';
475   else
476     OS << "aggregate initialization";
477   if (After.First || After.Second || After.Third) {
478     OS << " -> ";
479     After.dump();
480   }
481 }
482 
483 /// dump - Print this implicit conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 void ImplicitConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   if (isStdInitializerListElement())
488     OS << "Worst std::initializer_list element conversion: ";
489   switch (ConversionKind) {
490   case StandardConversion:
491     OS << "Standard conversion: ";
492     Standard.dump();
493     break;
494   case UserDefinedConversion:
495     OS << "User-defined conversion: ";
496     UserDefined.dump();
497     break;
498   case EllipsisConversion:
499     OS << "Ellipsis conversion";
500     break;
501   case AmbiguousConversion:
502     OS << "Ambiguous conversion";
503     break;
504   case BadConversion:
505     OS << "Bad conversion";
506     break;
507   }
508 
509   OS << "\n";
510 }
511 
512 void AmbiguousConversionSequence::construct() {
513   new (&conversions()) ConversionSet();
514 }
515 
516 void AmbiguousConversionSequence::destruct() {
517   conversions().~ConversionSet();
518 }
519 
520 void
521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522   FromTypePtr = O.FromTypePtr;
523   ToTypePtr = O.ToTypePtr;
524   new (&conversions()) ConversionSet(O.conversions());
525 }
526 
527 namespace {
528   // Structure used by DeductionFailureInfo to store
529   // template argument information.
530   struct DFIArguments {
531     TemplateArgument FirstArg;
532     TemplateArgument SecondArg;
533   };
534   // Structure used by DeductionFailureInfo to store
535   // template parameter and template argument information.
536   struct DFIParamWithArguments : DFIArguments {
537     TemplateParameter Param;
538   };
539 }
540 
541 /// \brief Convert from Sema's representation of template deduction information
542 /// to the form used in overload-candidate information.
543 DeductionFailureInfo
544 clang::MakeDeductionFailureInfo(ASTContext &Context,
545                                 Sema::TemplateDeductionResult TDK,
546                                 TemplateDeductionInfo &Info) {
547   DeductionFailureInfo Result;
548   Result.Result = static_cast<unsigned>(TDK);
549   Result.HasDiagnostic = false;
550   Result.Data = nullptr;
551   switch (TDK) {
552   case Sema::TDK_Success:
553   case Sema::TDK_Invalid:
554   case Sema::TDK_InstantiationDepth:
555   case Sema::TDK_TooManyArguments:
556   case Sema::TDK_TooFewArguments:
557     break;
558 
559   case Sema::TDK_Incomplete:
560   case Sema::TDK_InvalidExplicitArguments:
561     Result.Data = Info.Param.getOpaqueValue();
562     break;
563 
564   case Sema::TDK_NonDeducedMismatch: {
565     // FIXME: Should allocate from normal heap so that we can free this later.
566     DFIArguments *Saved = new (Context) DFIArguments;
567     Saved->FirstArg = Info.FirstArg;
568     Saved->SecondArg = Info.SecondArg;
569     Result.Data = Saved;
570     break;
571   }
572 
573   case Sema::TDK_Inconsistent:
574   case Sema::TDK_Underqualified: {
575     // FIXME: Should allocate from normal heap so that we can free this later.
576     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
577     Saved->Param = Info.Param;
578     Saved->FirstArg = Info.FirstArg;
579     Saved->SecondArg = Info.SecondArg;
580     Result.Data = Saved;
581     break;
582   }
583 
584   case Sema::TDK_SubstitutionFailure:
585     Result.Data = Info.take();
586     if (Info.hasSFINAEDiagnostic()) {
587       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588           SourceLocation(), PartialDiagnostic::NullDiagnostic());
589       Info.takeSFINAEDiagnostic(*Diag);
590       Result.HasDiagnostic = true;
591     }
592     break;
593 
594   case Sema::TDK_FailedOverloadResolution:
595     Result.Data = Info.Expression;
596     break;
597 
598   case Sema::TDK_MiscellaneousDeductionFailure:
599     break;
600   }
601 
602   return Result;
603 }
604 
605 void DeductionFailureInfo::Destroy() {
606   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607   case Sema::TDK_Success:
608   case Sema::TDK_Invalid:
609   case Sema::TDK_InstantiationDepth:
610   case Sema::TDK_Incomplete:
611   case Sema::TDK_TooManyArguments:
612   case Sema::TDK_TooFewArguments:
613   case Sema::TDK_InvalidExplicitArguments:
614   case Sema::TDK_FailedOverloadResolution:
615     break;
616 
617   case Sema::TDK_Inconsistent:
618   case Sema::TDK_Underqualified:
619   case Sema::TDK_NonDeducedMismatch:
620     // FIXME: Destroy the data?
621     Data = nullptr;
622     break;
623 
624   case Sema::TDK_SubstitutionFailure:
625     // FIXME: Destroy the template argument list?
626     Data = nullptr;
627     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628       Diag->~PartialDiagnosticAt();
629       HasDiagnostic = false;
630     }
631     break;
632 
633   // Unhandled
634   case Sema::TDK_MiscellaneousDeductionFailure:
635     break;
636   }
637 }
638 
639 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
640   if (HasDiagnostic)
641     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
642   return nullptr;
643 }
644 
645 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
646   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647   case Sema::TDK_Success:
648   case Sema::TDK_Invalid:
649   case Sema::TDK_InstantiationDepth:
650   case Sema::TDK_TooManyArguments:
651   case Sema::TDK_TooFewArguments:
652   case Sema::TDK_SubstitutionFailure:
653   case Sema::TDK_NonDeducedMismatch:
654   case Sema::TDK_FailedOverloadResolution:
655     return TemplateParameter();
656 
657   case Sema::TDK_Incomplete:
658   case Sema::TDK_InvalidExplicitArguments:
659     return TemplateParameter::getFromOpaqueValue(Data);
660 
661   case Sema::TDK_Inconsistent:
662   case Sema::TDK_Underqualified:
663     return static_cast<DFIParamWithArguments*>(Data)->Param;
664 
665   // Unhandled
666   case Sema::TDK_MiscellaneousDeductionFailure:
667     break;
668   }
669 
670   return TemplateParameter();
671 }
672 
673 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
674   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
675   case Sema::TDK_Success:
676   case Sema::TDK_Invalid:
677   case Sema::TDK_InstantiationDepth:
678   case Sema::TDK_TooManyArguments:
679   case Sema::TDK_TooFewArguments:
680   case Sema::TDK_Incomplete:
681   case Sema::TDK_InvalidExplicitArguments:
682   case Sema::TDK_Inconsistent:
683   case Sema::TDK_Underqualified:
684   case Sema::TDK_NonDeducedMismatch:
685   case Sema::TDK_FailedOverloadResolution:
686     return nullptr;
687 
688   case Sema::TDK_SubstitutionFailure:
689     return static_cast<TemplateArgumentList*>(Data);
690 
691   // Unhandled
692   case Sema::TDK_MiscellaneousDeductionFailure:
693     break;
694   }
695 
696   return nullptr;
697 }
698 
699 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
700   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701   case Sema::TDK_Success:
702   case Sema::TDK_Invalid:
703   case Sema::TDK_InstantiationDepth:
704   case Sema::TDK_Incomplete:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_InvalidExplicitArguments:
708   case Sema::TDK_SubstitutionFailure:
709   case Sema::TDK_FailedOverloadResolution:
710     return nullptr;
711 
712   case Sema::TDK_Inconsistent:
713   case Sema::TDK_Underqualified:
714   case Sema::TDK_NonDeducedMismatch:
715     return &static_cast<DFIArguments*>(Data)->FirstArg;
716 
717   // Unhandled
718   case Sema::TDK_MiscellaneousDeductionFailure:
719     break;
720   }
721 
722   return nullptr;
723 }
724 
725 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
726   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727   case Sema::TDK_Success:
728   case Sema::TDK_Invalid:
729   case Sema::TDK_InstantiationDepth:
730   case Sema::TDK_Incomplete:
731   case Sema::TDK_TooManyArguments:
732   case Sema::TDK_TooFewArguments:
733   case Sema::TDK_InvalidExplicitArguments:
734   case Sema::TDK_SubstitutionFailure:
735   case Sema::TDK_FailedOverloadResolution:
736     return nullptr;
737 
738   case Sema::TDK_Inconsistent:
739   case Sema::TDK_Underqualified:
740   case Sema::TDK_NonDeducedMismatch:
741     return &static_cast<DFIArguments*>(Data)->SecondArg;
742 
743   // Unhandled
744   case Sema::TDK_MiscellaneousDeductionFailure:
745     break;
746   }
747 
748   return nullptr;
749 }
750 
751 Expr *DeductionFailureInfo::getExpr() {
752   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753         Sema::TDK_FailedOverloadResolution)
754     return static_cast<Expr*>(Data);
755 
756   return nullptr;
757 }
758 
759 void OverloadCandidateSet::destroyCandidates() {
760   for (iterator i = begin(), e = end(); i != e; ++i) {
761     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762       i->Conversions[ii].~ImplicitConversionSequence();
763     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764       i->DeductionFailure.Destroy();
765   }
766 }
767 
768 void OverloadCandidateSet::clear() {
769   destroyCandidates();
770   NumInlineSequences = 0;
771   Candidates.clear();
772   Functions.clear();
773 }
774 
775 namespace {
776   class UnbridgedCastsSet {
777     struct Entry {
778       Expr **Addr;
779       Expr *Saved;
780     };
781     SmallVector<Entry, 2> Entries;
782 
783   public:
784     void save(Sema &S, Expr *&E) {
785       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786       Entry entry = { &E, E };
787       Entries.push_back(entry);
788       E = S.stripARCUnbridgedCast(E);
789     }
790 
791     void restore() {
792       for (SmallVectorImpl<Entry>::iterator
793              i = Entries.begin(), e = Entries.end(); i != e; ++i)
794         *i->Addr = i->Saved;
795     }
796   };
797 }
798 
799 /// checkPlaceholderForOverload - Do any interesting placeholder-like
800 /// preprocessing on the given expression.
801 ///
802 /// \param unbridgedCasts a collection to which to add unbridged casts;
803 ///   without this, they will be immediately diagnosed as errors
804 ///
805 /// Return true on unrecoverable error.
806 static bool
807 checkPlaceholderForOverload(Sema &S, Expr *&E,
808                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
809   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
810     // We can't handle overloaded expressions here because overload
811     // resolution might reasonably tweak them.
812     if (placeholder->getKind() == BuiltinType::Overload) return false;
813 
814     // If the context potentially accepts unbridged ARC casts, strip
815     // the unbridged cast and add it to the collection for later restoration.
816     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
817         unbridgedCasts) {
818       unbridgedCasts->save(S, E);
819       return false;
820     }
821 
822     // Go ahead and check everything else.
823     ExprResult result = S.CheckPlaceholderExpr(E);
824     if (result.isInvalid())
825       return true;
826 
827     E = result.get();
828     return false;
829   }
830 
831   // Nothing to do.
832   return false;
833 }
834 
835 /// checkArgPlaceholdersForOverload - Check a set of call operands for
836 /// placeholders.
837 static bool checkArgPlaceholdersForOverload(Sema &S,
838                                             MultiExprArg Args,
839                                             UnbridgedCastsSet &unbridged) {
840   for (unsigned i = 0, e = Args.size(); i != e; ++i)
841     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
842       return true;
843 
844   return false;
845 }
846 
847 // IsOverload - Determine whether the given New declaration is an
848 // overload of the declarations in Old. This routine returns false if
849 // New and Old cannot be overloaded, e.g., if New has the same
850 // signature as some function in Old (C++ 1.3.10) or if the Old
851 // declarations aren't functions (or function templates) at all. When
852 // it does return false, MatchedDecl will point to the decl that New
853 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
854 // top of the underlying declaration.
855 //
856 // Example: Given the following input:
857 //
858 //   void f(int, float); // #1
859 //   void f(int, int); // #2
860 //   int f(int, int); // #3
861 //
862 // When we process #1, there is no previous declaration of "f",
863 // so IsOverload will not be used.
864 //
865 // When we process #2, Old contains only the FunctionDecl for #1.  By
866 // comparing the parameter types, we see that #1 and #2 are overloaded
867 // (since they have different signatures), so this routine returns
868 // false; MatchedDecl is unchanged.
869 //
870 // When we process #3, Old is an overload set containing #1 and #2. We
871 // compare the signatures of #3 to #1 (they're overloaded, so we do
872 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873 // identical (return types of functions are not part of the
874 // signature), IsOverload returns false and MatchedDecl will be set to
875 // point to the FunctionDecl for #2.
876 //
877 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878 // into a class by a using declaration.  The rules for whether to hide
879 // shadow declarations ignore some properties which otherwise figure
880 // into a function template's signature.
881 Sema::OverloadKind
882 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883                     NamedDecl *&Match, bool NewIsUsingDecl) {
884   for (LookupResult::iterator I = Old.begin(), E = Old.end();
885          I != E; ++I) {
886     NamedDecl *OldD = *I;
887 
888     bool OldIsUsingDecl = false;
889     if (isa<UsingShadowDecl>(OldD)) {
890       OldIsUsingDecl = true;
891 
892       // We can always introduce two using declarations into the same
893       // context, even if they have identical signatures.
894       if (NewIsUsingDecl) continue;
895 
896       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
897     }
898 
899     // A using-declaration does not conflict with another declaration
900     // if one of them is hidden.
901     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
902       continue;
903 
904     // If either declaration was introduced by a using declaration,
905     // we'll need to use slightly different rules for matching.
906     // Essentially, these rules are the normal rules, except that
907     // function templates hide function templates with different
908     // return types or template parameter lists.
909     bool UseMemberUsingDeclRules =
910       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
911       !New->getFriendObjectKind();
912 
913     if (FunctionDecl *OldF = OldD->getAsFunction()) {
914       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
915         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
916           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
917           continue;
918         }
919 
920         if (!isa<FunctionTemplateDecl>(OldD) &&
921             !shouldLinkPossiblyHiddenDecl(*I, New))
922           continue;
923 
924         Match = *I;
925         return Ovl_Match;
926       }
927     } else if (isa<UsingDecl>(OldD)) {
928       // We can overload with these, which can show up when doing
929       // redeclaration checks for UsingDecls.
930       assert(Old.getLookupKind() == LookupUsingDeclName);
931     } else if (isa<TagDecl>(OldD)) {
932       // We can always overload with tags by hiding them.
933     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
934       // Optimistically assume that an unresolved using decl will
935       // overload; if it doesn't, we'll have to diagnose during
936       // template instantiation.
937     } else {
938       // (C++ 13p1):
939       //   Only function declarations can be overloaded; object and type
940       //   declarations cannot be overloaded.
941       Match = *I;
942       return Ovl_NonFunction;
943     }
944   }
945 
946   return Ovl_Overload;
947 }
948 
949 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
950                       bool UseUsingDeclRules) {
951   // C++ [basic.start.main]p2: This function shall not be overloaded.
952   if (New->isMain())
953     return false;
954 
955   // MSVCRT user defined entry points cannot be overloaded.
956   if (New->isMSVCRTEntryPoint())
957     return false;
958 
959   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
960   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
961 
962   // C++ [temp.fct]p2:
963   //   A function template can be overloaded with other function templates
964   //   and with normal (non-template) functions.
965   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
966     return true;
967 
968   // Is the function New an overload of the function Old?
969   QualType OldQType = Context.getCanonicalType(Old->getType());
970   QualType NewQType = Context.getCanonicalType(New->getType());
971 
972   // Compare the signatures (C++ 1.3.10) of the two functions to
973   // determine whether they are overloads. If we find any mismatch
974   // in the signature, they are overloads.
975 
976   // If either of these functions is a K&R-style function (no
977   // prototype), then we consider them to have matching signatures.
978   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
979       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
980     return false;
981 
982   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
983   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
984 
985   // The signature of a function includes the types of its
986   // parameters (C++ 1.3.10), which includes the presence or absence
987   // of the ellipsis; see C++ DR 357).
988   if (OldQType != NewQType &&
989       (OldType->getNumParams() != NewType->getNumParams() ||
990        OldType->isVariadic() != NewType->isVariadic() ||
991        !FunctionParamTypesAreEqual(OldType, NewType)))
992     return true;
993 
994   // C++ [temp.over.link]p4:
995   //   The signature of a function template consists of its function
996   //   signature, its return type and its template parameter list. The names
997   //   of the template parameters are significant only for establishing the
998   //   relationship between the template parameters and the rest of the
999   //   signature.
1000   //
1001   // We check the return type and template parameter lists for function
1002   // templates first; the remaining checks follow.
1003   //
1004   // However, we don't consider either of these when deciding whether
1005   // a member introduced by a shadow declaration is hidden.
1006   if (!UseUsingDeclRules && NewTemplate &&
1007       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1008                                        OldTemplate->getTemplateParameters(),
1009                                        false, TPL_TemplateMatch) ||
1010        OldType->getReturnType() != NewType->getReturnType()))
1011     return true;
1012 
1013   // If the function is a class member, its signature includes the
1014   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1015   //
1016   // As part of this, also check whether one of the member functions
1017   // is static, in which case they are not overloads (C++
1018   // 13.1p2). While not part of the definition of the signature,
1019   // this check is important to determine whether these functions
1020   // can be overloaded.
1021   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1022   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1023   if (OldMethod && NewMethod &&
1024       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1025     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1026       if (!UseUsingDeclRules &&
1027           (OldMethod->getRefQualifier() == RQ_None ||
1028            NewMethod->getRefQualifier() == RQ_None)) {
1029         // C++0x [over.load]p2:
1030         //   - Member function declarations with the same name and the same
1031         //     parameter-type-list as well as member function template
1032         //     declarations with the same name, the same parameter-type-list, and
1033         //     the same template parameter lists cannot be overloaded if any of
1034         //     them, but not all, have a ref-qualifier (8.3.5).
1035         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1036           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1037         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1038       }
1039       return true;
1040     }
1041 
1042     // We may not have applied the implicit const for a constexpr member
1043     // function yet (because we haven't yet resolved whether this is a static
1044     // or non-static member function). Add it now, on the assumption that this
1045     // is a redeclaration of OldMethod.
1046     unsigned OldQuals = OldMethod->getTypeQualifiers();
1047     unsigned NewQuals = NewMethod->getTypeQualifiers();
1048     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1049         !isa<CXXConstructorDecl>(NewMethod))
1050       NewQuals |= Qualifiers::Const;
1051 
1052     // We do not allow overloading based off of '__restrict'.
1053     OldQuals &= ~Qualifiers::Restrict;
1054     NewQuals &= ~Qualifiers::Restrict;
1055     if (OldQuals != NewQuals)
1056       return true;
1057   }
1058 
1059   // enable_if attributes are an order-sensitive part of the signature.
1060   for (specific_attr_iterator<EnableIfAttr>
1061          NewI = New->specific_attr_begin<EnableIfAttr>(),
1062          NewE = New->specific_attr_end<EnableIfAttr>(),
1063          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1064          OldE = Old->specific_attr_end<EnableIfAttr>();
1065        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1066     if (NewI == NewE || OldI == OldE)
1067       return true;
1068     llvm::FoldingSetNodeID NewID, OldID;
1069     NewI->getCond()->Profile(NewID, Context, true);
1070     OldI->getCond()->Profile(OldID, Context, true);
1071     if (NewID != OldID)
1072       return true;
1073   }
1074 
1075   // The signatures match; this is not an overload.
1076   return false;
1077 }
1078 
1079 /// \brief Checks availability of the function depending on the current
1080 /// function context. Inside an unavailable function, unavailability is ignored.
1081 ///
1082 /// \returns true if \arg FD is unavailable and current context is inside
1083 /// an available function, false otherwise.
1084 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1085   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1086 }
1087 
1088 /// \brief Tries a user-defined conversion from From to ToType.
1089 ///
1090 /// Produces an implicit conversion sequence for when a standard conversion
1091 /// is not an option. See TryImplicitConversion for more information.
1092 static ImplicitConversionSequence
1093 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1094                          bool SuppressUserConversions,
1095                          bool AllowExplicit,
1096                          bool InOverloadResolution,
1097                          bool CStyle,
1098                          bool AllowObjCWritebackConversion,
1099                          bool AllowObjCConversionOnExplicit) {
1100   ImplicitConversionSequence ICS;
1101 
1102   if (SuppressUserConversions) {
1103     // We're not in the case above, so there is no conversion that
1104     // we can perform.
1105     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1106     return ICS;
1107   }
1108 
1109   // Attempt user-defined conversion.
1110   OverloadCandidateSet Conversions(From->getExprLoc(),
1111                                    OverloadCandidateSet::CSK_Normal);
1112   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1113                                   Conversions, AllowExplicit,
1114                                   AllowObjCConversionOnExplicit)) {
1115   case OR_Success:
1116   case OR_Deleted:
1117     ICS.setUserDefined();
1118     ICS.UserDefined.Before.setAsIdentityConversion();
1119     // C++ [over.ics.user]p4:
1120     //   A conversion of an expression of class type to the same class
1121     //   type is given Exact Match rank, and a conversion of an
1122     //   expression of class type to a base class of that type is
1123     //   given Conversion rank, in spite of the fact that a copy
1124     //   constructor (i.e., a user-defined conversion function) is
1125     //   called for those cases.
1126     if (CXXConstructorDecl *Constructor
1127           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1128       QualType FromCanon
1129         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1130       QualType ToCanon
1131         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1132       if (Constructor->isCopyConstructor() &&
1133           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1134         // Turn this into a "standard" conversion sequence, so that it
1135         // gets ranked with standard conversion sequences.
1136         ICS.setStandard();
1137         ICS.Standard.setAsIdentityConversion();
1138         ICS.Standard.setFromType(From->getType());
1139         ICS.Standard.setAllToTypes(ToType);
1140         ICS.Standard.CopyConstructor = Constructor;
1141         if (ToCanon != FromCanon)
1142           ICS.Standard.Second = ICK_Derived_To_Base;
1143       }
1144     }
1145     break;
1146 
1147   case OR_Ambiguous:
1148     ICS.setAmbiguous();
1149     ICS.Ambiguous.setFromType(From->getType());
1150     ICS.Ambiguous.setToType(ToType);
1151     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1152          Cand != Conversions.end(); ++Cand)
1153       if (Cand->Viable)
1154         ICS.Ambiguous.addConversion(Cand->Function);
1155     break;
1156 
1157     // Fall through.
1158   case OR_No_Viable_Function:
1159     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1160     break;
1161   }
1162 
1163   return ICS;
1164 }
1165 
1166 /// TryImplicitConversion - Attempt to perform an implicit conversion
1167 /// from the given expression (Expr) to the given type (ToType). This
1168 /// function returns an implicit conversion sequence that can be used
1169 /// to perform the initialization. Given
1170 ///
1171 ///   void f(float f);
1172 ///   void g(int i) { f(i); }
1173 ///
1174 /// this routine would produce an implicit conversion sequence to
1175 /// describe the initialization of f from i, which will be a standard
1176 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1177 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1178 //
1179 /// Note that this routine only determines how the conversion can be
1180 /// performed; it does not actually perform the conversion. As such,
1181 /// it will not produce any diagnostics if no conversion is available,
1182 /// but will instead return an implicit conversion sequence of kind
1183 /// "BadConversion".
1184 ///
1185 /// If @p SuppressUserConversions, then user-defined conversions are
1186 /// not permitted.
1187 /// If @p AllowExplicit, then explicit user-defined conversions are
1188 /// permitted.
1189 ///
1190 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1191 /// writeback conversion, which allows __autoreleasing id* parameters to
1192 /// be initialized with __strong id* or __weak id* arguments.
1193 static ImplicitConversionSequence
1194 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1195                       bool SuppressUserConversions,
1196                       bool AllowExplicit,
1197                       bool InOverloadResolution,
1198                       bool CStyle,
1199                       bool AllowObjCWritebackConversion,
1200                       bool AllowObjCConversionOnExplicit) {
1201   ImplicitConversionSequence ICS;
1202   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1203                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1204     ICS.setStandard();
1205     return ICS;
1206   }
1207 
1208   if (!S.getLangOpts().CPlusPlus) {
1209     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1210     return ICS;
1211   }
1212 
1213   // C++ [over.ics.user]p4:
1214   //   A conversion of an expression of class type to the same class
1215   //   type is given Exact Match rank, and a conversion of an
1216   //   expression of class type to a base class of that type is
1217   //   given Conversion rank, in spite of the fact that a copy/move
1218   //   constructor (i.e., a user-defined conversion function) is
1219   //   called for those cases.
1220   QualType FromType = From->getType();
1221   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1222       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1223        S.IsDerivedFrom(FromType, ToType))) {
1224     ICS.setStandard();
1225     ICS.Standard.setAsIdentityConversion();
1226     ICS.Standard.setFromType(FromType);
1227     ICS.Standard.setAllToTypes(ToType);
1228 
1229     // We don't actually check at this point whether there is a valid
1230     // copy/move constructor, since overloading just assumes that it
1231     // exists. When we actually perform initialization, we'll find the
1232     // appropriate constructor to copy the returned object, if needed.
1233     ICS.Standard.CopyConstructor = nullptr;
1234 
1235     // Determine whether this is considered a derived-to-base conversion.
1236     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1237       ICS.Standard.Second = ICK_Derived_To_Base;
1238 
1239     return ICS;
1240   }
1241 
1242   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1243                                   AllowExplicit, InOverloadResolution, CStyle,
1244                                   AllowObjCWritebackConversion,
1245                                   AllowObjCConversionOnExplicit);
1246 }
1247 
1248 ImplicitConversionSequence
1249 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1250                             bool SuppressUserConversions,
1251                             bool AllowExplicit,
1252                             bool InOverloadResolution,
1253                             bool CStyle,
1254                             bool AllowObjCWritebackConversion) {
1255   return ::TryImplicitConversion(*this, From, ToType,
1256                                  SuppressUserConversions, AllowExplicit,
1257                                  InOverloadResolution, CStyle,
1258                                  AllowObjCWritebackConversion,
1259                                  /*AllowObjCConversionOnExplicit=*/false);
1260 }
1261 
1262 /// PerformImplicitConversion - Perform an implicit conversion of the
1263 /// expression From to the type ToType. Returns the
1264 /// converted expression. Flavor is the kind of conversion we're
1265 /// performing, used in the error message. If @p AllowExplicit,
1266 /// explicit user-defined conversions are permitted.
1267 ExprResult
1268 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1269                                 AssignmentAction Action, bool AllowExplicit) {
1270   ImplicitConversionSequence ICS;
1271   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1272 }
1273 
1274 ExprResult
1275 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1276                                 AssignmentAction Action, bool AllowExplicit,
1277                                 ImplicitConversionSequence& ICS) {
1278   if (checkPlaceholderForOverload(*this, From))
1279     return ExprError();
1280 
1281   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1282   bool AllowObjCWritebackConversion
1283     = getLangOpts().ObjCAutoRefCount &&
1284       (Action == AA_Passing || Action == AA_Sending);
1285   if (getLangOpts().ObjC1)
1286     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1287                                       ToType, From->getType(), From);
1288   ICS = ::TryImplicitConversion(*this, From, ToType,
1289                                 /*SuppressUserConversions=*/false,
1290                                 AllowExplicit,
1291                                 /*InOverloadResolution=*/false,
1292                                 /*CStyle=*/false,
1293                                 AllowObjCWritebackConversion,
1294                                 /*AllowObjCConversionOnExplicit=*/false);
1295   return PerformImplicitConversion(From, ToType, ICS, Action);
1296 }
1297 
1298 /// \brief Determine whether the conversion from FromType to ToType is a valid
1299 /// conversion that strips "noreturn" off the nested function type.
1300 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1301                                 QualType &ResultTy) {
1302   if (Context.hasSameUnqualifiedType(FromType, ToType))
1303     return false;
1304 
1305   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1306   // where F adds one of the following at most once:
1307   //   - a pointer
1308   //   - a member pointer
1309   //   - a block pointer
1310   CanQualType CanTo = Context.getCanonicalType(ToType);
1311   CanQualType CanFrom = Context.getCanonicalType(FromType);
1312   Type::TypeClass TyClass = CanTo->getTypeClass();
1313   if (TyClass != CanFrom->getTypeClass()) return false;
1314   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1315     if (TyClass == Type::Pointer) {
1316       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1317       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1318     } else if (TyClass == Type::BlockPointer) {
1319       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1320       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1321     } else if (TyClass == Type::MemberPointer) {
1322       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1323       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1324     } else {
1325       return false;
1326     }
1327 
1328     TyClass = CanTo->getTypeClass();
1329     if (TyClass != CanFrom->getTypeClass()) return false;
1330     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1331       return false;
1332   }
1333 
1334   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1335   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1336   if (!EInfo.getNoReturn()) return false;
1337 
1338   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1339   assert(QualType(FromFn, 0).isCanonical());
1340   if (QualType(FromFn, 0) != CanTo) return false;
1341 
1342   ResultTy = ToType;
1343   return true;
1344 }
1345 
1346 /// \brief Determine whether the conversion from FromType to ToType is a valid
1347 /// vector conversion.
1348 ///
1349 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1350 /// conversion.
1351 static bool IsVectorConversion(Sema &S, QualType FromType,
1352                                QualType ToType, ImplicitConversionKind &ICK) {
1353   // We need at least one of these types to be a vector type to have a vector
1354   // conversion.
1355   if (!ToType->isVectorType() && !FromType->isVectorType())
1356     return false;
1357 
1358   // Identical types require no conversions.
1359   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1360     return false;
1361 
1362   // There are no conversions between extended vector types, only identity.
1363   if (ToType->isExtVectorType()) {
1364     // There are no conversions between extended vector types other than the
1365     // identity conversion.
1366     if (FromType->isExtVectorType())
1367       return false;
1368 
1369     // Vector splat from any arithmetic type to a vector.
1370     if (FromType->isArithmeticType()) {
1371       ICK = ICK_Vector_Splat;
1372       return true;
1373     }
1374   }
1375 
1376   // We can perform the conversion between vector types in the following cases:
1377   // 1)vector types are equivalent AltiVec and GCC vector types
1378   // 2)lax vector conversions are permitted and the vector types are of the
1379   //   same size
1380   if (ToType->isVectorType() && FromType->isVectorType()) {
1381     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1382         S.isLaxVectorConversion(FromType, ToType)) {
1383       ICK = ICK_Vector_Conversion;
1384       return true;
1385     }
1386   }
1387 
1388   return false;
1389 }
1390 
1391 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1392                                 bool InOverloadResolution,
1393                                 StandardConversionSequence &SCS,
1394                                 bool CStyle);
1395 
1396 /// IsStandardConversion - Determines whether there is a standard
1397 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1398 /// expression From to the type ToType. Standard conversion sequences
1399 /// only consider non-class types; for conversions that involve class
1400 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1401 /// contain the standard conversion sequence required to perform this
1402 /// conversion and this routine will return true. Otherwise, this
1403 /// routine will return false and the value of SCS is unspecified.
1404 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1405                                  bool InOverloadResolution,
1406                                  StandardConversionSequence &SCS,
1407                                  bool CStyle,
1408                                  bool AllowObjCWritebackConversion) {
1409   QualType FromType = From->getType();
1410 
1411   // Standard conversions (C++ [conv])
1412   SCS.setAsIdentityConversion();
1413   SCS.IncompatibleObjC = false;
1414   SCS.setFromType(FromType);
1415   SCS.CopyConstructor = nullptr;
1416 
1417   // There are no standard conversions for class types in C++, so
1418   // abort early. When overloading in C, however, we do permit
1419   if (FromType->isRecordType() || ToType->isRecordType()) {
1420     if (S.getLangOpts().CPlusPlus)
1421       return false;
1422 
1423     // When we're overloading in C, we allow, as standard conversions,
1424   }
1425 
1426   // The first conversion can be an lvalue-to-rvalue conversion,
1427   // array-to-pointer conversion, or function-to-pointer conversion
1428   // (C++ 4p1).
1429 
1430   if (FromType == S.Context.OverloadTy) {
1431     DeclAccessPair AccessPair;
1432     if (FunctionDecl *Fn
1433           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1434                                                  AccessPair)) {
1435       // We were able to resolve the address of the overloaded function,
1436       // so we can convert to the type of that function.
1437       FromType = Fn->getType();
1438       SCS.setFromType(FromType);
1439 
1440       // we can sometimes resolve &foo<int> regardless of ToType, so check
1441       // if the type matches (identity) or we are converting to bool
1442       if (!S.Context.hasSameUnqualifiedType(
1443                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1444         QualType resultTy;
1445         // if the function type matches except for [[noreturn]], it's ok
1446         if (!S.IsNoReturnConversion(FromType,
1447               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1448           // otherwise, only a boolean conversion is standard
1449           if (!ToType->isBooleanType())
1450             return false;
1451       }
1452 
1453       // Check if the "from" expression is taking the address of an overloaded
1454       // function and recompute the FromType accordingly. Take advantage of the
1455       // fact that non-static member functions *must* have such an address-of
1456       // expression.
1457       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1458       if (Method && !Method->isStatic()) {
1459         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1460                "Non-unary operator on non-static member address");
1461         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1462                == UO_AddrOf &&
1463                "Non-address-of operator on non-static member address");
1464         const Type *ClassType
1465           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1466         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1467       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1468         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1469                UO_AddrOf &&
1470                "Non-address-of operator for overloaded function expression");
1471         FromType = S.Context.getPointerType(FromType);
1472       }
1473 
1474       // Check that we've computed the proper type after overload resolution.
1475       assert(S.Context.hasSameType(
1476         FromType,
1477         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1478     } else {
1479       return false;
1480     }
1481   }
1482   // Lvalue-to-rvalue conversion (C++11 4.1):
1483   //   A glvalue (3.10) of a non-function, non-array type T can
1484   //   be converted to a prvalue.
1485   bool argIsLValue = From->isGLValue();
1486   if (argIsLValue &&
1487       !FromType->isFunctionType() && !FromType->isArrayType() &&
1488       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1489     SCS.First = ICK_Lvalue_To_Rvalue;
1490 
1491     // C11 6.3.2.1p2:
1492     //   ... if the lvalue has atomic type, the value has the non-atomic version
1493     //   of the type of the lvalue ...
1494     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1495       FromType = Atomic->getValueType();
1496 
1497     // If T is a non-class type, the type of the rvalue is the
1498     // cv-unqualified version of T. Otherwise, the type of the rvalue
1499     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1500     // just strip the qualifiers because they don't matter.
1501     FromType = FromType.getUnqualifiedType();
1502   } else if (FromType->isArrayType()) {
1503     // Array-to-pointer conversion (C++ 4.2)
1504     SCS.First = ICK_Array_To_Pointer;
1505 
1506     // An lvalue or rvalue of type "array of N T" or "array of unknown
1507     // bound of T" can be converted to an rvalue of type "pointer to
1508     // T" (C++ 4.2p1).
1509     FromType = S.Context.getArrayDecayedType(FromType);
1510 
1511     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1512       // This conversion is deprecated in C++03 (D.4)
1513       SCS.DeprecatedStringLiteralToCharPtr = true;
1514 
1515       // For the purpose of ranking in overload resolution
1516       // (13.3.3.1.1), this conversion is considered an
1517       // array-to-pointer conversion followed by a qualification
1518       // conversion (4.4). (C++ 4.2p2)
1519       SCS.Second = ICK_Identity;
1520       SCS.Third = ICK_Qualification;
1521       SCS.QualificationIncludesObjCLifetime = false;
1522       SCS.setAllToTypes(FromType);
1523       return true;
1524     }
1525   } else if (FromType->isFunctionType() && argIsLValue) {
1526     // Function-to-pointer conversion (C++ 4.3).
1527     SCS.First = ICK_Function_To_Pointer;
1528 
1529     // An lvalue of function type T can be converted to an rvalue of
1530     // type "pointer to T." The result is a pointer to the
1531     // function. (C++ 4.3p1).
1532     FromType = S.Context.getPointerType(FromType);
1533   } else {
1534     // We don't require any conversions for the first step.
1535     SCS.First = ICK_Identity;
1536   }
1537   SCS.setToType(0, FromType);
1538 
1539   // The second conversion can be an integral promotion, floating
1540   // point promotion, integral conversion, floating point conversion,
1541   // floating-integral conversion, pointer conversion,
1542   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1543   // For overloading in C, this can also be a "compatible-type"
1544   // conversion.
1545   bool IncompatibleObjC = false;
1546   ImplicitConversionKind SecondICK = ICK_Identity;
1547   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1548     // The unqualified versions of the types are the same: there's no
1549     // conversion to do.
1550     SCS.Second = ICK_Identity;
1551   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1552     // Integral promotion (C++ 4.5).
1553     SCS.Second = ICK_Integral_Promotion;
1554     FromType = ToType.getUnqualifiedType();
1555   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1556     // Floating point promotion (C++ 4.6).
1557     SCS.Second = ICK_Floating_Promotion;
1558     FromType = ToType.getUnqualifiedType();
1559   } else if (S.IsComplexPromotion(FromType, ToType)) {
1560     // Complex promotion (Clang extension)
1561     SCS.Second = ICK_Complex_Promotion;
1562     FromType = ToType.getUnqualifiedType();
1563   } else if (ToType->isBooleanType() &&
1564              (FromType->isArithmeticType() ||
1565               FromType->isAnyPointerType() ||
1566               FromType->isBlockPointerType() ||
1567               FromType->isMemberPointerType() ||
1568               FromType->isNullPtrType())) {
1569     // Boolean conversions (C++ 4.12).
1570     SCS.Second = ICK_Boolean_Conversion;
1571     FromType = S.Context.BoolTy;
1572   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1573              ToType->isIntegralType(S.Context)) {
1574     // Integral conversions (C++ 4.7).
1575     SCS.Second = ICK_Integral_Conversion;
1576     FromType = ToType.getUnqualifiedType();
1577   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1578     // Complex conversions (C99 6.3.1.6)
1579     SCS.Second = ICK_Complex_Conversion;
1580     FromType = ToType.getUnqualifiedType();
1581   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1582              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1583     // Complex-real conversions (C99 6.3.1.7)
1584     SCS.Second = ICK_Complex_Real;
1585     FromType = ToType.getUnqualifiedType();
1586   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1587     // Floating point conversions (C++ 4.8).
1588     SCS.Second = ICK_Floating_Conversion;
1589     FromType = ToType.getUnqualifiedType();
1590   } else if ((FromType->isRealFloatingType() &&
1591               ToType->isIntegralType(S.Context)) ||
1592              (FromType->isIntegralOrUnscopedEnumerationType() &&
1593               ToType->isRealFloatingType())) {
1594     // Floating-integral conversions (C++ 4.9).
1595     SCS.Second = ICK_Floating_Integral;
1596     FromType = ToType.getUnqualifiedType();
1597   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1598     SCS.Second = ICK_Block_Pointer_Conversion;
1599   } else if (AllowObjCWritebackConversion &&
1600              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1601     SCS.Second = ICK_Writeback_Conversion;
1602   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1603                                    FromType, IncompatibleObjC)) {
1604     // Pointer conversions (C++ 4.10).
1605     SCS.Second = ICK_Pointer_Conversion;
1606     SCS.IncompatibleObjC = IncompatibleObjC;
1607     FromType = FromType.getUnqualifiedType();
1608   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1609                                          InOverloadResolution, FromType)) {
1610     // Pointer to member conversions (4.11).
1611     SCS.Second = ICK_Pointer_Member;
1612   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1613     SCS.Second = SecondICK;
1614     FromType = ToType.getUnqualifiedType();
1615   } else if (!S.getLangOpts().CPlusPlus &&
1616              S.Context.typesAreCompatible(ToType, FromType)) {
1617     // Compatible conversions (Clang extension for C function overloading)
1618     SCS.Second = ICK_Compatible_Conversion;
1619     FromType = ToType.getUnqualifiedType();
1620   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1621     // Treat a conversion that strips "noreturn" as an identity conversion.
1622     SCS.Second = ICK_NoReturn_Adjustment;
1623   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1624                                              InOverloadResolution,
1625                                              SCS, CStyle)) {
1626     SCS.Second = ICK_TransparentUnionConversion;
1627     FromType = ToType;
1628   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1629                                  CStyle)) {
1630     // tryAtomicConversion has updated the standard conversion sequence
1631     // appropriately.
1632     return true;
1633   } else if (ToType->isEventT() &&
1634              From->isIntegerConstantExpr(S.getASTContext()) &&
1635              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1636     SCS.Second = ICK_Zero_Event_Conversion;
1637     FromType = ToType;
1638   } else {
1639     // No second conversion required.
1640     SCS.Second = ICK_Identity;
1641   }
1642   SCS.setToType(1, FromType);
1643 
1644   QualType CanonFrom;
1645   QualType CanonTo;
1646   // The third conversion can be a qualification conversion (C++ 4p1).
1647   bool ObjCLifetimeConversion;
1648   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1649                                   ObjCLifetimeConversion)) {
1650     SCS.Third = ICK_Qualification;
1651     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1652     FromType = ToType;
1653     CanonFrom = S.Context.getCanonicalType(FromType);
1654     CanonTo = S.Context.getCanonicalType(ToType);
1655   } else {
1656     // No conversion required
1657     SCS.Third = ICK_Identity;
1658 
1659     // C++ [over.best.ics]p6:
1660     //   [...] Any difference in top-level cv-qualification is
1661     //   subsumed by the initialization itself and does not constitute
1662     //   a conversion. [...]
1663     CanonFrom = S.Context.getCanonicalType(FromType);
1664     CanonTo = S.Context.getCanonicalType(ToType);
1665     if (CanonFrom.getLocalUnqualifiedType()
1666                                        == CanonTo.getLocalUnqualifiedType() &&
1667         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1668       FromType = ToType;
1669       CanonFrom = CanonTo;
1670     }
1671   }
1672   SCS.setToType(2, FromType);
1673 
1674   // If we have not converted the argument type to the parameter type,
1675   // this is a bad conversion sequence.
1676   if (CanonFrom != CanonTo)
1677     return false;
1678 
1679   return true;
1680 }
1681 
1682 static bool
1683 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1684                                      QualType &ToType,
1685                                      bool InOverloadResolution,
1686                                      StandardConversionSequence &SCS,
1687                                      bool CStyle) {
1688 
1689   const RecordType *UT = ToType->getAsUnionType();
1690   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1691     return false;
1692   // The field to initialize within the transparent union.
1693   RecordDecl *UD = UT->getDecl();
1694   // It's compatible if the expression matches any of the fields.
1695   for (const auto *it : UD->fields()) {
1696     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1697                              CStyle, /*ObjCWritebackConversion=*/false)) {
1698       ToType = it->getType();
1699       return true;
1700     }
1701   }
1702   return false;
1703 }
1704 
1705 /// IsIntegralPromotion - Determines whether the conversion from the
1706 /// expression From (whose potentially-adjusted type is FromType) to
1707 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1708 /// sets PromotedType to the promoted type.
1709 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1710   const BuiltinType *To = ToType->getAs<BuiltinType>();
1711   // All integers are built-in.
1712   if (!To) {
1713     return false;
1714   }
1715 
1716   // An rvalue of type char, signed char, unsigned char, short int, or
1717   // unsigned short int can be converted to an rvalue of type int if
1718   // int can represent all the values of the source type; otherwise,
1719   // the source rvalue can be converted to an rvalue of type unsigned
1720   // int (C++ 4.5p1).
1721   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1722       !FromType->isEnumeralType()) {
1723     if (// We can promote any signed, promotable integer type to an int
1724         (FromType->isSignedIntegerType() ||
1725          // We can promote any unsigned integer type whose size is
1726          // less than int to an int.
1727          (!FromType->isSignedIntegerType() &&
1728           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1729       return To->getKind() == BuiltinType::Int;
1730     }
1731 
1732     return To->getKind() == BuiltinType::UInt;
1733   }
1734 
1735   // C++11 [conv.prom]p3:
1736   //   A prvalue of an unscoped enumeration type whose underlying type is not
1737   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1738   //   following types that can represent all the values of the enumeration
1739   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1740   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1741   //   long long int. If none of the types in that list can represent all the
1742   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1743   //   type can be converted to an rvalue a prvalue of the extended integer type
1744   //   with lowest integer conversion rank (4.13) greater than the rank of long
1745   //   long in which all the values of the enumeration can be represented. If
1746   //   there are two such extended types, the signed one is chosen.
1747   // C++11 [conv.prom]p4:
1748   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1749   //   can be converted to a prvalue of its underlying type. Moreover, if
1750   //   integral promotion can be applied to its underlying type, a prvalue of an
1751   //   unscoped enumeration type whose underlying type is fixed can also be
1752   //   converted to a prvalue of the promoted underlying type.
1753   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1754     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1755     // provided for a scoped enumeration.
1756     if (FromEnumType->getDecl()->isScoped())
1757       return false;
1758 
1759     // We can perform an integral promotion to the underlying type of the enum,
1760     // even if that's not the promoted type. Note that the check for promoting
1761     // the underlying type is based on the type alone, and does not consider
1762     // the bitfield-ness of the actual source expression.
1763     if (FromEnumType->getDecl()->isFixed()) {
1764       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1765       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1766              IsIntegralPromotion(nullptr, Underlying, ToType);
1767     }
1768 
1769     // We have already pre-calculated the promotion type, so this is trivial.
1770     if (ToType->isIntegerType() &&
1771         !RequireCompleteType(From->getLocStart(), FromType, 0))
1772       return Context.hasSameUnqualifiedType(
1773           ToType, FromEnumType->getDecl()->getPromotionType());
1774   }
1775 
1776   // C++0x [conv.prom]p2:
1777   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1778   //   to an rvalue a prvalue of the first of the following types that can
1779   //   represent all the values of its underlying type: int, unsigned int,
1780   //   long int, unsigned long int, long long int, or unsigned long long int.
1781   //   If none of the types in that list can represent all the values of its
1782   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1783   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1784   //   type.
1785   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1786       ToType->isIntegerType()) {
1787     // Determine whether the type we're converting from is signed or
1788     // unsigned.
1789     bool FromIsSigned = FromType->isSignedIntegerType();
1790     uint64_t FromSize = Context.getTypeSize(FromType);
1791 
1792     // The types we'll try to promote to, in the appropriate
1793     // order. Try each of these types.
1794     QualType PromoteTypes[6] = {
1795       Context.IntTy, Context.UnsignedIntTy,
1796       Context.LongTy, Context.UnsignedLongTy ,
1797       Context.LongLongTy, Context.UnsignedLongLongTy
1798     };
1799     for (int Idx = 0; Idx < 6; ++Idx) {
1800       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1801       if (FromSize < ToSize ||
1802           (FromSize == ToSize &&
1803            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1804         // We found the type that we can promote to. If this is the
1805         // type we wanted, we have a promotion. Otherwise, no
1806         // promotion.
1807         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1808       }
1809     }
1810   }
1811 
1812   // An rvalue for an integral bit-field (9.6) can be converted to an
1813   // rvalue of type int if int can represent all the values of the
1814   // bit-field; otherwise, it can be converted to unsigned int if
1815   // unsigned int can represent all the values of the bit-field. If
1816   // the bit-field is larger yet, no integral promotion applies to
1817   // it. If the bit-field has an enumerated type, it is treated as any
1818   // other value of that type for promotion purposes (C++ 4.5p3).
1819   // FIXME: We should delay checking of bit-fields until we actually perform the
1820   // conversion.
1821   if (From) {
1822     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1823       llvm::APSInt BitWidth;
1824       if (FromType->isIntegralType(Context) &&
1825           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1826         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1827         ToSize = Context.getTypeSize(ToType);
1828 
1829         // Are we promoting to an int from a bitfield that fits in an int?
1830         if (BitWidth < ToSize ||
1831             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1832           return To->getKind() == BuiltinType::Int;
1833         }
1834 
1835         // Are we promoting to an unsigned int from an unsigned bitfield
1836         // that fits into an unsigned int?
1837         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1838           return To->getKind() == BuiltinType::UInt;
1839         }
1840 
1841         return false;
1842       }
1843     }
1844   }
1845 
1846   // An rvalue of type bool can be converted to an rvalue of type int,
1847   // with false becoming zero and true becoming one (C++ 4.5p4).
1848   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1849     return true;
1850   }
1851 
1852   return false;
1853 }
1854 
1855 /// IsFloatingPointPromotion - Determines whether the conversion from
1856 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1857 /// returns true and sets PromotedType to the promoted type.
1858 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1859   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1860     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1861       /// An rvalue of type float can be converted to an rvalue of type
1862       /// double. (C++ 4.6p1).
1863       if (FromBuiltin->getKind() == BuiltinType::Float &&
1864           ToBuiltin->getKind() == BuiltinType::Double)
1865         return true;
1866 
1867       // C99 6.3.1.5p1:
1868       //   When a float is promoted to double or long double, or a
1869       //   double is promoted to long double [...].
1870       if (!getLangOpts().CPlusPlus &&
1871           (FromBuiltin->getKind() == BuiltinType::Float ||
1872            FromBuiltin->getKind() == BuiltinType::Double) &&
1873           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1874         return true;
1875 
1876       // Half can be promoted to float.
1877       if (!getLangOpts().NativeHalfType &&
1878            FromBuiltin->getKind() == BuiltinType::Half &&
1879           ToBuiltin->getKind() == BuiltinType::Float)
1880         return true;
1881     }
1882 
1883   return false;
1884 }
1885 
1886 /// \brief Determine if a conversion is a complex promotion.
1887 ///
1888 /// A complex promotion is defined as a complex -> complex conversion
1889 /// where the conversion between the underlying real types is a
1890 /// floating-point or integral promotion.
1891 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1892   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1893   if (!FromComplex)
1894     return false;
1895 
1896   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1897   if (!ToComplex)
1898     return false;
1899 
1900   return IsFloatingPointPromotion(FromComplex->getElementType(),
1901                                   ToComplex->getElementType()) ||
1902     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1903                         ToComplex->getElementType());
1904 }
1905 
1906 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1907 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1908 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1909 /// if non-empty, will be a pointer to ToType that may or may not have
1910 /// the right set of qualifiers on its pointee.
1911 ///
1912 static QualType
1913 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1914                                    QualType ToPointee, QualType ToType,
1915                                    ASTContext &Context,
1916                                    bool StripObjCLifetime = false) {
1917   assert((FromPtr->getTypeClass() == Type::Pointer ||
1918           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1919          "Invalid similarly-qualified pointer type");
1920 
1921   /// Conversions to 'id' subsume cv-qualifier conversions.
1922   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1923     return ToType.getUnqualifiedType();
1924 
1925   QualType CanonFromPointee
1926     = Context.getCanonicalType(FromPtr->getPointeeType());
1927   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1928   Qualifiers Quals = CanonFromPointee.getQualifiers();
1929 
1930   if (StripObjCLifetime)
1931     Quals.removeObjCLifetime();
1932 
1933   // Exact qualifier match -> return the pointer type we're converting to.
1934   if (CanonToPointee.getLocalQualifiers() == Quals) {
1935     // ToType is exactly what we need. Return it.
1936     if (!ToType.isNull())
1937       return ToType.getUnqualifiedType();
1938 
1939     // Build a pointer to ToPointee. It has the right qualifiers
1940     // already.
1941     if (isa<ObjCObjectPointerType>(ToType))
1942       return Context.getObjCObjectPointerType(ToPointee);
1943     return Context.getPointerType(ToPointee);
1944   }
1945 
1946   // Just build a canonical type that has the right qualifiers.
1947   QualType QualifiedCanonToPointee
1948     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1949 
1950   if (isa<ObjCObjectPointerType>(ToType))
1951     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1952   return Context.getPointerType(QualifiedCanonToPointee);
1953 }
1954 
1955 static bool isNullPointerConstantForConversion(Expr *Expr,
1956                                                bool InOverloadResolution,
1957                                                ASTContext &Context) {
1958   // Handle value-dependent integral null pointer constants correctly.
1959   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1960   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1961       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1962     return !InOverloadResolution;
1963 
1964   return Expr->isNullPointerConstant(Context,
1965                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1966                                         : Expr::NPC_ValueDependentIsNull);
1967 }
1968 
1969 /// IsPointerConversion - Determines whether the conversion of the
1970 /// expression From, which has the (possibly adjusted) type FromType,
1971 /// can be converted to the type ToType via a pointer conversion (C++
1972 /// 4.10). If so, returns true and places the converted type (that
1973 /// might differ from ToType in its cv-qualifiers at some level) into
1974 /// ConvertedType.
1975 ///
1976 /// This routine also supports conversions to and from block pointers
1977 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1978 /// pointers to interfaces. FIXME: Once we've determined the
1979 /// appropriate overloading rules for Objective-C, we may want to
1980 /// split the Objective-C checks into a different routine; however,
1981 /// GCC seems to consider all of these conversions to be pointer
1982 /// conversions, so for now they live here. IncompatibleObjC will be
1983 /// set if the conversion is an allowed Objective-C conversion that
1984 /// should result in a warning.
1985 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1986                                bool InOverloadResolution,
1987                                QualType& ConvertedType,
1988                                bool &IncompatibleObjC) {
1989   IncompatibleObjC = false;
1990   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1991                               IncompatibleObjC))
1992     return true;
1993 
1994   // Conversion from a null pointer constant to any Objective-C pointer type.
1995   if (ToType->isObjCObjectPointerType() &&
1996       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1997     ConvertedType = ToType;
1998     return true;
1999   }
2000 
2001   // Blocks: Block pointers can be converted to void*.
2002   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2003       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2004     ConvertedType = ToType;
2005     return true;
2006   }
2007   // Blocks: A null pointer constant can be converted to a block
2008   // pointer type.
2009   if (ToType->isBlockPointerType() &&
2010       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2011     ConvertedType = ToType;
2012     return true;
2013   }
2014 
2015   // If the left-hand-side is nullptr_t, the right side can be a null
2016   // pointer constant.
2017   if (ToType->isNullPtrType() &&
2018       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2019     ConvertedType = ToType;
2020     return true;
2021   }
2022 
2023   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2024   if (!ToTypePtr)
2025     return false;
2026 
2027   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2028   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2029     ConvertedType = ToType;
2030     return true;
2031   }
2032 
2033   // Beyond this point, both types need to be pointers
2034   // , including objective-c pointers.
2035   QualType ToPointeeType = ToTypePtr->getPointeeType();
2036   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2037       !getLangOpts().ObjCAutoRefCount) {
2038     ConvertedType = BuildSimilarlyQualifiedPointerType(
2039                                       FromType->getAs<ObjCObjectPointerType>(),
2040                                                        ToPointeeType,
2041                                                        ToType, Context);
2042     return true;
2043   }
2044   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2045   if (!FromTypePtr)
2046     return false;
2047 
2048   QualType FromPointeeType = FromTypePtr->getPointeeType();
2049 
2050   // If the unqualified pointee types are the same, this can't be a
2051   // pointer conversion, so don't do all of the work below.
2052   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2053     return false;
2054 
2055   // An rvalue of type "pointer to cv T," where T is an object type,
2056   // can be converted to an rvalue of type "pointer to cv void" (C++
2057   // 4.10p2).
2058   if (FromPointeeType->isIncompleteOrObjectType() &&
2059       ToPointeeType->isVoidType()) {
2060     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2061                                                        ToPointeeType,
2062                                                        ToType, Context,
2063                                                    /*StripObjCLifetime=*/true);
2064     return true;
2065   }
2066 
2067   // MSVC allows implicit function to void* type conversion.
2068   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2069       ToPointeeType->isVoidType()) {
2070     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2071                                                        ToPointeeType,
2072                                                        ToType, Context);
2073     return true;
2074   }
2075 
2076   // When we're overloading in C, we allow a special kind of pointer
2077   // conversion for compatible-but-not-identical pointee types.
2078   if (!getLangOpts().CPlusPlus &&
2079       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2080     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2081                                                        ToPointeeType,
2082                                                        ToType, Context);
2083     return true;
2084   }
2085 
2086   // C++ [conv.ptr]p3:
2087   //
2088   //   An rvalue of type "pointer to cv D," where D is a class type,
2089   //   can be converted to an rvalue of type "pointer to cv B," where
2090   //   B is a base class (clause 10) of D. If B is an inaccessible
2091   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2092   //   necessitates this conversion is ill-formed. The result of the
2093   //   conversion is a pointer to the base class sub-object of the
2094   //   derived class object. The null pointer value is converted to
2095   //   the null pointer value of the destination type.
2096   //
2097   // Note that we do not check for ambiguity or inaccessibility
2098   // here. That is handled by CheckPointerConversion.
2099   if (getLangOpts().CPlusPlus &&
2100       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2101       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2102       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2103       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2104     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2105                                                        ToPointeeType,
2106                                                        ToType, Context);
2107     return true;
2108   }
2109 
2110   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2111       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2112     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2113                                                        ToPointeeType,
2114                                                        ToType, Context);
2115     return true;
2116   }
2117 
2118   return false;
2119 }
2120 
2121 /// \brief Adopt the given qualifiers for the given type.
2122 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2123   Qualifiers TQs = T.getQualifiers();
2124 
2125   // Check whether qualifiers already match.
2126   if (TQs == Qs)
2127     return T;
2128 
2129   if (Qs.compatiblyIncludes(TQs))
2130     return Context.getQualifiedType(T, Qs);
2131 
2132   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2133 }
2134 
2135 /// isObjCPointerConversion - Determines whether this is an
2136 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2137 /// with the same arguments and return values.
2138 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2139                                    QualType& ConvertedType,
2140                                    bool &IncompatibleObjC) {
2141   if (!getLangOpts().ObjC1)
2142     return false;
2143 
2144   // The set of qualifiers on the type we're converting from.
2145   Qualifiers FromQualifiers = FromType.getQualifiers();
2146 
2147   // First, we handle all conversions on ObjC object pointer types.
2148   const ObjCObjectPointerType* ToObjCPtr =
2149     ToType->getAs<ObjCObjectPointerType>();
2150   const ObjCObjectPointerType *FromObjCPtr =
2151     FromType->getAs<ObjCObjectPointerType>();
2152 
2153   if (ToObjCPtr && FromObjCPtr) {
2154     // If the pointee types are the same (ignoring qualifications),
2155     // then this is not a pointer conversion.
2156     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2157                                        FromObjCPtr->getPointeeType()))
2158       return false;
2159 
2160     // Conversion between Objective-C pointers.
2161     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2162       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2163       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2164       if (getLangOpts().CPlusPlus && LHS && RHS &&
2165           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2166                                                 FromObjCPtr->getPointeeType()))
2167         return false;
2168       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2169                                                    ToObjCPtr->getPointeeType(),
2170                                                          ToType, Context);
2171       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2172       return true;
2173     }
2174 
2175     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2176       // Okay: this is some kind of implicit downcast of Objective-C
2177       // interfaces, which is permitted. However, we're going to
2178       // complain about it.
2179       IncompatibleObjC = true;
2180       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2181                                                    ToObjCPtr->getPointeeType(),
2182                                                          ToType, Context);
2183       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2184       return true;
2185     }
2186   }
2187   // Beyond this point, both types need to be C pointers or block pointers.
2188   QualType ToPointeeType;
2189   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2190     ToPointeeType = ToCPtr->getPointeeType();
2191   else if (const BlockPointerType *ToBlockPtr =
2192             ToType->getAs<BlockPointerType>()) {
2193     // Objective C++: We're able to convert from a pointer to any object
2194     // to a block pointer type.
2195     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2196       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2197       return true;
2198     }
2199     ToPointeeType = ToBlockPtr->getPointeeType();
2200   }
2201   else if (FromType->getAs<BlockPointerType>() &&
2202            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2203     // Objective C++: We're able to convert from a block pointer type to a
2204     // pointer to any object.
2205     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2206     return true;
2207   }
2208   else
2209     return false;
2210 
2211   QualType FromPointeeType;
2212   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2213     FromPointeeType = FromCPtr->getPointeeType();
2214   else if (const BlockPointerType *FromBlockPtr =
2215            FromType->getAs<BlockPointerType>())
2216     FromPointeeType = FromBlockPtr->getPointeeType();
2217   else
2218     return false;
2219 
2220   // If we have pointers to pointers, recursively check whether this
2221   // is an Objective-C conversion.
2222   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2223       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2224                               IncompatibleObjC)) {
2225     // We always complain about this conversion.
2226     IncompatibleObjC = true;
2227     ConvertedType = Context.getPointerType(ConvertedType);
2228     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2229     return true;
2230   }
2231   // Allow conversion of pointee being objective-c pointer to another one;
2232   // as in I* to id.
2233   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2234       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2235       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2236                               IncompatibleObjC)) {
2237 
2238     ConvertedType = Context.getPointerType(ConvertedType);
2239     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2240     return true;
2241   }
2242 
2243   // If we have pointers to functions or blocks, check whether the only
2244   // differences in the argument and result types are in Objective-C
2245   // pointer conversions. If so, we permit the conversion (but
2246   // complain about it).
2247   const FunctionProtoType *FromFunctionType
2248     = FromPointeeType->getAs<FunctionProtoType>();
2249   const FunctionProtoType *ToFunctionType
2250     = ToPointeeType->getAs<FunctionProtoType>();
2251   if (FromFunctionType && ToFunctionType) {
2252     // If the function types are exactly the same, this isn't an
2253     // Objective-C pointer conversion.
2254     if (Context.getCanonicalType(FromPointeeType)
2255           == Context.getCanonicalType(ToPointeeType))
2256       return false;
2257 
2258     // Perform the quick checks that will tell us whether these
2259     // function types are obviously different.
2260     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2261         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2262         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2263       return false;
2264 
2265     bool HasObjCConversion = false;
2266     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2267         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2268       // Okay, the types match exactly. Nothing to do.
2269     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2270                                        ToFunctionType->getReturnType(),
2271                                        ConvertedType, IncompatibleObjC)) {
2272       // Okay, we have an Objective-C pointer conversion.
2273       HasObjCConversion = true;
2274     } else {
2275       // Function types are too different. Abort.
2276       return false;
2277     }
2278 
2279     // Check argument types.
2280     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2281          ArgIdx != NumArgs; ++ArgIdx) {
2282       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2283       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2284       if (Context.getCanonicalType(FromArgType)
2285             == Context.getCanonicalType(ToArgType)) {
2286         // Okay, the types match exactly. Nothing to do.
2287       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2288                                          ConvertedType, IncompatibleObjC)) {
2289         // Okay, we have an Objective-C pointer conversion.
2290         HasObjCConversion = true;
2291       } else {
2292         // Argument types are too different. Abort.
2293         return false;
2294       }
2295     }
2296 
2297     if (HasObjCConversion) {
2298       // We had an Objective-C conversion. Allow this pointer
2299       // conversion, but complain about it.
2300       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2301       IncompatibleObjC = true;
2302       return true;
2303     }
2304   }
2305 
2306   return false;
2307 }
2308 
2309 /// \brief Determine whether this is an Objective-C writeback conversion,
2310 /// used for parameter passing when performing automatic reference counting.
2311 ///
2312 /// \param FromType The type we're converting form.
2313 ///
2314 /// \param ToType The type we're converting to.
2315 ///
2316 /// \param ConvertedType The type that will be produced after applying
2317 /// this conversion.
2318 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2319                                      QualType &ConvertedType) {
2320   if (!getLangOpts().ObjCAutoRefCount ||
2321       Context.hasSameUnqualifiedType(FromType, ToType))
2322     return false;
2323 
2324   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2325   QualType ToPointee;
2326   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2327     ToPointee = ToPointer->getPointeeType();
2328   else
2329     return false;
2330 
2331   Qualifiers ToQuals = ToPointee.getQualifiers();
2332   if (!ToPointee->isObjCLifetimeType() ||
2333       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2334       !ToQuals.withoutObjCLifetime().empty())
2335     return false;
2336 
2337   // Argument must be a pointer to __strong to __weak.
2338   QualType FromPointee;
2339   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2340     FromPointee = FromPointer->getPointeeType();
2341   else
2342     return false;
2343 
2344   Qualifiers FromQuals = FromPointee.getQualifiers();
2345   if (!FromPointee->isObjCLifetimeType() ||
2346       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2347        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2348     return false;
2349 
2350   // Make sure that we have compatible qualifiers.
2351   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2352   if (!ToQuals.compatiblyIncludes(FromQuals))
2353     return false;
2354 
2355   // Remove qualifiers from the pointee type we're converting from; they
2356   // aren't used in the compatibility check belong, and we'll be adding back
2357   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2358   FromPointee = FromPointee.getUnqualifiedType();
2359 
2360   // The unqualified form of the pointee types must be compatible.
2361   ToPointee = ToPointee.getUnqualifiedType();
2362   bool IncompatibleObjC;
2363   if (Context.typesAreCompatible(FromPointee, ToPointee))
2364     FromPointee = ToPointee;
2365   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2366                                     IncompatibleObjC))
2367     return false;
2368 
2369   /// \brief Construct the type we're converting to, which is a pointer to
2370   /// __autoreleasing pointee.
2371   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2372   ConvertedType = Context.getPointerType(FromPointee);
2373   return true;
2374 }
2375 
2376 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2377                                     QualType& ConvertedType) {
2378   QualType ToPointeeType;
2379   if (const BlockPointerType *ToBlockPtr =
2380         ToType->getAs<BlockPointerType>())
2381     ToPointeeType = ToBlockPtr->getPointeeType();
2382   else
2383     return false;
2384 
2385   QualType FromPointeeType;
2386   if (const BlockPointerType *FromBlockPtr =
2387       FromType->getAs<BlockPointerType>())
2388     FromPointeeType = FromBlockPtr->getPointeeType();
2389   else
2390     return false;
2391   // We have pointer to blocks, check whether the only
2392   // differences in the argument and result types are in Objective-C
2393   // pointer conversions. If so, we permit the conversion.
2394 
2395   const FunctionProtoType *FromFunctionType
2396     = FromPointeeType->getAs<FunctionProtoType>();
2397   const FunctionProtoType *ToFunctionType
2398     = ToPointeeType->getAs<FunctionProtoType>();
2399 
2400   if (!FromFunctionType || !ToFunctionType)
2401     return false;
2402 
2403   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2404     return true;
2405 
2406   // Perform the quick checks that will tell us whether these
2407   // function types are obviously different.
2408   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2409       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2410     return false;
2411 
2412   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2413   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2414   if (FromEInfo != ToEInfo)
2415     return false;
2416 
2417   bool IncompatibleObjC = false;
2418   if (Context.hasSameType(FromFunctionType->getReturnType(),
2419                           ToFunctionType->getReturnType())) {
2420     // Okay, the types match exactly. Nothing to do.
2421   } else {
2422     QualType RHS = FromFunctionType->getReturnType();
2423     QualType LHS = ToFunctionType->getReturnType();
2424     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2425         !RHS.hasQualifiers() && LHS.hasQualifiers())
2426        LHS = LHS.getUnqualifiedType();
2427 
2428      if (Context.hasSameType(RHS,LHS)) {
2429        // OK exact match.
2430      } else if (isObjCPointerConversion(RHS, LHS,
2431                                         ConvertedType, IncompatibleObjC)) {
2432      if (IncompatibleObjC)
2433        return false;
2434      // Okay, we have an Objective-C pointer conversion.
2435      }
2436      else
2437        return false;
2438    }
2439 
2440    // Check argument types.
2441    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2442         ArgIdx != NumArgs; ++ArgIdx) {
2443      IncompatibleObjC = false;
2444      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2445      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2446      if (Context.hasSameType(FromArgType, ToArgType)) {
2447        // Okay, the types match exactly. Nothing to do.
2448      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2449                                         ConvertedType, IncompatibleObjC)) {
2450        if (IncompatibleObjC)
2451          return false;
2452        // Okay, we have an Objective-C pointer conversion.
2453      } else
2454        // Argument types are too different. Abort.
2455        return false;
2456    }
2457    if (LangOpts.ObjCAutoRefCount &&
2458        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2459                                                     ToFunctionType))
2460      return false;
2461 
2462    ConvertedType = ToType;
2463    return true;
2464 }
2465 
2466 enum {
2467   ft_default,
2468   ft_different_class,
2469   ft_parameter_arity,
2470   ft_parameter_mismatch,
2471   ft_return_type,
2472   ft_qualifer_mismatch
2473 };
2474 
2475 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2476 /// function types.  Catches different number of parameter, mismatch in
2477 /// parameter types, and different return types.
2478 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2479                                       QualType FromType, QualType ToType) {
2480   // If either type is not valid, include no extra info.
2481   if (FromType.isNull() || ToType.isNull()) {
2482     PDiag << ft_default;
2483     return;
2484   }
2485 
2486   // Get the function type from the pointers.
2487   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2488     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2489                             *ToMember = ToType->getAs<MemberPointerType>();
2490     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2491       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2492             << QualType(FromMember->getClass(), 0);
2493       return;
2494     }
2495     FromType = FromMember->getPointeeType();
2496     ToType = ToMember->getPointeeType();
2497   }
2498 
2499   if (FromType->isPointerType())
2500     FromType = FromType->getPointeeType();
2501   if (ToType->isPointerType())
2502     ToType = ToType->getPointeeType();
2503 
2504   // Remove references.
2505   FromType = FromType.getNonReferenceType();
2506   ToType = ToType.getNonReferenceType();
2507 
2508   // Don't print extra info for non-specialized template functions.
2509   if (FromType->isInstantiationDependentType() &&
2510       !FromType->getAs<TemplateSpecializationType>()) {
2511     PDiag << ft_default;
2512     return;
2513   }
2514 
2515   // No extra info for same types.
2516   if (Context.hasSameType(FromType, ToType)) {
2517     PDiag << ft_default;
2518     return;
2519   }
2520 
2521   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2522                           *ToFunction = ToType->getAs<FunctionProtoType>();
2523 
2524   // Both types need to be function types.
2525   if (!FromFunction || !ToFunction) {
2526     PDiag << ft_default;
2527     return;
2528   }
2529 
2530   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2531     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2532           << FromFunction->getNumParams();
2533     return;
2534   }
2535 
2536   // Handle different parameter types.
2537   unsigned ArgPos;
2538   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2539     PDiag << ft_parameter_mismatch << ArgPos + 1
2540           << ToFunction->getParamType(ArgPos)
2541           << FromFunction->getParamType(ArgPos);
2542     return;
2543   }
2544 
2545   // Handle different return type.
2546   if (!Context.hasSameType(FromFunction->getReturnType(),
2547                            ToFunction->getReturnType())) {
2548     PDiag << ft_return_type << ToFunction->getReturnType()
2549           << FromFunction->getReturnType();
2550     return;
2551   }
2552 
2553   unsigned FromQuals = FromFunction->getTypeQuals(),
2554            ToQuals = ToFunction->getTypeQuals();
2555   if (FromQuals != ToQuals) {
2556     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2557     return;
2558   }
2559 
2560   // Unable to find a difference, so add no extra info.
2561   PDiag << ft_default;
2562 }
2563 
2564 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2565 /// for equality of their argument types. Caller has already checked that
2566 /// they have same number of arguments.  If the parameters are different,
2567 /// ArgPos will have the parameter index of the first different parameter.
2568 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2569                                       const FunctionProtoType *NewType,
2570                                       unsigned *ArgPos) {
2571   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2572                                               N = NewType->param_type_begin(),
2573                                               E = OldType->param_type_end();
2574        O && (O != E); ++O, ++N) {
2575     if (!Context.hasSameType(O->getUnqualifiedType(),
2576                              N->getUnqualifiedType())) {
2577       if (ArgPos)
2578         *ArgPos = O - OldType->param_type_begin();
2579       return false;
2580     }
2581   }
2582   return true;
2583 }
2584 
2585 /// CheckPointerConversion - Check the pointer conversion from the
2586 /// expression From to the type ToType. This routine checks for
2587 /// ambiguous or inaccessible derived-to-base pointer
2588 /// conversions for which IsPointerConversion has already returned
2589 /// true. It returns true and produces a diagnostic if there was an
2590 /// error, or returns false otherwise.
2591 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2592                                   CastKind &Kind,
2593                                   CXXCastPath& BasePath,
2594                                   bool IgnoreBaseAccess) {
2595   QualType FromType = From->getType();
2596   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2597 
2598   Kind = CK_BitCast;
2599 
2600   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2601       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2602       Expr::NPCK_ZeroExpression) {
2603     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2604       DiagRuntimeBehavior(From->getExprLoc(), From,
2605                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2606                             << ToType << From->getSourceRange());
2607     else if (!isUnevaluatedContext())
2608       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2609         << ToType << From->getSourceRange();
2610   }
2611   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2612     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2613       QualType FromPointeeType = FromPtrType->getPointeeType(),
2614                ToPointeeType   = ToPtrType->getPointeeType();
2615 
2616       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2617           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2618         // We must have a derived-to-base conversion. Check an
2619         // ambiguous or inaccessible conversion.
2620         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2621                                          From->getExprLoc(),
2622                                          From->getSourceRange(), &BasePath,
2623                                          IgnoreBaseAccess))
2624           return true;
2625 
2626         // The conversion was successful.
2627         Kind = CK_DerivedToBase;
2628       }
2629     }
2630   } else if (const ObjCObjectPointerType *ToPtrType =
2631                ToType->getAs<ObjCObjectPointerType>()) {
2632     if (const ObjCObjectPointerType *FromPtrType =
2633           FromType->getAs<ObjCObjectPointerType>()) {
2634       // Objective-C++ conversions are always okay.
2635       // FIXME: We should have a different class of conversions for the
2636       // Objective-C++ implicit conversions.
2637       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2638         return false;
2639     } else if (FromType->isBlockPointerType()) {
2640       Kind = CK_BlockPointerToObjCPointerCast;
2641     } else {
2642       Kind = CK_CPointerToObjCPointerCast;
2643     }
2644   } else if (ToType->isBlockPointerType()) {
2645     if (!FromType->isBlockPointerType())
2646       Kind = CK_AnyPointerToBlockPointerCast;
2647   }
2648 
2649   // We shouldn't fall into this case unless it's valid for other
2650   // reasons.
2651   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2652     Kind = CK_NullToPointer;
2653 
2654   return false;
2655 }
2656 
2657 /// IsMemberPointerConversion - Determines whether the conversion of the
2658 /// expression From, which has the (possibly adjusted) type FromType, can be
2659 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2660 /// If so, returns true and places the converted type (that might differ from
2661 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2662 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2663                                      QualType ToType,
2664                                      bool InOverloadResolution,
2665                                      QualType &ConvertedType) {
2666   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2667   if (!ToTypePtr)
2668     return false;
2669 
2670   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2671   if (From->isNullPointerConstant(Context,
2672                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2673                                         : Expr::NPC_ValueDependentIsNull)) {
2674     ConvertedType = ToType;
2675     return true;
2676   }
2677 
2678   // Otherwise, both types have to be member pointers.
2679   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2680   if (!FromTypePtr)
2681     return false;
2682 
2683   // A pointer to member of B can be converted to a pointer to member of D,
2684   // where D is derived from B (C++ 4.11p2).
2685   QualType FromClass(FromTypePtr->getClass(), 0);
2686   QualType ToClass(ToTypePtr->getClass(), 0);
2687 
2688   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2689       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2690       IsDerivedFrom(ToClass, FromClass)) {
2691     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2692                                                  ToClass.getTypePtr());
2693     return true;
2694   }
2695 
2696   return false;
2697 }
2698 
2699 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2700 /// expression From to the type ToType. This routine checks for ambiguous or
2701 /// virtual or inaccessible base-to-derived member pointer conversions
2702 /// for which IsMemberPointerConversion has already returned true. It returns
2703 /// true and produces a diagnostic if there was an error, or returns false
2704 /// otherwise.
2705 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2706                                         CastKind &Kind,
2707                                         CXXCastPath &BasePath,
2708                                         bool IgnoreBaseAccess) {
2709   QualType FromType = From->getType();
2710   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2711   if (!FromPtrType) {
2712     // This must be a null pointer to member pointer conversion
2713     assert(From->isNullPointerConstant(Context,
2714                                        Expr::NPC_ValueDependentIsNull) &&
2715            "Expr must be null pointer constant!");
2716     Kind = CK_NullToMemberPointer;
2717     return false;
2718   }
2719 
2720   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2721   assert(ToPtrType && "No member pointer cast has a target type "
2722                       "that is not a member pointer.");
2723 
2724   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2725   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2726 
2727   // FIXME: What about dependent types?
2728   assert(FromClass->isRecordType() && "Pointer into non-class.");
2729   assert(ToClass->isRecordType() && "Pointer into non-class.");
2730 
2731   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2732                      /*DetectVirtual=*/true);
2733   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2734   assert(DerivationOkay &&
2735          "Should not have been called if derivation isn't OK.");
2736   (void)DerivationOkay;
2737 
2738   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2739                                   getUnqualifiedType())) {
2740     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2741     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2742       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2743     return true;
2744   }
2745 
2746   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2747     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2748       << FromClass << ToClass << QualType(VBase, 0)
2749       << From->getSourceRange();
2750     return true;
2751   }
2752 
2753   if (!IgnoreBaseAccess)
2754     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2755                          Paths.front(),
2756                          diag::err_downcast_from_inaccessible_base);
2757 
2758   // Must be a base to derived member conversion.
2759   BuildBasePathArray(Paths, BasePath);
2760   Kind = CK_BaseToDerivedMemberPointer;
2761   return false;
2762 }
2763 
2764 /// Determine whether the lifetime conversion between the two given
2765 /// qualifiers sets is nontrivial.
2766 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2767                                                Qualifiers ToQuals) {
2768   // Converting anything to const __unsafe_unretained is trivial.
2769   if (ToQuals.hasConst() &&
2770       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2771     return false;
2772 
2773   return true;
2774 }
2775 
2776 /// IsQualificationConversion - Determines whether the conversion from
2777 /// an rvalue of type FromType to ToType is a qualification conversion
2778 /// (C++ 4.4).
2779 ///
2780 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2781 /// when the qualification conversion involves a change in the Objective-C
2782 /// object lifetime.
2783 bool
2784 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2785                                 bool CStyle, bool &ObjCLifetimeConversion) {
2786   FromType = Context.getCanonicalType(FromType);
2787   ToType = Context.getCanonicalType(ToType);
2788   ObjCLifetimeConversion = false;
2789 
2790   // If FromType and ToType are the same type, this is not a
2791   // qualification conversion.
2792   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2793     return false;
2794 
2795   // (C++ 4.4p4):
2796   //   A conversion can add cv-qualifiers at levels other than the first
2797   //   in multi-level pointers, subject to the following rules: [...]
2798   bool PreviousToQualsIncludeConst = true;
2799   bool UnwrappedAnyPointer = false;
2800   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2801     // Within each iteration of the loop, we check the qualifiers to
2802     // determine if this still looks like a qualification
2803     // conversion. Then, if all is well, we unwrap one more level of
2804     // pointers or pointers-to-members and do it all again
2805     // until there are no more pointers or pointers-to-members left to
2806     // unwrap.
2807     UnwrappedAnyPointer = true;
2808 
2809     Qualifiers FromQuals = FromType.getQualifiers();
2810     Qualifiers ToQuals = ToType.getQualifiers();
2811 
2812     // Objective-C ARC:
2813     //   Check Objective-C lifetime conversions.
2814     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2815         UnwrappedAnyPointer) {
2816       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2817         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2818           ObjCLifetimeConversion = true;
2819         FromQuals.removeObjCLifetime();
2820         ToQuals.removeObjCLifetime();
2821       } else {
2822         // Qualification conversions cannot cast between different
2823         // Objective-C lifetime qualifiers.
2824         return false;
2825       }
2826     }
2827 
2828     // Allow addition/removal of GC attributes but not changing GC attributes.
2829     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2830         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2831       FromQuals.removeObjCGCAttr();
2832       ToQuals.removeObjCGCAttr();
2833     }
2834 
2835     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2836     //      2,j, and similarly for volatile.
2837     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2838       return false;
2839 
2840     //   -- if the cv 1,j and cv 2,j are different, then const is in
2841     //      every cv for 0 < k < j.
2842     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2843         && !PreviousToQualsIncludeConst)
2844       return false;
2845 
2846     // Keep track of whether all prior cv-qualifiers in the "to" type
2847     // include const.
2848     PreviousToQualsIncludeConst
2849       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2850   }
2851 
2852   // We are left with FromType and ToType being the pointee types
2853   // after unwrapping the original FromType and ToType the same number
2854   // of types. If we unwrapped any pointers, and if FromType and
2855   // ToType have the same unqualified type (since we checked
2856   // qualifiers above), then this is a qualification conversion.
2857   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2858 }
2859 
2860 /// \brief - Determine whether this is a conversion from a scalar type to an
2861 /// atomic type.
2862 ///
2863 /// If successful, updates \c SCS's second and third steps in the conversion
2864 /// sequence to finish the conversion.
2865 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2866                                 bool InOverloadResolution,
2867                                 StandardConversionSequence &SCS,
2868                                 bool CStyle) {
2869   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2870   if (!ToAtomic)
2871     return false;
2872 
2873   StandardConversionSequence InnerSCS;
2874   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2875                             InOverloadResolution, InnerSCS,
2876                             CStyle, /*AllowObjCWritebackConversion=*/false))
2877     return false;
2878 
2879   SCS.Second = InnerSCS.Second;
2880   SCS.setToType(1, InnerSCS.getToType(1));
2881   SCS.Third = InnerSCS.Third;
2882   SCS.QualificationIncludesObjCLifetime
2883     = InnerSCS.QualificationIncludesObjCLifetime;
2884   SCS.setToType(2, InnerSCS.getToType(2));
2885   return true;
2886 }
2887 
2888 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2889                                               CXXConstructorDecl *Constructor,
2890                                               QualType Type) {
2891   const FunctionProtoType *CtorType =
2892       Constructor->getType()->getAs<FunctionProtoType>();
2893   if (CtorType->getNumParams() > 0) {
2894     QualType FirstArg = CtorType->getParamType(0);
2895     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2896       return true;
2897   }
2898   return false;
2899 }
2900 
2901 static OverloadingResult
2902 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2903                                        CXXRecordDecl *To,
2904                                        UserDefinedConversionSequence &User,
2905                                        OverloadCandidateSet &CandidateSet,
2906                                        bool AllowExplicit) {
2907   DeclContext::lookup_result R = S.LookupConstructors(To);
2908   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2909        Con != ConEnd; ++Con) {
2910     NamedDecl *D = *Con;
2911     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2912 
2913     // Find the constructor (which may be a template).
2914     CXXConstructorDecl *Constructor = nullptr;
2915     FunctionTemplateDecl *ConstructorTmpl
2916       = dyn_cast<FunctionTemplateDecl>(D);
2917     if (ConstructorTmpl)
2918       Constructor
2919         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2920     else
2921       Constructor = cast<CXXConstructorDecl>(D);
2922 
2923     bool Usable = !Constructor->isInvalidDecl() &&
2924                   S.isInitListConstructor(Constructor) &&
2925                   (AllowExplicit || !Constructor->isExplicit());
2926     if (Usable) {
2927       // If the first argument is (a reference to) the target type,
2928       // suppress conversions.
2929       bool SuppressUserConversions =
2930           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2931       if (ConstructorTmpl)
2932         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2933                                        /*ExplicitArgs*/ nullptr,
2934                                        From, CandidateSet,
2935                                        SuppressUserConversions);
2936       else
2937         S.AddOverloadCandidate(Constructor, FoundDecl,
2938                                From, CandidateSet,
2939                                SuppressUserConversions);
2940     }
2941   }
2942 
2943   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2944 
2945   OverloadCandidateSet::iterator Best;
2946   switch (auto Result =
2947             CandidateSet.BestViableFunction(S, From->getLocStart(),
2948                                             Best, true)) {
2949   case OR_Deleted:
2950   case OR_Success: {
2951     // Record the standard conversion we used and the conversion function.
2952     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2953     QualType ThisType = Constructor->getThisType(S.Context);
2954     // Initializer lists don't have conversions as such.
2955     User.Before.setAsIdentityConversion();
2956     User.HadMultipleCandidates = HadMultipleCandidates;
2957     User.ConversionFunction = Constructor;
2958     User.FoundConversionFunction = Best->FoundDecl;
2959     User.After.setAsIdentityConversion();
2960     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2961     User.After.setAllToTypes(ToType);
2962     return Result;
2963   }
2964 
2965   case OR_No_Viable_Function:
2966     return OR_No_Viable_Function;
2967   case OR_Ambiguous:
2968     return OR_Ambiguous;
2969   }
2970 
2971   llvm_unreachable("Invalid OverloadResult!");
2972 }
2973 
2974 /// Determines whether there is a user-defined conversion sequence
2975 /// (C++ [over.ics.user]) that converts expression From to the type
2976 /// ToType. If such a conversion exists, User will contain the
2977 /// user-defined conversion sequence that performs such a conversion
2978 /// and this routine will return true. Otherwise, this routine returns
2979 /// false and User is unspecified.
2980 ///
2981 /// \param AllowExplicit  true if the conversion should consider C++0x
2982 /// "explicit" conversion functions as well as non-explicit conversion
2983 /// functions (C++0x [class.conv.fct]p2).
2984 ///
2985 /// \param AllowObjCConversionOnExplicit true if the conversion should
2986 /// allow an extra Objective-C pointer conversion on uses of explicit
2987 /// constructors. Requires \c AllowExplicit to also be set.
2988 static OverloadingResult
2989 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2990                         UserDefinedConversionSequence &User,
2991                         OverloadCandidateSet &CandidateSet,
2992                         bool AllowExplicit,
2993                         bool AllowObjCConversionOnExplicit) {
2994   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
2995 
2996   // Whether we will only visit constructors.
2997   bool ConstructorsOnly = false;
2998 
2999   // If the type we are conversion to is a class type, enumerate its
3000   // constructors.
3001   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3002     // C++ [over.match.ctor]p1:
3003     //   When objects of class type are direct-initialized (8.5), or
3004     //   copy-initialized from an expression of the same or a
3005     //   derived class type (8.5), overload resolution selects the
3006     //   constructor. [...] For copy-initialization, the candidate
3007     //   functions are all the converting constructors (12.3.1) of
3008     //   that class. The argument list is the expression-list within
3009     //   the parentheses of the initializer.
3010     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3011         (From->getType()->getAs<RecordType>() &&
3012          S.IsDerivedFrom(From->getType(), ToType)))
3013       ConstructorsOnly = true;
3014 
3015     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3016     // RequireCompleteType may have returned true due to some invalid decl
3017     // during template instantiation, but ToType may be complete enough now
3018     // to try to recover.
3019     if (ToType->isIncompleteType()) {
3020       // We're not going to find any constructors.
3021     } else if (CXXRecordDecl *ToRecordDecl
3022                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3023 
3024       Expr **Args = &From;
3025       unsigned NumArgs = 1;
3026       bool ListInitializing = false;
3027       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3028         // But first, see if there is an init-list-constructor that will work.
3029         OverloadingResult Result = IsInitializerListConstructorConversion(
3030             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3031         if (Result != OR_No_Viable_Function)
3032           return Result;
3033         // Never mind.
3034         CandidateSet.clear();
3035 
3036         // If we're list-initializing, we pass the individual elements as
3037         // arguments, not the entire list.
3038         Args = InitList->getInits();
3039         NumArgs = InitList->getNumInits();
3040         ListInitializing = true;
3041       }
3042 
3043       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3044       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3045            Con != ConEnd; ++Con) {
3046         NamedDecl *D = *Con;
3047         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3048 
3049         // Find the constructor (which may be a template).
3050         CXXConstructorDecl *Constructor = nullptr;
3051         FunctionTemplateDecl *ConstructorTmpl
3052           = dyn_cast<FunctionTemplateDecl>(D);
3053         if (ConstructorTmpl)
3054           Constructor
3055             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3056         else
3057           Constructor = cast<CXXConstructorDecl>(D);
3058 
3059         bool Usable = !Constructor->isInvalidDecl();
3060         if (ListInitializing)
3061           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3062         else
3063           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3064         if (Usable) {
3065           bool SuppressUserConversions = !ConstructorsOnly;
3066           if (SuppressUserConversions && ListInitializing) {
3067             SuppressUserConversions = false;
3068             if (NumArgs == 1) {
3069               // If the first argument is (a reference to) the target type,
3070               // suppress conversions.
3071               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3072                                                 S.Context, Constructor, ToType);
3073             }
3074           }
3075           if (ConstructorTmpl)
3076             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3077                                            /*ExplicitArgs*/ nullptr,
3078                                            llvm::makeArrayRef(Args, NumArgs),
3079                                            CandidateSet, SuppressUserConversions);
3080           else
3081             // Allow one user-defined conversion when user specifies a
3082             // From->ToType conversion via an static cast (c-style, etc).
3083             S.AddOverloadCandidate(Constructor, FoundDecl,
3084                                    llvm::makeArrayRef(Args, NumArgs),
3085                                    CandidateSet, SuppressUserConversions);
3086         }
3087       }
3088     }
3089   }
3090 
3091   // Enumerate conversion functions, if we're allowed to.
3092   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3093   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3094     // No conversion functions from incomplete types.
3095   } else if (const RecordType *FromRecordType
3096                                    = From->getType()->getAs<RecordType>()) {
3097     if (CXXRecordDecl *FromRecordDecl
3098          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3099       // Add all of the conversion functions as candidates.
3100       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3101       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3102         DeclAccessPair FoundDecl = I.getPair();
3103         NamedDecl *D = FoundDecl.getDecl();
3104         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3105         if (isa<UsingShadowDecl>(D))
3106           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3107 
3108         CXXConversionDecl *Conv;
3109         FunctionTemplateDecl *ConvTemplate;
3110         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3111           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3112         else
3113           Conv = cast<CXXConversionDecl>(D);
3114 
3115         if (AllowExplicit || !Conv->isExplicit()) {
3116           if (ConvTemplate)
3117             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3118                                              ActingContext, From, ToType,
3119                                              CandidateSet,
3120                                              AllowObjCConversionOnExplicit);
3121           else
3122             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3123                                      From, ToType, CandidateSet,
3124                                      AllowObjCConversionOnExplicit);
3125         }
3126       }
3127     }
3128   }
3129 
3130   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3131 
3132   OverloadCandidateSet::iterator Best;
3133   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3134                                                         Best, true)) {
3135   case OR_Success:
3136   case OR_Deleted:
3137     // Record the standard conversion we used and the conversion function.
3138     if (CXXConstructorDecl *Constructor
3139           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3140       // C++ [over.ics.user]p1:
3141       //   If the user-defined conversion is specified by a
3142       //   constructor (12.3.1), the initial standard conversion
3143       //   sequence converts the source type to the type required by
3144       //   the argument of the constructor.
3145       //
3146       QualType ThisType = Constructor->getThisType(S.Context);
3147       if (isa<InitListExpr>(From)) {
3148         // Initializer lists don't have conversions as such.
3149         User.Before.setAsIdentityConversion();
3150       } else {
3151         if (Best->Conversions[0].isEllipsis())
3152           User.EllipsisConversion = true;
3153         else {
3154           User.Before = Best->Conversions[0].Standard;
3155           User.EllipsisConversion = false;
3156         }
3157       }
3158       User.HadMultipleCandidates = HadMultipleCandidates;
3159       User.ConversionFunction = Constructor;
3160       User.FoundConversionFunction = Best->FoundDecl;
3161       User.After.setAsIdentityConversion();
3162       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3163       User.After.setAllToTypes(ToType);
3164       return Result;
3165     }
3166     if (CXXConversionDecl *Conversion
3167                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3168       // C++ [over.ics.user]p1:
3169       //
3170       //   [...] If the user-defined conversion is specified by a
3171       //   conversion function (12.3.2), the initial standard
3172       //   conversion sequence converts the source type to the
3173       //   implicit object parameter of the conversion function.
3174       User.Before = Best->Conversions[0].Standard;
3175       User.HadMultipleCandidates = HadMultipleCandidates;
3176       User.ConversionFunction = Conversion;
3177       User.FoundConversionFunction = Best->FoundDecl;
3178       User.EllipsisConversion = false;
3179 
3180       // C++ [over.ics.user]p2:
3181       //   The second standard conversion sequence converts the
3182       //   result of the user-defined conversion to the target type
3183       //   for the sequence. Since an implicit conversion sequence
3184       //   is an initialization, the special rules for
3185       //   initialization by user-defined conversion apply when
3186       //   selecting the best user-defined conversion for a
3187       //   user-defined conversion sequence (see 13.3.3 and
3188       //   13.3.3.1).
3189       User.After = Best->FinalConversion;
3190       return Result;
3191     }
3192     llvm_unreachable("Not a constructor or conversion function?");
3193 
3194   case OR_No_Viable_Function:
3195     return OR_No_Viable_Function;
3196 
3197   case OR_Ambiguous:
3198     return OR_Ambiguous;
3199   }
3200 
3201   llvm_unreachable("Invalid OverloadResult!");
3202 }
3203 
3204 bool
3205 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3206   ImplicitConversionSequence ICS;
3207   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3208                                     OverloadCandidateSet::CSK_Normal);
3209   OverloadingResult OvResult =
3210     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3211                             CandidateSet, false, false);
3212   if (OvResult == OR_Ambiguous)
3213     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3214         << From->getType() << ToType << From->getSourceRange();
3215   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3216     if (!RequireCompleteType(From->getLocStart(), ToType,
3217                              diag::err_typecheck_nonviable_condition_incomplete,
3218                              From->getType(), From->getSourceRange()))
3219       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3220           << false << From->getType() << From->getSourceRange() << ToType;
3221   } else
3222     return false;
3223   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3224   return true;
3225 }
3226 
3227 /// \brief Compare the user-defined conversion functions or constructors
3228 /// of two user-defined conversion sequences to determine whether any ordering
3229 /// is possible.
3230 static ImplicitConversionSequence::CompareKind
3231 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3232                            FunctionDecl *Function2) {
3233   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3234     return ImplicitConversionSequence::Indistinguishable;
3235 
3236   // Objective-C++:
3237   //   If both conversion functions are implicitly-declared conversions from
3238   //   a lambda closure type to a function pointer and a block pointer,
3239   //   respectively, always prefer the conversion to a function pointer,
3240   //   because the function pointer is more lightweight and is more likely
3241   //   to keep code working.
3242   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3243   if (!Conv1)
3244     return ImplicitConversionSequence::Indistinguishable;
3245 
3246   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247   if (!Conv2)
3248     return ImplicitConversionSequence::Indistinguishable;
3249 
3250   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253     if (Block1 != Block2)
3254       return Block1 ? ImplicitConversionSequence::Worse
3255                     : ImplicitConversionSequence::Better;
3256   }
3257 
3258   return ImplicitConversionSequence::Indistinguishable;
3259 }
3260 
3261 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3262     const ImplicitConversionSequence &ICS) {
3263   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3264          (ICS.isUserDefined() &&
3265           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3266 }
3267 
3268 /// CompareImplicitConversionSequences - Compare two implicit
3269 /// conversion sequences to determine whether one is better than the
3270 /// other or if they are indistinguishable (C++ 13.3.3.2).
3271 static ImplicitConversionSequence::CompareKind
3272 CompareImplicitConversionSequences(Sema &S,
3273                                    const ImplicitConversionSequence& ICS1,
3274                                    const ImplicitConversionSequence& ICS2)
3275 {
3276   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3277   // conversion sequences (as defined in 13.3.3.1)
3278   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3279   //      conversion sequence than a user-defined conversion sequence or
3280   //      an ellipsis conversion sequence, and
3281   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3282   //      conversion sequence than an ellipsis conversion sequence
3283   //      (13.3.3.1.3).
3284   //
3285   // C++0x [over.best.ics]p10:
3286   //   For the purpose of ranking implicit conversion sequences as
3287   //   described in 13.3.3.2, the ambiguous conversion sequence is
3288   //   treated as a user-defined sequence that is indistinguishable
3289   //   from any other user-defined conversion sequence.
3290 
3291   // String literal to 'char *' conversion has been deprecated in C++03. It has
3292   // been removed from C++11. We still accept this conversion, if it happens at
3293   // the best viable function. Otherwise, this conversion is considered worse
3294   // than ellipsis conversion. Consider this as an extension; this is not in the
3295   // standard. For example:
3296   //
3297   // int &f(...);    // #1
3298   // void f(char*);  // #2
3299   // void g() { int &r = f("foo"); }
3300   //
3301   // In C++03, we pick #2 as the best viable function.
3302   // In C++11, we pick #1 as the best viable function, because ellipsis
3303   // conversion is better than string-literal to char* conversion (since there
3304   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3305   // convert arguments, #2 would be the best viable function in C++11.
3306   // If the best viable function has this conversion, a warning will be issued
3307   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3308 
3309   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3310       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3311       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3312     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3313                ? ImplicitConversionSequence::Worse
3314                : ImplicitConversionSequence::Better;
3315 
3316   if (ICS1.getKindRank() < ICS2.getKindRank())
3317     return ImplicitConversionSequence::Better;
3318   if (ICS2.getKindRank() < ICS1.getKindRank())
3319     return ImplicitConversionSequence::Worse;
3320 
3321   // The following checks require both conversion sequences to be of
3322   // the same kind.
3323   if (ICS1.getKind() != ICS2.getKind())
3324     return ImplicitConversionSequence::Indistinguishable;
3325 
3326   ImplicitConversionSequence::CompareKind Result =
3327       ImplicitConversionSequence::Indistinguishable;
3328 
3329   // Two implicit conversion sequences of the same form are
3330   // indistinguishable conversion sequences unless one of the
3331   // following rules apply: (C++ 13.3.3.2p3):
3332 
3333   // List-initialization sequence L1 is a better conversion sequence than
3334   // list-initialization sequence L2 if:
3335   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3336   //   if not that,
3337   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3338   //   and N1 is smaller than N2.,
3339   // even if one of the other rules in this paragraph would otherwise apply.
3340   if (!ICS1.isBad()) {
3341     if (ICS1.isStdInitializerListElement() &&
3342         !ICS2.isStdInitializerListElement())
3343       return ImplicitConversionSequence::Better;
3344     if (!ICS1.isStdInitializerListElement() &&
3345         ICS2.isStdInitializerListElement())
3346       return ImplicitConversionSequence::Worse;
3347   }
3348 
3349   if (ICS1.isStandard())
3350     // Standard conversion sequence S1 is a better conversion sequence than
3351     // standard conversion sequence S2 if [...]
3352     Result = CompareStandardConversionSequences(S,
3353                                                 ICS1.Standard, ICS2.Standard);
3354   else if (ICS1.isUserDefined()) {
3355     // User-defined conversion sequence U1 is a better conversion
3356     // sequence than another user-defined conversion sequence U2 if
3357     // they contain the same user-defined conversion function or
3358     // constructor and if the second standard conversion sequence of
3359     // U1 is better than the second standard conversion sequence of
3360     // U2 (C++ 13.3.3.2p3).
3361     if (ICS1.UserDefined.ConversionFunction ==
3362           ICS2.UserDefined.ConversionFunction)
3363       Result = CompareStandardConversionSequences(S,
3364                                                   ICS1.UserDefined.After,
3365                                                   ICS2.UserDefined.After);
3366     else
3367       Result = compareConversionFunctions(S,
3368                                           ICS1.UserDefined.ConversionFunction,
3369                                           ICS2.UserDefined.ConversionFunction);
3370   }
3371 
3372   return Result;
3373 }
3374 
3375 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3376   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3377     Qualifiers Quals;
3378     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3379     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3380   }
3381 
3382   return Context.hasSameUnqualifiedType(T1, T2);
3383 }
3384 
3385 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3386 // determine if one is a proper subset of the other.
3387 static ImplicitConversionSequence::CompareKind
3388 compareStandardConversionSubsets(ASTContext &Context,
3389                                  const StandardConversionSequence& SCS1,
3390                                  const StandardConversionSequence& SCS2) {
3391   ImplicitConversionSequence::CompareKind Result
3392     = ImplicitConversionSequence::Indistinguishable;
3393 
3394   // the identity conversion sequence is considered to be a subsequence of
3395   // any non-identity conversion sequence
3396   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3397     return ImplicitConversionSequence::Better;
3398   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3399     return ImplicitConversionSequence::Worse;
3400 
3401   if (SCS1.Second != SCS2.Second) {
3402     if (SCS1.Second == ICK_Identity)
3403       Result = ImplicitConversionSequence::Better;
3404     else if (SCS2.Second == ICK_Identity)
3405       Result = ImplicitConversionSequence::Worse;
3406     else
3407       return ImplicitConversionSequence::Indistinguishable;
3408   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3409     return ImplicitConversionSequence::Indistinguishable;
3410 
3411   if (SCS1.Third == SCS2.Third) {
3412     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3413                              : ImplicitConversionSequence::Indistinguishable;
3414   }
3415 
3416   if (SCS1.Third == ICK_Identity)
3417     return Result == ImplicitConversionSequence::Worse
3418              ? ImplicitConversionSequence::Indistinguishable
3419              : ImplicitConversionSequence::Better;
3420 
3421   if (SCS2.Third == ICK_Identity)
3422     return Result == ImplicitConversionSequence::Better
3423              ? ImplicitConversionSequence::Indistinguishable
3424              : ImplicitConversionSequence::Worse;
3425 
3426   return ImplicitConversionSequence::Indistinguishable;
3427 }
3428 
3429 /// \brief Determine whether one of the given reference bindings is better
3430 /// than the other based on what kind of bindings they are.
3431 static bool
3432 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3433                              const StandardConversionSequence &SCS2) {
3434   // C++0x [over.ics.rank]p3b4:
3435   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3436   //      implicit object parameter of a non-static member function declared
3437   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3438   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3439   //      lvalue reference to a function lvalue and S2 binds an rvalue
3440   //      reference*.
3441   //
3442   // FIXME: Rvalue references. We're going rogue with the above edits,
3443   // because the semantics in the current C++0x working paper (N3225 at the
3444   // time of this writing) break the standard definition of std::forward
3445   // and std::reference_wrapper when dealing with references to functions.
3446   // Proposed wording changes submitted to CWG for consideration.
3447   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3448       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3449     return false;
3450 
3451   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3452           SCS2.IsLvalueReference) ||
3453          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3454           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3455 }
3456 
3457 /// CompareStandardConversionSequences - Compare two standard
3458 /// conversion sequences to determine whether one is better than the
3459 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3460 static ImplicitConversionSequence::CompareKind
3461 CompareStandardConversionSequences(Sema &S,
3462                                    const StandardConversionSequence& SCS1,
3463                                    const StandardConversionSequence& SCS2)
3464 {
3465   // Standard conversion sequence S1 is a better conversion sequence
3466   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3467 
3468   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3469   //     sequences in the canonical form defined by 13.3.3.1.1,
3470   //     excluding any Lvalue Transformation; the identity conversion
3471   //     sequence is considered to be a subsequence of any
3472   //     non-identity conversion sequence) or, if not that,
3473   if (ImplicitConversionSequence::CompareKind CK
3474         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3475     return CK;
3476 
3477   //  -- the rank of S1 is better than the rank of S2 (by the rules
3478   //     defined below), or, if not that,
3479   ImplicitConversionRank Rank1 = SCS1.getRank();
3480   ImplicitConversionRank Rank2 = SCS2.getRank();
3481   if (Rank1 < Rank2)
3482     return ImplicitConversionSequence::Better;
3483   else if (Rank2 < Rank1)
3484     return ImplicitConversionSequence::Worse;
3485 
3486   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3487   // are indistinguishable unless one of the following rules
3488   // applies:
3489 
3490   //   A conversion that is not a conversion of a pointer, or
3491   //   pointer to member, to bool is better than another conversion
3492   //   that is such a conversion.
3493   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3494     return SCS2.isPointerConversionToBool()
3495              ? ImplicitConversionSequence::Better
3496              : ImplicitConversionSequence::Worse;
3497 
3498   // C++ [over.ics.rank]p4b2:
3499   //
3500   //   If class B is derived directly or indirectly from class A,
3501   //   conversion of B* to A* is better than conversion of B* to
3502   //   void*, and conversion of A* to void* is better than conversion
3503   //   of B* to void*.
3504   bool SCS1ConvertsToVoid
3505     = SCS1.isPointerConversionToVoidPointer(S.Context);
3506   bool SCS2ConvertsToVoid
3507     = SCS2.isPointerConversionToVoidPointer(S.Context);
3508   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3509     // Exactly one of the conversion sequences is a conversion to
3510     // a void pointer; it's the worse conversion.
3511     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3512                               : ImplicitConversionSequence::Worse;
3513   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3514     // Neither conversion sequence converts to a void pointer; compare
3515     // their derived-to-base conversions.
3516     if (ImplicitConversionSequence::CompareKind DerivedCK
3517           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3518       return DerivedCK;
3519   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3520              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3521     // Both conversion sequences are conversions to void
3522     // pointers. Compare the source types to determine if there's an
3523     // inheritance relationship in their sources.
3524     QualType FromType1 = SCS1.getFromType();
3525     QualType FromType2 = SCS2.getFromType();
3526 
3527     // Adjust the types we're converting from via the array-to-pointer
3528     // conversion, if we need to.
3529     if (SCS1.First == ICK_Array_To_Pointer)
3530       FromType1 = S.Context.getArrayDecayedType(FromType1);
3531     if (SCS2.First == ICK_Array_To_Pointer)
3532       FromType2 = S.Context.getArrayDecayedType(FromType2);
3533 
3534     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3535     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3536 
3537     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3538       return ImplicitConversionSequence::Better;
3539     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3540       return ImplicitConversionSequence::Worse;
3541 
3542     // Objective-C++: If one interface is more specific than the
3543     // other, it is the better one.
3544     const ObjCObjectPointerType* FromObjCPtr1
3545       = FromType1->getAs<ObjCObjectPointerType>();
3546     const ObjCObjectPointerType* FromObjCPtr2
3547       = FromType2->getAs<ObjCObjectPointerType>();
3548     if (FromObjCPtr1 && FromObjCPtr2) {
3549       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3550                                                           FromObjCPtr2);
3551       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3552                                                            FromObjCPtr1);
3553       if (AssignLeft != AssignRight) {
3554         return AssignLeft? ImplicitConversionSequence::Better
3555                          : ImplicitConversionSequence::Worse;
3556       }
3557     }
3558   }
3559 
3560   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3561   // bullet 3).
3562   if (ImplicitConversionSequence::CompareKind QualCK
3563         = CompareQualificationConversions(S, SCS1, SCS2))
3564     return QualCK;
3565 
3566   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3567     // Check for a better reference binding based on the kind of bindings.
3568     if (isBetterReferenceBindingKind(SCS1, SCS2))
3569       return ImplicitConversionSequence::Better;
3570     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3571       return ImplicitConversionSequence::Worse;
3572 
3573     // C++ [over.ics.rank]p3b4:
3574     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3575     //      which the references refer are the same type except for
3576     //      top-level cv-qualifiers, and the type to which the reference
3577     //      initialized by S2 refers is more cv-qualified than the type
3578     //      to which the reference initialized by S1 refers.
3579     QualType T1 = SCS1.getToType(2);
3580     QualType T2 = SCS2.getToType(2);
3581     T1 = S.Context.getCanonicalType(T1);
3582     T2 = S.Context.getCanonicalType(T2);
3583     Qualifiers T1Quals, T2Quals;
3584     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3585     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3586     if (UnqualT1 == UnqualT2) {
3587       // Objective-C++ ARC: If the references refer to objects with different
3588       // lifetimes, prefer bindings that don't change lifetime.
3589       if (SCS1.ObjCLifetimeConversionBinding !=
3590                                           SCS2.ObjCLifetimeConversionBinding) {
3591         return SCS1.ObjCLifetimeConversionBinding
3592                                            ? ImplicitConversionSequence::Worse
3593                                            : ImplicitConversionSequence::Better;
3594       }
3595 
3596       // If the type is an array type, promote the element qualifiers to the
3597       // type for comparison.
3598       if (isa<ArrayType>(T1) && T1Quals)
3599         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3600       if (isa<ArrayType>(T2) && T2Quals)
3601         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3602       if (T2.isMoreQualifiedThan(T1))
3603         return ImplicitConversionSequence::Better;
3604       else if (T1.isMoreQualifiedThan(T2))
3605         return ImplicitConversionSequence::Worse;
3606     }
3607   }
3608 
3609   // In Microsoft mode, prefer an integral conversion to a
3610   // floating-to-integral conversion if the integral conversion
3611   // is between types of the same size.
3612   // For example:
3613   // void f(float);
3614   // void f(int);
3615   // int main {
3616   //    long a;
3617   //    f(a);
3618   // }
3619   // Here, MSVC will call f(int) instead of generating a compile error
3620   // as clang will do in standard mode.
3621   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3622       SCS2.Second == ICK_Floating_Integral &&
3623       S.Context.getTypeSize(SCS1.getFromType()) ==
3624           S.Context.getTypeSize(SCS1.getToType(2)))
3625     return ImplicitConversionSequence::Better;
3626 
3627   return ImplicitConversionSequence::Indistinguishable;
3628 }
3629 
3630 /// CompareQualificationConversions - Compares two standard conversion
3631 /// sequences to determine whether they can be ranked based on their
3632 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3633 static ImplicitConversionSequence::CompareKind
3634 CompareQualificationConversions(Sema &S,
3635                                 const StandardConversionSequence& SCS1,
3636                                 const StandardConversionSequence& SCS2) {
3637   // C++ 13.3.3.2p3:
3638   //  -- S1 and S2 differ only in their qualification conversion and
3639   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3640   //     cv-qualification signature of type T1 is a proper subset of
3641   //     the cv-qualification signature of type T2, and S1 is not the
3642   //     deprecated string literal array-to-pointer conversion (4.2).
3643   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3644       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3645     return ImplicitConversionSequence::Indistinguishable;
3646 
3647   // FIXME: the example in the standard doesn't use a qualification
3648   // conversion (!)
3649   QualType T1 = SCS1.getToType(2);
3650   QualType T2 = SCS2.getToType(2);
3651   T1 = S.Context.getCanonicalType(T1);
3652   T2 = S.Context.getCanonicalType(T2);
3653   Qualifiers T1Quals, T2Quals;
3654   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3655   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3656 
3657   // If the types are the same, we won't learn anything by unwrapped
3658   // them.
3659   if (UnqualT1 == UnqualT2)
3660     return ImplicitConversionSequence::Indistinguishable;
3661 
3662   // If the type is an array type, promote the element qualifiers to the type
3663   // for comparison.
3664   if (isa<ArrayType>(T1) && T1Quals)
3665     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3666   if (isa<ArrayType>(T2) && T2Quals)
3667     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3668 
3669   ImplicitConversionSequence::CompareKind Result
3670     = ImplicitConversionSequence::Indistinguishable;
3671 
3672   // Objective-C++ ARC:
3673   //   Prefer qualification conversions not involving a change in lifetime
3674   //   to qualification conversions that do not change lifetime.
3675   if (SCS1.QualificationIncludesObjCLifetime !=
3676                                       SCS2.QualificationIncludesObjCLifetime) {
3677     Result = SCS1.QualificationIncludesObjCLifetime
3678                ? ImplicitConversionSequence::Worse
3679                : ImplicitConversionSequence::Better;
3680   }
3681 
3682   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3683     // Within each iteration of the loop, we check the qualifiers to
3684     // determine if this still looks like a qualification
3685     // conversion. Then, if all is well, we unwrap one more level of
3686     // pointers or pointers-to-members and do it all again
3687     // until there are no more pointers or pointers-to-members left
3688     // to unwrap. This essentially mimics what
3689     // IsQualificationConversion does, but here we're checking for a
3690     // strict subset of qualifiers.
3691     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3692       // The qualifiers are the same, so this doesn't tell us anything
3693       // about how the sequences rank.
3694       ;
3695     else if (T2.isMoreQualifiedThan(T1)) {
3696       // T1 has fewer qualifiers, so it could be the better sequence.
3697       if (Result == ImplicitConversionSequence::Worse)
3698         // Neither has qualifiers that are a subset of the other's
3699         // qualifiers.
3700         return ImplicitConversionSequence::Indistinguishable;
3701 
3702       Result = ImplicitConversionSequence::Better;
3703     } else if (T1.isMoreQualifiedThan(T2)) {
3704       // T2 has fewer qualifiers, so it could be the better sequence.
3705       if (Result == ImplicitConversionSequence::Better)
3706         // Neither has qualifiers that are a subset of the other's
3707         // qualifiers.
3708         return ImplicitConversionSequence::Indistinguishable;
3709 
3710       Result = ImplicitConversionSequence::Worse;
3711     } else {
3712       // Qualifiers are disjoint.
3713       return ImplicitConversionSequence::Indistinguishable;
3714     }
3715 
3716     // If the types after this point are equivalent, we're done.
3717     if (S.Context.hasSameUnqualifiedType(T1, T2))
3718       break;
3719   }
3720 
3721   // Check that the winning standard conversion sequence isn't using
3722   // the deprecated string literal array to pointer conversion.
3723   switch (Result) {
3724   case ImplicitConversionSequence::Better:
3725     if (SCS1.DeprecatedStringLiteralToCharPtr)
3726       Result = ImplicitConversionSequence::Indistinguishable;
3727     break;
3728 
3729   case ImplicitConversionSequence::Indistinguishable:
3730     break;
3731 
3732   case ImplicitConversionSequence::Worse:
3733     if (SCS2.DeprecatedStringLiteralToCharPtr)
3734       Result = ImplicitConversionSequence::Indistinguishable;
3735     break;
3736   }
3737 
3738   return Result;
3739 }
3740 
3741 /// CompareDerivedToBaseConversions - Compares two standard conversion
3742 /// sequences to determine whether they can be ranked based on their
3743 /// various kinds of derived-to-base conversions (C++
3744 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3745 /// conversions between Objective-C interface types.
3746 static ImplicitConversionSequence::CompareKind
3747 CompareDerivedToBaseConversions(Sema &S,
3748                                 const StandardConversionSequence& SCS1,
3749                                 const StandardConversionSequence& SCS2) {
3750   QualType FromType1 = SCS1.getFromType();
3751   QualType ToType1 = SCS1.getToType(1);
3752   QualType FromType2 = SCS2.getFromType();
3753   QualType ToType2 = SCS2.getToType(1);
3754 
3755   // Adjust the types we're converting from via the array-to-pointer
3756   // conversion, if we need to.
3757   if (SCS1.First == ICK_Array_To_Pointer)
3758     FromType1 = S.Context.getArrayDecayedType(FromType1);
3759   if (SCS2.First == ICK_Array_To_Pointer)
3760     FromType2 = S.Context.getArrayDecayedType(FromType2);
3761 
3762   // Canonicalize all of the types.
3763   FromType1 = S.Context.getCanonicalType(FromType1);
3764   ToType1 = S.Context.getCanonicalType(ToType1);
3765   FromType2 = S.Context.getCanonicalType(FromType2);
3766   ToType2 = S.Context.getCanonicalType(ToType2);
3767 
3768   // C++ [over.ics.rank]p4b3:
3769   //
3770   //   If class B is derived directly or indirectly from class A and
3771   //   class C is derived directly or indirectly from B,
3772   //
3773   // Compare based on pointer conversions.
3774   if (SCS1.Second == ICK_Pointer_Conversion &&
3775       SCS2.Second == ICK_Pointer_Conversion &&
3776       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3777       FromType1->isPointerType() && FromType2->isPointerType() &&
3778       ToType1->isPointerType() && ToType2->isPointerType()) {
3779     QualType FromPointee1
3780       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781     QualType ToPointee1
3782       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3783     QualType FromPointee2
3784       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3785     QualType ToPointee2
3786       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3787 
3788     //   -- conversion of C* to B* is better than conversion of C* to A*,
3789     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3790       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3791         return ImplicitConversionSequence::Better;
3792       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3793         return ImplicitConversionSequence::Worse;
3794     }
3795 
3796     //   -- conversion of B* to A* is better than conversion of C* to A*,
3797     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3798       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3799         return ImplicitConversionSequence::Better;
3800       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3801         return ImplicitConversionSequence::Worse;
3802     }
3803   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3804              SCS2.Second == ICK_Pointer_Conversion) {
3805     const ObjCObjectPointerType *FromPtr1
3806       = FromType1->getAs<ObjCObjectPointerType>();
3807     const ObjCObjectPointerType *FromPtr2
3808       = FromType2->getAs<ObjCObjectPointerType>();
3809     const ObjCObjectPointerType *ToPtr1
3810       = ToType1->getAs<ObjCObjectPointerType>();
3811     const ObjCObjectPointerType *ToPtr2
3812       = ToType2->getAs<ObjCObjectPointerType>();
3813 
3814     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3815       // Apply the same conversion ranking rules for Objective-C pointer types
3816       // that we do for C++ pointers to class types. However, we employ the
3817       // Objective-C pseudo-subtyping relationship used for assignment of
3818       // Objective-C pointer types.
3819       bool FromAssignLeft
3820         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3821       bool FromAssignRight
3822         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3823       bool ToAssignLeft
3824         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3825       bool ToAssignRight
3826         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3827 
3828       // A conversion to an a non-id object pointer type or qualified 'id'
3829       // type is better than a conversion to 'id'.
3830       if (ToPtr1->isObjCIdType() &&
3831           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3832         return ImplicitConversionSequence::Worse;
3833       if (ToPtr2->isObjCIdType() &&
3834           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3835         return ImplicitConversionSequence::Better;
3836 
3837       // A conversion to a non-id object pointer type is better than a
3838       // conversion to a qualified 'id' type
3839       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3840         return ImplicitConversionSequence::Worse;
3841       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3842         return ImplicitConversionSequence::Better;
3843 
3844       // A conversion to an a non-Class object pointer type or qualified 'Class'
3845       // type is better than a conversion to 'Class'.
3846       if (ToPtr1->isObjCClassType() &&
3847           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3848         return ImplicitConversionSequence::Worse;
3849       if (ToPtr2->isObjCClassType() &&
3850           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3851         return ImplicitConversionSequence::Better;
3852 
3853       // A conversion to a non-Class object pointer type is better than a
3854       // conversion to a qualified 'Class' type.
3855       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3856         return ImplicitConversionSequence::Worse;
3857       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3858         return ImplicitConversionSequence::Better;
3859 
3860       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3861       if (S.Context.hasSameType(FromType1, FromType2) &&
3862           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3863           (ToAssignLeft != ToAssignRight))
3864         return ToAssignLeft? ImplicitConversionSequence::Worse
3865                            : ImplicitConversionSequence::Better;
3866 
3867       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3868       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3869           (FromAssignLeft != FromAssignRight))
3870         return FromAssignLeft? ImplicitConversionSequence::Better
3871         : ImplicitConversionSequence::Worse;
3872     }
3873   }
3874 
3875   // Ranking of member-pointer types.
3876   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3877       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3878       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3879     const MemberPointerType * FromMemPointer1 =
3880                                         FromType1->getAs<MemberPointerType>();
3881     const MemberPointerType * ToMemPointer1 =
3882                                           ToType1->getAs<MemberPointerType>();
3883     const MemberPointerType * FromMemPointer2 =
3884                                           FromType2->getAs<MemberPointerType>();
3885     const MemberPointerType * ToMemPointer2 =
3886                                           ToType2->getAs<MemberPointerType>();
3887     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3888     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3889     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3890     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3891     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3892     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3893     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3894     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3895     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3896     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3897       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3898         return ImplicitConversionSequence::Worse;
3899       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3900         return ImplicitConversionSequence::Better;
3901     }
3902     // conversion of B::* to C::* is better than conversion of A::* to C::*
3903     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3904       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3905         return ImplicitConversionSequence::Better;
3906       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3907         return ImplicitConversionSequence::Worse;
3908     }
3909   }
3910 
3911   if (SCS1.Second == ICK_Derived_To_Base) {
3912     //   -- conversion of C to B is better than conversion of C to A,
3913     //   -- binding of an expression of type C to a reference of type
3914     //      B& is better than binding an expression of type C to a
3915     //      reference of type A&,
3916     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3917         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3918       if (S.IsDerivedFrom(ToType1, ToType2))
3919         return ImplicitConversionSequence::Better;
3920       else if (S.IsDerivedFrom(ToType2, ToType1))
3921         return ImplicitConversionSequence::Worse;
3922     }
3923 
3924     //   -- conversion of B to A is better than conversion of C to A.
3925     //   -- binding of an expression of type B to a reference of type
3926     //      A& is better than binding an expression of type C to a
3927     //      reference of type A&,
3928     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3929         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3930       if (S.IsDerivedFrom(FromType2, FromType1))
3931         return ImplicitConversionSequence::Better;
3932       else if (S.IsDerivedFrom(FromType1, FromType2))
3933         return ImplicitConversionSequence::Worse;
3934     }
3935   }
3936 
3937   return ImplicitConversionSequence::Indistinguishable;
3938 }
3939 
3940 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3941 /// C++ class.
3942 static bool isTypeValid(QualType T) {
3943   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3944     return !Record->isInvalidDecl();
3945 
3946   return true;
3947 }
3948 
3949 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3950 /// determine whether they are reference-related,
3951 /// reference-compatible, reference-compatible with added
3952 /// qualification, or incompatible, for use in C++ initialization by
3953 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3954 /// type, and the first type (T1) is the pointee type of the reference
3955 /// type being initialized.
3956 Sema::ReferenceCompareResult
3957 Sema::CompareReferenceRelationship(SourceLocation Loc,
3958                                    QualType OrigT1, QualType OrigT2,
3959                                    bool &DerivedToBase,
3960                                    bool &ObjCConversion,
3961                                    bool &ObjCLifetimeConversion) {
3962   assert(!OrigT1->isReferenceType() &&
3963     "T1 must be the pointee type of the reference type");
3964   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3965 
3966   QualType T1 = Context.getCanonicalType(OrigT1);
3967   QualType T2 = Context.getCanonicalType(OrigT2);
3968   Qualifiers T1Quals, T2Quals;
3969   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3970   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3971 
3972   // C++ [dcl.init.ref]p4:
3973   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3974   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3975   //   T1 is a base class of T2.
3976   DerivedToBase = false;
3977   ObjCConversion = false;
3978   ObjCLifetimeConversion = false;
3979   if (UnqualT1 == UnqualT2) {
3980     // Nothing to do.
3981   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3982              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3983              IsDerivedFrom(UnqualT2, UnqualT1))
3984     DerivedToBase = true;
3985   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3986            UnqualT2->isObjCObjectOrInterfaceType() &&
3987            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3988     ObjCConversion = true;
3989   else
3990     return Ref_Incompatible;
3991 
3992   // At this point, we know that T1 and T2 are reference-related (at
3993   // least).
3994 
3995   // If the type is an array type, promote the element qualifiers to the type
3996   // for comparison.
3997   if (isa<ArrayType>(T1) && T1Quals)
3998     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3999   if (isa<ArrayType>(T2) && T2Quals)
4000     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4001 
4002   // C++ [dcl.init.ref]p4:
4003   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4004   //   reference-related to T2 and cv1 is the same cv-qualification
4005   //   as, or greater cv-qualification than, cv2. For purposes of
4006   //   overload resolution, cases for which cv1 is greater
4007   //   cv-qualification than cv2 are identified as
4008   //   reference-compatible with added qualification (see 13.3.3.2).
4009   //
4010   // Note that we also require equivalence of Objective-C GC and address-space
4011   // qualifiers when performing these computations, so that e.g., an int in
4012   // address space 1 is not reference-compatible with an int in address
4013   // space 2.
4014   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4015       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4016     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4017       ObjCLifetimeConversion = true;
4018 
4019     T1Quals.removeObjCLifetime();
4020     T2Quals.removeObjCLifetime();
4021   }
4022 
4023   if (T1Quals == T2Quals)
4024     return Ref_Compatible;
4025   else if (T1Quals.compatiblyIncludes(T2Quals))
4026     return Ref_Compatible_With_Added_Qualification;
4027   else
4028     return Ref_Related;
4029 }
4030 
4031 /// \brief Look for a user-defined conversion to an value reference-compatible
4032 ///        with DeclType. Return true if something definite is found.
4033 static bool
4034 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4035                          QualType DeclType, SourceLocation DeclLoc,
4036                          Expr *Init, QualType T2, bool AllowRvalues,
4037                          bool AllowExplicit) {
4038   assert(T2->isRecordType() && "Can only find conversions of record types.");
4039   CXXRecordDecl *T2RecordDecl
4040     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4041 
4042   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4043   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4044   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4045     NamedDecl *D = *I;
4046     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4047     if (isa<UsingShadowDecl>(D))
4048       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4049 
4050     FunctionTemplateDecl *ConvTemplate
4051       = dyn_cast<FunctionTemplateDecl>(D);
4052     CXXConversionDecl *Conv;
4053     if (ConvTemplate)
4054       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4055     else
4056       Conv = cast<CXXConversionDecl>(D);
4057 
4058     // If this is an explicit conversion, and we're not allowed to consider
4059     // explicit conversions, skip it.
4060     if (!AllowExplicit && Conv->isExplicit())
4061       continue;
4062 
4063     if (AllowRvalues) {
4064       bool DerivedToBase = false;
4065       bool ObjCConversion = false;
4066       bool ObjCLifetimeConversion = false;
4067 
4068       // If we are initializing an rvalue reference, don't permit conversion
4069       // functions that return lvalues.
4070       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4071         const ReferenceType *RefType
4072           = Conv->getConversionType()->getAs<LValueReferenceType>();
4073         if (RefType && !RefType->getPointeeType()->isFunctionType())
4074           continue;
4075       }
4076 
4077       if (!ConvTemplate &&
4078           S.CompareReferenceRelationship(
4079             DeclLoc,
4080             Conv->getConversionType().getNonReferenceType()
4081               .getUnqualifiedType(),
4082             DeclType.getNonReferenceType().getUnqualifiedType(),
4083             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4084           Sema::Ref_Incompatible)
4085         continue;
4086     } else {
4087       // If the conversion function doesn't return a reference type,
4088       // it can't be considered for this conversion. An rvalue reference
4089       // is only acceptable if its referencee is a function type.
4090 
4091       const ReferenceType *RefType =
4092         Conv->getConversionType()->getAs<ReferenceType>();
4093       if (!RefType ||
4094           (!RefType->isLValueReferenceType() &&
4095            !RefType->getPointeeType()->isFunctionType()))
4096         continue;
4097     }
4098 
4099     if (ConvTemplate)
4100       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4101                                        Init, DeclType, CandidateSet,
4102                                        /*AllowObjCConversionOnExplicit=*/false);
4103     else
4104       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4105                                DeclType, CandidateSet,
4106                                /*AllowObjCConversionOnExplicit=*/false);
4107   }
4108 
4109   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4110 
4111   OverloadCandidateSet::iterator Best;
4112   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4113   case OR_Success:
4114     // C++ [over.ics.ref]p1:
4115     //
4116     //   [...] If the parameter binds directly to the result of
4117     //   applying a conversion function to the argument
4118     //   expression, the implicit conversion sequence is a
4119     //   user-defined conversion sequence (13.3.3.1.2), with the
4120     //   second standard conversion sequence either an identity
4121     //   conversion or, if the conversion function returns an
4122     //   entity of a type that is a derived class of the parameter
4123     //   type, a derived-to-base Conversion.
4124     if (!Best->FinalConversion.DirectBinding)
4125       return false;
4126 
4127     ICS.setUserDefined();
4128     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4129     ICS.UserDefined.After = Best->FinalConversion;
4130     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4131     ICS.UserDefined.ConversionFunction = Best->Function;
4132     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4133     ICS.UserDefined.EllipsisConversion = false;
4134     assert(ICS.UserDefined.After.ReferenceBinding &&
4135            ICS.UserDefined.After.DirectBinding &&
4136            "Expected a direct reference binding!");
4137     return true;
4138 
4139   case OR_Ambiguous:
4140     ICS.setAmbiguous();
4141     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4142          Cand != CandidateSet.end(); ++Cand)
4143       if (Cand->Viable)
4144         ICS.Ambiguous.addConversion(Cand->Function);
4145     return true;
4146 
4147   case OR_No_Viable_Function:
4148   case OR_Deleted:
4149     // There was no suitable conversion, or we found a deleted
4150     // conversion; continue with other checks.
4151     return false;
4152   }
4153 
4154   llvm_unreachable("Invalid OverloadResult!");
4155 }
4156 
4157 /// \brief Compute an implicit conversion sequence for reference
4158 /// initialization.
4159 static ImplicitConversionSequence
4160 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4161                  SourceLocation DeclLoc,
4162                  bool SuppressUserConversions,
4163                  bool AllowExplicit) {
4164   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4165 
4166   // Most paths end in a failed conversion.
4167   ImplicitConversionSequence ICS;
4168   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4169 
4170   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4171   QualType T2 = Init->getType();
4172 
4173   // If the initializer is the address of an overloaded function, try
4174   // to resolve the overloaded function. If all goes well, T2 is the
4175   // type of the resulting function.
4176   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4177     DeclAccessPair Found;
4178     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4179                                                                 false, Found))
4180       T2 = Fn->getType();
4181   }
4182 
4183   // Compute some basic properties of the types and the initializer.
4184   bool isRValRef = DeclType->isRValueReferenceType();
4185   bool DerivedToBase = false;
4186   bool ObjCConversion = false;
4187   bool ObjCLifetimeConversion = false;
4188   Expr::Classification InitCategory = Init->Classify(S.Context);
4189   Sema::ReferenceCompareResult RefRelationship
4190     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4191                                      ObjCConversion, ObjCLifetimeConversion);
4192 
4193 
4194   // C++0x [dcl.init.ref]p5:
4195   //   A reference to type "cv1 T1" is initialized by an expression
4196   //   of type "cv2 T2" as follows:
4197 
4198   //     -- If reference is an lvalue reference and the initializer expression
4199   if (!isRValRef) {
4200     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4201     //        reference-compatible with "cv2 T2," or
4202     //
4203     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4204     if (InitCategory.isLValue() &&
4205         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4206       // C++ [over.ics.ref]p1:
4207       //   When a parameter of reference type binds directly (8.5.3)
4208       //   to an argument expression, the implicit conversion sequence
4209       //   is the identity conversion, unless the argument expression
4210       //   has a type that is a derived class of the parameter type,
4211       //   in which case the implicit conversion sequence is a
4212       //   derived-to-base Conversion (13.3.3.1).
4213       ICS.setStandard();
4214       ICS.Standard.First = ICK_Identity;
4215       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4216                          : ObjCConversion? ICK_Compatible_Conversion
4217                          : ICK_Identity;
4218       ICS.Standard.Third = ICK_Identity;
4219       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4220       ICS.Standard.setToType(0, T2);
4221       ICS.Standard.setToType(1, T1);
4222       ICS.Standard.setToType(2, T1);
4223       ICS.Standard.ReferenceBinding = true;
4224       ICS.Standard.DirectBinding = true;
4225       ICS.Standard.IsLvalueReference = !isRValRef;
4226       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4227       ICS.Standard.BindsToRvalue = false;
4228       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4229       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4230       ICS.Standard.CopyConstructor = nullptr;
4231       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4232 
4233       // Nothing more to do: the inaccessibility/ambiguity check for
4234       // derived-to-base conversions is suppressed when we're
4235       // computing the implicit conversion sequence (C++
4236       // [over.best.ics]p2).
4237       return ICS;
4238     }
4239 
4240     //       -- has a class type (i.e., T2 is a class type), where T1 is
4241     //          not reference-related to T2, and can be implicitly
4242     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4243     //          is reference-compatible with "cv3 T3" 92) (this
4244     //          conversion is selected by enumerating the applicable
4245     //          conversion functions (13.3.1.6) and choosing the best
4246     //          one through overload resolution (13.3)),
4247     if (!SuppressUserConversions && T2->isRecordType() &&
4248         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4249         RefRelationship == Sema::Ref_Incompatible) {
4250       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4251                                    Init, T2, /*AllowRvalues=*/false,
4252                                    AllowExplicit))
4253         return ICS;
4254     }
4255   }
4256 
4257   //     -- Otherwise, the reference shall be an lvalue reference to a
4258   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4259   //        shall be an rvalue reference.
4260   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4261     return ICS;
4262 
4263   //       -- If the initializer expression
4264   //
4265   //            -- is an xvalue, class prvalue, array prvalue or function
4266   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4267   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4268       (InitCategory.isXValue() ||
4269       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4270       (InitCategory.isLValue() && T2->isFunctionType()))) {
4271     ICS.setStandard();
4272     ICS.Standard.First = ICK_Identity;
4273     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4274                       : ObjCConversion? ICK_Compatible_Conversion
4275                       : ICK_Identity;
4276     ICS.Standard.Third = ICK_Identity;
4277     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4278     ICS.Standard.setToType(0, T2);
4279     ICS.Standard.setToType(1, T1);
4280     ICS.Standard.setToType(2, T1);
4281     ICS.Standard.ReferenceBinding = true;
4282     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4283     // binding unless we're binding to a class prvalue.
4284     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4285     // allow the use of rvalue references in C++98/03 for the benefit of
4286     // standard library implementors; therefore, we need the xvalue check here.
4287     ICS.Standard.DirectBinding =
4288       S.getLangOpts().CPlusPlus11 ||
4289       !(InitCategory.isPRValue() || T2->isRecordType());
4290     ICS.Standard.IsLvalueReference = !isRValRef;
4291     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4292     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4293     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4294     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4295     ICS.Standard.CopyConstructor = nullptr;
4296     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4297     return ICS;
4298   }
4299 
4300   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4301   //               reference-related to T2, and can be implicitly converted to
4302   //               an xvalue, class prvalue, or function lvalue of type
4303   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4304   //               "cv3 T3",
4305   //
4306   //          then the reference is bound to the value of the initializer
4307   //          expression in the first case and to the result of the conversion
4308   //          in the second case (or, in either case, to an appropriate base
4309   //          class subobject).
4310   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4311       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4312       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4313                                Init, T2, /*AllowRvalues=*/true,
4314                                AllowExplicit)) {
4315     // In the second case, if the reference is an rvalue reference
4316     // and the second standard conversion sequence of the
4317     // user-defined conversion sequence includes an lvalue-to-rvalue
4318     // conversion, the program is ill-formed.
4319     if (ICS.isUserDefined() && isRValRef &&
4320         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4321       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4322 
4323     return ICS;
4324   }
4325 
4326   // A temporary of function type cannot be created; don't even try.
4327   if (T1->isFunctionType())
4328     return ICS;
4329 
4330   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4331   //          initialized from the initializer expression using the
4332   //          rules for a non-reference copy initialization (8.5). The
4333   //          reference is then bound to the temporary. If T1 is
4334   //          reference-related to T2, cv1 must be the same
4335   //          cv-qualification as, or greater cv-qualification than,
4336   //          cv2; otherwise, the program is ill-formed.
4337   if (RefRelationship == Sema::Ref_Related) {
4338     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4339     // we would be reference-compatible or reference-compatible with
4340     // added qualification. But that wasn't the case, so the reference
4341     // initialization fails.
4342     //
4343     // Note that we only want to check address spaces and cvr-qualifiers here.
4344     // ObjC GC and lifetime qualifiers aren't important.
4345     Qualifiers T1Quals = T1.getQualifiers();
4346     Qualifiers T2Quals = T2.getQualifiers();
4347     T1Quals.removeObjCGCAttr();
4348     T1Quals.removeObjCLifetime();
4349     T2Quals.removeObjCGCAttr();
4350     T2Quals.removeObjCLifetime();
4351     if (!T1Quals.compatiblyIncludes(T2Quals))
4352       return ICS;
4353   }
4354 
4355   // If at least one of the types is a class type, the types are not
4356   // related, and we aren't allowed any user conversions, the
4357   // reference binding fails. This case is important for breaking
4358   // recursion, since TryImplicitConversion below will attempt to
4359   // create a temporary through the use of a copy constructor.
4360   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4361       (T1->isRecordType() || T2->isRecordType()))
4362     return ICS;
4363 
4364   // If T1 is reference-related to T2 and the reference is an rvalue
4365   // reference, the initializer expression shall not be an lvalue.
4366   if (RefRelationship >= Sema::Ref_Related &&
4367       isRValRef && Init->Classify(S.Context).isLValue())
4368     return ICS;
4369 
4370   // C++ [over.ics.ref]p2:
4371   //   When a parameter of reference type is not bound directly to
4372   //   an argument expression, the conversion sequence is the one
4373   //   required to convert the argument expression to the
4374   //   underlying type of the reference according to
4375   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4376   //   to copy-initializing a temporary of the underlying type with
4377   //   the argument expression. Any difference in top-level
4378   //   cv-qualification is subsumed by the initialization itself
4379   //   and does not constitute a conversion.
4380   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4381                               /*AllowExplicit=*/false,
4382                               /*InOverloadResolution=*/false,
4383                               /*CStyle=*/false,
4384                               /*AllowObjCWritebackConversion=*/false,
4385                               /*AllowObjCConversionOnExplicit=*/false);
4386 
4387   // Of course, that's still a reference binding.
4388   if (ICS.isStandard()) {
4389     ICS.Standard.ReferenceBinding = true;
4390     ICS.Standard.IsLvalueReference = !isRValRef;
4391     ICS.Standard.BindsToFunctionLvalue = false;
4392     ICS.Standard.BindsToRvalue = true;
4393     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4394     ICS.Standard.ObjCLifetimeConversionBinding = false;
4395   } else if (ICS.isUserDefined()) {
4396     const ReferenceType *LValRefType =
4397         ICS.UserDefined.ConversionFunction->getReturnType()
4398             ->getAs<LValueReferenceType>();
4399 
4400     // C++ [over.ics.ref]p3:
4401     //   Except for an implicit object parameter, for which see 13.3.1, a
4402     //   standard conversion sequence cannot be formed if it requires [...]
4403     //   binding an rvalue reference to an lvalue other than a function
4404     //   lvalue.
4405     // Note that the function case is not possible here.
4406     if (DeclType->isRValueReferenceType() && LValRefType) {
4407       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4408       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4409       // reference to an rvalue!
4410       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4411       return ICS;
4412     }
4413 
4414     ICS.UserDefined.Before.setAsIdentityConversion();
4415     ICS.UserDefined.After.ReferenceBinding = true;
4416     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4417     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4418     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4419     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4420     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4421   }
4422 
4423   return ICS;
4424 }
4425 
4426 static ImplicitConversionSequence
4427 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4428                       bool SuppressUserConversions,
4429                       bool InOverloadResolution,
4430                       bool AllowObjCWritebackConversion,
4431                       bool AllowExplicit = false);
4432 
4433 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4434 /// initializer list From.
4435 static ImplicitConversionSequence
4436 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4437                   bool SuppressUserConversions,
4438                   bool InOverloadResolution,
4439                   bool AllowObjCWritebackConversion) {
4440   // C++11 [over.ics.list]p1:
4441   //   When an argument is an initializer list, it is not an expression and
4442   //   special rules apply for converting it to a parameter type.
4443 
4444   ImplicitConversionSequence Result;
4445   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4446 
4447   // We need a complete type for what follows. Incomplete types can never be
4448   // initialized from init lists.
4449   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4450     return Result;
4451 
4452   // Per DR1467:
4453   //   If the parameter type is a class X and the initializer list has a single
4454   //   element of type cv U, where U is X or a class derived from X, the
4455   //   implicit conversion sequence is the one required to convert the element
4456   //   to the parameter type.
4457   //
4458   //   Otherwise, if the parameter type is a character array [... ]
4459   //   and the initializer list has a single element that is an
4460   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4461   //   implicit conversion sequence is the identity conversion.
4462   if (From->getNumInits() == 1) {
4463     if (ToType->isRecordType()) {
4464       QualType InitType = From->getInit(0)->getType();
4465       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4466           S.IsDerivedFrom(InitType, ToType))
4467         return TryCopyInitialization(S, From->getInit(0), ToType,
4468                                      SuppressUserConversions,
4469                                      InOverloadResolution,
4470                                      AllowObjCWritebackConversion);
4471     }
4472     // FIXME: Check the other conditions here: array of character type,
4473     // initializer is a string literal.
4474     if (ToType->isArrayType()) {
4475       InitializedEntity Entity =
4476         InitializedEntity::InitializeParameter(S.Context, ToType,
4477                                                /*Consumed=*/false);
4478       if (S.CanPerformCopyInitialization(Entity, From)) {
4479         Result.setStandard();
4480         Result.Standard.setAsIdentityConversion();
4481         Result.Standard.setFromType(ToType);
4482         Result.Standard.setAllToTypes(ToType);
4483         return Result;
4484       }
4485     }
4486   }
4487 
4488   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4489   // C++11 [over.ics.list]p2:
4490   //   If the parameter type is std::initializer_list<X> or "array of X" and
4491   //   all the elements can be implicitly converted to X, the implicit
4492   //   conversion sequence is the worst conversion necessary to convert an
4493   //   element of the list to X.
4494   //
4495   // C++14 [over.ics.list]p3:
4496   //   Otherwise, if the parameter type is "array of N X", if the initializer
4497   //   list has exactly N elements or if it has fewer than N elements and X is
4498   //   default-constructible, and if all the elements of the initializer list
4499   //   can be implicitly converted to X, the implicit conversion sequence is
4500   //   the worst conversion necessary to convert an element of the list to X.
4501   //
4502   // FIXME: We're missing a lot of these checks.
4503   bool toStdInitializerList = false;
4504   QualType X;
4505   if (ToType->isArrayType())
4506     X = S.Context.getAsArrayType(ToType)->getElementType();
4507   else
4508     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4509   if (!X.isNull()) {
4510     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4511       Expr *Init = From->getInit(i);
4512       ImplicitConversionSequence ICS =
4513           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4514                                 InOverloadResolution,
4515                                 AllowObjCWritebackConversion);
4516       // If a single element isn't convertible, fail.
4517       if (ICS.isBad()) {
4518         Result = ICS;
4519         break;
4520       }
4521       // Otherwise, look for the worst conversion.
4522       if (Result.isBad() ||
4523           CompareImplicitConversionSequences(S, ICS, Result) ==
4524               ImplicitConversionSequence::Worse)
4525         Result = ICS;
4526     }
4527 
4528     // For an empty list, we won't have computed any conversion sequence.
4529     // Introduce the identity conversion sequence.
4530     if (From->getNumInits() == 0) {
4531       Result.setStandard();
4532       Result.Standard.setAsIdentityConversion();
4533       Result.Standard.setFromType(ToType);
4534       Result.Standard.setAllToTypes(ToType);
4535     }
4536 
4537     Result.setStdInitializerListElement(toStdInitializerList);
4538     return Result;
4539   }
4540 
4541   // C++14 [over.ics.list]p4:
4542   // C++11 [over.ics.list]p3:
4543   //   Otherwise, if the parameter is a non-aggregate class X and overload
4544   //   resolution chooses a single best constructor [...] the implicit
4545   //   conversion sequence is a user-defined conversion sequence. If multiple
4546   //   constructors are viable but none is better than the others, the
4547   //   implicit conversion sequence is a user-defined conversion sequence.
4548   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4549     // This function can deal with initializer lists.
4550     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4551                                     /*AllowExplicit=*/false,
4552                                     InOverloadResolution, /*CStyle=*/false,
4553                                     AllowObjCWritebackConversion,
4554                                     /*AllowObjCConversionOnExplicit=*/false);
4555   }
4556 
4557   // C++14 [over.ics.list]p5:
4558   // C++11 [over.ics.list]p4:
4559   //   Otherwise, if the parameter has an aggregate type which can be
4560   //   initialized from the initializer list [...] the implicit conversion
4561   //   sequence is a user-defined conversion sequence.
4562   if (ToType->isAggregateType()) {
4563     // Type is an aggregate, argument is an init list. At this point it comes
4564     // down to checking whether the initialization works.
4565     // FIXME: Find out whether this parameter is consumed or not.
4566     InitializedEntity Entity =
4567         InitializedEntity::InitializeParameter(S.Context, ToType,
4568                                                /*Consumed=*/false);
4569     if (S.CanPerformCopyInitialization(Entity, From)) {
4570       Result.setUserDefined();
4571       Result.UserDefined.Before.setAsIdentityConversion();
4572       // Initializer lists don't have a type.
4573       Result.UserDefined.Before.setFromType(QualType());
4574       Result.UserDefined.Before.setAllToTypes(QualType());
4575 
4576       Result.UserDefined.After.setAsIdentityConversion();
4577       Result.UserDefined.After.setFromType(ToType);
4578       Result.UserDefined.After.setAllToTypes(ToType);
4579       Result.UserDefined.ConversionFunction = nullptr;
4580     }
4581     return Result;
4582   }
4583 
4584   // C++14 [over.ics.list]p6:
4585   // C++11 [over.ics.list]p5:
4586   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4587   if (ToType->isReferenceType()) {
4588     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4589     // mention initializer lists in any way. So we go by what list-
4590     // initialization would do and try to extrapolate from that.
4591 
4592     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4593 
4594     // If the initializer list has a single element that is reference-related
4595     // to the parameter type, we initialize the reference from that.
4596     if (From->getNumInits() == 1) {
4597       Expr *Init = From->getInit(0);
4598 
4599       QualType T2 = Init->getType();
4600 
4601       // If the initializer is the address of an overloaded function, try
4602       // to resolve the overloaded function. If all goes well, T2 is the
4603       // type of the resulting function.
4604       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4605         DeclAccessPair Found;
4606         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4607                                    Init, ToType, false, Found))
4608           T2 = Fn->getType();
4609       }
4610 
4611       // Compute some basic properties of the types and the initializer.
4612       bool dummy1 = false;
4613       bool dummy2 = false;
4614       bool dummy3 = false;
4615       Sema::ReferenceCompareResult RefRelationship
4616         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4617                                          dummy2, dummy3);
4618 
4619       if (RefRelationship >= Sema::Ref_Related) {
4620         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4621                                 SuppressUserConversions,
4622                                 /*AllowExplicit=*/false);
4623       }
4624     }
4625 
4626     // Otherwise, we bind the reference to a temporary created from the
4627     // initializer list.
4628     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4629                                InOverloadResolution,
4630                                AllowObjCWritebackConversion);
4631     if (Result.isFailure())
4632       return Result;
4633     assert(!Result.isEllipsis() &&
4634            "Sub-initialization cannot result in ellipsis conversion.");
4635 
4636     // Can we even bind to a temporary?
4637     if (ToType->isRValueReferenceType() ||
4638         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4639       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4640                                             Result.UserDefined.After;
4641       SCS.ReferenceBinding = true;
4642       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4643       SCS.BindsToRvalue = true;
4644       SCS.BindsToFunctionLvalue = false;
4645       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4646       SCS.ObjCLifetimeConversionBinding = false;
4647     } else
4648       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4649                     From, ToType);
4650     return Result;
4651   }
4652 
4653   // C++14 [over.ics.list]p7:
4654   // C++11 [over.ics.list]p6:
4655   //   Otherwise, if the parameter type is not a class:
4656   if (!ToType->isRecordType()) {
4657     //    - if the initializer list has one element that is not itself an
4658     //      initializer list, the implicit conversion sequence is the one
4659     //      required to convert the element to the parameter type.
4660     unsigned NumInits = From->getNumInits();
4661     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4662       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4663                                      SuppressUserConversions,
4664                                      InOverloadResolution,
4665                                      AllowObjCWritebackConversion);
4666     //    - if the initializer list has no elements, the implicit conversion
4667     //      sequence is the identity conversion.
4668     else if (NumInits == 0) {
4669       Result.setStandard();
4670       Result.Standard.setAsIdentityConversion();
4671       Result.Standard.setFromType(ToType);
4672       Result.Standard.setAllToTypes(ToType);
4673     }
4674     return Result;
4675   }
4676 
4677   // C++14 [over.ics.list]p8:
4678   // C++11 [over.ics.list]p7:
4679   //   In all cases other than those enumerated above, no conversion is possible
4680   return Result;
4681 }
4682 
4683 /// TryCopyInitialization - Try to copy-initialize a value of type
4684 /// ToType from the expression From. Return the implicit conversion
4685 /// sequence required to pass this argument, which may be a bad
4686 /// conversion sequence (meaning that the argument cannot be passed to
4687 /// a parameter of this type). If @p SuppressUserConversions, then we
4688 /// do not permit any user-defined conversion sequences.
4689 static ImplicitConversionSequence
4690 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4691                       bool SuppressUserConversions,
4692                       bool InOverloadResolution,
4693                       bool AllowObjCWritebackConversion,
4694                       bool AllowExplicit) {
4695   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4696     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4697                              InOverloadResolution,AllowObjCWritebackConversion);
4698 
4699   if (ToType->isReferenceType())
4700     return TryReferenceInit(S, From, ToType,
4701                             /*FIXME:*/From->getLocStart(),
4702                             SuppressUserConversions,
4703                             AllowExplicit);
4704 
4705   return TryImplicitConversion(S, From, ToType,
4706                                SuppressUserConversions,
4707                                /*AllowExplicit=*/false,
4708                                InOverloadResolution,
4709                                /*CStyle=*/false,
4710                                AllowObjCWritebackConversion,
4711                                /*AllowObjCConversionOnExplicit=*/false);
4712 }
4713 
4714 static bool TryCopyInitialization(const CanQualType FromQTy,
4715                                   const CanQualType ToQTy,
4716                                   Sema &S,
4717                                   SourceLocation Loc,
4718                                   ExprValueKind FromVK) {
4719   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4720   ImplicitConversionSequence ICS =
4721     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4722 
4723   return !ICS.isBad();
4724 }
4725 
4726 /// TryObjectArgumentInitialization - Try to initialize the object
4727 /// parameter of the given member function (@c Method) from the
4728 /// expression @p From.
4729 static ImplicitConversionSequence
4730 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4731                                 Expr::Classification FromClassification,
4732                                 CXXMethodDecl *Method,
4733                                 CXXRecordDecl *ActingContext) {
4734   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4735   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4736   //                 const volatile object.
4737   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4738     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4739   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4740 
4741   // Set up the conversion sequence as a "bad" conversion, to allow us
4742   // to exit early.
4743   ImplicitConversionSequence ICS;
4744 
4745   // We need to have an object of class type.
4746   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4747     FromType = PT->getPointeeType();
4748 
4749     // When we had a pointer, it's implicitly dereferenced, so we
4750     // better have an lvalue.
4751     assert(FromClassification.isLValue());
4752   }
4753 
4754   assert(FromType->isRecordType());
4755 
4756   // C++0x [over.match.funcs]p4:
4757   //   For non-static member functions, the type of the implicit object
4758   //   parameter is
4759   //
4760   //     - "lvalue reference to cv X" for functions declared without a
4761   //        ref-qualifier or with the & ref-qualifier
4762   //     - "rvalue reference to cv X" for functions declared with the &&
4763   //        ref-qualifier
4764   //
4765   // where X is the class of which the function is a member and cv is the
4766   // cv-qualification on the member function declaration.
4767   //
4768   // However, when finding an implicit conversion sequence for the argument, we
4769   // are not allowed to create temporaries or perform user-defined conversions
4770   // (C++ [over.match.funcs]p5). We perform a simplified version of
4771   // reference binding here, that allows class rvalues to bind to
4772   // non-constant references.
4773 
4774   // First check the qualifiers.
4775   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4776   if (ImplicitParamType.getCVRQualifiers()
4777                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4778       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4779     ICS.setBad(BadConversionSequence::bad_qualifiers,
4780                FromType, ImplicitParamType);
4781     return ICS;
4782   }
4783 
4784   // Check that we have either the same type or a derived type. It
4785   // affects the conversion rank.
4786   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4787   ImplicitConversionKind SecondKind;
4788   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4789     SecondKind = ICK_Identity;
4790   } else if (S.IsDerivedFrom(FromType, ClassType))
4791     SecondKind = ICK_Derived_To_Base;
4792   else {
4793     ICS.setBad(BadConversionSequence::unrelated_class,
4794                FromType, ImplicitParamType);
4795     return ICS;
4796   }
4797 
4798   // Check the ref-qualifier.
4799   switch (Method->getRefQualifier()) {
4800   case RQ_None:
4801     // Do nothing; we don't care about lvalueness or rvalueness.
4802     break;
4803 
4804   case RQ_LValue:
4805     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4806       // non-const lvalue reference cannot bind to an rvalue
4807       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4808                  ImplicitParamType);
4809       return ICS;
4810     }
4811     break;
4812 
4813   case RQ_RValue:
4814     if (!FromClassification.isRValue()) {
4815       // rvalue reference cannot bind to an lvalue
4816       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4817                  ImplicitParamType);
4818       return ICS;
4819     }
4820     break;
4821   }
4822 
4823   // Success. Mark this as a reference binding.
4824   ICS.setStandard();
4825   ICS.Standard.setAsIdentityConversion();
4826   ICS.Standard.Second = SecondKind;
4827   ICS.Standard.setFromType(FromType);
4828   ICS.Standard.setAllToTypes(ImplicitParamType);
4829   ICS.Standard.ReferenceBinding = true;
4830   ICS.Standard.DirectBinding = true;
4831   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4832   ICS.Standard.BindsToFunctionLvalue = false;
4833   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4834   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4835     = (Method->getRefQualifier() == RQ_None);
4836   return ICS;
4837 }
4838 
4839 /// PerformObjectArgumentInitialization - Perform initialization of
4840 /// the implicit object parameter for the given Method with the given
4841 /// expression.
4842 ExprResult
4843 Sema::PerformObjectArgumentInitialization(Expr *From,
4844                                           NestedNameSpecifier *Qualifier,
4845                                           NamedDecl *FoundDecl,
4846                                           CXXMethodDecl *Method) {
4847   QualType FromRecordType, DestType;
4848   QualType ImplicitParamRecordType  =
4849     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4850 
4851   Expr::Classification FromClassification;
4852   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4853     FromRecordType = PT->getPointeeType();
4854     DestType = Method->getThisType(Context);
4855     FromClassification = Expr::Classification::makeSimpleLValue();
4856   } else {
4857     FromRecordType = From->getType();
4858     DestType = ImplicitParamRecordType;
4859     FromClassification = From->Classify(Context);
4860   }
4861 
4862   // Note that we always use the true parent context when performing
4863   // the actual argument initialization.
4864   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4865       *this, From->getType(), FromClassification, Method, Method->getParent());
4866   if (ICS.isBad()) {
4867     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4868       Qualifiers FromQs = FromRecordType.getQualifiers();
4869       Qualifiers ToQs = DestType.getQualifiers();
4870       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4871       if (CVR) {
4872         Diag(From->getLocStart(),
4873              diag::err_member_function_call_bad_cvr)
4874           << Method->getDeclName() << FromRecordType << (CVR - 1)
4875           << From->getSourceRange();
4876         Diag(Method->getLocation(), diag::note_previous_decl)
4877           << Method->getDeclName();
4878         return ExprError();
4879       }
4880     }
4881 
4882     return Diag(From->getLocStart(),
4883                 diag::err_implicit_object_parameter_init)
4884        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4885   }
4886 
4887   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4888     ExprResult FromRes =
4889       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4890     if (FromRes.isInvalid())
4891       return ExprError();
4892     From = FromRes.get();
4893   }
4894 
4895   if (!Context.hasSameType(From->getType(), DestType))
4896     From = ImpCastExprToType(From, DestType, CK_NoOp,
4897                              From->getValueKind()).get();
4898   return From;
4899 }
4900 
4901 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4902 /// expression From to bool (C++0x [conv]p3).
4903 static ImplicitConversionSequence
4904 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4905   return TryImplicitConversion(S, From, S.Context.BoolTy,
4906                                /*SuppressUserConversions=*/false,
4907                                /*AllowExplicit=*/true,
4908                                /*InOverloadResolution=*/false,
4909                                /*CStyle=*/false,
4910                                /*AllowObjCWritebackConversion=*/false,
4911                                /*AllowObjCConversionOnExplicit=*/false);
4912 }
4913 
4914 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4915 /// of the expression From to bool (C++0x [conv]p3).
4916 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4917   if (checkPlaceholderForOverload(*this, From))
4918     return ExprError();
4919 
4920   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4921   if (!ICS.isBad())
4922     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4923 
4924   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4925     return Diag(From->getLocStart(),
4926                 diag::err_typecheck_bool_condition)
4927                   << From->getType() << From->getSourceRange();
4928   return ExprError();
4929 }
4930 
4931 /// Check that the specified conversion is permitted in a converted constant
4932 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4933 /// is acceptable.
4934 static bool CheckConvertedConstantConversions(Sema &S,
4935                                               StandardConversionSequence &SCS) {
4936   // Since we know that the target type is an integral or unscoped enumeration
4937   // type, most conversion kinds are impossible. All possible First and Third
4938   // conversions are fine.
4939   switch (SCS.Second) {
4940   case ICK_Identity:
4941   case ICK_NoReturn_Adjustment:
4942   case ICK_Integral_Promotion:
4943   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4944     return true;
4945 
4946   case ICK_Boolean_Conversion:
4947     // Conversion from an integral or unscoped enumeration type to bool is
4948     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4949     // conversion, so we allow it in a converted constant expression.
4950     //
4951     // FIXME: Per core issue 1407, we should not allow this, but that breaks
4952     // a lot of popular code. We should at least add a warning for this
4953     // (non-conforming) extension.
4954     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4955            SCS.getToType(2)->isBooleanType();
4956 
4957   case ICK_Pointer_Conversion:
4958   case ICK_Pointer_Member:
4959     // C++1z: null pointer conversions and null member pointer conversions are
4960     // only permitted if the source type is std::nullptr_t.
4961     return SCS.getFromType()->isNullPtrType();
4962 
4963   case ICK_Floating_Promotion:
4964   case ICK_Complex_Promotion:
4965   case ICK_Floating_Conversion:
4966   case ICK_Complex_Conversion:
4967   case ICK_Floating_Integral:
4968   case ICK_Compatible_Conversion:
4969   case ICK_Derived_To_Base:
4970   case ICK_Vector_Conversion:
4971   case ICK_Vector_Splat:
4972   case ICK_Complex_Real:
4973   case ICK_Block_Pointer_Conversion:
4974   case ICK_TransparentUnionConversion:
4975   case ICK_Writeback_Conversion:
4976   case ICK_Zero_Event_Conversion:
4977     return false;
4978 
4979   case ICK_Lvalue_To_Rvalue:
4980   case ICK_Array_To_Pointer:
4981   case ICK_Function_To_Pointer:
4982     llvm_unreachable("found a first conversion kind in Second");
4983 
4984   case ICK_Qualification:
4985     llvm_unreachable("found a third conversion kind in Second");
4986 
4987   case ICK_Num_Conversion_Kinds:
4988     break;
4989   }
4990 
4991   llvm_unreachable("unknown conversion kind");
4992 }
4993 
4994 /// CheckConvertedConstantExpression - Check that the expression From is a
4995 /// converted constant expression of type T, perform the conversion and produce
4996 /// the converted expression, per C++11 [expr.const]p3.
4997 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4998                                                    QualType T, APValue &Value,
4999                                                    Sema::CCEKind CCE,
5000                                                    bool RequireInt) {
5001   assert(S.getLangOpts().CPlusPlus11 &&
5002          "converted constant expression outside C++11");
5003 
5004   if (checkPlaceholderForOverload(S, From))
5005     return ExprError();
5006 
5007   // C++1z [expr.const]p3:
5008   //  A converted constant expression of type T is an expression,
5009   //  implicitly converted to type T, where the converted
5010   //  expression is a constant expression and the implicit conversion
5011   //  sequence contains only [... list of conversions ...].
5012   ImplicitConversionSequence ICS =
5013     TryCopyInitialization(S, From, T,
5014                           /*SuppressUserConversions=*/false,
5015                           /*InOverloadResolution=*/false,
5016                           /*AllowObjcWritebackConversion=*/false,
5017                           /*AllowExplicit=*/false);
5018   StandardConversionSequence *SCS = nullptr;
5019   switch (ICS.getKind()) {
5020   case ImplicitConversionSequence::StandardConversion:
5021     SCS = &ICS.Standard;
5022     break;
5023   case ImplicitConversionSequence::UserDefinedConversion:
5024     // We are converting to a non-class type, so the Before sequence
5025     // must be trivial.
5026     SCS = &ICS.UserDefined.After;
5027     break;
5028   case ImplicitConversionSequence::AmbiguousConversion:
5029   case ImplicitConversionSequence::BadConversion:
5030     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5031       return S.Diag(From->getLocStart(),
5032                     diag::err_typecheck_converted_constant_expression)
5033                 << From->getType() << From->getSourceRange() << T;
5034     return ExprError();
5035 
5036   case ImplicitConversionSequence::EllipsisConversion:
5037     llvm_unreachable("ellipsis conversion in converted constant expression");
5038   }
5039 
5040   // Check that we would only use permitted conversions.
5041   if (!CheckConvertedConstantConversions(S, *SCS)) {
5042     return S.Diag(From->getLocStart(),
5043                   diag::err_typecheck_converted_constant_expression_disallowed)
5044              << From->getType() << From->getSourceRange() << T;
5045   }
5046   // [...] and where the reference binding (if any) binds directly.
5047   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5048     return S.Diag(From->getLocStart(),
5049                   diag::err_typecheck_converted_constant_expression_indirect)
5050              << From->getType() << From->getSourceRange() << T;
5051   }
5052 
5053   ExprResult Result =
5054       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5055   if (Result.isInvalid())
5056     return Result;
5057 
5058   // Check for a narrowing implicit conversion.
5059   APValue PreNarrowingValue;
5060   QualType PreNarrowingType;
5061   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5062                                 PreNarrowingType)) {
5063   case NK_Variable_Narrowing:
5064     // Implicit conversion to a narrower type, and the value is not a constant
5065     // expression. We'll diagnose this in a moment.
5066   case NK_Not_Narrowing:
5067     break;
5068 
5069   case NK_Constant_Narrowing:
5070     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5071       << CCE << /*Constant*/1
5072       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5073     break;
5074 
5075   case NK_Type_Narrowing:
5076     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5077       << CCE << /*Constant*/0 << From->getType() << T;
5078     break;
5079   }
5080 
5081   // Check the expression is a constant expression.
5082   SmallVector<PartialDiagnosticAt, 8> Notes;
5083   Expr::EvalResult Eval;
5084   Eval.Diag = &Notes;
5085 
5086   if ((T->isReferenceType()
5087            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5088            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5089       (RequireInt && !Eval.Val.isInt())) {
5090     // The expression can't be folded, so we can't keep it at this position in
5091     // the AST.
5092     Result = ExprError();
5093   } else {
5094     Value = Eval.Val;
5095 
5096     if (Notes.empty()) {
5097       // It's a constant expression.
5098       return Result;
5099     }
5100   }
5101 
5102   // It's not a constant expression. Produce an appropriate diagnostic.
5103   if (Notes.size() == 1 &&
5104       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5105     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5106   else {
5107     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5108       << CCE << From->getSourceRange();
5109     for (unsigned I = 0; I < Notes.size(); ++I)
5110       S.Diag(Notes[I].first, Notes[I].second);
5111   }
5112   return ExprError();
5113 }
5114 
5115 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5116                                                   APValue &Value, CCEKind CCE) {
5117   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5118 }
5119 
5120 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5121                                                   llvm::APSInt &Value,
5122                                                   CCEKind CCE) {
5123   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5124 
5125   APValue V;
5126   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5127   if (!R.isInvalid())
5128     Value = V.getInt();
5129   return R;
5130 }
5131 
5132 
5133 /// dropPointerConversions - If the given standard conversion sequence
5134 /// involves any pointer conversions, remove them.  This may change
5135 /// the result type of the conversion sequence.
5136 static void dropPointerConversion(StandardConversionSequence &SCS) {
5137   if (SCS.Second == ICK_Pointer_Conversion) {
5138     SCS.Second = ICK_Identity;
5139     SCS.Third = ICK_Identity;
5140     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5141   }
5142 }
5143 
5144 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5145 /// convert the expression From to an Objective-C pointer type.
5146 static ImplicitConversionSequence
5147 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5148   // Do an implicit conversion to 'id'.
5149   QualType Ty = S.Context.getObjCIdType();
5150   ImplicitConversionSequence ICS
5151     = TryImplicitConversion(S, From, Ty,
5152                             // FIXME: Are these flags correct?
5153                             /*SuppressUserConversions=*/false,
5154                             /*AllowExplicit=*/true,
5155                             /*InOverloadResolution=*/false,
5156                             /*CStyle=*/false,
5157                             /*AllowObjCWritebackConversion=*/false,
5158                             /*AllowObjCConversionOnExplicit=*/true);
5159 
5160   // Strip off any final conversions to 'id'.
5161   switch (ICS.getKind()) {
5162   case ImplicitConversionSequence::BadConversion:
5163   case ImplicitConversionSequence::AmbiguousConversion:
5164   case ImplicitConversionSequence::EllipsisConversion:
5165     break;
5166 
5167   case ImplicitConversionSequence::UserDefinedConversion:
5168     dropPointerConversion(ICS.UserDefined.After);
5169     break;
5170 
5171   case ImplicitConversionSequence::StandardConversion:
5172     dropPointerConversion(ICS.Standard);
5173     break;
5174   }
5175 
5176   return ICS;
5177 }
5178 
5179 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5180 /// conversion of the expression From to an Objective-C pointer type.
5181 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5182   if (checkPlaceholderForOverload(*this, From))
5183     return ExprError();
5184 
5185   QualType Ty = Context.getObjCIdType();
5186   ImplicitConversionSequence ICS =
5187     TryContextuallyConvertToObjCPointer(*this, From);
5188   if (!ICS.isBad())
5189     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5190   return ExprError();
5191 }
5192 
5193 /// Determine whether the provided type is an integral type, or an enumeration
5194 /// type of a permitted flavor.
5195 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5196   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5197                                  : T->isIntegralOrUnscopedEnumerationType();
5198 }
5199 
5200 static ExprResult
5201 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5202                             Sema::ContextualImplicitConverter &Converter,
5203                             QualType T, UnresolvedSetImpl &ViableConversions) {
5204 
5205   if (Converter.Suppress)
5206     return ExprError();
5207 
5208   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5209   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5210     CXXConversionDecl *Conv =
5211         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5212     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5213     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5214   }
5215   return From;
5216 }
5217 
5218 static bool
5219 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5220                            Sema::ContextualImplicitConverter &Converter,
5221                            QualType T, bool HadMultipleCandidates,
5222                            UnresolvedSetImpl &ExplicitConversions) {
5223   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5224     DeclAccessPair Found = ExplicitConversions[0];
5225     CXXConversionDecl *Conversion =
5226         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5227 
5228     // The user probably meant to invoke the given explicit
5229     // conversion; use it.
5230     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5231     std::string TypeStr;
5232     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5233 
5234     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5235         << FixItHint::CreateInsertion(From->getLocStart(),
5236                                       "static_cast<" + TypeStr + ">(")
5237         << FixItHint::CreateInsertion(
5238                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5239     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5240 
5241     // If we aren't in a SFINAE context, build a call to the
5242     // explicit conversion function.
5243     if (SemaRef.isSFINAEContext())
5244       return true;
5245 
5246     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5247     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5248                                                        HadMultipleCandidates);
5249     if (Result.isInvalid())
5250       return true;
5251     // Record usage of conversion in an implicit cast.
5252     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5253                                     CK_UserDefinedConversion, Result.get(),
5254                                     nullptr, Result.get()->getValueKind());
5255   }
5256   return false;
5257 }
5258 
5259 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5260                              Sema::ContextualImplicitConverter &Converter,
5261                              QualType T, bool HadMultipleCandidates,
5262                              DeclAccessPair &Found) {
5263   CXXConversionDecl *Conversion =
5264       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5265   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5266 
5267   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5268   if (!Converter.SuppressConversion) {
5269     if (SemaRef.isSFINAEContext())
5270       return true;
5271 
5272     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5273         << From->getSourceRange();
5274   }
5275 
5276   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5277                                                      HadMultipleCandidates);
5278   if (Result.isInvalid())
5279     return true;
5280   // Record usage of conversion in an implicit cast.
5281   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5282                                   CK_UserDefinedConversion, Result.get(),
5283                                   nullptr, Result.get()->getValueKind());
5284   return false;
5285 }
5286 
5287 static ExprResult finishContextualImplicitConversion(
5288     Sema &SemaRef, SourceLocation Loc, Expr *From,
5289     Sema::ContextualImplicitConverter &Converter) {
5290   if (!Converter.match(From->getType()) && !Converter.Suppress)
5291     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5292         << From->getSourceRange();
5293 
5294   return SemaRef.DefaultLvalueConversion(From);
5295 }
5296 
5297 static void
5298 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5299                                   UnresolvedSetImpl &ViableConversions,
5300                                   OverloadCandidateSet &CandidateSet) {
5301   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5302     DeclAccessPair FoundDecl = ViableConversions[I];
5303     NamedDecl *D = FoundDecl.getDecl();
5304     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5305     if (isa<UsingShadowDecl>(D))
5306       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5307 
5308     CXXConversionDecl *Conv;
5309     FunctionTemplateDecl *ConvTemplate;
5310     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5311       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5312     else
5313       Conv = cast<CXXConversionDecl>(D);
5314 
5315     if (ConvTemplate)
5316       SemaRef.AddTemplateConversionCandidate(
5317         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5318         /*AllowObjCConversionOnExplicit=*/false);
5319     else
5320       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5321                                      ToType, CandidateSet,
5322                                      /*AllowObjCConversionOnExplicit=*/false);
5323   }
5324 }
5325 
5326 /// \brief Attempt to convert the given expression to a type which is accepted
5327 /// by the given converter.
5328 ///
5329 /// This routine will attempt to convert an expression of class type to a
5330 /// type accepted by the specified converter. In C++11 and before, the class
5331 /// must have a single non-explicit conversion function converting to a matching
5332 /// type. In C++1y, there can be multiple such conversion functions, but only
5333 /// one target type.
5334 ///
5335 /// \param Loc The source location of the construct that requires the
5336 /// conversion.
5337 ///
5338 /// \param From The expression we're converting from.
5339 ///
5340 /// \param Converter Used to control and diagnose the conversion process.
5341 ///
5342 /// \returns The expression, converted to an integral or enumeration type if
5343 /// successful.
5344 ExprResult Sema::PerformContextualImplicitConversion(
5345     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5346   // We can't perform any more checking for type-dependent expressions.
5347   if (From->isTypeDependent())
5348     return From;
5349 
5350   // Process placeholders immediately.
5351   if (From->hasPlaceholderType()) {
5352     ExprResult result = CheckPlaceholderExpr(From);
5353     if (result.isInvalid())
5354       return result;
5355     From = result.get();
5356   }
5357 
5358   // If the expression already has a matching type, we're golden.
5359   QualType T = From->getType();
5360   if (Converter.match(T))
5361     return DefaultLvalueConversion(From);
5362 
5363   // FIXME: Check for missing '()' if T is a function type?
5364 
5365   // We can only perform contextual implicit conversions on objects of class
5366   // type.
5367   const RecordType *RecordTy = T->getAs<RecordType>();
5368   if (!RecordTy || !getLangOpts().CPlusPlus) {
5369     if (!Converter.Suppress)
5370       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5371     return From;
5372   }
5373 
5374   // We must have a complete class type.
5375   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5376     ContextualImplicitConverter &Converter;
5377     Expr *From;
5378 
5379     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5380         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5381 
5382     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5383       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5384     }
5385   } IncompleteDiagnoser(Converter, From);
5386 
5387   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5388     return From;
5389 
5390   // Look for a conversion to an integral or enumeration type.
5391   UnresolvedSet<4>
5392       ViableConversions; // These are *potentially* viable in C++1y.
5393   UnresolvedSet<4> ExplicitConversions;
5394   const auto &Conversions =
5395       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5396 
5397   bool HadMultipleCandidates =
5398       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5399 
5400   // To check that there is only one target type, in C++1y:
5401   QualType ToType;
5402   bool HasUniqueTargetType = true;
5403 
5404   // Collect explicit or viable (potentially in C++1y) conversions.
5405   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5406     NamedDecl *D = (*I)->getUnderlyingDecl();
5407     CXXConversionDecl *Conversion;
5408     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5409     if (ConvTemplate) {
5410       if (getLangOpts().CPlusPlus14)
5411         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5412       else
5413         continue; // C++11 does not consider conversion operator templates(?).
5414     } else
5415       Conversion = cast<CXXConversionDecl>(D);
5416 
5417     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5418            "Conversion operator templates are considered potentially "
5419            "viable in C++1y");
5420 
5421     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5422     if (Converter.match(CurToType) || ConvTemplate) {
5423 
5424       if (Conversion->isExplicit()) {
5425         // FIXME: For C++1y, do we need this restriction?
5426         // cf. diagnoseNoViableConversion()
5427         if (!ConvTemplate)
5428           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5429       } else {
5430         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5431           if (ToType.isNull())
5432             ToType = CurToType.getUnqualifiedType();
5433           else if (HasUniqueTargetType &&
5434                    (CurToType.getUnqualifiedType() != ToType))
5435             HasUniqueTargetType = false;
5436         }
5437         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5438       }
5439     }
5440   }
5441 
5442   if (getLangOpts().CPlusPlus14) {
5443     // C++1y [conv]p6:
5444     // ... An expression e of class type E appearing in such a context
5445     // is said to be contextually implicitly converted to a specified
5446     // type T and is well-formed if and only if e can be implicitly
5447     // converted to a type T that is determined as follows: E is searched
5448     // for conversion functions whose return type is cv T or reference to
5449     // cv T such that T is allowed by the context. There shall be
5450     // exactly one such T.
5451 
5452     // If no unique T is found:
5453     if (ToType.isNull()) {
5454       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5455                                      HadMultipleCandidates,
5456                                      ExplicitConversions))
5457         return ExprError();
5458       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5459     }
5460 
5461     // If more than one unique Ts are found:
5462     if (!HasUniqueTargetType)
5463       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5464                                          ViableConversions);
5465 
5466     // If one unique T is found:
5467     // First, build a candidate set from the previously recorded
5468     // potentially viable conversions.
5469     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5470     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5471                                       CandidateSet);
5472 
5473     // Then, perform overload resolution over the candidate set.
5474     OverloadCandidateSet::iterator Best;
5475     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5476     case OR_Success: {
5477       // Apply this conversion.
5478       DeclAccessPair Found =
5479           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5480       if (recordConversion(*this, Loc, From, Converter, T,
5481                            HadMultipleCandidates, Found))
5482         return ExprError();
5483       break;
5484     }
5485     case OR_Ambiguous:
5486       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5487                                          ViableConversions);
5488     case OR_No_Viable_Function:
5489       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5490                                      HadMultipleCandidates,
5491                                      ExplicitConversions))
5492         return ExprError();
5493     // fall through 'OR_Deleted' case.
5494     case OR_Deleted:
5495       // We'll complain below about a non-integral condition type.
5496       break;
5497     }
5498   } else {
5499     switch (ViableConversions.size()) {
5500     case 0: {
5501       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5502                                      HadMultipleCandidates,
5503                                      ExplicitConversions))
5504         return ExprError();
5505 
5506       // We'll complain below about a non-integral condition type.
5507       break;
5508     }
5509     case 1: {
5510       // Apply this conversion.
5511       DeclAccessPair Found = ViableConversions[0];
5512       if (recordConversion(*this, Loc, From, Converter, T,
5513                            HadMultipleCandidates, Found))
5514         return ExprError();
5515       break;
5516     }
5517     default:
5518       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5519                                          ViableConversions);
5520     }
5521   }
5522 
5523   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5524 }
5525 
5526 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5527 /// an acceptable non-member overloaded operator for a call whose
5528 /// arguments have types T1 (and, if non-empty, T2). This routine
5529 /// implements the check in C++ [over.match.oper]p3b2 concerning
5530 /// enumeration types.
5531 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5532                                                    FunctionDecl *Fn,
5533                                                    ArrayRef<Expr *> Args) {
5534   QualType T1 = Args[0]->getType();
5535   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5536 
5537   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5538     return true;
5539 
5540   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5541     return true;
5542 
5543   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5544   if (Proto->getNumParams() < 1)
5545     return false;
5546 
5547   if (T1->isEnumeralType()) {
5548     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5549     if (Context.hasSameUnqualifiedType(T1, ArgType))
5550       return true;
5551   }
5552 
5553   if (Proto->getNumParams() < 2)
5554     return false;
5555 
5556   if (!T2.isNull() && T2->isEnumeralType()) {
5557     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5558     if (Context.hasSameUnqualifiedType(T2, ArgType))
5559       return true;
5560   }
5561 
5562   return false;
5563 }
5564 
5565 /// AddOverloadCandidate - Adds the given function to the set of
5566 /// candidate functions, using the given function call arguments.  If
5567 /// @p SuppressUserConversions, then don't allow user-defined
5568 /// conversions via constructors or conversion operators.
5569 ///
5570 /// \param PartialOverloading true if we are performing "partial" overloading
5571 /// based on an incomplete set of function arguments. This feature is used by
5572 /// code completion.
5573 void
5574 Sema::AddOverloadCandidate(FunctionDecl *Function,
5575                            DeclAccessPair FoundDecl,
5576                            ArrayRef<Expr *> Args,
5577                            OverloadCandidateSet &CandidateSet,
5578                            bool SuppressUserConversions,
5579                            bool PartialOverloading,
5580                            bool AllowExplicit) {
5581   const FunctionProtoType *Proto
5582     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5583   assert(Proto && "Functions without a prototype cannot be overloaded");
5584   assert(!Function->getDescribedFunctionTemplate() &&
5585          "Use AddTemplateOverloadCandidate for function templates");
5586 
5587   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5588     if (!isa<CXXConstructorDecl>(Method)) {
5589       // If we get here, it's because we're calling a member function
5590       // that is named without a member access expression (e.g.,
5591       // "this->f") that was either written explicitly or created
5592       // implicitly. This can happen with a qualified call to a member
5593       // function, e.g., X::f(). We use an empty type for the implied
5594       // object argument (C++ [over.call.func]p3), and the acting context
5595       // is irrelevant.
5596       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5597                          QualType(), Expr::Classification::makeSimpleLValue(),
5598                          Args, CandidateSet, SuppressUserConversions,
5599                          PartialOverloading);
5600       return;
5601     }
5602     // We treat a constructor like a non-member function, since its object
5603     // argument doesn't participate in overload resolution.
5604   }
5605 
5606   if (!CandidateSet.isNewCandidate(Function))
5607     return;
5608 
5609   // C++ [over.match.oper]p3:
5610   //   if no operand has a class type, only those non-member functions in the
5611   //   lookup set that have a first parameter of type T1 or "reference to
5612   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5613   //   is a right operand) a second parameter of type T2 or "reference to
5614   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5615   //   candidate functions.
5616   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5617       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5618     return;
5619 
5620   // C++11 [class.copy]p11: [DR1402]
5621   //   A defaulted move constructor that is defined as deleted is ignored by
5622   //   overload resolution.
5623   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5624   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5625       Constructor->isMoveConstructor())
5626     return;
5627 
5628   // Overload resolution is always an unevaluated context.
5629   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5630 
5631   // Add this candidate
5632   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5633   Candidate.FoundDecl = FoundDecl;
5634   Candidate.Function = Function;
5635   Candidate.Viable = true;
5636   Candidate.IsSurrogate = false;
5637   Candidate.IgnoreObjectArgument = false;
5638   Candidate.ExplicitCallArguments = Args.size();
5639 
5640   if (Constructor) {
5641     // C++ [class.copy]p3:
5642     //   A member function template is never instantiated to perform the copy
5643     //   of a class object to an object of its class type.
5644     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5645     if (Args.size() == 1 &&
5646         Constructor->isSpecializationCopyingObject() &&
5647         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5648          IsDerivedFrom(Args[0]->getType(), ClassType))) {
5649       Candidate.Viable = false;
5650       Candidate.FailureKind = ovl_fail_illegal_constructor;
5651       return;
5652     }
5653   }
5654 
5655   unsigned NumParams = Proto->getNumParams();
5656 
5657   // (C++ 13.3.2p2): A candidate function having fewer than m
5658   // parameters is viable only if it has an ellipsis in its parameter
5659   // list (8.3.5).
5660   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5661       !Proto->isVariadic()) {
5662     Candidate.Viable = false;
5663     Candidate.FailureKind = ovl_fail_too_many_arguments;
5664     return;
5665   }
5666 
5667   // (C++ 13.3.2p2): A candidate function having more than m parameters
5668   // is viable only if the (m+1)st parameter has a default argument
5669   // (8.3.6). For the purposes of overload resolution, the
5670   // parameter list is truncated on the right, so that there are
5671   // exactly m parameters.
5672   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5673   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5674     // Not enough arguments.
5675     Candidate.Viable = false;
5676     Candidate.FailureKind = ovl_fail_too_few_arguments;
5677     return;
5678   }
5679 
5680   // (CUDA B.1): Check for invalid calls between targets.
5681   if (getLangOpts().CUDA)
5682     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5683       // Skip the check for callers that are implicit members, because in this
5684       // case we may not yet know what the member's target is; the target is
5685       // inferred for the member automatically, based on the bases and fields of
5686       // the class.
5687       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5688         Candidate.Viable = false;
5689         Candidate.FailureKind = ovl_fail_bad_target;
5690         return;
5691       }
5692 
5693   // Determine the implicit conversion sequences for each of the
5694   // arguments.
5695   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5696     if (ArgIdx < NumParams) {
5697       // (C++ 13.3.2p3): for F to be a viable function, there shall
5698       // exist for each argument an implicit conversion sequence
5699       // (13.3.3.1) that converts that argument to the corresponding
5700       // parameter of F.
5701       QualType ParamType = Proto->getParamType(ArgIdx);
5702       Candidate.Conversions[ArgIdx]
5703         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5704                                 SuppressUserConversions,
5705                                 /*InOverloadResolution=*/true,
5706                                 /*AllowObjCWritebackConversion=*/
5707                                   getLangOpts().ObjCAutoRefCount,
5708                                 AllowExplicit);
5709       if (Candidate.Conversions[ArgIdx].isBad()) {
5710         Candidate.Viable = false;
5711         Candidate.FailureKind = ovl_fail_bad_conversion;
5712         return;
5713       }
5714     } else {
5715       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5716       // argument for which there is no corresponding parameter is
5717       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5718       Candidate.Conversions[ArgIdx].setEllipsis();
5719     }
5720   }
5721 
5722   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5723     Candidate.Viable = false;
5724     Candidate.FailureKind = ovl_fail_enable_if;
5725     Candidate.DeductionFailure.Data = FailedAttr;
5726     return;
5727   }
5728 }
5729 
5730 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5731                                        bool IsInstance) {
5732   SmallVector<ObjCMethodDecl*, 4> Methods;
5733   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5734     return nullptr;
5735 
5736   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5737     bool Match = true;
5738     ObjCMethodDecl *Method = Methods[b];
5739     unsigned NumNamedArgs = Sel.getNumArgs();
5740     // Method might have more arguments than selector indicates. This is due
5741     // to addition of c-style arguments in method.
5742     if (Method->param_size() > NumNamedArgs)
5743       NumNamedArgs = Method->param_size();
5744     if (Args.size() < NumNamedArgs)
5745       continue;
5746 
5747     for (unsigned i = 0; i < NumNamedArgs; i++) {
5748       // We can't do any type-checking on a type-dependent argument.
5749       if (Args[i]->isTypeDependent()) {
5750         Match = false;
5751         break;
5752       }
5753 
5754       ParmVarDecl *param = Method->parameters()[i];
5755       Expr *argExpr = Args[i];
5756       assert(argExpr && "SelectBestMethod(): missing expression");
5757 
5758       // Strip the unbridged-cast placeholder expression off unless it's
5759       // a consumed argument.
5760       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5761           !param->hasAttr<CFConsumedAttr>())
5762         argExpr = stripARCUnbridgedCast(argExpr);
5763 
5764       // If the parameter is __unknown_anytype, move on to the next method.
5765       if (param->getType() == Context.UnknownAnyTy) {
5766         Match = false;
5767         break;
5768       }
5769 
5770       ImplicitConversionSequence ConversionState
5771         = TryCopyInitialization(*this, argExpr, param->getType(),
5772                                 /*SuppressUserConversions*/false,
5773                                 /*InOverloadResolution=*/true,
5774                                 /*AllowObjCWritebackConversion=*/
5775                                 getLangOpts().ObjCAutoRefCount,
5776                                 /*AllowExplicit*/false);
5777         if (ConversionState.isBad()) {
5778           Match = false;
5779           break;
5780         }
5781     }
5782     // Promote additional arguments to variadic methods.
5783     if (Match && Method->isVariadic()) {
5784       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5785         if (Args[i]->isTypeDependent()) {
5786           Match = false;
5787           break;
5788         }
5789         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5790                                                           nullptr);
5791         if (Arg.isInvalid()) {
5792           Match = false;
5793           break;
5794         }
5795       }
5796     } else {
5797       // Check for extra arguments to non-variadic methods.
5798       if (Args.size() != NumNamedArgs)
5799         Match = false;
5800       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5801         // Special case when selectors have no argument. In this case, select
5802         // one with the most general result type of 'id'.
5803         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5804           QualType ReturnT = Methods[b]->getReturnType();
5805           if (ReturnT->isObjCIdType())
5806             return Methods[b];
5807         }
5808       }
5809     }
5810 
5811     if (Match)
5812       return Method;
5813   }
5814   return nullptr;
5815 }
5816 
5817 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5818 
5819 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5820                                   bool MissingImplicitThis) {
5821   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5822   // we need to find the first failing one.
5823   if (!Function->hasAttrs())
5824     return nullptr;
5825   AttrVec Attrs = Function->getAttrs();
5826   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5827                                        IsNotEnableIfAttr);
5828   if (Attrs.begin() == E)
5829     return nullptr;
5830   std::reverse(Attrs.begin(), E);
5831 
5832   SFINAETrap Trap(*this);
5833 
5834   SmallVector<Expr *, 16> ConvertedArgs;
5835   bool InitializationFailed = false;
5836   bool ContainsValueDependentExpr = false;
5837 
5838   // Convert the arguments.
5839   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5840     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5841         !cast<CXXMethodDecl>(Function)->isStatic() &&
5842         !isa<CXXConstructorDecl>(Function)) {
5843       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5844       ExprResult R =
5845         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5846                                             Method, Method);
5847       if (R.isInvalid()) {
5848         InitializationFailed = true;
5849         break;
5850       }
5851       ContainsValueDependentExpr |= R.get()->isValueDependent();
5852       ConvertedArgs.push_back(R.get());
5853     } else {
5854       ExprResult R =
5855         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5856                                                 Context,
5857                                                 Function->getParamDecl(i)),
5858                                   SourceLocation(),
5859                                   Args[i]);
5860       if (R.isInvalid()) {
5861         InitializationFailed = true;
5862         break;
5863       }
5864       ContainsValueDependentExpr |= R.get()->isValueDependent();
5865       ConvertedArgs.push_back(R.get());
5866     }
5867   }
5868 
5869   if (InitializationFailed || Trap.hasErrorOccurred())
5870     return cast<EnableIfAttr>(Attrs[0]);
5871 
5872   // Push default arguments if needed.
5873   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5874     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5875       ParmVarDecl *P = Function->getParamDecl(i);
5876       ExprResult R = PerformCopyInitialization(
5877           InitializedEntity::InitializeParameter(Context,
5878                                                  Function->getParamDecl(i)),
5879           SourceLocation(),
5880           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5881                                            : P->getDefaultArg());
5882       if (R.isInvalid()) {
5883         InitializationFailed = true;
5884         break;
5885       }
5886       ContainsValueDependentExpr |= R.get()->isValueDependent();
5887       ConvertedArgs.push_back(R.get());
5888     }
5889 
5890     if (InitializationFailed || Trap.hasErrorOccurred())
5891       return cast<EnableIfAttr>(Attrs[0]);
5892   }
5893 
5894   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5895     APValue Result;
5896     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5897     if (EIA->getCond()->isValueDependent()) {
5898       // Don't even try now, we'll examine it after instantiation.
5899       continue;
5900     }
5901 
5902     if (!EIA->getCond()->EvaluateWithSubstitution(
5903             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5904       if (!ContainsValueDependentExpr)
5905         return EIA;
5906     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5907       return EIA;
5908     }
5909   }
5910   return nullptr;
5911 }
5912 
5913 /// \brief Add all of the function declarations in the given function set to
5914 /// the overload candidate set.
5915 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5916                                  ArrayRef<Expr *> Args,
5917                                  OverloadCandidateSet& CandidateSet,
5918                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5919                                  bool SuppressUserConversions,
5920                                  bool PartialOverloading) {
5921   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5922     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5923     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5924       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5925         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5926                            cast<CXXMethodDecl>(FD)->getParent(),
5927                            Args[0]->getType(), Args[0]->Classify(Context),
5928                            Args.slice(1), CandidateSet,
5929                            SuppressUserConversions, PartialOverloading);
5930       else
5931         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5932                              SuppressUserConversions, PartialOverloading);
5933     } else {
5934       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5935       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5936           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5937         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5938                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5939                                    ExplicitTemplateArgs,
5940                                    Args[0]->getType(),
5941                                    Args[0]->Classify(Context), Args.slice(1),
5942                                    CandidateSet, SuppressUserConversions,
5943                                    PartialOverloading);
5944       else
5945         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5946                                      ExplicitTemplateArgs, Args,
5947                                      CandidateSet, SuppressUserConversions,
5948                                      PartialOverloading);
5949     }
5950   }
5951 }
5952 
5953 /// AddMethodCandidate - Adds a named decl (which is some kind of
5954 /// method) as a method candidate to the given overload set.
5955 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5956                               QualType ObjectType,
5957                               Expr::Classification ObjectClassification,
5958                               ArrayRef<Expr *> Args,
5959                               OverloadCandidateSet& CandidateSet,
5960                               bool SuppressUserConversions) {
5961   NamedDecl *Decl = FoundDecl.getDecl();
5962   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5963 
5964   if (isa<UsingShadowDecl>(Decl))
5965     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5966 
5967   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5968     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5969            "Expected a member function template");
5970     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5971                                /*ExplicitArgs*/ nullptr,
5972                                ObjectType, ObjectClassification,
5973                                Args, CandidateSet,
5974                                SuppressUserConversions);
5975   } else {
5976     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5977                        ObjectType, ObjectClassification,
5978                        Args,
5979                        CandidateSet, SuppressUserConversions);
5980   }
5981 }
5982 
5983 /// AddMethodCandidate - Adds the given C++ member function to the set
5984 /// of candidate functions, using the given function call arguments
5985 /// and the object argument (@c Object). For example, in a call
5986 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5987 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5988 /// allow user-defined conversions via constructors or conversion
5989 /// operators.
5990 void
5991 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5992                          CXXRecordDecl *ActingContext, QualType ObjectType,
5993                          Expr::Classification ObjectClassification,
5994                          ArrayRef<Expr *> Args,
5995                          OverloadCandidateSet &CandidateSet,
5996                          bool SuppressUserConversions,
5997                          bool PartialOverloading) {
5998   const FunctionProtoType *Proto
5999     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6000   assert(Proto && "Methods without a prototype cannot be overloaded");
6001   assert(!isa<CXXConstructorDecl>(Method) &&
6002          "Use AddOverloadCandidate for constructors");
6003 
6004   if (!CandidateSet.isNewCandidate(Method))
6005     return;
6006 
6007   // C++11 [class.copy]p23: [DR1402]
6008   //   A defaulted move assignment operator that is defined as deleted is
6009   //   ignored by overload resolution.
6010   if (Method->isDefaulted() && Method->isDeleted() &&
6011       Method->isMoveAssignmentOperator())
6012     return;
6013 
6014   // Overload resolution is always an unevaluated context.
6015   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6016 
6017   // Add this candidate
6018   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6019   Candidate.FoundDecl = FoundDecl;
6020   Candidate.Function = Method;
6021   Candidate.IsSurrogate = false;
6022   Candidate.IgnoreObjectArgument = false;
6023   Candidate.ExplicitCallArguments = Args.size();
6024 
6025   unsigned NumParams = Proto->getNumParams();
6026 
6027   // (C++ 13.3.2p2): A candidate function having fewer than m
6028   // parameters is viable only if it has an ellipsis in its parameter
6029   // list (8.3.5).
6030   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6031       !Proto->isVariadic()) {
6032     Candidate.Viable = false;
6033     Candidate.FailureKind = ovl_fail_too_many_arguments;
6034     return;
6035   }
6036 
6037   // (C++ 13.3.2p2): A candidate function having more than m parameters
6038   // is viable only if the (m+1)st parameter has a default argument
6039   // (8.3.6). For the purposes of overload resolution, the
6040   // parameter list is truncated on the right, so that there are
6041   // exactly m parameters.
6042   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6043   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6044     // Not enough arguments.
6045     Candidate.Viable = false;
6046     Candidate.FailureKind = ovl_fail_too_few_arguments;
6047     return;
6048   }
6049 
6050   Candidate.Viable = true;
6051 
6052   if (Method->isStatic() || ObjectType.isNull())
6053     // The implicit object argument is ignored.
6054     Candidate.IgnoreObjectArgument = true;
6055   else {
6056     // Determine the implicit conversion sequence for the object
6057     // parameter.
6058     Candidate.Conversions[0]
6059       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6060                                         Method, ActingContext);
6061     if (Candidate.Conversions[0].isBad()) {
6062       Candidate.Viable = false;
6063       Candidate.FailureKind = ovl_fail_bad_conversion;
6064       return;
6065     }
6066   }
6067 
6068   // (CUDA B.1): Check for invalid calls between targets.
6069   if (getLangOpts().CUDA)
6070     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6071       if (CheckCUDATarget(Caller, Method)) {
6072         Candidate.Viable = false;
6073         Candidate.FailureKind = ovl_fail_bad_target;
6074         return;
6075       }
6076 
6077   // Determine the implicit conversion sequences for each of the
6078   // arguments.
6079   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6080     if (ArgIdx < NumParams) {
6081       // (C++ 13.3.2p3): for F to be a viable function, there shall
6082       // exist for each argument an implicit conversion sequence
6083       // (13.3.3.1) that converts that argument to the corresponding
6084       // parameter of F.
6085       QualType ParamType = Proto->getParamType(ArgIdx);
6086       Candidate.Conversions[ArgIdx + 1]
6087         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6088                                 SuppressUserConversions,
6089                                 /*InOverloadResolution=*/true,
6090                                 /*AllowObjCWritebackConversion=*/
6091                                   getLangOpts().ObjCAutoRefCount);
6092       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6093         Candidate.Viable = false;
6094         Candidate.FailureKind = ovl_fail_bad_conversion;
6095         return;
6096       }
6097     } else {
6098       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6099       // argument for which there is no corresponding parameter is
6100       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6101       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6102     }
6103   }
6104 
6105   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6106     Candidate.Viable = false;
6107     Candidate.FailureKind = ovl_fail_enable_if;
6108     Candidate.DeductionFailure.Data = FailedAttr;
6109     return;
6110   }
6111 }
6112 
6113 /// \brief Add a C++ member function template as a candidate to the candidate
6114 /// set, using template argument deduction to produce an appropriate member
6115 /// function template specialization.
6116 void
6117 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6118                                  DeclAccessPair FoundDecl,
6119                                  CXXRecordDecl *ActingContext,
6120                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6121                                  QualType ObjectType,
6122                                  Expr::Classification ObjectClassification,
6123                                  ArrayRef<Expr *> Args,
6124                                  OverloadCandidateSet& CandidateSet,
6125                                  bool SuppressUserConversions,
6126                                  bool PartialOverloading) {
6127   if (!CandidateSet.isNewCandidate(MethodTmpl))
6128     return;
6129 
6130   // C++ [over.match.funcs]p7:
6131   //   In each case where a candidate is a function template, candidate
6132   //   function template specializations are generated using template argument
6133   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6134   //   candidate functions in the usual way.113) A given name can refer to one
6135   //   or more function templates and also to a set of overloaded non-template
6136   //   functions. In such a case, the candidate functions generated from each
6137   //   function template are combined with the set of non-template candidate
6138   //   functions.
6139   TemplateDeductionInfo Info(CandidateSet.getLocation());
6140   FunctionDecl *Specialization = nullptr;
6141   if (TemplateDeductionResult Result
6142       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6143                                 Specialization, Info, PartialOverloading)) {
6144     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6145     Candidate.FoundDecl = FoundDecl;
6146     Candidate.Function = MethodTmpl->getTemplatedDecl();
6147     Candidate.Viable = false;
6148     Candidate.FailureKind = ovl_fail_bad_deduction;
6149     Candidate.IsSurrogate = false;
6150     Candidate.IgnoreObjectArgument = false;
6151     Candidate.ExplicitCallArguments = Args.size();
6152     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6153                                                           Info);
6154     return;
6155   }
6156 
6157   // Add the function template specialization produced by template argument
6158   // deduction as a candidate.
6159   assert(Specialization && "Missing member function template specialization?");
6160   assert(isa<CXXMethodDecl>(Specialization) &&
6161          "Specialization is not a member function?");
6162   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6163                      ActingContext, ObjectType, ObjectClassification, Args,
6164                      CandidateSet, SuppressUserConversions, PartialOverloading);
6165 }
6166 
6167 /// \brief Add a C++ function template specialization as a candidate
6168 /// in the candidate set, using template argument deduction to produce
6169 /// an appropriate function template specialization.
6170 void
6171 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6172                                    DeclAccessPair FoundDecl,
6173                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6174                                    ArrayRef<Expr *> Args,
6175                                    OverloadCandidateSet& CandidateSet,
6176                                    bool SuppressUserConversions,
6177                                    bool PartialOverloading) {
6178   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6179     return;
6180 
6181   // C++ [over.match.funcs]p7:
6182   //   In each case where a candidate is a function template, candidate
6183   //   function template specializations are generated using template argument
6184   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6185   //   candidate functions in the usual way.113) A given name can refer to one
6186   //   or more function templates and also to a set of overloaded non-template
6187   //   functions. In such a case, the candidate functions generated from each
6188   //   function template are combined with the set of non-template candidate
6189   //   functions.
6190   TemplateDeductionInfo Info(CandidateSet.getLocation());
6191   FunctionDecl *Specialization = nullptr;
6192   if (TemplateDeductionResult Result
6193         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6194                                   Specialization, Info, PartialOverloading)) {
6195     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6196     Candidate.FoundDecl = FoundDecl;
6197     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6198     Candidate.Viable = false;
6199     Candidate.FailureKind = ovl_fail_bad_deduction;
6200     Candidate.IsSurrogate = false;
6201     Candidate.IgnoreObjectArgument = false;
6202     Candidate.ExplicitCallArguments = Args.size();
6203     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6204                                                           Info);
6205     return;
6206   }
6207 
6208   // Add the function template specialization produced by template argument
6209   // deduction as a candidate.
6210   assert(Specialization && "Missing function template specialization?");
6211   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6212                        SuppressUserConversions, PartialOverloading);
6213 }
6214 
6215 /// Determine whether this is an allowable conversion from the result
6216 /// of an explicit conversion operator to the expected type, per C++
6217 /// [over.match.conv]p1 and [over.match.ref]p1.
6218 ///
6219 /// \param ConvType The return type of the conversion function.
6220 ///
6221 /// \param ToType The type we are converting to.
6222 ///
6223 /// \param AllowObjCPointerConversion Allow a conversion from one
6224 /// Objective-C pointer to another.
6225 ///
6226 /// \returns true if the conversion is allowable, false otherwise.
6227 static bool isAllowableExplicitConversion(Sema &S,
6228                                           QualType ConvType, QualType ToType,
6229                                           bool AllowObjCPointerConversion) {
6230   QualType ToNonRefType = ToType.getNonReferenceType();
6231 
6232   // Easy case: the types are the same.
6233   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6234     return true;
6235 
6236   // Allow qualification conversions.
6237   bool ObjCLifetimeConversion;
6238   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6239                                   ObjCLifetimeConversion))
6240     return true;
6241 
6242   // If we're not allowed to consider Objective-C pointer conversions,
6243   // we're done.
6244   if (!AllowObjCPointerConversion)
6245     return false;
6246 
6247   // Is this an Objective-C pointer conversion?
6248   bool IncompatibleObjC = false;
6249   QualType ConvertedType;
6250   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6251                                    IncompatibleObjC);
6252 }
6253 
6254 /// AddConversionCandidate - Add a C++ conversion function as a
6255 /// candidate in the candidate set (C++ [over.match.conv],
6256 /// C++ [over.match.copy]). From is the expression we're converting from,
6257 /// and ToType is the type that we're eventually trying to convert to
6258 /// (which may or may not be the same type as the type that the
6259 /// conversion function produces).
6260 void
6261 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6262                              DeclAccessPair FoundDecl,
6263                              CXXRecordDecl *ActingContext,
6264                              Expr *From, QualType ToType,
6265                              OverloadCandidateSet& CandidateSet,
6266                              bool AllowObjCConversionOnExplicit) {
6267   assert(!Conversion->getDescribedFunctionTemplate() &&
6268          "Conversion function templates use AddTemplateConversionCandidate");
6269   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6270   if (!CandidateSet.isNewCandidate(Conversion))
6271     return;
6272 
6273   // If the conversion function has an undeduced return type, trigger its
6274   // deduction now.
6275   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6276     if (DeduceReturnType(Conversion, From->getExprLoc()))
6277       return;
6278     ConvType = Conversion->getConversionType().getNonReferenceType();
6279   }
6280 
6281   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6282   // operator is only a candidate if its return type is the target type or
6283   // can be converted to the target type with a qualification conversion.
6284   if (Conversion->isExplicit() &&
6285       !isAllowableExplicitConversion(*this, ConvType, ToType,
6286                                      AllowObjCConversionOnExplicit))
6287     return;
6288 
6289   // Overload resolution is always an unevaluated context.
6290   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6291 
6292   // Add this candidate
6293   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6294   Candidate.FoundDecl = FoundDecl;
6295   Candidate.Function = Conversion;
6296   Candidate.IsSurrogate = false;
6297   Candidate.IgnoreObjectArgument = false;
6298   Candidate.FinalConversion.setAsIdentityConversion();
6299   Candidate.FinalConversion.setFromType(ConvType);
6300   Candidate.FinalConversion.setAllToTypes(ToType);
6301   Candidate.Viable = true;
6302   Candidate.ExplicitCallArguments = 1;
6303 
6304   // C++ [over.match.funcs]p4:
6305   //   For conversion functions, the function is considered to be a member of
6306   //   the class of the implicit implied object argument for the purpose of
6307   //   defining the type of the implicit object parameter.
6308   //
6309   // Determine the implicit conversion sequence for the implicit
6310   // object parameter.
6311   QualType ImplicitParamType = From->getType();
6312   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6313     ImplicitParamType = FromPtrType->getPointeeType();
6314   CXXRecordDecl *ConversionContext
6315     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6316 
6317   Candidate.Conversions[0]
6318     = TryObjectArgumentInitialization(*this, From->getType(),
6319                                       From->Classify(Context),
6320                                       Conversion, ConversionContext);
6321 
6322   if (Candidate.Conversions[0].isBad()) {
6323     Candidate.Viable = false;
6324     Candidate.FailureKind = ovl_fail_bad_conversion;
6325     return;
6326   }
6327 
6328   // We won't go through a user-defined type conversion function to convert a
6329   // derived to base as such conversions are given Conversion Rank. They only
6330   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6331   QualType FromCanon
6332     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6333   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6334   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6335     Candidate.Viable = false;
6336     Candidate.FailureKind = ovl_fail_trivial_conversion;
6337     return;
6338   }
6339 
6340   // To determine what the conversion from the result of calling the
6341   // conversion function to the type we're eventually trying to
6342   // convert to (ToType), we need to synthesize a call to the
6343   // conversion function and attempt copy initialization from it. This
6344   // makes sure that we get the right semantics with respect to
6345   // lvalues/rvalues and the type. Fortunately, we can allocate this
6346   // call on the stack and we don't need its arguments to be
6347   // well-formed.
6348   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6349                             VK_LValue, From->getLocStart());
6350   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6351                                 Context.getPointerType(Conversion->getType()),
6352                                 CK_FunctionToPointerDecay,
6353                                 &ConversionRef, VK_RValue);
6354 
6355   QualType ConversionType = Conversion->getConversionType();
6356   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6357     Candidate.Viable = false;
6358     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6359     return;
6360   }
6361 
6362   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6363 
6364   // Note that it is safe to allocate CallExpr on the stack here because
6365   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6366   // allocator).
6367   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6368   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6369                 From->getLocStart());
6370   ImplicitConversionSequence ICS =
6371     TryCopyInitialization(*this, &Call, ToType,
6372                           /*SuppressUserConversions=*/true,
6373                           /*InOverloadResolution=*/false,
6374                           /*AllowObjCWritebackConversion=*/false);
6375 
6376   switch (ICS.getKind()) {
6377   case ImplicitConversionSequence::StandardConversion:
6378     Candidate.FinalConversion = ICS.Standard;
6379 
6380     // C++ [over.ics.user]p3:
6381     //   If the user-defined conversion is specified by a specialization of a
6382     //   conversion function template, the second standard conversion sequence
6383     //   shall have exact match rank.
6384     if (Conversion->getPrimaryTemplate() &&
6385         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6386       Candidate.Viable = false;
6387       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6388       return;
6389     }
6390 
6391     // C++0x [dcl.init.ref]p5:
6392     //    In the second case, if the reference is an rvalue reference and
6393     //    the second standard conversion sequence of the user-defined
6394     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6395     //    program is ill-formed.
6396     if (ToType->isRValueReferenceType() &&
6397         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6398       Candidate.Viable = false;
6399       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6400       return;
6401     }
6402     break;
6403 
6404   case ImplicitConversionSequence::BadConversion:
6405     Candidate.Viable = false;
6406     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6407     return;
6408 
6409   default:
6410     llvm_unreachable(
6411            "Can only end up with a standard conversion sequence or failure");
6412   }
6413 
6414   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6415     Candidate.Viable = false;
6416     Candidate.FailureKind = ovl_fail_enable_if;
6417     Candidate.DeductionFailure.Data = FailedAttr;
6418     return;
6419   }
6420 }
6421 
6422 /// \brief Adds a conversion function template specialization
6423 /// candidate to the overload set, using template argument deduction
6424 /// to deduce the template arguments of the conversion function
6425 /// template from the type that we are converting to (C++
6426 /// [temp.deduct.conv]).
6427 void
6428 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6429                                      DeclAccessPair FoundDecl,
6430                                      CXXRecordDecl *ActingDC,
6431                                      Expr *From, QualType ToType,
6432                                      OverloadCandidateSet &CandidateSet,
6433                                      bool AllowObjCConversionOnExplicit) {
6434   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6435          "Only conversion function templates permitted here");
6436 
6437   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6438     return;
6439 
6440   TemplateDeductionInfo Info(CandidateSet.getLocation());
6441   CXXConversionDecl *Specialization = nullptr;
6442   if (TemplateDeductionResult Result
6443         = DeduceTemplateArguments(FunctionTemplate, ToType,
6444                                   Specialization, Info)) {
6445     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6446     Candidate.FoundDecl = FoundDecl;
6447     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6448     Candidate.Viable = false;
6449     Candidate.FailureKind = ovl_fail_bad_deduction;
6450     Candidate.IsSurrogate = false;
6451     Candidate.IgnoreObjectArgument = false;
6452     Candidate.ExplicitCallArguments = 1;
6453     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6454                                                           Info);
6455     return;
6456   }
6457 
6458   // Add the conversion function template specialization produced by
6459   // template argument deduction as a candidate.
6460   assert(Specialization && "Missing function template specialization?");
6461   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6462                          CandidateSet, AllowObjCConversionOnExplicit);
6463 }
6464 
6465 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6466 /// converts the given @c Object to a function pointer via the
6467 /// conversion function @c Conversion, and then attempts to call it
6468 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6469 /// the type of function that we'll eventually be calling.
6470 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6471                                  DeclAccessPair FoundDecl,
6472                                  CXXRecordDecl *ActingContext,
6473                                  const FunctionProtoType *Proto,
6474                                  Expr *Object,
6475                                  ArrayRef<Expr *> Args,
6476                                  OverloadCandidateSet& CandidateSet) {
6477   if (!CandidateSet.isNewCandidate(Conversion))
6478     return;
6479 
6480   // Overload resolution is always an unevaluated context.
6481   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6482 
6483   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6484   Candidate.FoundDecl = FoundDecl;
6485   Candidate.Function = nullptr;
6486   Candidate.Surrogate = Conversion;
6487   Candidate.Viable = true;
6488   Candidate.IsSurrogate = true;
6489   Candidate.IgnoreObjectArgument = false;
6490   Candidate.ExplicitCallArguments = Args.size();
6491 
6492   // Determine the implicit conversion sequence for the implicit
6493   // object parameter.
6494   ImplicitConversionSequence ObjectInit
6495     = TryObjectArgumentInitialization(*this, Object->getType(),
6496                                       Object->Classify(Context),
6497                                       Conversion, ActingContext);
6498   if (ObjectInit.isBad()) {
6499     Candidate.Viable = false;
6500     Candidate.FailureKind = ovl_fail_bad_conversion;
6501     Candidate.Conversions[0] = ObjectInit;
6502     return;
6503   }
6504 
6505   // The first conversion is actually a user-defined conversion whose
6506   // first conversion is ObjectInit's standard conversion (which is
6507   // effectively a reference binding). Record it as such.
6508   Candidate.Conversions[0].setUserDefined();
6509   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6510   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6511   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6512   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6513   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6514   Candidate.Conversions[0].UserDefined.After
6515     = Candidate.Conversions[0].UserDefined.Before;
6516   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6517 
6518   // Find the
6519   unsigned NumParams = Proto->getNumParams();
6520 
6521   // (C++ 13.3.2p2): A candidate function having fewer than m
6522   // parameters is viable only if it has an ellipsis in its parameter
6523   // list (8.3.5).
6524   if (Args.size() > NumParams && !Proto->isVariadic()) {
6525     Candidate.Viable = false;
6526     Candidate.FailureKind = ovl_fail_too_many_arguments;
6527     return;
6528   }
6529 
6530   // Function types don't have any default arguments, so just check if
6531   // we have enough arguments.
6532   if (Args.size() < NumParams) {
6533     // Not enough arguments.
6534     Candidate.Viable = false;
6535     Candidate.FailureKind = ovl_fail_too_few_arguments;
6536     return;
6537   }
6538 
6539   // Determine the implicit conversion sequences for each of the
6540   // arguments.
6541   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6542     if (ArgIdx < NumParams) {
6543       // (C++ 13.3.2p3): for F to be a viable function, there shall
6544       // exist for each argument an implicit conversion sequence
6545       // (13.3.3.1) that converts that argument to the corresponding
6546       // parameter of F.
6547       QualType ParamType = Proto->getParamType(ArgIdx);
6548       Candidate.Conversions[ArgIdx + 1]
6549         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6550                                 /*SuppressUserConversions=*/false,
6551                                 /*InOverloadResolution=*/false,
6552                                 /*AllowObjCWritebackConversion=*/
6553                                   getLangOpts().ObjCAutoRefCount);
6554       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6555         Candidate.Viable = false;
6556         Candidate.FailureKind = ovl_fail_bad_conversion;
6557         return;
6558       }
6559     } else {
6560       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6561       // argument for which there is no corresponding parameter is
6562       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6563       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6564     }
6565   }
6566 
6567   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6568     Candidate.Viable = false;
6569     Candidate.FailureKind = ovl_fail_enable_if;
6570     Candidate.DeductionFailure.Data = FailedAttr;
6571     return;
6572   }
6573 }
6574 
6575 /// \brief Add overload candidates for overloaded operators that are
6576 /// member functions.
6577 ///
6578 /// Add the overloaded operator candidates that are member functions
6579 /// for the operator Op that was used in an operator expression such
6580 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6581 /// CandidateSet will store the added overload candidates. (C++
6582 /// [over.match.oper]).
6583 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6584                                        SourceLocation OpLoc,
6585                                        ArrayRef<Expr *> Args,
6586                                        OverloadCandidateSet& CandidateSet,
6587                                        SourceRange OpRange) {
6588   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6589 
6590   // C++ [over.match.oper]p3:
6591   //   For a unary operator @ with an operand of a type whose
6592   //   cv-unqualified version is T1, and for a binary operator @ with
6593   //   a left operand of a type whose cv-unqualified version is T1 and
6594   //   a right operand of a type whose cv-unqualified version is T2,
6595   //   three sets of candidate functions, designated member
6596   //   candidates, non-member candidates and built-in candidates, are
6597   //   constructed as follows:
6598   QualType T1 = Args[0]->getType();
6599 
6600   //     -- If T1 is a complete class type or a class currently being
6601   //        defined, the set of member candidates is the result of the
6602   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6603   //        the set of member candidates is empty.
6604   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6605     // Complete the type if it can be completed.
6606     RequireCompleteType(OpLoc, T1, 0);
6607     // If the type is neither complete nor being defined, bail out now.
6608     if (!T1Rec->getDecl()->getDefinition())
6609       return;
6610 
6611     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6612     LookupQualifiedName(Operators, T1Rec->getDecl());
6613     Operators.suppressDiagnostics();
6614 
6615     for (LookupResult::iterator Oper = Operators.begin(),
6616                              OperEnd = Operators.end();
6617          Oper != OperEnd;
6618          ++Oper)
6619       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6620                          Args[0]->Classify(Context),
6621                          Args.slice(1),
6622                          CandidateSet,
6623                          /* SuppressUserConversions = */ false);
6624   }
6625 }
6626 
6627 /// AddBuiltinCandidate - Add a candidate for a built-in
6628 /// operator. ResultTy and ParamTys are the result and parameter types
6629 /// of the built-in candidate, respectively. Args and NumArgs are the
6630 /// arguments being passed to the candidate. IsAssignmentOperator
6631 /// should be true when this built-in candidate is an assignment
6632 /// operator. NumContextualBoolArguments is the number of arguments
6633 /// (at the beginning of the argument list) that will be contextually
6634 /// converted to bool.
6635 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6636                                ArrayRef<Expr *> Args,
6637                                OverloadCandidateSet& CandidateSet,
6638                                bool IsAssignmentOperator,
6639                                unsigned NumContextualBoolArguments) {
6640   // Overload resolution is always an unevaluated context.
6641   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6642 
6643   // Add this candidate
6644   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6645   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6646   Candidate.Function = nullptr;
6647   Candidate.IsSurrogate = false;
6648   Candidate.IgnoreObjectArgument = false;
6649   Candidate.BuiltinTypes.ResultTy = ResultTy;
6650   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6651     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6652 
6653   // Determine the implicit conversion sequences for each of the
6654   // arguments.
6655   Candidate.Viable = true;
6656   Candidate.ExplicitCallArguments = Args.size();
6657   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6658     // C++ [over.match.oper]p4:
6659     //   For the built-in assignment operators, conversions of the
6660     //   left operand are restricted as follows:
6661     //     -- no temporaries are introduced to hold the left operand, and
6662     //     -- no user-defined conversions are applied to the left
6663     //        operand to achieve a type match with the left-most
6664     //        parameter of a built-in candidate.
6665     //
6666     // We block these conversions by turning off user-defined
6667     // conversions, since that is the only way that initialization of
6668     // a reference to a non-class type can occur from something that
6669     // is not of the same type.
6670     if (ArgIdx < NumContextualBoolArguments) {
6671       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6672              "Contextual conversion to bool requires bool type");
6673       Candidate.Conversions[ArgIdx]
6674         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6675     } else {
6676       Candidate.Conversions[ArgIdx]
6677         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6678                                 ArgIdx == 0 && IsAssignmentOperator,
6679                                 /*InOverloadResolution=*/false,
6680                                 /*AllowObjCWritebackConversion=*/
6681                                   getLangOpts().ObjCAutoRefCount);
6682     }
6683     if (Candidate.Conversions[ArgIdx].isBad()) {
6684       Candidate.Viable = false;
6685       Candidate.FailureKind = ovl_fail_bad_conversion;
6686       break;
6687     }
6688   }
6689 }
6690 
6691 namespace {
6692 
6693 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6694 /// candidate operator functions for built-in operators (C++
6695 /// [over.built]). The types are separated into pointer types and
6696 /// enumeration types.
6697 class BuiltinCandidateTypeSet  {
6698   /// TypeSet - A set of types.
6699   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6700 
6701   /// PointerTypes - The set of pointer types that will be used in the
6702   /// built-in candidates.
6703   TypeSet PointerTypes;
6704 
6705   /// MemberPointerTypes - The set of member pointer types that will be
6706   /// used in the built-in candidates.
6707   TypeSet MemberPointerTypes;
6708 
6709   /// EnumerationTypes - The set of enumeration types that will be
6710   /// used in the built-in candidates.
6711   TypeSet EnumerationTypes;
6712 
6713   /// \brief The set of vector types that will be used in the built-in
6714   /// candidates.
6715   TypeSet VectorTypes;
6716 
6717   /// \brief A flag indicating non-record types are viable candidates
6718   bool HasNonRecordTypes;
6719 
6720   /// \brief A flag indicating whether either arithmetic or enumeration types
6721   /// were present in the candidate set.
6722   bool HasArithmeticOrEnumeralTypes;
6723 
6724   /// \brief A flag indicating whether the nullptr type was present in the
6725   /// candidate set.
6726   bool HasNullPtrType;
6727 
6728   /// Sema - The semantic analysis instance where we are building the
6729   /// candidate type set.
6730   Sema &SemaRef;
6731 
6732   /// Context - The AST context in which we will build the type sets.
6733   ASTContext &Context;
6734 
6735   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6736                                                const Qualifiers &VisibleQuals);
6737   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6738 
6739 public:
6740   /// iterator - Iterates through the types that are part of the set.
6741   typedef TypeSet::iterator iterator;
6742 
6743   BuiltinCandidateTypeSet(Sema &SemaRef)
6744     : HasNonRecordTypes(false),
6745       HasArithmeticOrEnumeralTypes(false),
6746       HasNullPtrType(false),
6747       SemaRef(SemaRef),
6748       Context(SemaRef.Context) { }
6749 
6750   void AddTypesConvertedFrom(QualType Ty,
6751                              SourceLocation Loc,
6752                              bool AllowUserConversions,
6753                              bool AllowExplicitConversions,
6754                              const Qualifiers &VisibleTypeConversionsQuals);
6755 
6756   /// pointer_begin - First pointer type found;
6757   iterator pointer_begin() { return PointerTypes.begin(); }
6758 
6759   /// pointer_end - Past the last pointer type found;
6760   iterator pointer_end() { return PointerTypes.end(); }
6761 
6762   /// member_pointer_begin - First member pointer type found;
6763   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6764 
6765   /// member_pointer_end - Past the last member pointer type found;
6766   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6767 
6768   /// enumeration_begin - First enumeration type found;
6769   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6770 
6771   /// enumeration_end - Past the last enumeration type found;
6772   iterator enumeration_end() { return EnumerationTypes.end(); }
6773 
6774   iterator vector_begin() { return VectorTypes.begin(); }
6775   iterator vector_end() { return VectorTypes.end(); }
6776 
6777   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6778   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6779   bool hasNullPtrType() const { return HasNullPtrType; }
6780 };
6781 
6782 } // end anonymous namespace
6783 
6784 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6785 /// the set of pointer types along with any more-qualified variants of
6786 /// that type. For example, if @p Ty is "int const *", this routine
6787 /// will add "int const *", "int const volatile *", "int const
6788 /// restrict *", and "int const volatile restrict *" to the set of
6789 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6790 /// false otherwise.
6791 ///
6792 /// FIXME: what to do about extended qualifiers?
6793 bool
6794 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6795                                              const Qualifiers &VisibleQuals) {
6796 
6797   // Insert this type.
6798   if (!PointerTypes.insert(Ty).second)
6799     return false;
6800 
6801   QualType PointeeTy;
6802   const PointerType *PointerTy = Ty->getAs<PointerType>();
6803   bool buildObjCPtr = false;
6804   if (!PointerTy) {
6805     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6806     PointeeTy = PTy->getPointeeType();
6807     buildObjCPtr = true;
6808   } else {
6809     PointeeTy = PointerTy->getPointeeType();
6810   }
6811 
6812   // Don't add qualified variants of arrays. For one, they're not allowed
6813   // (the qualifier would sink to the element type), and for another, the
6814   // only overload situation where it matters is subscript or pointer +- int,
6815   // and those shouldn't have qualifier variants anyway.
6816   if (PointeeTy->isArrayType())
6817     return true;
6818 
6819   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6820   bool hasVolatile = VisibleQuals.hasVolatile();
6821   bool hasRestrict = VisibleQuals.hasRestrict();
6822 
6823   // Iterate through all strict supersets of BaseCVR.
6824   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6825     if ((CVR | BaseCVR) != CVR) continue;
6826     // Skip over volatile if no volatile found anywhere in the types.
6827     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6828 
6829     // Skip over restrict if no restrict found anywhere in the types, or if
6830     // the type cannot be restrict-qualified.
6831     if ((CVR & Qualifiers::Restrict) &&
6832         (!hasRestrict ||
6833          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6834       continue;
6835 
6836     // Build qualified pointee type.
6837     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6838 
6839     // Build qualified pointer type.
6840     QualType QPointerTy;
6841     if (!buildObjCPtr)
6842       QPointerTy = Context.getPointerType(QPointeeTy);
6843     else
6844       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6845 
6846     // Insert qualified pointer type.
6847     PointerTypes.insert(QPointerTy);
6848   }
6849 
6850   return true;
6851 }
6852 
6853 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6854 /// to the set of pointer types along with any more-qualified variants of
6855 /// that type. For example, if @p Ty is "int const *", this routine
6856 /// will add "int const *", "int const volatile *", "int const
6857 /// restrict *", and "int const volatile restrict *" to the set of
6858 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6859 /// false otherwise.
6860 ///
6861 /// FIXME: what to do about extended qualifiers?
6862 bool
6863 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6864     QualType Ty) {
6865   // Insert this type.
6866   if (!MemberPointerTypes.insert(Ty).second)
6867     return false;
6868 
6869   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6870   assert(PointerTy && "type was not a member pointer type!");
6871 
6872   QualType PointeeTy = PointerTy->getPointeeType();
6873   // Don't add qualified variants of arrays. For one, they're not allowed
6874   // (the qualifier would sink to the element type), and for another, the
6875   // only overload situation where it matters is subscript or pointer +- int,
6876   // and those shouldn't have qualifier variants anyway.
6877   if (PointeeTy->isArrayType())
6878     return true;
6879   const Type *ClassTy = PointerTy->getClass();
6880 
6881   // Iterate through all strict supersets of the pointee type's CVR
6882   // qualifiers.
6883   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6884   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6885     if ((CVR | BaseCVR) != CVR) continue;
6886 
6887     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6888     MemberPointerTypes.insert(
6889       Context.getMemberPointerType(QPointeeTy, ClassTy));
6890   }
6891 
6892   return true;
6893 }
6894 
6895 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6896 /// Ty can be implicit converted to the given set of @p Types. We're
6897 /// primarily interested in pointer types and enumeration types. We also
6898 /// take member pointer types, for the conditional operator.
6899 /// AllowUserConversions is true if we should look at the conversion
6900 /// functions of a class type, and AllowExplicitConversions if we
6901 /// should also include the explicit conversion functions of a class
6902 /// type.
6903 void
6904 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6905                                                SourceLocation Loc,
6906                                                bool AllowUserConversions,
6907                                                bool AllowExplicitConversions,
6908                                                const Qualifiers &VisibleQuals) {
6909   // Only deal with canonical types.
6910   Ty = Context.getCanonicalType(Ty);
6911 
6912   // Look through reference types; they aren't part of the type of an
6913   // expression for the purposes of conversions.
6914   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6915     Ty = RefTy->getPointeeType();
6916 
6917   // If we're dealing with an array type, decay to the pointer.
6918   if (Ty->isArrayType())
6919     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6920 
6921   // Otherwise, we don't care about qualifiers on the type.
6922   Ty = Ty.getLocalUnqualifiedType();
6923 
6924   // Flag if we ever add a non-record type.
6925   const RecordType *TyRec = Ty->getAs<RecordType>();
6926   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6927 
6928   // Flag if we encounter an arithmetic type.
6929   HasArithmeticOrEnumeralTypes =
6930     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6931 
6932   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6933     PointerTypes.insert(Ty);
6934   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6935     // Insert our type, and its more-qualified variants, into the set
6936     // of types.
6937     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6938       return;
6939   } else if (Ty->isMemberPointerType()) {
6940     // Member pointers are far easier, since the pointee can't be converted.
6941     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6942       return;
6943   } else if (Ty->isEnumeralType()) {
6944     HasArithmeticOrEnumeralTypes = true;
6945     EnumerationTypes.insert(Ty);
6946   } else if (Ty->isVectorType()) {
6947     // We treat vector types as arithmetic types in many contexts as an
6948     // extension.
6949     HasArithmeticOrEnumeralTypes = true;
6950     VectorTypes.insert(Ty);
6951   } else if (Ty->isNullPtrType()) {
6952     HasNullPtrType = true;
6953   } else if (AllowUserConversions && TyRec) {
6954     // No conversion functions in incomplete types.
6955     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6956       return;
6957 
6958     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6959     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6960       if (isa<UsingShadowDecl>(D))
6961         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6962 
6963       // Skip conversion function templates; they don't tell us anything
6964       // about which builtin types we can convert to.
6965       if (isa<FunctionTemplateDecl>(D))
6966         continue;
6967 
6968       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6969       if (AllowExplicitConversions || !Conv->isExplicit()) {
6970         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6971                               VisibleQuals);
6972       }
6973     }
6974   }
6975 }
6976 
6977 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6978 /// the volatile- and non-volatile-qualified assignment operators for the
6979 /// given type to the candidate set.
6980 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6981                                                    QualType T,
6982                                                    ArrayRef<Expr *> Args,
6983                                     OverloadCandidateSet &CandidateSet) {
6984   QualType ParamTypes[2];
6985 
6986   // T& operator=(T&, T)
6987   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6988   ParamTypes[1] = T;
6989   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6990                         /*IsAssignmentOperator=*/true);
6991 
6992   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6993     // volatile T& operator=(volatile T&, T)
6994     ParamTypes[0]
6995       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6996     ParamTypes[1] = T;
6997     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6998                           /*IsAssignmentOperator=*/true);
6999   }
7000 }
7001 
7002 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7003 /// if any, found in visible type conversion functions found in ArgExpr's type.
7004 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7005     Qualifiers VRQuals;
7006     const RecordType *TyRec;
7007     if (const MemberPointerType *RHSMPType =
7008         ArgExpr->getType()->getAs<MemberPointerType>())
7009       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7010     else
7011       TyRec = ArgExpr->getType()->getAs<RecordType>();
7012     if (!TyRec) {
7013       // Just to be safe, assume the worst case.
7014       VRQuals.addVolatile();
7015       VRQuals.addRestrict();
7016       return VRQuals;
7017     }
7018 
7019     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7020     if (!ClassDecl->hasDefinition())
7021       return VRQuals;
7022 
7023     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7024       if (isa<UsingShadowDecl>(D))
7025         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7026       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7027         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7028         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7029           CanTy = ResTypeRef->getPointeeType();
7030         // Need to go down the pointer/mempointer chain and add qualifiers
7031         // as see them.
7032         bool done = false;
7033         while (!done) {
7034           if (CanTy.isRestrictQualified())
7035             VRQuals.addRestrict();
7036           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7037             CanTy = ResTypePtr->getPointeeType();
7038           else if (const MemberPointerType *ResTypeMPtr =
7039                 CanTy->getAs<MemberPointerType>())
7040             CanTy = ResTypeMPtr->getPointeeType();
7041           else
7042             done = true;
7043           if (CanTy.isVolatileQualified())
7044             VRQuals.addVolatile();
7045           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7046             return VRQuals;
7047         }
7048       }
7049     }
7050     return VRQuals;
7051 }
7052 
7053 namespace {
7054 
7055 /// \brief Helper class to manage the addition of builtin operator overload
7056 /// candidates. It provides shared state and utility methods used throughout
7057 /// the process, as well as a helper method to add each group of builtin
7058 /// operator overloads from the standard to a candidate set.
7059 class BuiltinOperatorOverloadBuilder {
7060   // Common instance state available to all overload candidate addition methods.
7061   Sema &S;
7062   ArrayRef<Expr *> Args;
7063   Qualifiers VisibleTypeConversionsQuals;
7064   bool HasArithmeticOrEnumeralCandidateType;
7065   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7066   OverloadCandidateSet &CandidateSet;
7067 
7068   // Define some constants used to index and iterate over the arithemetic types
7069   // provided via the getArithmeticType() method below.
7070   // The "promoted arithmetic types" are the arithmetic
7071   // types are that preserved by promotion (C++ [over.built]p2).
7072   static const unsigned FirstIntegralType = 3;
7073   static const unsigned LastIntegralType = 20;
7074   static const unsigned FirstPromotedIntegralType = 3,
7075                         LastPromotedIntegralType = 11;
7076   static const unsigned FirstPromotedArithmeticType = 0,
7077                         LastPromotedArithmeticType = 11;
7078   static const unsigned NumArithmeticTypes = 20;
7079 
7080   /// \brief Get the canonical type for a given arithmetic type index.
7081   CanQualType getArithmeticType(unsigned index) {
7082     assert(index < NumArithmeticTypes);
7083     static CanQualType ASTContext::* const
7084       ArithmeticTypes[NumArithmeticTypes] = {
7085       // Start of promoted types.
7086       &ASTContext::FloatTy,
7087       &ASTContext::DoubleTy,
7088       &ASTContext::LongDoubleTy,
7089 
7090       // Start of integral types.
7091       &ASTContext::IntTy,
7092       &ASTContext::LongTy,
7093       &ASTContext::LongLongTy,
7094       &ASTContext::Int128Ty,
7095       &ASTContext::UnsignedIntTy,
7096       &ASTContext::UnsignedLongTy,
7097       &ASTContext::UnsignedLongLongTy,
7098       &ASTContext::UnsignedInt128Ty,
7099       // End of promoted types.
7100 
7101       &ASTContext::BoolTy,
7102       &ASTContext::CharTy,
7103       &ASTContext::WCharTy,
7104       &ASTContext::Char16Ty,
7105       &ASTContext::Char32Ty,
7106       &ASTContext::SignedCharTy,
7107       &ASTContext::ShortTy,
7108       &ASTContext::UnsignedCharTy,
7109       &ASTContext::UnsignedShortTy,
7110       // End of integral types.
7111       // FIXME: What about complex? What about half?
7112     };
7113     return S.Context.*ArithmeticTypes[index];
7114   }
7115 
7116   /// \brief Gets the canonical type resulting from the usual arithemetic
7117   /// converions for the given arithmetic types.
7118   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7119     // Accelerator table for performing the usual arithmetic conversions.
7120     // The rules are basically:
7121     //   - if either is floating-point, use the wider floating-point
7122     //   - if same signedness, use the higher rank
7123     //   - if same size, use unsigned of the higher rank
7124     //   - use the larger type
7125     // These rules, together with the axiom that higher ranks are
7126     // never smaller, are sufficient to precompute all of these results
7127     // *except* when dealing with signed types of higher rank.
7128     // (we could precompute SLL x UI for all known platforms, but it's
7129     // better not to make any assumptions).
7130     // We assume that int128 has a higher rank than long long on all platforms.
7131     enum PromotedType {
7132             Dep=-1,
7133             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7134     };
7135     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7136                                         [LastPromotedArithmeticType] = {
7137 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7138 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7139 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7140 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7141 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7142 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7143 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7144 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7145 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7146 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7147 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7148     };
7149 
7150     assert(L < LastPromotedArithmeticType);
7151     assert(R < LastPromotedArithmeticType);
7152     int Idx = ConversionsTable[L][R];
7153 
7154     // Fast path: the table gives us a concrete answer.
7155     if (Idx != Dep) return getArithmeticType(Idx);
7156 
7157     // Slow path: we need to compare widths.
7158     // An invariant is that the signed type has higher rank.
7159     CanQualType LT = getArithmeticType(L),
7160                 RT = getArithmeticType(R);
7161     unsigned LW = S.Context.getIntWidth(LT),
7162              RW = S.Context.getIntWidth(RT);
7163 
7164     // If they're different widths, use the signed type.
7165     if (LW > RW) return LT;
7166     else if (LW < RW) return RT;
7167 
7168     // Otherwise, use the unsigned type of the signed type's rank.
7169     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7170     assert(L == SLL || R == SLL);
7171     return S.Context.UnsignedLongLongTy;
7172   }
7173 
7174   /// \brief Helper method to factor out the common pattern of adding overloads
7175   /// for '++' and '--' builtin operators.
7176   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7177                                            bool HasVolatile,
7178                                            bool HasRestrict) {
7179     QualType ParamTypes[2] = {
7180       S.Context.getLValueReferenceType(CandidateTy),
7181       S.Context.IntTy
7182     };
7183 
7184     // Non-volatile version.
7185     if (Args.size() == 1)
7186       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7187     else
7188       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7189 
7190     // Use a heuristic to reduce number of builtin candidates in the set:
7191     // add volatile version only if there are conversions to a volatile type.
7192     if (HasVolatile) {
7193       ParamTypes[0] =
7194         S.Context.getLValueReferenceType(
7195           S.Context.getVolatileType(CandidateTy));
7196       if (Args.size() == 1)
7197         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7198       else
7199         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7200     }
7201 
7202     // Add restrict version only if there are conversions to a restrict type
7203     // and our candidate type is a non-restrict-qualified pointer.
7204     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7205         !CandidateTy.isRestrictQualified()) {
7206       ParamTypes[0]
7207         = S.Context.getLValueReferenceType(
7208             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7209       if (Args.size() == 1)
7210         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7211       else
7212         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7213 
7214       if (HasVolatile) {
7215         ParamTypes[0]
7216           = S.Context.getLValueReferenceType(
7217               S.Context.getCVRQualifiedType(CandidateTy,
7218                                             (Qualifiers::Volatile |
7219                                              Qualifiers::Restrict)));
7220         if (Args.size() == 1)
7221           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7222         else
7223           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7224       }
7225     }
7226 
7227   }
7228 
7229 public:
7230   BuiltinOperatorOverloadBuilder(
7231     Sema &S, ArrayRef<Expr *> Args,
7232     Qualifiers VisibleTypeConversionsQuals,
7233     bool HasArithmeticOrEnumeralCandidateType,
7234     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7235     OverloadCandidateSet &CandidateSet)
7236     : S(S), Args(Args),
7237       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7238       HasArithmeticOrEnumeralCandidateType(
7239         HasArithmeticOrEnumeralCandidateType),
7240       CandidateTypes(CandidateTypes),
7241       CandidateSet(CandidateSet) {
7242     // Validate some of our static helper constants in debug builds.
7243     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7244            "Invalid first promoted integral type");
7245     assert(getArithmeticType(LastPromotedIntegralType - 1)
7246              == S.Context.UnsignedInt128Ty &&
7247            "Invalid last promoted integral type");
7248     assert(getArithmeticType(FirstPromotedArithmeticType)
7249              == S.Context.FloatTy &&
7250            "Invalid first promoted arithmetic type");
7251     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7252              == S.Context.UnsignedInt128Ty &&
7253            "Invalid last promoted arithmetic type");
7254   }
7255 
7256   // C++ [over.built]p3:
7257   //
7258   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7259   //   is either volatile or empty, there exist candidate operator
7260   //   functions of the form
7261   //
7262   //       VQ T&      operator++(VQ T&);
7263   //       T          operator++(VQ T&, int);
7264   //
7265   // C++ [over.built]p4:
7266   //
7267   //   For every pair (T, VQ), where T is an arithmetic type other
7268   //   than bool, and VQ is either volatile or empty, there exist
7269   //   candidate operator functions of the form
7270   //
7271   //       VQ T&      operator--(VQ T&);
7272   //       T          operator--(VQ T&, int);
7273   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7274     if (!HasArithmeticOrEnumeralCandidateType)
7275       return;
7276 
7277     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7278          Arith < NumArithmeticTypes; ++Arith) {
7279       addPlusPlusMinusMinusStyleOverloads(
7280         getArithmeticType(Arith),
7281         VisibleTypeConversionsQuals.hasVolatile(),
7282         VisibleTypeConversionsQuals.hasRestrict());
7283     }
7284   }
7285 
7286   // C++ [over.built]p5:
7287   //
7288   //   For every pair (T, VQ), where T is a cv-qualified or
7289   //   cv-unqualified object type, and VQ is either volatile or
7290   //   empty, there exist candidate operator functions of the form
7291   //
7292   //       T*VQ&      operator++(T*VQ&);
7293   //       T*VQ&      operator--(T*VQ&);
7294   //       T*         operator++(T*VQ&, int);
7295   //       T*         operator--(T*VQ&, int);
7296   void addPlusPlusMinusMinusPointerOverloads() {
7297     for (BuiltinCandidateTypeSet::iterator
7298               Ptr = CandidateTypes[0].pointer_begin(),
7299            PtrEnd = CandidateTypes[0].pointer_end();
7300          Ptr != PtrEnd; ++Ptr) {
7301       // Skip pointer types that aren't pointers to object types.
7302       if (!(*Ptr)->getPointeeType()->isObjectType())
7303         continue;
7304 
7305       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7306         (!(*Ptr).isVolatileQualified() &&
7307          VisibleTypeConversionsQuals.hasVolatile()),
7308         (!(*Ptr).isRestrictQualified() &&
7309          VisibleTypeConversionsQuals.hasRestrict()));
7310     }
7311   }
7312 
7313   // C++ [over.built]p6:
7314   //   For every cv-qualified or cv-unqualified object type T, there
7315   //   exist candidate operator functions of the form
7316   //
7317   //       T&         operator*(T*);
7318   //
7319   // C++ [over.built]p7:
7320   //   For every function type T that does not have cv-qualifiers or a
7321   //   ref-qualifier, there exist candidate operator functions of the form
7322   //       T&         operator*(T*);
7323   void addUnaryStarPointerOverloads() {
7324     for (BuiltinCandidateTypeSet::iterator
7325               Ptr = CandidateTypes[0].pointer_begin(),
7326            PtrEnd = CandidateTypes[0].pointer_end();
7327          Ptr != PtrEnd; ++Ptr) {
7328       QualType ParamTy = *Ptr;
7329       QualType PointeeTy = ParamTy->getPointeeType();
7330       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7331         continue;
7332 
7333       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7334         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7335           continue;
7336 
7337       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7338                             &ParamTy, Args, CandidateSet);
7339     }
7340   }
7341 
7342   // C++ [over.built]p9:
7343   //  For every promoted arithmetic type T, there exist candidate
7344   //  operator functions of the form
7345   //
7346   //       T         operator+(T);
7347   //       T         operator-(T);
7348   void addUnaryPlusOrMinusArithmeticOverloads() {
7349     if (!HasArithmeticOrEnumeralCandidateType)
7350       return;
7351 
7352     for (unsigned Arith = FirstPromotedArithmeticType;
7353          Arith < LastPromotedArithmeticType; ++Arith) {
7354       QualType ArithTy = getArithmeticType(Arith);
7355       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7356     }
7357 
7358     // Extension: We also add these operators for vector types.
7359     for (BuiltinCandidateTypeSet::iterator
7360               Vec = CandidateTypes[0].vector_begin(),
7361            VecEnd = CandidateTypes[0].vector_end();
7362          Vec != VecEnd; ++Vec) {
7363       QualType VecTy = *Vec;
7364       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7365     }
7366   }
7367 
7368   // C++ [over.built]p8:
7369   //   For every type T, there exist candidate operator functions of
7370   //   the form
7371   //
7372   //       T*         operator+(T*);
7373   void addUnaryPlusPointerOverloads() {
7374     for (BuiltinCandidateTypeSet::iterator
7375               Ptr = CandidateTypes[0].pointer_begin(),
7376            PtrEnd = CandidateTypes[0].pointer_end();
7377          Ptr != PtrEnd; ++Ptr) {
7378       QualType ParamTy = *Ptr;
7379       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7380     }
7381   }
7382 
7383   // C++ [over.built]p10:
7384   //   For every promoted integral type T, there exist candidate
7385   //   operator functions of the form
7386   //
7387   //        T         operator~(T);
7388   void addUnaryTildePromotedIntegralOverloads() {
7389     if (!HasArithmeticOrEnumeralCandidateType)
7390       return;
7391 
7392     for (unsigned Int = FirstPromotedIntegralType;
7393          Int < LastPromotedIntegralType; ++Int) {
7394       QualType IntTy = getArithmeticType(Int);
7395       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7396     }
7397 
7398     // Extension: We also add this operator for vector types.
7399     for (BuiltinCandidateTypeSet::iterator
7400               Vec = CandidateTypes[0].vector_begin(),
7401            VecEnd = CandidateTypes[0].vector_end();
7402          Vec != VecEnd; ++Vec) {
7403       QualType VecTy = *Vec;
7404       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7405     }
7406   }
7407 
7408   // C++ [over.match.oper]p16:
7409   //   For every pointer to member type T, there exist candidate operator
7410   //   functions of the form
7411   //
7412   //        bool operator==(T,T);
7413   //        bool operator!=(T,T);
7414   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7415     /// Set of (canonical) types that we've already handled.
7416     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7417 
7418     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7419       for (BuiltinCandidateTypeSet::iterator
7420                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7421              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7422            MemPtr != MemPtrEnd;
7423            ++MemPtr) {
7424         // Don't add the same builtin candidate twice.
7425         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7426           continue;
7427 
7428         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7429         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7430       }
7431     }
7432   }
7433 
7434   // C++ [over.built]p15:
7435   //
7436   //   For every T, where T is an enumeration type, a pointer type, or
7437   //   std::nullptr_t, there exist candidate operator functions of the form
7438   //
7439   //        bool       operator<(T, T);
7440   //        bool       operator>(T, T);
7441   //        bool       operator<=(T, T);
7442   //        bool       operator>=(T, T);
7443   //        bool       operator==(T, T);
7444   //        bool       operator!=(T, T);
7445   void addRelationalPointerOrEnumeralOverloads() {
7446     // C++ [over.match.oper]p3:
7447     //   [...]the built-in candidates include all of the candidate operator
7448     //   functions defined in 13.6 that, compared to the given operator, [...]
7449     //   do not have the same parameter-type-list as any non-template non-member
7450     //   candidate.
7451     //
7452     // Note that in practice, this only affects enumeration types because there
7453     // aren't any built-in candidates of record type, and a user-defined operator
7454     // must have an operand of record or enumeration type. Also, the only other
7455     // overloaded operator with enumeration arguments, operator=,
7456     // cannot be overloaded for enumeration types, so this is the only place
7457     // where we must suppress candidates like this.
7458     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7459       UserDefinedBinaryOperators;
7460 
7461     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7462       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7463           CandidateTypes[ArgIdx].enumeration_end()) {
7464         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7465                                          CEnd = CandidateSet.end();
7466              C != CEnd; ++C) {
7467           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7468             continue;
7469 
7470           if (C->Function->isFunctionTemplateSpecialization())
7471             continue;
7472 
7473           QualType FirstParamType =
7474             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7475           QualType SecondParamType =
7476             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7477 
7478           // Skip if either parameter isn't of enumeral type.
7479           if (!FirstParamType->isEnumeralType() ||
7480               !SecondParamType->isEnumeralType())
7481             continue;
7482 
7483           // Add this operator to the set of known user-defined operators.
7484           UserDefinedBinaryOperators.insert(
7485             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7486                            S.Context.getCanonicalType(SecondParamType)));
7487         }
7488       }
7489     }
7490 
7491     /// Set of (canonical) types that we've already handled.
7492     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7493 
7494     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7495       for (BuiltinCandidateTypeSet::iterator
7496                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7497              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7498            Ptr != PtrEnd; ++Ptr) {
7499         // Don't add the same builtin candidate twice.
7500         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7501           continue;
7502 
7503         QualType ParamTypes[2] = { *Ptr, *Ptr };
7504         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7505       }
7506       for (BuiltinCandidateTypeSet::iterator
7507                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7508              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7509            Enum != EnumEnd; ++Enum) {
7510         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7511 
7512         // Don't add the same builtin candidate twice, or if a user defined
7513         // candidate exists.
7514         if (!AddedTypes.insert(CanonType).second ||
7515             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7516                                                             CanonType)))
7517           continue;
7518 
7519         QualType ParamTypes[2] = { *Enum, *Enum };
7520         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7521       }
7522 
7523       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7524         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7525         if (AddedTypes.insert(NullPtrTy).second &&
7526             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7527                                                              NullPtrTy))) {
7528           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7529           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7530                                 CandidateSet);
7531         }
7532       }
7533     }
7534   }
7535 
7536   // C++ [over.built]p13:
7537   //
7538   //   For every cv-qualified or cv-unqualified object type T
7539   //   there exist candidate operator functions of the form
7540   //
7541   //      T*         operator+(T*, ptrdiff_t);
7542   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7543   //      T*         operator-(T*, ptrdiff_t);
7544   //      T*         operator+(ptrdiff_t, T*);
7545   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7546   //
7547   // C++ [over.built]p14:
7548   //
7549   //   For every T, where T is a pointer to object type, there
7550   //   exist candidate operator functions of the form
7551   //
7552   //      ptrdiff_t  operator-(T, T);
7553   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7554     /// Set of (canonical) types that we've already handled.
7555     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7556 
7557     for (int Arg = 0; Arg < 2; ++Arg) {
7558       QualType AsymmetricParamTypes[2] = {
7559         S.Context.getPointerDiffType(),
7560         S.Context.getPointerDiffType(),
7561       };
7562       for (BuiltinCandidateTypeSet::iterator
7563                 Ptr = CandidateTypes[Arg].pointer_begin(),
7564              PtrEnd = CandidateTypes[Arg].pointer_end();
7565            Ptr != PtrEnd; ++Ptr) {
7566         QualType PointeeTy = (*Ptr)->getPointeeType();
7567         if (!PointeeTy->isObjectType())
7568           continue;
7569 
7570         AsymmetricParamTypes[Arg] = *Ptr;
7571         if (Arg == 0 || Op == OO_Plus) {
7572           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7573           // T* operator+(ptrdiff_t, T*);
7574           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7575         }
7576         if (Op == OO_Minus) {
7577           // ptrdiff_t operator-(T, T);
7578           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7579             continue;
7580 
7581           QualType ParamTypes[2] = { *Ptr, *Ptr };
7582           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7583                                 Args, CandidateSet);
7584         }
7585       }
7586     }
7587   }
7588 
7589   // C++ [over.built]p12:
7590   //
7591   //   For every pair of promoted arithmetic types L and R, there
7592   //   exist candidate operator functions of the form
7593   //
7594   //        LR         operator*(L, R);
7595   //        LR         operator/(L, R);
7596   //        LR         operator+(L, R);
7597   //        LR         operator-(L, R);
7598   //        bool       operator<(L, R);
7599   //        bool       operator>(L, R);
7600   //        bool       operator<=(L, R);
7601   //        bool       operator>=(L, R);
7602   //        bool       operator==(L, R);
7603   //        bool       operator!=(L, R);
7604   //
7605   //   where LR is the result of the usual arithmetic conversions
7606   //   between types L and R.
7607   //
7608   // C++ [over.built]p24:
7609   //
7610   //   For every pair of promoted arithmetic types L and R, there exist
7611   //   candidate operator functions of the form
7612   //
7613   //        LR       operator?(bool, L, R);
7614   //
7615   //   where LR is the result of the usual arithmetic conversions
7616   //   between types L and R.
7617   // Our candidates ignore the first parameter.
7618   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7619     if (!HasArithmeticOrEnumeralCandidateType)
7620       return;
7621 
7622     for (unsigned Left = FirstPromotedArithmeticType;
7623          Left < LastPromotedArithmeticType; ++Left) {
7624       for (unsigned Right = FirstPromotedArithmeticType;
7625            Right < LastPromotedArithmeticType; ++Right) {
7626         QualType LandR[2] = { getArithmeticType(Left),
7627                               getArithmeticType(Right) };
7628         QualType Result =
7629           isComparison ? S.Context.BoolTy
7630                        : getUsualArithmeticConversions(Left, Right);
7631         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7632       }
7633     }
7634 
7635     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7636     // conditional operator for vector types.
7637     for (BuiltinCandidateTypeSet::iterator
7638               Vec1 = CandidateTypes[0].vector_begin(),
7639            Vec1End = CandidateTypes[0].vector_end();
7640          Vec1 != Vec1End; ++Vec1) {
7641       for (BuiltinCandidateTypeSet::iterator
7642                 Vec2 = CandidateTypes[1].vector_begin(),
7643              Vec2End = CandidateTypes[1].vector_end();
7644            Vec2 != Vec2End; ++Vec2) {
7645         QualType LandR[2] = { *Vec1, *Vec2 };
7646         QualType Result = S.Context.BoolTy;
7647         if (!isComparison) {
7648           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7649             Result = *Vec1;
7650           else
7651             Result = *Vec2;
7652         }
7653 
7654         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7655       }
7656     }
7657   }
7658 
7659   // C++ [over.built]p17:
7660   //
7661   //   For every pair of promoted integral types L and R, there
7662   //   exist candidate operator functions of the form
7663   //
7664   //      LR         operator%(L, R);
7665   //      LR         operator&(L, R);
7666   //      LR         operator^(L, R);
7667   //      LR         operator|(L, R);
7668   //      L          operator<<(L, R);
7669   //      L          operator>>(L, R);
7670   //
7671   //   where LR is the result of the usual arithmetic conversions
7672   //   between types L and R.
7673   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7674     if (!HasArithmeticOrEnumeralCandidateType)
7675       return;
7676 
7677     for (unsigned Left = FirstPromotedIntegralType;
7678          Left < LastPromotedIntegralType; ++Left) {
7679       for (unsigned Right = FirstPromotedIntegralType;
7680            Right < LastPromotedIntegralType; ++Right) {
7681         QualType LandR[2] = { getArithmeticType(Left),
7682                               getArithmeticType(Right) };
7683         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7684             ? LandR[0]
7685             : getUsualArithmeticConversions(Left, Right);
7686         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7687       }
7688     }
7689   }
7690 
7691   // C++ [over.built]p20:
7692   //
7693   //   For every pair (T, VQ), where T is an enumeration or
7694   //   pointer to member type and VQ is either volatile or
7695   //   empty, there exist candidate operator functions of the form
7696   //
7697   //        VQ T&      operator=(VQ T&, T);
7698   void addAssignmentMemberPointerOrEnumeralOverloads() {
7699     /// Set of (canonical) types that we've already handled.
7700     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7701 
7702     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7703       for (BuiltinCandidateTypeSet::iterator
7704                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7705              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7706            Enum != EnumEnd; ++Enum) {
7707         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7708           continue;
7709 
7710         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7711       }
7712 
7713       for (BuiltinCandidateTypeSet::iterator
7714                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7715              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7716            MemPtr != MemPtrEnd; ++MemPtr) {
7717         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7718           continue;
7719 
7720         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7721       }
7722     }
7723   }
7724 
7725   // C++ [over.built]p19:
7726   //
7727   //   For every pair (T, VQ), where T is any type and VQ is either
7728   //   volatile or empty, there exist candidate operator functions
7729   //   of the form
7730   //
7731   //        T*VQ&      operator=(T*VQ&, T*);
7732   //
7733   // C++ [over.built]p21:
7734   //
7735   //   For every pair (T, VQ), where T is a cv-qualified or
7736   //   cv-unqualified object type and VQ is either volatile or
7737   //   empty, there exist candidate operator functions of the form
7738   //
7739   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7740   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7741   void addAssignmentPointerOverloads(bool isEqualOp) {
7742     /// Set of (canonical) types that we've already handled.
7743     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7744 
7745     for (BuiltinCandidateTypeSet::iterator
7746               Ptr = CandidateTypes[0].pointer_begin(),
7747            PtrEnd = CandidateTypes[0].pointer_end();
7748          Ptr != PtrEnd; ++Ptr) {
7749       // If this is operator=, keep track of the builtin candidates we added.
7750       if (isEqualOp)
7751         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7752       else if (!(*Ptr)->getPointeeType()->isObjectType())
7753         continue;
7754 
7755       // non-volatile version
7756       QualType ParamTypes[2] = {
7757         S.Context.getLValueReferenceType(*Ptr),
7758         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7759       };
7760       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7761                             /*IsAssigmentOperator=*/ isEqualOp);
7762 
7763       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7764                           VisibleTypeConversionsQuals.hasVolatile();
7765       if (NeedVolatile) {
7766         // volatile version
7767         ParamTypes[0] =
7768           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7769         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7770                               /*IsAssigmentOperator=*/isEqualOp);
7771       }
7772 
7773       if (!(*Ptr).isRestrictQualified() &&
7774           VisibleTypeConversionsQuals.hasRestrict()) {
7775         // restrict version
7776         ParamTypes[0]
7777           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7778         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7779                               /*IsAssigmentOperator=*/isEqualOp);
7780 
7781         if (NeedVolatile) {
7782           // volatile restrict version
7783           ParamTypes[0]
7784             = S.Context.getLValueReferenceType(
7785                 S.Context.getCVRQualifiedType(*Ptr,
7786                                               (Qualifiers::Volatile |
7787                                                Qualifiers::Restrict)));
7788           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7789                                 /*IsAssigmentOperator=*/isEqualOp);
7790         }
7791       }
7792     }
7793 
7794     if (isEqualOp) {
7795       for (BuiltinCandidateTypeSet::iterator
7796                 Ptr = CandidateTypes[1].pointer_begin(),
7797              PtrEnd = CandidateTypes[1].pointer_end();
7798            Ptr != PtrEnd; ++Ptr) {
7799         // Make sure we don't add the same candidate twice.
7800         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7801           continue;
7802 
7803         QualType ParamTypes[2] = {
7804           S.Context.getLValueReferenceType(*Ptr),
7805           *Ptr,
7806         };
7807 
7808         // non-volatile version
7809         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7810                               /*IsAssigmentOperator=*/true);
7811 
7812         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7813                            VisibleTypeConversionsQuals.hasVolatile();
7814         if (NeedVolatile) {
7815           // volatile version
7816           ParamTypes[0] =
7817             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7818           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7819                                 /*IsAssigmentOperator=*/true);
7820         }
7821 
7822         if (!(*Ptr).isRestrictQualified() &&
7823             VisibleTypeConversionsQuals.hasRestrict()) {
7824           // restrict version
7825           ParamTypes[0]
7826             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7827           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7828                                 /*IsAssigmentOperator=*/true);
7829 
7830           if (NeedVolatile) {
7831             // volatile restrict version
7832             ParamTypes[0]
7833               = S.Context.getLValueReferenceType(
7834                   S.Context.getCVRQualifiedType(*Ptr,
7835                                                 (Qualifiers::Volatile |
7836                                                  Qualifiers::Restrict)));
7837             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7838                                   /*IsAssigmentOperator=*/true);
7839           }
7840         }
7841       }
7842     }
7843   }
7844 
7845   // C++ [over.built]p18:
7846   //
7847   //   For every triple (L, VQ, R), where L is an arithmetic type,
7848   //   VQ is either volatile or empty, and R is a promoted
7849   //   arithmetic type, there exist candidate operator functions of
7850   //   the form
7851   //
7852   //        VQ L&      operator=(VQ L&, R);
7853   //        VQ L&      operator*=(VQ L&, R);
7854   //        VQ L&      operator/=(VQ L&, R);
7855   //        VQ L&      operator+=(VQ L&, R);
7856   //        VQ L&      operator-=(VQ L&, R);
7857   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7858     if (!HasArithmeticOrEnumeralCandidateType)
7859       return;
7860 
7861     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7862       for (unsigned Right = FirstPromotedArithmeticType;
7863            Right < LastPromotedArithmeticType; ++Right) {
7864         QualType ParamTypes[2];
7865         ParamTypes[1] = getArithmeticType(Right);
7866 
7867         // Add this built-in operator as a candidate (VQ is empty).
7868         ParamTypes[0] =
7869           S.Context.getLValueReferenceType(getArithmeticType(Left));
7870         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7871                               /*IsAssigmentOperator=*/isEqualOp);
7872 
7873         // Add this built-in operator as a candidate (VQ is 'volatile').
7874         if (VisibleTypeConversionsQuals.hasVolatile()) {
7875           ParamTypes[0] =
7876             S.Context.getVolatileType(getArithmeticType(Left));
7877           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7878           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7879                                 /*IsAssigmentOperator=*/isEqualOp);
7880         }
7881       }
7882     }
7883 
7884     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7885     for (BuiltinCandidateTypeSet::iterator
7886               Vec1 = CandidateTypes[0].vector_begin(),
7887            Vec1End = CandidateTypes[0].vector_end();
7888          Vec1 != Vec1End; ++Vec1) {
7889       for (BuiltinCandidateTypeSet::iterator
7890                 Vec2 = CandidateTypes[1].vector_begin(),
7891              Vec2End = CandidateTypes[1].vector_end();
7892            Vec2 != Vec2End; ++Vec2) {
7893         QualType ParamTypes[2];
7894         ParamTypes[1] = *Vec2;
7895         // Add this built-in operator as a candidate (VQ is empty).
7896         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7897         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7898                               /*IsAssigmentOperator=*/isEqualOp);
7899 
7900         // Add this built-in operator as a candidate (VQ is 'volatile').
7901         if (VisibleTypeConversionsQuals.hasVolatile()) {
7902           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7903           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7904           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7905                                 /*IsAssigmentOperator=*/isEqualOp);
7906         }
7907       }
7908     }
7909   }
7910 
7911   // C++ [over.built]p22:
7912   //
7913   //   For every triple (L, VQ, R), where L is an integral type, VQ
7914   //   is either volatile or empty, and R is a promoted integral
7915   //   type, there exist candidate operator functions of the form
7916   //
7917   //        VQ L&       operator%=(VQ L&, R);
7918   //        VQ L&       operator<<=(VQ L&, R);
7919   //        VQ L&       operator>>=(VQ L&, R);
7920   //        VQ L&       operator&=(VQ L&, R);
7921   //        VQ L&       operator^=(VQ L&, R);
7922   //        VQ L&       operator|=(VQ L&, R);
7923   void addAssignmentIntegralOverloads() {
7924     if (!HasArithmeticOrEnumeralCandidateType)
7925       return;
7926 
7927     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7928       for (unsigned Right = FirstPromotedIntegralType;
7929            Right < LastPromotedIntegralType; ++Right) {
7930         QualType ParamTypes[2];
7931         ParamTypes[1] = getArithmeticType(Right);
7932 
7933         // Add this built-in operator as a candidate (VQ is empty).
7934         ParamTypes[0] =
7935           S.Context.getLValueReferenceType(getArithmeticType(Left));
7936         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7937         if (VisibleTypeConversionsQuals.hasVolatile()) {
7938           // Add this built-in operator as a candidate (VQ is 'volatile').
7939           ParamTypes[0] = getArithmeticType(Left);
7940           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7941           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7942           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7943         }
7944       }
7945     }
7946   }
7947 
7948   // C++ [over.operator]p23:
7949   //
7950   //   There also exist candidate operator functions of the form
7951   //
7952   //        bool        operator!(bool);
7953   //        bool        operator&&(bool, bool);
7954   //        bool        operator||(bool, bool);
7955   void addExclaimOverload() {
7956     QualType ParamTy = S.Context.BoolTy;
7957     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7958                           /*IsAssignmentOperator=*/false,
7959                           /*NumContextualBoolArguments=*/1);
7960   }
7961   void addAmpAmpOrPipePipeOverload() {
7962     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7963     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7964                           /*IsAssignmentOperator=*/false,
7965                           /*NumContextualBoolArguments=*/2);
7966   }
7967 
7968   // C++ [over.built]p13:
7969   //
7970   //   For every cv-qualified or cv-unqualified object type T there
7971   //   exist candidate operator functions of the form
7972   //
7973   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7974   //        T&         operator[](T*, ptrdiff_t);
7975   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7976   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7977   //        T&         operator[](ptrdiff_t, T*);
7978   void addSubscriptOverloads() {
7979     for (BuiltinCandidateTypeSet::iterator
7980               Ptr = CandidateTypes[0].pointer_begin(),
7981            PtrEnd = CandidateTypes[0].pointer_end();
7982          Ptr != PtrEnd; ++Ptr) {
7983       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7984       QualType PointeeType = (*Ptr)->getPointeeType();
7985       if (!PointeeType->isObjectType())
7986         continue;
7987 
7988       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7989 
7990       // T& operator[](T*, ptrdiff_t)
7991       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7992     }
7993 
7994     for (BuiltinCandidateTypeSet::iterator
7995               Ptr = CandidateTypes[1].pointer_begin(),
7996            PtrEnd = CandidateTypes[1].pointer_end();
7997          Ptr != PtrEnd; ++Ptr) {
7998       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7999       QualType PointeeType = (*Ptr)->getPointeeType();
8000       if (!PointeeType->isObjectType())
8001         continue;
8002 
8003       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8004 
8005       // T& operator[](ptrdiff_t, T*)
8006       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8007     }
8008   }
8009 
8010   // C++ [over.built]p11:
8011   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8012   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8013   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8014   //    there exist candidate operator functions of the form
8015   //
8016   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8017   //
8018   //    where CV12 is the union of CV1 and CV2.
8019   void addArrowStarOverloads() {
8020     for (BuiltinCandidateTypeSet::iterator
8021              Ptr = CandidateTypes[0].pointer_begin(),
8022            PtrEnd = CandidateTypes[0].pointer_end();
8023          Ptr != PtrEnd; ++Ptr) {
8024       QualType C1Ty = (*Ptr);
8025       QualType C1;
8026       QualifierCollector Q1;
8027       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8028       if (!isa<RecordType>(C1))
8029         continue;
8030       // heuristic to reduce number of builtin candidates in the set.
8031       // Add volatile/restrict version only if there are conversions to a
8032       // volatile/restrict type.
8033       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8034         continue;
8035       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8036         continue;
8037       for (BuiltinCandidateTypeSet::iterator
8038                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8039              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8040            MemPtr != MemPtrEnd; ++MemPtr) {
8041         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8042         QualType C2 = QualType(mptr->getClass(), 0);
8043         C2 = C2.getUnqualifiedType();
8044         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8045           break;
8046         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8047         // build CV12 T&
8048         QualType T = mptr->getPointeeType();
8049         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8050             T.isVolatileQualified())
8051           continue;
8052         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8053             T.isRestrictQualified())
8054           continue;
8055         T = Q1.apply(S.Context, T);
8056         QualType ResultTy = S.Context.getLValueReferenceType(T);
8057         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8058       }
8059     }
8060   }
8061 
8062   // Note that we don't consider the first argument, since it has been
8063   // contextually converted to bool long ago. The candidates below are
8064   // therefore added as binary.
8065   //
8066   // C++ [over.built]p25:
8067   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8068   //   enumeration type, there exist candidate operator functions of the form
8069   //
8070   //        T        operator?(bool, T, T);
8071   //
8072   void addConditionalOperatorOverloads() {
8073     /// Set of (canonical) types that we've already handled.
8074     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8075 
8076     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8077       for (BuiltinCandidateTypeSet::iterator
8078                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8079              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8080            Ptr != PtrEnd; ++Ptr) {
8081         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8082           continue;
8083 
8084         QualType ParamTypes[2] = { *Ptr, *Ptr };
8085         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8086       }
8087 
8088       for (BuiltinCandidateTypeSet::iterator
8089                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8090              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8091            MemPtr != MemPtrEnd; ++MemPtr) {
8092         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8093           continue;
8094 
8095         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8096         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8097       }
8098 
8099       if (S.getLangOpts().CPlusPlus11) {
8100         for (BuiltinCandidateTypeSet::iterator
8101                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8102                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8103              Enum != EnumEnd; ++Enum) {
8104           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8105             continue;
8106 
8107           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8108             continue;
8109 
8110           QualType ParamTypes[2] = { *Enum, *Enum };
8111           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8112         }
8113       }
8114     }
8115   }
8116 };
8117 
8118 } // end anonymous namespace
8119 
8120 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8121 /// operator overloads to the candidate set (C++ [over.built]), based
8122 /// on the operator @p Op and the arguments given. For example, if the
8123 /// operator is a binary '+', this routine might add "int
8124 /// operator+(int, int)" to cover integer addition.
8125 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8126                                         SourceLocation OpLoc,
8127                                         ArrayRef<Expr *> Args,
8128                                         OverloadCandidateSet &CandidateSet) {
8129   // Find all of the types that the arguments can convert to, but only
8130   // if the operator we're looking at has built-in operator candidates
8131   // that make use of these types. Also record whether we encounter non-record
8132   // candidate types or either arithmetic or enumeral candidate types.
8133   Qualifiers VisibleTypeConversionsQuals;
8134   VisibleTypeConversionsQuals.addConst();
8135   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8136     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8137 
8138   bool HasNonRecordCandidateType = false;
8139   bool HasArithmeticOrEnumeralCandidateType = false;
8140   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8141   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8142     CandidateTypes.emplace_back(*this);
8143     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8144                                                  OpLoc,
8145                                                  true,
8146                                                  (Op == OO_Exclaim ||
8147                                                   Op == OO_AmpAmp ||
8148                                                   Op == OO_PipePipe),
8149                                                  VisibleTypeConversionsQuals);
8150     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8151         CandidateTypes[ArgIdx].hasNonRecordTypes();
8152     HasArithmeticOrEnumeralCandidateType =
8153         HasArithmeticOrEnumeralCandidateType ||
8154         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8155   }
8156 
8157   // Exit early when no non-record types have been added to the candidate set
8158   // for any of the arguments to the operator.
8159   //
8160   // We can't exit early for !, ||, or &&, since there we have always have
8161   // 'bool' overloads.
8162   if (!HasNonRecordCandidateType &&
8163       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8164     return;
8165 
8166   // Setup an object to manage the common state for building overloads.
8167   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8168                                            VisibleTypeConversionsQuals,
8169                                            HasArithmeticOrEnumeralCandidateType,
8170                                            CandidateTypes, CandidateSet);
8171 
8172   // Dispatch over the operation to add in only those overloads which apply.
8173   switch (Op) {
8174   case OO_None:
8175   case NUM_OVERLOADED_OPERATORS:
8176     llvm_unreachable("Expected an overloaded operator");
8177 
8178   case OO_New:
8179   case OO_Delete:
8180   case OO_Array_New:
8181   case OO_Array_Delete:
8182   case OO_Call:
8183     llvm_unreachable(
8184                     "Special operators don't use AddBuiltinOperatorCandidates");
8185 
8186   case OO_Comma:
8187   case OO_Arrow:
8188     // C++ [over.match.oper]p3:
8189     //   -- For the operator ',', the unary operator '&', or the
8190     //      operator '->', the built-in candidates set is empty.
8191     break;
8192 
8193   case OO_Plus: // '+' is either unary or binary
8194     if (Args.size() == 1)
8195       OpBuilder.addUnaryPlusPointerOverloads();
8196     // Fall through.
8197 
8198   case OO_Minus: // '-' is either unary or binary
8199     if (Args.size() == 1) {
8200       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8201     } else {
8202       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8203       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8204     }
8205     break;
8206 
8207   case OO_Star: // '*' is either unary or binary
8208     if (Args.size() == 1)
8209       OpBuilder.addUnaryStarPointerOverloads();
8210     else
8211       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8212     break;
8213 
8214   case OO_Slash:
8215     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8216     break;
8217 
8218   case OO_PlusPlus:
8219   case OO_MinusMinus:
8220     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8221     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8222     break;
8223 
8224   case OO_EqualEqual:
8225   case OO_ExclaimEqual:
8226     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8227     // Fall through.
8228 
8229   case OO_Less:
8230   case OO_Greater:
8231   case OO_LessEqual:
8232   case OO_GreaterEqual:
8233     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8234     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8235     break;
8236 
8237   case OO_Percent:
8238   case OO_Caret:
8239   case OO_Pipe:
8240   case OO_LessLess:
8241   case OO_GreaterGreater:
8242     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8243     break;
8244 
8245   case OO_Amp: // '&' is either unary or binary
8246     if (Args.size() == 1)
8247       // C++ [over.match.oper]p3:
8248       //   -- For the operator ',', the unary operator '&', or the
8249       //      operator '->', the built-in candidates set is empty.
8250       break;
8251 
8252     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8253     break;
8254 
8255   case OO_Tilde:
8256     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8257     break;
8258 
8259   case OO_Equal:
8260     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8261     // Fall through.
8262 
8263   case OO_PlusEqual:
8264   case OO_MinusEqual:
8265     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8266     // Fall through.
8267 
8268   case OO_StarEqual:
8269   case OO_SlashEqual:
8270     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8271     break;
8272 
8273   case OO_PercentEqual:
8274   case OO_LessLessEqual:
8275   case OO_GreaterGreaterEqual:
8276   case OO_AmpEqual:
8277   case OO_CaretEqual:
8278   case OO_PipeEqual:
8279     OpBuilder.addAssignmentIntegralOverloads();
8280     break;
8281 
8282   case OO_Exclaim:
8283     OpBuilder.addExclaimOverload();
8284     break;
8285 
8286   case OO_AmpAmp:
8287   case OO_PipePipe:
8288     OpBuilder.addAmpAmpOrPipePipeOverload();
8289     break;
8290 
8291   case OO_Subscript:
8292     OpBuilder.addSubscriptOverloads();
8293     break;
8294 
8295   case OO_ArrowStar:
8296     OpBuilder.addArrowStarOverloads();
8297     break;
8298 
8299   case OO_Conditional:
8300     OpBuilder.addConditionalOperatorOverloads();
8301     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8302     break;
8303   }
8304 }
8305 
8306 /// \brief Add function candidates found via argument-dependent lookup
8307 /// to the set of overloading candidates.
8308 ///
8309 /// This routine performs argument-dependent name lookup based on the
8310 /// given function name (which may also be an operator name) and adds
8311 /// all of the overload candidates found by ADL to the overload
8312 /// candidate set (C++ [basic.lookup.argdep]).
8313 void
8314 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8315                                            SourceLocation Loc,
8316                                            ArrayRef<Expr *> Args,
8317                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8318                                            OverloadCandidateSet& CandidateSet,
8319                                            bool PartialOverloading) {
8320   ADLResult Fns;
8321 
8322   // FIXME: This approach for uniquing ADL results (and removing
8323   // redundant candidates from the set) relies on pointer-equality,
8324   // which means we need to key off the canonical decl.  However,
8325   // always going back to the canonical decl might not get us the
8326   // right set of default arguments.  What default arguments are
8327   // we supposed to consider on ADL candidates, anyway?
8328 
8329   // FIXME: Pass in the explicit template arguments?
8330   ArgumentDependentLookup(Name, Loc, Args, Fns);
8331 
8332   // Erase all of the candidates we already knew about.
8333   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8334                                    CandEnd = CandidateSet.end();
8335        Cand != CandEnd; ++Cand)
8336     if (Cand->Function) {
8337       Fns.erase(Cand->Function);
8338       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8339         Fns.erase(FunTmpl);
8340     }
8341 
8342   // For each of the ADL candidates we found, add it to the overload
8343   // set.
8344   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8345     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8346     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8347       if (ExplicitTemplateArgs)
8348         continue;
8349 
8350       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8351                            PartialOverloading);
8352     } else
8353       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8354                                    FoundDecl, ExplicitTemplateArgs,
8355                                    Args, CandidateSet, PartialOverloading);
8356   }
8357 }
8358 
8359 /// isBetterOverloadCandidate - Determines whether the first overload
8360 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8361 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8362                                       const OverloadCandidate &Cand2,
8363                                       SourceLocation Loc,
8364                                       bool UserDefinedConversion) {
8365   // Define viable functions to be better candidates than non-viable
8366   // functions.
8367   if (!Cand2.Viable)
8368     return Cand1.Viable;
8369   else if (!Cand1.Viable)
8370     return false;
8371 
8372   // C++ [over.match.best]p1:
8373   //
8374   //   -- if F is a static member function, ICS1(F) is defined such
8375   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8376   //      any function G, and, symmetrically, ICS1(G) is neither
8377   //      better nor worse than ICS1(F).
8378   unsigned StartArg = 0;
8379   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8380     StartArg = 1;
8381 
8382   // C++ [over.match.best]p1:
8383   //   A viable function F1 is defined to be a better function than another
8384   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8385   //   conversion sequence than ICSi(F2), and then...
8386   unsigned NumArgs = Cand1.NumConversions;
8387   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8388   bool HasBetterConversion = false;
8389   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8390     switch (CompareImplicitConversionSequences(S,
8391                                                Cand1.Conversions[ArgIdx],
8392                                                Cand2.Conversions[ArgIdx])) {
8393     case ImplicitConversionSequence::Better:
8394       // Cand1 has a better conversion sequence.
8395       HasBetterConversion = true;
8396       break;
8397 
8398     case ImplicitConversionSequence::Worse:
8399       // Cand1 can't be better than Cand2.
8400       return false;
8401 
8402     case ImplicitConversionSequence::Indistinguishable:
8403       // Do nothing.
8404       break;
8405     }
8406   }
8407 
8408   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8409   //       ICSj(F2), or, if not that,
8410   if (HasBetterConversion)
8411     return true;
8412 
8413   //   -- the context is an initialization by user-defined conversion
8414   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8415   //      from the return type of F1 to the destination type (i.e.,
8416   //      the type of the entity being initialized) is a better
8417   //      conversion sequence than the standard conversion sequence
8418   //      from the return type of F2 to the destination type.
8419   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8420       isa<CXXConversionDecl>(Cand1.Function) &&
8421       isa<CXXConversionDecl>(Cand2.Function)) {
8422     // First check whether we prefer one of the conversion functions over the
8423     // other. This only distinguishes the results in non-standard, extension
8424     // cases such as the conversion from a lambda closure type to a function
8425     // pointer or block.
8426     ImplicitConversionSequence::CompareKind Result =
8427         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8428     if (Result == ImplicitConversionSequence::Indistinguishable)
8429       Result = CompareStandardConversionSequences(S,
8430                                                   Cand1.FinalConversion,
8431                                                   Cand2.FinalConversion);
8432 
8433     if (Result != ImplicitConversionSequence::Indistinguishable)
8434       return Result == ImplicitConversionSequence::Better;
8435 
8436     // FIXME: Compare kind of reference binding if conversion functions
8437     // convert to a reference type used in direct reference binding, per
8438     // C++14 [over.match.best]p1 section 2 bullet 3.
8439   }
8440 
8441   //    -- F1 is a non-template function and F2 is a function template
8442   //       specialization, or, if not that,
8443   bool Cand1IsSpecialization = Cand1.Function &&
8444                                Cand1.Function->getPrimaryTemplate();
8445   bool Cand2IsSpecialization = Cand2.Function &&
8446                                Cand2.Function->getPrimaryTemplate();
8447   if (Cand1IsSpecialization != Cand2IsSpecialization)
8448     return Cand2IsSpecialization;
8449 
8450   //   -- F1 and F2 are function template specializations, and the function
8451   //      template for F1 is more specialized than the template for F2
8452   //      according to the partial ordering rules described in 14.5.5.2, or,
8453   //      if not that,
8454   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8455     if (FunctionTemplateDecl *BetterTemplate
8456           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8457                                          Cand2.Function->getPrimaryTemplate(),
8458                                          Loc,
8459                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8460                                                              : TPOC_Call,
8461                                          Cand1.ExplicitCallArguments,
8462                                          Cand2.ExplicitCallArguments))
8463       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8464   }
8465 
8466   // Check for enable_if value-based overload resolution.
8467   if (Cand1.Function && Cand2.Function &&
8468       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8469        Cand2.Function->hasAttr<EnableIfAttr>())) {
8470     // FIXME: The next several lines are just
8471     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8472     // instead of reverse order which is how they're stored in the AST.
8473     AttrVec Cand1Attrs;
8474     if (Cand1.Function->hasAttrs()) {
8475       Cand1Attrs = Cand1.Function->getAttrs();
8476       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8477                                       IsNotEnableIfAttr),
8478                        Cand1Attrs.end());
8479       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8480     }
8481 
8482     AttrVec Cand2Attrs;
8483     if (Cand2.Function->hasAttrs()) {
8484       Cand2Attrs = Cand2.Function->getAttrs();
8485       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8486                                       IsNotEnableIfAttr),
8487                        Cand2Attrs.end());
8488       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8489     }
8490 
8491     // Candidate 1 is better if it has strictly more attributes and
8492     // the common sequence is identical.
8493     if (Cand1Attrs.size() <= Cand2Attrs.size())
8494       return false;
8495 
8496     auto Cand1I = Cand1Attrs.begin();
8497     for (auto &Cand2A : Cand2Attrs) {
8498       auto &Cand1A = *Cand1I++;
8499       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8500       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8501                                                      S.getASTContext(), true);
8502       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8503                                                      S.getASTContext(), true);
8504       if (Cand1ID != Cand2ID)
8505         return false;
8506     }
8507 
8508     return true;
8509   }
8510 
8511   return false;
8512 }
8513 
8514 /// \brief Computes the best viable function (C++ 13.3.3)
8515 /// within an overload candidate set.
8516 ///
8517 /// \param Loc The location of the function name (or operator symbol) for
8518 /// which overload resolution occurs.
8519 ///
8520 /// \param Best If overload resolution was successful or found a deleted
8521 /// function, \p Best points to the candidate function found.
8522 ///
8523 /// \returns The result of overload resolution.
8524 OverloadingResult
8525 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8526                                          iterator &Best,
8527                                          bool UserDefinedConversion) {
8528   // Find the best viable function.
8529   Best = end();
8530   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8531     if (Cand->Viable)
8532       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8533                                                      UserDefinedConversion))
8534         Best = Cand;
8535   }
8536 
8537   // If we didn't find any viable functions, abort.
8538   if (Best == end())
8539     return OR_No_Viable_Function;
8540 
8541   // Make sure that this function is better than every other viable
8542   // function. If not, we have an ambiguity.
8543   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8544     if (Cand->Viable &&
8545         Cand != Best &&
8546         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8547                                    UserDefinedConversion)) {
8548       Best = end();
8549       return OR_Ambiguous;
8550     }
8551   }
8552 
8553   // Best is the best viable function.
8554   if (Best->Function &&
8555       (Best->Function->isDeleted() ||
8556        S.isFunctionConsideredUnavailable(Best->Function)))
8557     return OR_Deleted;
8558 
8559   return OR_Success;
8560 }
8561 
8562 namespace {
8563 
8564 enum OverloadCandidateKind {
8565   oc_function,
8566   oc_method,
8567   oc_constructor,
8568   oc_function_template,
8569   oc_method_template,
8570   oc_constructor_template,
8571   oc_implicit_default_constructor,
8572   oc_implicit_copy_constructor,
8573   oc_implicit_move_constructor,
8574   oc_implicit_copy_assignment,
8575   oc_implicit_move_assignment,
8576   oc_implicit_inherited_constructor
8577 };
8578 
8579 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8580                                                 FunctionDecl *Fn,
8581                                                 std::string &Description) {
8582   bool isTemplate = false;
8583 
8584   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8585     isTemplate = true;
8586     Description = S.getTemplateArgumentBindingsText(
8587       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8588   }
8589 
8590   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8591     if (!Ctor->isImplicit())
8592       return isTemplate ? oc_constructor_template : oc_constructor;
8593 
8594     if (Ctor->getInheritedConstructor())
8595       return oc_implicit_inherited_constructor;
8596 
8597     if (Ctor->isDefaultConstructor())
8598       return oc_implicit_default_constructor;
8599 
8600     if (Ctor->isMoveConstructor())
8601       return oc_implicit_move_constructor;
8602 
8603     assert(Ctor->isCopyConstructor() &&
8604            "unexpected sort of implicit constructor");
8605     return oc_implicit_copy_constructor;
8606   }
8607 
8608   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8609     // This actually gets spelled 'candidate function' for now, but
8610     // it doesn't hurt to split it out.
8611     if (!Meth->isImplicit())
8612       return isTemplate ? oc_method_template : oc_method;
8613 
8614     if (Meth->isMoveAssignmentOperator())
8615       return oc_implicit_move_assignment;
8616 
8617     if (Meth->isCopyAssignmentOperator())
8618       return oc_implicit_copy_assignment;
8619 
8620     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8621     return oc_method;
8622   }
8623 
8624   return isTemplate ? oc_function_template : oc_function;
8625 }
8626 
8627 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8628   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8629   if (!Ctor) return;
8630 
8631   Ctor = Ctor->getInheritedConstructor();
8632   if (!Ctor) return;
8633 
8634   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8635 }
8636 
8637 } // end anonymous namespace
8638 
8639 // Notes the location of an overload candidate.
8640 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8641   std::string FnDesc;
8642   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8643   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8644                              << (unsigned) K << FnDesc;
8645   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8646   Diag(Fn->getLocation(), PD);
8647   MaybeEmitInheritedConstructorNote(*this, Fn);
8648 }
8649 
8650 // Notes the location of all overload candidates designated through
8651 // OverloadedExpr
8652 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8653   assert(OverloadedExpr->getType() == Context.OverloadTy);
8654 
8655   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8656   OverloadExpr *OvlExpr = Ovl.Expression;
8657 
8658   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8659                             IEnd = OvlExpr->decls_end();
8660        I != IEnd; ++I) {
8661     if (FunctionTemplateDecl *FunTmpl =
8662                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8663       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8664     } else if (FunctionDecl *Fun
8665                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8666       NoteOverloadCandidate(Fun, DestType);
8667     }
8668   }
8669 }
8670 
8671 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8672 /// "lead" diagnostic; it will be given two arguments, the source and
8673 /// target types of the conversion.
8674 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8675                                  Sema &S,
8676                                  SourceLocation CaretLoc,
8677                                  const PartialDiagnostic &PDiag) const {
8678   S.Diag(CaretLoc, PDiag)
8679     << Ambiguous.getFromType() << Ambiguous.getToType();
8680   // FIXME: The note limiting machinery is borrowed from
8681   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8682   // refactoring here.
8683   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8684   unsigned CandsShown = 0;
8685   AmbiguousConversionSequence::const_iterator I, E;
8686   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8687     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8688       break;
8689     ++CandsShown;
8690     S.NoteOverloadCandidate(*I);
8691   }
8692   if (I != E)
8693     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8694 }
8695 
8696 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8697                                   unsigned I) {
8698   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8699   assert(Conv.isBad());
8700   assert(Cand->Function && "for now, candidate must be a function");
8701   FunctionDecl *Fn = Cand->Function;
8702 
8703   // There's a conversion slot for the object argument if this is a
8704   // non-constructor method.  Note that 'I' corresponds the
8705   // conversion-slot index.
8706   bool isObjectArgument = false;
8707   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8708     if (I == 0)
8709       isObjectArgument = true;
8710     else
8711       I--;
8712   }
8713 
8714   std::string FnDesc;
8715   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8716 
8717   Expr *FromExpr = Conv.Bad.FromExpr;
8718   QualType FromTy = Conv.Bad.getFromType();
8719   QualType ToTy = Conv.Bad.getToType();
8720 
8721   if (FromTy == S.Context.OverloadTy) {
8722     assert(FromExpr && "overload set argument came from implicit argument?");
8723     Expr *E = FromExpr->IgnoreParens();
8724     if (isa<UnaryOperator>(E))
8725       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8726     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8727 
8728     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8729       << (unsigned) FnKind << FnDesc
8730       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8731       << ToTy << Name << I+1;
8732     MaybeEmitInheritedConstructorNote(S, Fn);
8733     return;
8734   }
8735 
8736   // Do some hand-waving analysis to see if the non-viability is due
8737   // to a qualifier mismatch.
8738   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8739   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8740   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8741     CToTy = RT->getPointeeType();
8742   else {
8743     // TODO: detect and diagnose the full richness of const mismatches.
8744     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8745       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8746         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8747   }
8748 
8749   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8750       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8751     Qualifiers FromQs = CFromTy.getQualifiers();
8752     Qualifiers ToQs = CToTy.getQualifiers();
8753 
8754     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8755       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8756         << (unsigned) FnKind << FnDesc
8757         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8758         << FromTy
8759         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8760         << (unsigned) isObjectArgument << I+1;
8761       MaybeEmitInheritedConstructorNote(S, Fn);
8762       return;
8763     }
8764 
8765     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8766       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8767         << (unsigned) FnKind << FnDesc
8768         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8769         << FromTy
8770         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8771         << (unsigned) isObjectArgument << I+1;
8772       MaybeEmitInheritedConstructorNote(S, Fn);
8773       return;
8774     }
8775 
8776     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8777       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8778       << (unsigned) FnKind << FnDesc
8779       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8780       << FromTy
8781       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8782       << (unsigned) isObjectArgument << I+1;
8783       MaybeEmitInheritedConstructorNote(S, Fn);
8784       return;
8785     }
8786 
8787     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8788     assert(CVR && "unexpected qualifiers mismatch");
8789 
8790     if (isObjectArgument) {
8791       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8792         << (unsigned) FnKind << FnDesc
8793         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8794         << FromTy << (CVR - 1);
8795     } else {
8796       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8797         << (unsigned) FnKind << FnDesc
8798         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8799         << FromTy << (CVR - 1) << I+1;
8800     }
8801     MaybeEmitInheritedConstructorNote(S, Fn);
8802     return;
8803   }
8804 
8805   // Special diagnostic for failure to convert an initializer list, since
8806   // telling the user that it has type void is not useful.
8807   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8808     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8809       << (unsigned) FnKind << FnDesc
8810       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8811       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8812     MaybeEmitInheritedConstructorNote(S, Fn);
8813     return;
8814   }
8815 
8816   // Diagnose references or pointers to incomplete types differently,
8817   // since it's far from impossible that the incompleteness triggered
8818   // the failure.
8819   QualType TempFromTy = FromTy.getNonReferenceType();
8820   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8821     TempFromTy = PTy->getPointeeType();
8822   if (TempFromTy->isIncompleteType()) {
8823     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8824       << (unsigned) FnKind << FnDesc
8825       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8826       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8827     MaybeEmitInheritedConstructorNote(S, Fn);
8828     return;
8829   }
8830 
8831   // Diagnose base -> derived pointer conversions.
8832   unsigned BaseToDerivedConversion = 0;
8833   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8834     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8835       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8836                                                FromPtrTy->getPointeeType()) &&
8837           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8838           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8839           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8840                           FromPtrTy->getPointeeType()))
8841         BaseToDerivedConversion = 1;
8842     }
8843   } else if (const ObjCObjectPointerType *FromPtrTy
8844                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8845     if (const ObjCObjectPointerType *ToPtrTy
8846                                         = ToTy->getAs<ObjCObjectPointerType>())
8847       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8848         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8849           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8850                                                 FromPtrTy->getPointeeType()) &&
8851               FromIface->isSuperClassOf(ToIface))
8852             BaseToDerivedConversion = 2;
8853   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8854     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8855         !FromTy->isIncompleteType() &&
8856         !ToRefTy->getPointeeType()->isIncompleteType() &&
8857         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8858       BaseToDerivedConversion = 3;
8859     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8860                ToTy.getNonReferenceType().getCanonicalType() ==
8861                FromTy.getNonReferenceType().getCanonicalType()) {
8862       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8863         << (unsigned) FnKind << FnDesc
8864         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8865         << (unsigned) isObjectArgument << I + 1;
8866       MaybeEmitInheritedConstructorNote(S, Fn);
8867       return;
8868     }
8869   }
8870 
8871   if (BaseToDerivedConversion) {
8872     S.Diag(Fn->getLocation(),
8873            diag::note_ovl_candidate_bad_base_to_derived_conv)
8874       << (unsigned) FnKind << FnDesc
8875       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8876       << (BaseToDerivedConversion - 1)
8877       << FromTy << ToTy << I+1;
8878     MaybeEmitInheritedConstructorNote(S, Fn);
8879     return;
8880   }
8881 
8882   if (isa<ObjCObjectPointerType>(CFromTy) &&
8883       isa<PointerType>(CToTy)) {
8884       Qualifiers FromQs = CFromTy.getQualifiers();
8885       Qualifiers ToQs = CToTy.getQualifiers();
8886       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8887         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8888         << (unsigned) FnKind << FnDesc
8889         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8890         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8891         MaybeEmitInheritedConstructorNote(S, Fn);
8892         return;
8893       }
8894   }
8895 
8896   // Emit the generic diagnostic and, optionally, add the hints to it.
8897   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8898   FDiag << (unsigned) FnKind << FnDesc
8899     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8900     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8901     << (unsigned) (Cand->Fix.Kind);
8902 
8903   // If we can fix the conversion, suggest the FixIts.
8904   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8905        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8906     FDiag << *HI;
8907   S.Diag(Fn->getLocation(), FDiag);
8908 
8909   MaybeEmitInheritedConstructorNote(S, Fn);
8910 }
8911 
8912 /// Additional arity mismatch diagnosis specific to a function overload
8913 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8914 /// over a candidate in any candidate set.
8915 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8916                                unsigned NumArgs) {
8917   FunctionDecl *Fn = Cand->Function;
8918   unsigned MinParams = Fn->getMinRequiredArguments();
8919 
8920   // With invalid overloaded operators, it's possible that we think we
8921   // have an arity mismatch when in fact it looks like we have the
8922   // right number of arguments, because only overloaded operators have
8923   // the weird behavior of overloading member and non-member functions.
8924   // Just don't report anything.
8925   if (Fn->isInvalidDecl() &&
8926       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8927     return true;
8928 
8929   if (NumArgs < MinParams) {
8930     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8931            (Cand->FailureKind == ovl_fail_bad_deduction &&
8932             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8933   } else {
8934     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8935            (Cand->FailureKind == ovl_fail_bad_deduction &&
8936             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8937   }
8938 
8939   return false;
8940 }
8941 
8942 /// General arity mismatch diagnosis over a candidate in a candidate set.
8943 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8944   assert(isa<FunctionDecl>(D) &&
8945       "The templated declaration should at least be a function"
8946       " when diagnosing bad template argument deduction due to too many"
8947       " or too few arguments");
8948 
8949   FunctionDecl *Fn = cast<FunctionDecl>(D);
8950 
8951   // TODO: treat calls to a missing default constructor as a special case
8952   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8953   unsigned MinParams = Fn->getMinRequiredArguments();
8954 
8955   // at least / at most / exactly
8956   unsigned mode, modeCount;
8957   if (NumFormalArgs < MinParams) {
8958     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8959         FnTy->isTemplateVariadic())
8960       mode = 0; // "at least"
8961     else
8962       mode = 2; // "exactly"
8963     modeCount = MinParams;
8964   } else {
8965     if (MinParams != FnTy->getNumParams())
8966       mode = 1; // "at most"
8967     else
8968       mode = 2; // "exactly"
8969     modeCount = FnTy->getNumParams();
8970   }
8971 
8972   std::string Description;
8973   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8974 
8975   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8976     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8977       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8978       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8979   else
8980     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8981       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8982       << mode << modeCount << NumFormalArgs;
8983   MaybeEmitInheritedConstructorNote(S, Fn);
8984 }
8985 
8986 /// Arity mismatch diagnosis specific to a function overload candidate.
8987 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8988                                   unsigned NumFormalArgs) {
8989   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8990     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8991 }
8992 
8993 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8994   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8995     return FD->getDescribedFunctionTemplate();
8996   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8997     return RD->getDescribedClassTemplate();
8998 
8999   llvm_unreachable("Unsupported: Getting the described template declaration"
9000                    " for bad deduction diagnosis");
9001 }
9002 
9003 /// Diagnose a failed template-argument deduction.
9004 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9005                                  DeductionFailureInfo &DeductionFailure,
9006                                  unsigned NumArgs) {
9007   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9008   NamedDecl *ParamD;
9009   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9010   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9011   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9012   switch (DeductionFailure.Result) {
9013   case Sema::TDK_Success:
9014     llvm_unreachable("TDK_success while diagnosing bad deduction");
9015 
9016   case Sema::TDK_Incomplete: {
9017     assert(ParamD && "no parameter found for incomplete deduction result");
9018     S.Diag(Templated->getLocation(),
9019            diag::note_ovl_candidate_incomplete_deduction)
9020         << ParamD->getDeclName();
9021     MaybeEmitInheritedConstructorNote(S, Templated);
9022     return;
9023   }
9024 
9025   case Sema::TDK_Underqualified: {
9026     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9027     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9028 
9029     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9030 
9031     // Param will have been canonicalized, but it should just be a
9032     // qualified version of ParamD, so move the qualifiers to that.
9033     QualifierCollector Qs;
9034     Qs.strip(Param);
9035     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9036     assert(S.Context.hasSameType(Param, NonCanonParam));
9037 
9038     // Arg has also been canonicalized, but there's nothing we can do
9039     // about that.  It also doesn't matter as much, because it won't
9040     // have any template parameters in it (because deduction isn't
9041     // done on dependent types).
9042     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9043 
9044     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9045         << ParamD->getDeclName() << Arg << NonCanonParam;
9046     MaybeEmitInheritedConstructorNote(S, Templated);
9047     return;
9048   }
9049 
9050   case Sema::TDK_Inconsistent: {
9051     assert(ParamD && "no parameter found for inconsistent deduction result");
9052     int which = 0;
9053     if (isa<TemplateTypeParmDecl>(ParamD))
9054       which = 0;
9055     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9056       which = 1;
9057     else {
9058       which = 2;
9059     }
9060 
9061     S.Diag(Templated->getLocation(),
9062            diag::note_ovl_candidate_inconsistent_deduction)
9063         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9064         << *DeductionFailure.getSecondArg();
9065     MaybeEmitInheritedConstructorNote(S, Templated);
9066     return;
9067   }
9068 
9069   case Sema::TDK_InvalidExplicitArguments:
9070     assert(ParamD && "no parameter found for invalid explicit arguments");
9071     if (ParamD->getDeclName())
9072       S.Diag(Templated->getLocation(),
9073              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9074           << ParamD->getDeclName();
9075     else {
9076       int index = 0;
9077       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9078         index = TTP->getIndex();
9079       else if (NonTypeTemplateParmDecl *NTTP
9080                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9081         index = NTTP->getIndex();
9082       else
9083         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9084       S.Diag(Templated->getLocation(),
9085              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9086           << (index + 1);
9087     }
9088     MaybeEmitInheritedConstructorNote(S, Templated);
9089     return;
9090 
9091   case Sema::TDK_TooManyArguments:
9092   case Sema::TDK_TooFewArguments:
9093     DiagnoseArityMismatch(S, Templated, NumArgs);
9094     return;
9095 
9096   case Sema::TDK_InstantiationDepth:
9097     S.Diag(Templated->getLocation(),
9098            diag::note_ovl_candidate_instantiation_depth);
9099     MaybeEmitInheritedConstructorNote(S, Templated);
9100     return;
9101 
9102   case Sema::TDK_SubstitutionFailure: {
9103     // Format the template argument list into the argument string.
9104     SmallString<128> TemplateArgString;
9105     if (TemplateArgumentList *Args =
9106             DeductionFailure.getTemplateArgumentList()) {
9107       TemplateArgString = " ";
9108       TemplateArgString += S.getTemplateArgumentBindingsText(
9109           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9110     }
9111 
9112     // If this candidate was disabled by enable_if, say so.
9113     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9114     if (PDiag && PDiag->second.getDiagID() ==
9115           diag::err_typename_nested_not_found_enable_if) {
9116       // FIXME: Use the source range of the condition, and the fully-qualified
9117       //        name of the enable_if template. These are both present in PDiag.
9118       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9119         << "'enable_if'" << TemplateArgString;
9120       return;
9121     }
9122 
9123     // Format the SFINAE diagnostic into the argument string.
9124     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9125     //        formatted message in another diagnostic.
9126     SmallString<128> SFINAEArgString;
9127     SourceRange R;
9128     if (PDiag) {
9129       SFINAEArgString = ": ";
9130       R = SourceRange(PDiag->first, PDiag->first);
9131       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9132     }
9133 
9134     S.Diag(Templated->getLocation(),
9135            diag::note_ovl_candidate_substitution_failure)
9136         << TemplateArgString << SFINAEArgString << R;
9137     MaybeEmitInheritedConstructorNote(S, Templated);
9138     return;
9139   }
9140 
9141   case Sema::TDK_FailedOverloadResolution: {
9142     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9143     S.Diag(Templated->getLocation(),
9144            diag::note_ovl_candidate_failed_overload_resolution)
9145         << R.Expression->getName();
9146     return;
9147   }
9148 
9149   case Sema::TDK_NonDeducedMismatch: {
9150     // FIXME: Provide a source location to indicate what we couldn't match.
9151     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9152     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9153     if (FirstTA.getKind() == TemplateArgument::Template &&
9154         SecondTA.getKind() == TemplateArgument::Template) {
9155       TemplateName FirstTN = FirstTA.getAsTemplate();
9156       TemplateName SecondTN = SecondTA.getAsTemplate();
9157       if (FirstTN.getKind() == TemplateName::Template &&
9158           SecondTN.getKind() == TemplateName::Template) {
9159         if (FirstTN.getAsTemplateDecl()->getName() ==
9160             SecondTN.getAsTemplateDecl()->getName()) {
9161           // FIXME: This fixes a bad diagnostic where both templates are named
9162           // the same.  This particular case is a bit difficult since:
9163           // 1) It is passed as a string to the diagnostic printer.
9164           // 2) The diagnostic printer only attempts to find a better
9165           //    name for types, not decls.
9166           // Ideally, this should folded into the diagnostic printer.
9167           S.Diag(Templated->getLocation(),
9168                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9169               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9170           return;
9171         }
9172       }
9173     }
9174     // FIXME: For generic lambda parameters, check if the function is a lambda
9175     // call operator, and if so, emit a prettier and more informative
9176     // diagnostic that mentions 'auto' and lambda in addition to
9177     // (or instead of?) the canonical template type parameters.
9178     S.Diag(Templated->getLocation(),
9179            diag::note_ovl_candidate_non_deduced_mismatch)
9180         << FirstTA << SecondTA;
9181     return;
9182   }
9183   // TODO: diagnose these individually, then kill off
9184   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9185   case Sema::TDK_MiscellaneousDeductionFailure:
9186     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9187     MaybeEmitInheritedConstructorNote(S, Templated);
9188     return;
9189   }
9190 }
9191 
9192 /// Diagnose a failed template-argument deduction, for function calls.
9193 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9194                                  unsigned NumArgs) {
9195   unsigned TDK = Cand->DeductionFailure.Result;
9196   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9197     if (CheckArityMismatch(S, Cand, NumArgs))
9198       return;
9199   }
9200   DiagnoseBadDeduction(S, Cand->Function, // pattern
9201                        Cand->DeductionFailure, NumArgs);
9202 }
9203 
9204 /// CUDA: diagnose an invalid call across targets.
9205 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9206   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9207   FunctionDecl *Callee = Cand->Function;
9208 
9209   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9210                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9211 
9212   std::string FnDesc;
9213   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9214 
9215   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9216       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9217 
9218   // This could be an implicit constructor for which we could not infer the
9219   // target due to a collsion. Diagnose that case.
9220   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9221   if (Meth != nullptr && Meth->isImplicit()) {
9222     CXXRecordDecl *ParentClass = Meth->getParent();
9223     Sema::CXXSpecialMember CSM;
9224 
9225     switch (FnKind) {
9226     default:
9227       return;
9228     case oc_implicit_default_constructor:
9229       CSM = Sema::CXXDefaultConstructor;
9230       break;
9231     case oc_implicit_copy_constructor:
9232       CSM = Sema::CXXCopyConstructor;
9233       break;
9234     case oc_implicit_move_constructor:
9235       CSM = Sema::CXXMoveConstructor;
9236       break;
9237     case oc_implicit_copy_assignment:
9238       CSM = Sema::CXXCopyAssignment;
9239       break;
9240     case oc_implicit_move_assignment:
9241       CSM = Sema::CXXMoveAssignment;
9242       break;
9243     };
9244 
9245     bool ConstRHS = false;
9246     if (Meth->getNumParams()) {
9247       if (const ReferenceType *RT =
9248               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9249         ConstRHS = RT->getPointeeType().isConstQualified();
9250       }
9251     }
9252 
9253     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9254                                               /* ConstRHS */ ConstRHS,
9255                                               /* Diagnose */ true);
9256   }
9257 }
9258 
9259 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9260   FunctionDecl *Callee = Cand->Function;
9261   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9262 
9263   S.Diag(Callee->getLocation(),
9264          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9265       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9266 }
9267 
9268 /// Generates a 'note' diagnostic for an overload candidate.  We've
9269 /// already generated a primary error at the call site.
9270 ///
9271 /// It really does need to be a single diagnostic with its caret
9272 /// pointed at the candidate declaration.  Yes, this creates some
9273 /// major challenges of technical writing.  Yes, this makes pointing
9274 /// out problems with specific arguments quite awkward.  It's still
9275 /// better than generating twenty screens of text for every failed
9276 /// overload.
9277 ///
9278 /// It would be great to be able to express per-candidate problems
9279 /// more richly for those diagnostic clients that cared, but we'd
9280 /// still have to be just as careful with the default diagnostics.
9281 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9282                                   unsigned NumArgs) {
9283   FunctionDecl *Fn = Cand->Function;
9284 
9285   // Note deleted candidates, but only if they're viable.
9286   if (Cand->Viable && (Fn->isDeleted() ||
9287       S.isFunctionConsideredUnavailable(Fn))) {
9288     std::string FnDesc;
9289     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9290 
9291     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9292       << FnKind << FnDesc
9293       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9294     MaybeEmitInheritedConstructorNote(S, Fn);
9295     return;
9296   }
9297 
9298   // We don't really have anything else to say about viable candidates.
9299   if (Cand->Viable) {
9300     S.NoteOverloadCandidate(Fn);
9301     return;
9302   }
9303 
9304   switch (Cand->FailureKind) {
9305   case ovl_fail_too_many_arguments:
9306   case ovl_fail_too_few_arguments:
9307     return DiagnoseArityMismatch(S, Cand, NumArgs);
9308 
9309   case ovl_fail_bad_deduction:
9310     return DiagnoseBadDeduction(S, Cand, NumArgs);
9311 
9312   case ovl_fail_illegal_constructor: {
9313     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9314       << (Fn->getPrimaryTemplate() ? 1 : 0);
9315     MaybeEmitInheritedConstructorNote(S, Fn);
9316     return;
9317   }
9318 
9319   case ovl_fail_trivial_conversion:
9320   case ovl_fail_bad_final_conversion:
9321   case ovl_fail_final_conversion_not_exact:
9322     return S.NoteOverloadCandidate(Fn);
9323 
9324   case ovl_fail_bad_conversion: {
9325     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9326     for (unsigned N = Cand->NumConversions; I != N; ++I)
9327       if (Cand->Conversions[I].isBad())
9328         return DiagnoseBadConversion(S, Cand, I);
9329 
9330     // FIXME: this currently happens when we're called from SemaInit
9331     // when user-conversion overload fails.  Figure out how to handle
9332     // those conditions and diagnose them well.
9333     return S.NoteOverloadCandidate(Fn);
9334   }
9335 
9336   case ovl_fail_bad_target:
9337     return DiagnoseBadTarget(S, Cand);
9338 
9339   case ovl_fail_enable_if:
9340     return DiagnoseFailedEnableIfAttr(S, Cand);
9341   }
9342 }
9343 
9344 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9345   // Desugar the type of the surrogate down to a function type,
9346   // retaining as many typedefs as possible while still showing
9347   // the function type (and, therefore, its parameter types).
9348   QualType FnType = Cand->Surrogate->getConversionType();
9349   bool isLValueReference = false;
9350   bool isRValueReference = false;
9351   bool isPointer = false;
9352   if (const LValueReferenceType *FnTypeRef =
9353         FnType->getAs<LValueReferenceType>()) {
9354     FnType = FnTypeRef->getPointeeType();
9355     isLValueReference = true;
9356   } else if (const RValueReferenceType *FnTypeRef =
9357                FnType->getAs<RValueReferenceType>()) {
9358     FnType = FnTypeRef->getPointeeType();
9359     isRValueReference = true;
9360   }
9361   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9362     FnType = FnTypePtr->getPointeeType();
9363     isPointer = true;
9364   }
9365   // Desugar down to a function type.
9366   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9367   // Reconstruct the pointer/reference as appropriate.
9368   if (isPointer) FnType = S.Context.getPointerType(FnType);
9369   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9370   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9371 
9372   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9373     << FnType;
9374   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9375 }
9376 
9377 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9378                                          SourceLocation OpLoc,
9379                                          OverloadCandidate *Cand) {
9380   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9381   std::string TypeStr("operator");
9382   TypeStr += Opc;
9383   TypeStr += "(";
9384   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9385   if (Cand->NumConversions == 1) {
9386     TypeStr += ")";
9387     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9388   } else {
9389     TypeStr += ", ";
9390     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9391     TypeStr += ")";
9392     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9393   }
9394 }
9395 
9396 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9397                                          OverloadCandidate *Cand) {
9398   unsigned NoOperands = Cand->NumConversions;
9399   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9400     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9401     if (ICS.isBad()) break; // all meaningless after first invalid
9402     if (!ICS.isAmbiguous()) continue;
9403 
9404     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9405                               S.PDiag(diag::note_ambiguous_type_conversion));
9406   }
9407 }
9408 
9409 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9410   if (Cand->Function)
9411     return Cand->Function->getLocation();
9412   if (Cand->IsSurrogate)
9413     return Cand->Surrogate->getLocation();
9414   return SourceLocation();
9415 }
9416 
9417 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9418   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9419   case Sema::TDK_Success:
9420     llvm_unreachable("TDK_success while diagnosing bad deduction");
9421 
9422   case Sema::TDK_Invalid:
9423   case Sema::TDK_Incomplete:
9424     return 1;
9425 
9426   case Sema::TDK_Underqualified:
9427   case Sema::TDK_Inconsistent:
9428     return 2;
9429 
9430   case Sema::TDK_SubstitutionFailure:
9431   case Sema::TDK_NonDeducedMismatch:
9432   case Sema::TDK_MiscellaneousDeductionFailure:
9433     return 3;
9434 
9435   case Sema::TDK_InstantiationDepth:
9436   case Sema::TDK_FailedOverloadResolution:
9437     return 4;
9438 
9439   case Sema::TDK_InvalidExplicitArguments:
9440     return 5;
9441 
9442   case Sema::TDK_TooManyArguments:
9443   case Sema::TDK_TooFewArguments:
9444     return 6;
9445   }
9446   llvm_unreachable("Unhandled deduction result");
9447 }
9448 
9449 namespace {
9450 struct CompareOverloadCandidatesForDisplay {
9451   Sema &S;
9452   size_t NumArgs;
9453 
9454   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9455       : S(S), NumArgs(nArgs) {}
9456 
9457   bool operator()(const OverloadCandidate *L,
9458                   const OverloadCandidate *R) {
9459     // Fast-path this check.
9460     if (L == R) return false;
9461 
9462     // Order first by viability.
9463     if (L->Viable) {
9464       if (!R->Viable) return true;
9465 
9466       // TODO: introduce a tri-valued comparison for overload
9467       // candidates.  Would be more worthwhile if we had a sort
9468       // that could exploit it.
9469       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9470       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9471     } else if (R->Viable)
9472       return false;
9473 
9474     assert(L->Viable == R->Viable);
9475 
9476     // Criteria by which we can sort non-viable candidates:
9477     if (!L->Viable) {
9478       // 1. Arity mismatches come after other candidates.
9479       if (L->FailureKind == ovl_fail_too_many_arguments ||
9480           L->FailureKind == ovl_fail_too_few_arguments) {
9481         if (R->FailureKind == ovl_fail_too_many_arguments ||
9482             R->FailureKind == ovl_fail_too_few_arguments) {
9483           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9484           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9485           if (LDist == RDist) {
9486             if (L->FailureKind == R->FailureKind)
9487               // Sort non-surrogates before surrogates.
9488               return !L->IsSurrogate && R->IsSurrogate;
9489             // Sort candidates requiring fewer parameters than there were
9490             // arguments given after candidates requiring more parameters
9491             // than there were arguments given.
9492             return L->FailureKind == ovl_fail_too_many_arguments;
9493           }
9494           return LDist < RDist;
9495         }
9496         return false;
9497       }
9498       if (R->FailureKind == ovl_fail_too_many_arguments ||
9499           R->FailureKind == ovl_fail_too_few_arguments)
9500         return true;
9501 
9502       // 2. Bad conversions come first and are ordered by the number
9503       // of bad conversions and quality of good conversions.
9504       if (L->FailureKind == ovl_fail_bad_conversion) {
9505         if (R->FailureKind != ovl_fail_bad_conversion)
9506           return true;
9507 
9508         // The conversion that can be fixed with a smaller number of changes,
9509         // comes first.
9510         unsigned numLFixes = L->Fix.NumConversionsFixed;
9511         unsigned numRFixes = R->Fix.NumConversionsFixed;
9512         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9513         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9514         if (numLFixes != numRFixes) {
9515           return numLFixes < numRFixes;
9516         }
9517 
9518         // If there's any ordering between the defined conversions...
9519         // FIXME: this might not be transitive.
9520         assert(L->NumConversions == R->NumConversions);
9521 
9522         int leftBetter = 0;
9523         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9524         for (unsigned E = L->NumConversions; I != E; ++I) {
9525           switch (CompareImplicitConversionSequences(S,
9526                                                      L->Conversions[I],
9527                                                      R->Conversions[I])) {
9528           case ImplicitConversionSequence::Better:
9529             leftBetter++;
9530             break;
9531 
9532           case ImplicitConversionSequence::Worse:
9533             leftBetter--;
9534             break;
9535 
9536           case ImplicitConversionSequence::Indistinguishable:
9537             break;
9538           }
9539         }
9540         if (leftBetter > 0) return true;
9541         if (leftBetter < 0) return false;
9542 
9543       } else if (R->FailureKind == ovl_fail_bad_conversion)
9544         return false;
9545 
9546       if (L->FailureKind == ovl_fail_bad_deduction) {
9547         if (R->FailureKind != ovl_fail_bad_deduction)
9548           return true;
9549 
9550         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9551           return RankDeductionFailure(L->DeductionFailure)
9552                < RankDeductionFailure(R->DeductionFailure);
9553       } else if (R->FailureKind == ovl_fail_bad_deduction)
9554         return false;
9555 
9556       // TODO: others?
9557     }
9558 
9559     // Sort everything else by location.
9560     SourceLocation LLoc = GetLocationForCandidate(L);
9561     SourceLocation RLoc = GetLocationForCandidate(R);
9562 
9563     // Put candidates without locations (e.g. builtins) at the end.
9564     if (LLoc.isInvalid()) return false;
9565     if (RLoc.isInvalid()) return true;
9566 
9567     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9568   }
9569 };
9570 }
9571 
9572 /// CompleteNonViableCandidate - Normally, overload resolution only
9573 /// computes up to the first. Produces the FixIt set if possible.
9574 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9575                                        ArrayRef<Expr *> Args) {
9576   assert(!Cand->Viable);
9577 
9578   // Don't do anything on failures other than bad conversion.
9579   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9580 
9581   // We only want the FixIts if all the arguments can be corrected.
9582   bool Unfixable = false;
9583   // Use a implicit copy initialization to check conversion fixes.
9584   Cand->Fix.setConversionChecker(TryCopyInitialization);
9585 
9586   // Skip forward to the first bad conversion.
9587   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9588   unsigned ConvCount = Cand->NumConversions;
9589   while (true) {
9590     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9591     ConvIdx++;
9592     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9593       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9594       break;
9595     }
9596   }
9597 
9598   if (ConvIdx == ConvCount)
9599     return;
9600 
9601   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9602          "remaining conversion is initialized?");
9603 
9604   // FIXME: this should probably be preserved from the overload
9605   // operation somehow.
9606   bool SuppressUserConversions = false;
9607 
9608   const FunctionProtoType* Proto;
9609   unsigned ArgIdx = ConvIdx;
9610 
9611   if (Cand->IsSurrogate) {
9612     QualType ConvType
9613       = Cand->Surrogate->getConversionType().getNonReferenceType();
9614     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9615       ConvType = ConvPtrType->getPointeeType();
9616     Proto = ConvType->getAs<FunctionProtoType>();
9617     ArgIdx--;
9618   } else if (Cand->Function) {
9619     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9620     if (isa<CXXMethodDecl>(Cand->Function) &&
9621         !isa<CXXConstructorDecl>(Cand->Function))
9622       ArgIdx--;
9623   } else {
9624     // Builtin binary operator with a bad first conversion.
9625     assert(ConvCount <= 3);
9626     for (; ConvIdx != ConvCount; ++ConvIdx)
9627       Cand->Conversions[ConvIdx]
9628         = TryCopyInitialization(S, Args[ConvIdx],
9629                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9630                                 SuppressUserConversions,
9631                                 /*InOverloadResolution*/ true,
9632                                 /*AllowObjCWritebackConversion=*/
9633                                   S.getLangOpts().ObjCAutoRefCount);
9634     return;
9635   }
9636 
9637   // Fill in the rest of the conversions.
9638   unsigned NumParams = Proto->getNumParams();
9639   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9640     if (ArgIdx < NumParams) {
9641       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9642           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9643           /*InOverloadResolution=*/true,
9644           /*AllowObjCWritebackConversion=*/
9645           S.getLangOpts().ObjCAutoRefCount);
9646       // Store the FixIt in the candidate if it exists.
9647       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9648         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9649     }
9650     else
9651       Cand->Conversions[ConvIdx].setEllipsis();
9652   }
9653 }
9654 
9655 /// PrintOverloadCandidates - When overload resolution fails, prints
9656 /// diagnostic messages containing the candidates in the candidate
9657 /// set.
9658 void OverloadCandidateSet::NoteCandidates(Sema &S,
9659                                           OverloadCandidateDisplayKind OCD,
9660                                           ArrayRef<Expr *> Args,
9661                                           StringRef Opc,
9662                                           SourceLocation OpLoc) {
9663   // Sort the candidates by viability and position.  Sorting directly would
9664   // be prohibitive, so we make a set of pointers and sort those.
9665   SmallVector<OverloadCandidate*, 32> Cands;
9666   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9667   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9668     if (Cand->Viable)
9669       Cands.push_back(Cand);
9670     else if (OCD == OCD_AllCandidates) {
9671       CompleteNonViableCandidate(S, Cand, Args);
9672       if (Cand->Function || Cand->IsSurrogate)
9673         Cands.push_back(Cand);
9674       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9675       // want to list every possible builtin candidate.
9676     }
9677   }
9678 
9679   std::sort(Cands.begin(), Cands.end(),
9680             CompareOverloadCandidatesForDisplay(S, Args.size()));
9681 
9682   bool ReportedAmbiguousConversions = false;
9683 
9684   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9685   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9686   unsigned CandsShown = 0;
9687   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9688     OverloadCandidate *Cand = *I;
9689 
9690     // Set an arbitrary limit on the number of candidate functions we'll spam
9691     // the user with.  FIXME: This limit should depend on details of the
9692     // candidate list.
9693     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9694       break;
9695     }
9696     ++CandsShown;
9697 
9698     if (Cand->Function)
9699       NoteFunctionCandidate(S, Cand, Args.size());
9700     else if (Cand->IsSurrogate)
9701       NoteSurrogateCandidate(S, Cand);
9702     else {
9703       assert(Cand->Viable &&
9704              "Non-viable built-in candidates are not added to Cands.");
9705       // Generally we only see ambiguities including viable builtin
9706       // operators if overload resolution got screwed up by an
9707       // ambiguous user-defined conversion.
9708       //
9709       // FIXME: It's quite possible for different conversions to see
9710       // different ambiguities, though.
9711       if (!ReportedAmbiguousConversions) {
9712         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9713         ReportedAmbiguousConversions = true;
9714       }
9715 
9716       // If this is a viable builtin, print it.
9717       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9718     }
9719   }
9720 
9721   if (I != E)
9722     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9723 }
9724 
9725 static SourceLocation
9726 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9727   return Cand->Specialization ? Cand->Specialization->getLocation()
9728                               : SourceLocation();
9729 }
9730 
9731 namespace {
9732 struct CompareTemplateSpecCandidatesForDisplay {
9733   Sema &S;
9734   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9735 
9736   bool operator()(const TemplateSpecCandidate *L,
9737                   const TemplateSpecCandidate *R) {
9738     // Fast-path this check.
9739     if (L == R)
9740       return false;
9741 
9742     // Assuming that both candidates are not matches...
9743 
9744     // Sort by the ranking of deduction failures.
9745     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9746       return RankDeductionFailure(L->DeductionFailure) <
9747              RankDeductionFailure(R->DeductionFailure);
9748 
9749     // Sort everything else by location.
9750     SourceLocation LLoc = GetLocationForCandidate(L);
9751     SourceLocation RLoc = GetLocationForCandidate(R);
9752 
9753     // Put candidates without locations (e.g. builtins) at the end.
9754     if (LLoc.isInvalid())
9755       return false;
9756     if (RLoc.isInvalid())
9757       return true;
9758 
9759     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9760   }
9761 };
9762 }
9763 
9764 /// Diagnose a template argument deduction failure.
9765 /// We are treating these failures as overload failures due to bad
9766 /// deductions.
9767 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9768   DiagnoseBadDeduction(S, Specialization, // pattern
9769                        DeductionFailure, /*NumArgs=*/0);
9770 }
9771 
9772 void TemplateSpecCandidateSet::destroyCandidates() {
9773   for (iterator i = begin(), e = end(); i != e; ++i) {
9774     i->DeductionFailure.Destroy();
9775   }
9776 }
9777 
9778 void TemplateSpecCandidateSet::clear() {
9779   destroyCandidates();
9780   Candidates.clear();
9781 }
9782 
9783 /// NoteCandidates - When no template specialization match is found, prints
9784 /// diagnostic messages containing the non-matching specializations that form
9785 /// the candidate set.
9786 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9787 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9788 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9789   // Sort the candidates by position (assuming no candidate is a match).
9790   // Sorting directly would be prohibitive, so we make a set of pointers
9791   // and sort those.
9792   SmallVector<TemplateSpecCandidate *, 32> Cands;
9793   Cands.reserve(size());
9794   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9795     if (Cand->Specialization)
9796       Cands.push_back(Cand);
9797     // Otherwise, this is a non-matching builtin candidate.  We do not,
9798     // in general, want to list every possible builtin candidate.
9799   }
9800 
9801   std::sort(Cands.begin(), Cands.end(),
9802             CompareTemplateSpecCandidatesForDisplay(S));
9803 
9804   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9805   // for generalization purposes (?).
9806   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9807 
9808   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9809   unsigned CandsShown = 0;
9810   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9811     TemplateSpecCandidate *Cand = *I;
9812 
9813     // Set an arbitrary limit on the number of candidates we'll spam
9814     // the user with.  FIXME: This limit should depend on details of the
9815     // candidate list.
9816     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9817       break;
9818     ++CandsShown;
9819 
9820     assert(Cand->Specialization &&
9821            "Non-matching built-in candidates are not added to Cands.");
9822     Cand->NoteDeductionFailure(S);
9823   }
9824 
9825   if (I != E)
9826     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9827 }
9828 
9829 // [PossiblyAFunctionType]  -->   [Return]
9830 // NonFunctionType --> NonFunctionType
9831 // R (A) --> R(A)
9832 // R (*)(A) --> R (A)
9833 // R (&)(A) --> R (A)
9834 // R (S::*)(A) --> R (A)
9835 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9836   QualType Ret = PossiblyAFunctionType;
9837   if (const PointerType *ToTypePtr =
9838     PossiblyAFunctionType->getAs<PointerType>())
9839     Ret = ToTypePtr->getPointeeType();
9840   else if (const ReferenceType *ToTypeRef =
9841     PossiblyAFunctionType->getAs<ReferenceType>())
9842     Ret = ToTypeRef->getPointeeType();
9843   else if (const MemberPointerType *MemTypePtr =
9844     PossiblyAFunctionType->getAs<MemberPointerType>())
9845     Ret = MemTypePtr->getPointeeType();
9846   Ret =
9847     Context.getCanonicalType(Ret).getUnqualifiedType();
9848   return Ret;
9849 }
9850 
9851 namespace {
9852 // A helper class to help with address of function resolution
9853 // - allows us to avoid passing around all those ugly parameters
9854 class AddressOfFunctionResolver {
9855   Sema& S;
9856   Expr* SourceExpr;
9857   const QualType& TargetType;
9858   QualType TargetFunctionType; // Extracted function type from target type
9859 
9860   bool Complain;
9861   //DeclAccessPair& ResultFunctionAccessPair;
9862   ASTContext& Context;
9863 
9864   bool TargetTypeIsNonStaticMemberFunction;
9865   bool FoundNonTemplateFunction;
9866   bool StaticMemberFunctionFromBoundPointer;
9867 
9868   OverloadExpr::FindResult OvlExprInfo;
9869   OverloadExpr *OvlExpr;
9870   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9871   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9872   TemplateSpecCandidateSet FailedCandidates;
9873 
9874 public:
9875   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9876                             const QualType &TargetType, bool Complain)
9877       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9878         Complain(Complain), Context(S.getASTContext()),
9879         TargetTypeIsNonStaticMemberFunction(
9880             !!TargetType->getAs<MemberPointerType>()),
9881         FoundNonTemplateFunction(false),
9882         StaticMemberFunctionFromBoundPointer(false),
9883         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9884         OvlExpr(OvlExprInfo.Expression),
9885         FailedCandidates(OvlExpr->getNameLoc()) {
9886     ExtractUnqualifiedFunctionTypeFromTargetType();
9887 
9888     if (TargetFunctionType->isFunctionType()) {
9889       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9890         if (!UME->isImplicitAccess() &&
9891             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9892           StaticMemberFunctionFromBoundPointer = true;
9893     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9894       DeclAccessPair dap;
9895       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9896               OvlExpr, false, &dap)) {
9897         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9898           if (!Method->isStatic()) {
9899             // If the target type is a non-function type and the function found
9900             // is a non-static member function, pretend as if that was the
9901             // target, it's the only possible type to end up with.
9902             TargetTypeIsNonStaticMemberFunction = true;
9903 
9904             // And skip adding the function if its not in the proper form.
9905             // We'll diagnose this due to an empty set of functions.
9906             if (!OvlExprInfo.HasFormOfMemberPointer)
9907               return;
9908           }
9909 
9910         Matches.push_back(std::make_pair(dap, Fn));
9911       }
9912       return;
9913     }
9914 
9915     if (OvlExpr->hasExplicitTemplateArgs())
9916       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9917 
9918     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9919       // C++ [over.over]p4:
9920       //   If more than one function is selected, [...]
9921       if (Matches.size() > 1) {
9922         if (FoundNonTemplateFunction)
9923           EliminateAllTemplateMatches();
9924         else
9925           EliminateAllExceptMostSpecializedTemplate();
9926       }
9927     }
9928   }
9929 
9930 private:
9931   bool isTargetTypeAFunction() const {
9932     return TargetFunctionType->isFunctionType();
9933   }
9934 
9935   // [ToType]     [Return]
9936 
9937   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9938   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9939   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9940   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9941     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9942   }
9943 
9944   // return true if any matching specializations were found
9945   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9946                                    const DeclAccessPair& CurAccessFunPair) {
9947     if (CXXMethodDecl *Method
9948               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9949       // Skip non-static function templates when converting to pointer, and
9950       // static when converting to member pointer.
9951       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9952         return false;
9953     }
9954     else if (TargetTypeIsNonStaticMemberFunction)
9955       return false;
9956 
9957     // C++ [over.over]p2:
9958     //   If the name is a function template, template argument deduction is
9959     //   done (14.8.2.2), and if the argument deduction succeeds, the
9960     //   resulting template argument list is used to generate a single
9961     //   function template specialization, which is added to the set of
9962     //   overloaded functions considered.
9963     FunctionDecl *Specialization = nullptr;
9964     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9965     if (Sema::TemplateDeductionResult Result
9966           = S.DeduceTemplateArguments(FunctionTemplate,
9967                                       &OvlExplicitTemplateArgs,
9968                                       TargetFunctionType, Specialization,
9969                                       Info, /*InOverloadResolution=*/true)) {
9970       // Make a note of the failed deduction for diagnostics.
9971       FailedCandidates.addCandidate()
9972           .set(FunctionTemplate->getTemplatedDecl(),
9973                MakeDeductionFailureInfo(Context, Result, Info));
9974       return false;
9975     }
9976 
9977     // Template argument deduction ensures that we have an exact match or
9978     // compatible pointer-to-function arguments that would be adjusted by ICS.
9979     // This function template specicalization works.
9980     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9981     assert(S.isSameOrCompatibleFunctionType(
9982               Context.getCanonicalType(Specialization->getType()),
9983               Context.getCanonicalType(TargetFunctionType)));
9984     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9985     return true;
9986   }
9987 
9988   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9989                                       const DeclAccessPair& CurAccessFunPair) {
9990     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9991       // Skip non-static functions when converting to pointer, and static
9992       // when converting to member pointer.
9993       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9994         return false;
9995     }
9996     else if (TargetTypeIsNonStaticMemberFunction)
9997       return false;
9998 
9999     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10000       if (S.getLangOpts().CUDA)
10001         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10002           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10003             return false;
10004 
10005       // If any candidate has a placeholder return type, trigger its deduction
10006       // now.
10007       if (S.getLangOpts().CPlusPlus14 &&
10008           FunDecl->getReturnType()->isUndeducedType() &&
10009           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10010         return false;
10011 
10012       QualType ResultTy;
10013       if (Context.hasSameUnqualifiedType(TargetFunctionType,
10014                                          FunDecl->getType()) ||
10015           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10016                                  ResultTy)) {
10017         Matches.push_back(std::make_pair(CurAccessFunPair,
10018           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10019         FoundNonTemplateFunction = true;
10020         return true;
10021       }
10022     }
10023 
10024     return false;
10025   }
10026 
10027   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10028     bool Ret = false;
10029 
10030     // If the overload expression doesn't have the form of a pointer to
10031     // member, don't try to convert it to a pointer-to-member type.
10032     if (IsInvalidFormOfPointerToMemberFunction())
10033       return false;
10034 
10035     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10036                                E = OvlExpr->decls_end();
10037          I != E; ++I) {
10038       // Look through any using declarations to find the underlying function.
10039       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10040 
10041       // C++ [over.over]p3:
10042       //   Non-member functions and static member functions match
10043       //   targets of type "pointer-to-function" or "reference-to-function."
10044       //   Nonstatic member functions match targets of
10045       //   type "pointer-to-member-function."
10046       // Note that according to DR 247, the containing class does not matter.
10047       if (FunctionTemplateDecl *FunctionTemplate
10048                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10049         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10050           Ret = true;
10051       }
10052       // If we have explicit template arguments supplied, skip non-templates.
10053       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10054                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10055         Ret = true;
10056     }
10057     assert(Ret || Matches.empty());
10058     return Ret;
10059   }
10060 
10061   void EliminateAllExceptMostSpecializedTemplate() {
10062     //   [...] and any given function template specialization F1 is
10063     //   eliminated if the set contains a second function template
10064     //   specialization whose function template is more specialized
10065     //   than the function template of F1 according to the partial
10066     //   ordering rules of 14.5.5.2.
10067 
10068     // The algorithm specified above is quadratic. We instead use a
10069     // two-pass algorithm (similar to the one used to identify the
10070     // best viable function in an overload set) that identifies the
10071     // best function template (if it exists).
10072 
10073     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10074     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10075       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10076 
10077     // TODO: It looks like FailedCandidates does not serve much purpose
10078     // here, since the no_viable diagnostic has index 0.
10079     UnresolvedSetIterator Result = S.getMostSpecialized(
10080         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10081         SourceExpr->getLocStart(), S.PDiag(),
10082         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10083                                                      .second->getDeclName(),
10084         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10085         Complain, TargetFunctionType);
10086 
10087     if (Result != MatchesCopy.end()) {
10088       // Make it the first and only element
10089       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10090       Matches[0].second = cast<FunctionDecl>(*Result);
10091       Matches.resize(1);
10092     }
10093   }
10094 
10095   void EliminateAllTemplateMatches() {
10096     //   [...] any function template specializations in the set are
10097     //   eliminated if the set also contains a non-template function, [...]
10098     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10099       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10100         ++I;
10101       else {
10102         Matches[I] = Matches[--N];
10103         Matches.set_size(N);
10104       }
10105     }
10106   }
10107 
10108 public:
10109   void ComplainNoMatchesFound() const {
10110     assert(Matches.empty());
10111     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10112         << OvlExpr->getName() << TargetFunctionType
10113         << OvlExpr->getSourceRange();
10114     if (FailedCandidates.empty())
10115       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10116     else {
10117       // We have some deduction failure messages. Use them to diagnose
10118       // the function templates, and diagnose the non-template candidates
10119       // normally.
10120       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10121                                  IEnd = OvlExpr->decls_end();
10122            I != IEnd; ++I)
10123         if (FunctionDecl *Fun =
10124                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10125           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10126       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10127     }
10128   }
10129 
10130   bool IsInvalidFormOfPointerToMemberFunction() const {
10131     return TargetTypeIsNonStaticMemberFunction &&
10132       !OvlExprInfo.HasFormOfMemberPointer;
10133   }
10134 
10135   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10136       // TODO: Should we condition this on whether any functions might
10137       // have matched, or is it more appropriate to do that in callers?
10138       // TODO: a fixit wouldn't hurt.
10139       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10140         << TargetType << OvlExpr->getSourceRange();
10141   }
10142 
10143   bool IsStaticMemberFunctionFromBoundPointer() const {
10144     return StaticMemberFunctionFromBoundPointer;
10145   }
10146 
10147   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10148     S.Diag(OvlExpr->getLocStart(),
10149            diag::err_invalid_form_pointer_member_function)
10150       << OvlExpr->getSourceRange();
10151   }
10152 
10153   void ComplainOfInvalidConversion() const {
10154     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10155       << OvlExpr->getName() << TargetType;
10156   }
10157 
10158   void ComplainMultipleMatchesFound() const {
10159     assert(Matches.size() > 1);
10160     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10161       << OvlExpr->getName()
10162       << OvlExpr->getSourceRange();
10163     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10164   }
10165 
10166   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10167 
10168   int getNumMatches() const { return Matches.size(); }
10169 
10170   FunctionDecl* getMatchingFunctionDecl() const {
10171     if (Matches.size() != 1) return nullptr;
10172     return Matches[0].second;
10173   }
10174 
10175   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10176     if (Matches.size() != 1) return nullptr;
10177     return &Matches[0].first;
10178   }
10179 };
10180 }
10181 
10182 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10183 /// an overloaded function (C++ [over.over]), where @p From is an
10184 /// expression with overloaded function type and @p ToType is the type
10185 /// we're trying to resolve to. For example:
10186 ///
10187 /// @code
10188 /// int f(double);
10189 /// int f(int);
10190 ///
10191 /// int (*pfd)(double) = f; // selects f(double)
10192 /// @endcode
10193 ///
10194 /// This routine returns the resulting FunctionDecl if it could be
10195 /// resolved, and NULL otherwise. When @p Complain is true, this
10196 /// routine will emit diagnostics if there is an error.
10197 FunctionDecl *
10198 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10199                                          QualType TargetType,
10200                                          bool Complain,
10201                                          DeclAccessPair &FoundResult,
10202                                          bool *pHadMultipleCandidates) {
10203   assert(AddressOfExpr->getType() == Context.OverloadTy);
10204 
10205   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10206                                      Complain);
10207   int NumMatches = Resolver.getNumMatches();
10208   FunctionDecl *Fn = nullptr;
10209   if (NumMatches == 0 && Complain) {
10210     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10211       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10212     else
10213       Resolver.ComplainNoMatchesFound();
10214   }
10215   else if (NumMatches > 1 && Complain)
10216     Resolver.ComplainMultipleMatchesFound();
10217   else if (NumMatches == 1) {
10218     Fn = Resolver.getMatchingFunctionDecl();
10219     assert(Fn);
10220     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10221     if (Complain) {
10222       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10223         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10224       else
10225         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10226     }
10227   }
10228 
10229   if (pHadMultipleCandidates)
10230     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10231   return Fn;
10232 }
10233 
10234 /// \brief Given an expression that refers to an overloaded function, try to
10235 /// resolve that overloaded function expression down to a single function.
10236 ///
10237 /// This routine can only resolve template-ids that refer to a single function
10238 /// template, where that template-id refers to a single template whose template
10239 /// arguments are either provided by the template-id or have defaults,
10240 /// as described in C++0x [temp.arg.explicit]p3.
10241 ///
10242 /// If no template-ids are found, no diagnostics are emitted and NULL is
10243 /// returned.
10244 FunctionDecl *
10245 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10246                                                   bool Complain,
10247                                                   DeclAccessPair *FoundResult) {
10248   // C++ [over.over]p1:
10249   //   [...] [Note: any redundant set of parentheses surrounding the
10250   //   overloaded function name is ignored (5.1). ]
10251   // C++ [over.over]p1:
10252   //   [...] The overloaded function name can be preceded by the &
10253   //   operator.
10254 
10255   // If we didn't actually find any template-ids, we're done.
10256   if (!ovl->hasExplicitTemplateArgs())
10257     return nullptr;
10258 
10259   TemplateArgumentListInfo ExplicitTemplateArgs;
10260   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10261   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10262 
10263   // Look through all of the overloaded functions, searching for one
10264   // whose type matches exactly.
10265   FunctionDecl *Matched = nullptr;
10266   for (UnresolvedSetIterator I = ovl->decls_begin(),
10267          E = ovl->decls_end(); I != E; ++I) {
10268     // C++0x [temp.arg.explicit]p3:
10269     //   [...] In contexts where deduction is done and fails, or in contexts
10270     //   where deduction is not done, if a template argument list is
10271     //   specified and it, along with any default template arguments,
10272     //   identifies a single function template specialization, then the
10273     //   template-id is an lvalue for the function template specialization.
10274     FunctionTemplateDecl *FunctionTemplate
10275       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10276 
10277     // C++ [over.over]p2:
10278     //   If the name is a function template, template argument deduction is
10279     //   done (14.8.2.2), and if the argument deduction succeeds, the
10280     //   resulting template argument list is used to generate a single
10281     //   function template specialization, which is added to the set of
10282     //   overloaded functions considered.
10283     FunctionDecl *Specialization = nullptr;
10284     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10285     if (TemplateDeductionResult Result
10286           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10287                                     Specialization, Info,
10288                                     /*InOverloadResolution=*/true)) {
10289       // Make a note of the failed deduction for diagnostics.
10290       // TODO: Actually use the failed-deduction info?
10291       FailedCandidates.addCandidate()
10292           .set(FunctionTemplate->getTemplatedDecl(),
10293                MakeDeductionFailureInfo(Context, Result, Info));
10294       continue;
10295     }
10296 
10297     assert(Specialization && "no specialization and no error?");
10298 
10299     // Multiple matches; we can't resolve to a single declaration.
10300     if (Matched) {
10301       if (Complain) {
10302         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10303           << ovl->getName();
10304         NoteAllOverloadCandidates(ovl);
10305       }
10306       return nullptr;
10307     }
10308 
10309     Matched = Specialization;
10310     if (FoundResult) *FoundResult = I.getPair();
10311   }
10312 
10313   if (Matched && getLangOpts().CPlusPlus14 &&
10314       Matched->getReturnType()->isUndeducedType() &&
10315       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10316     return nullptr;
10317 
10318   return Matched;
10319 }
10320 
10321 
10322 
10323 
10324 // Resolve and fix an overloaded expression that can be resolved
10325 // because it identifies a single function template specialization.
10326 //
10327 // Last three arguments should only be supplied if Complain = true
10328 //
10329 // Return true if it was logically possible to so resolve the
10330 // expression, regardless of whether or not it succeeded.  Always
10331 // returns true if 'complain' is set.
10332 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10333                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10334                    bool complain, const SourceRange& OpRangeForComplaining,
10335                                            QualType DestTypeForComplaining,
10336                                             unsigned DiagIDForComplaining) {
10337   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10338 
10339   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10340 
10341   DeclAccessPair found;
10342   ExprResult SingleFunctionExpression;
10343   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10344                            ovl.Expression, /*complain*/ false, &found)) {
10345     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10346       SrcExpr = ExprError();
10347       return true;
10348     }
10349 
10350     // It is only correct to resolve to an instance method if we're
10351     // resolving a form that's permitted to be a pointer to member.
10352     // Otherwise we'll end up making a bound member expression, which
10353     // is illegal in all the contexts we resolve like this.
10354     if (!ovl.HasFormOfMemberPointer &&
10355         isa<CXXMethodDecl>(fn) &&
10356         cast<CXXMethodDecl>(fn)->isInstance()) {
10357       if (!complain) return false;
10358 
10359       Diag(ovl.Expression->getExprLoc(),
10360            diag::err_bound_member_function)
10361         << 0 << ovl.Expression->getSourceRange();
10362 
10363       // TODO: I believe we only end up here if there's a mix of
10364       // static and non-static candidates (otherwise the expression
10365       // would have 'bound member' type, not 'overload' type).
10366       // Ideally we would note which candidate was chosen and why
10367       // the static candidates were rejected.
10368       SrcExpr = ExprError();
10369       return true;
10370     }
10371 
10372     // Fix the expression to refer to 'fn'.
10373     SingleFunctionExpression =
10374         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10375 
10376     // If desired, do function-to-pointer decay.
10377     if (doFunctionPointerConverion) {
10378       SingleFunctionExpression =
10379         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10380       if (SingleFunctionExpression.isInvalid()) {
10381         SrcExpr = ExprError();
10382         return true;
10383       }
10384     }
10385   }
10386 
10387   if (!SingleFunctionExpression.isUsable()) {
10388     if (complain) {
10389       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10390         << ovl.Expression->getName()
10391         << DestTypeForComplaining
10392         << OpRangeForComplaining
10393         << ovl.Expression->getQualifierLoc().getSourceRange();
10394       NoteAllOverloadCandidates(SrcExpr.get());
10395 
10396       SrcExpr = ExprError();
10397       return true;
10398     }
10399 
10400     return false;
10401   }
10402 
10403   SrcExpr = SingleFunctionExpression;
10404   return true;
10405 }
10406 
10407 /// \brief Add a single candidate to the overload set.
10408 static void AddOverloadedCallCandidate(Sema &S,
10409                                        DeclAccessPair FoundDecl,
10410                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10411                                        ArrayRef<Expr *> Args,
10412                                        OverloadCandidateSet &CandidateSet,
10413                                        bool PartialOverloading,
10414                                        bool KnownValid) {
10415   NamedDecl *Callee = FoundDecl.getDecl();
10416   if (isa<UsingShadowDecl>(Callee))
10417     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10418 
10419   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10420     if (ExplicitTemplateArgs) {
10421       assert(!KnownValid && "Explicit template arguments?");
10422       return;
10423     }
10424     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10425                            /*SuppressUsedConversions=*/false,
10426                            PartialOverloading);
10427     return;
10428   }
10429 
10430   if (FunctionTemplateDecl *FuncTemplate
10431       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10432     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10433                                    ExplicitTemplateArgs, Args, CandidateSet,
10434                                    /*SuppressUsedConversions=*/false,
10435                                    PartialOverloading);
10436     return;
10437   }
10438 
10439   assert(!KnownValid && "unhandled case in overloaded call candidate");
10440 }
10441 
10442 /// \brief Add the overload candidates named by callee and/or found by argument
10443 /// dependent lookup to the given overload set.
10444 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10445                                        ArrayRef<Expr *> Args,
10446                                        OverloadCandidateSet &CandidateSet,
10447                                        bool PartialOverloading) {
10448 
10449 #ifndef NDEBUG
10450   // Verify that ArgumentDependentLookup is consistent with the rules
10451   // in C++0x [basic.lookup.argdep]p3:
10452   //
10453   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10454   //   and let Y be the lookup set produced by argument dependent
10455   //   lookup (defined as follows). If X contains
10456   //
10457   //     -- a declaration of a class member, or
10458   //
10459   //     -- a block-scope function declaration that is not a
10460   //        using-declaration, or
10461   //
10462   //     -- a declaration that is neither a function or a function
10463   //        template
10464   //
10465   //   then Y is empty.
10466 
10467   if (ULE->requiresADL()) {
10468     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10469            E = ULE->decls_end(); I != E; ++I) {
10470       assert(!(*I)->getDeclContext()->isRecord());
10471       assert(isa<UsingShadowDecl>(*I) ||
10472              !(*I)->getDeclContext()->isFunctionOrMethod());
10473       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10474     }
10475   }
10476 #endif
10477 
10478   // It would be nice to avoid this copy.
10479   TemplateArgumentListInfo TABuffer;
10480   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10481   if (ULE->hasExplicitTemplateArgs()) {
10482     ULE->copyTemplateArgumentsInto(TABuffer);
10483     ExplicitTemplateArgs = &TABuffer;
10484   }
10485 
10486   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10487          E = ULE->decls_end(); I != E; ++I)
10488     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10489                                CandidateSet, PartialOverloading,
10490                                /*KnownValid*/ true);
10491 
10492   if (ULE->requiresADL())
10493     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10494                                          Args, ExplicitTemplateArgs,
10495                                          CandidateSet, PartialOverloading);
10496 }
10497 
10498 /// Determine whether a declaration with the specified name could be moved into
10499 /// a different namespace.
10500 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10501   switch (Name.getCXXOverloadedOperator()) {
10502   case OO_New: case OO_Array_New:
10503   case OO_Delete: case OO_Array_Delete:
10504     return false;
10505 
10506   default:
10507     return true;
10508   }
10509 }
10510 
10511 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10512 /// template, where the non-dependent name was declared after the template
10513 /// was defined. This is common in code written for a compilers which do not
10514 /// correctly implement two-stage name lookup.
10515 ///
10516 /// Returns true if a viable candidate was found and a diagnostic was issued.
10517 static bool
10518 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10519                        const CXXScopeSpec &SS, LookupResult &R,
10520                        OverloadCandidateSet::CandidateSetKind CSK,
10521                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10522                        ArrayRef<Expr *> Args,
10523                        bool *DoDiagnoseEmptyLookup = nullptr) {
10524   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10525     return false;
10526 
10527   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10528     if (DC->isTransparentContext())
10529       continue;
10530 
10531     SemaRef.LookupQualifiedName(R, DC);
10532 
10533     if (!R.empty()) {
10534       R.suppressDiagnostics();
10535 
10536       if (isa<CXXRecordDecl>(DC)) {
10537         // Don't diagnose names we find in classes; we get much better
10538         // diagnostics for these from DiagnoseEmptyLookup.
10539         R.clear();
10540         if (DoDiagnoseEmptyLookup)
10541           *DoDiagnoseEmptyLookup = true;
10542         return false;
10543       }
10544 
10545       OverloadCandidateSet Candidates(FnLoc, CSK);
10546       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10547         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10548                                    ExplicitTemplateArgs, Args,
10549                                    Candidates, false, /*KnownValid*/ false);
10550 
10551       OverloadCandidateSet::iterator Best;
10552       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10553         // No viable functions. Don't bother the user with notes for functions
10554         // which don't work and shouldn't be found anyway.
10555         R.clear();
10556         return false;
10557       }
10558 
10559       // Find the namespaces where ADL would have looked, and suggest
10560       // declaring the function there instead.
10561       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10562       Sema::AssociatedClassSet AssociatedClasses;
10563       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10564                                                  AssociatedNamespaces,
10565                                                  AssociatedClasses);
10566       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10567       if (canBeDeclaredInNamespace(R.getLookupName())) {
10568         DeclContext *Std = SemaRef.getStdNamespace();
10569         for (Sema::AssociatedNamespaceSet::iterator
10570                it = AssociatedNamespaces.begin(),
10571                end = AssociatedNamespaces.end(); it != end; ++it) {
10572           // Never suggest declaring a function within namespace 'std'.
10573           if (Std && Std->Encloses(*it))
10574             continue;
10575 
10576           // Never suggest declaring a function within a namespace with a
10577           // reserved name, like __gnu_cxx.
10578           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10579           if (NS &&
10580               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10581             continue;
10582 
10583           SuggestedNamespaces.insert(*it);
10584         }
10585       }
10586 
10587       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10588         << R.getLookupName();
10589       if (SuggestedNamespaces.empty()) {
10590         SemaRef.Diag(Best->Function->getLocation(),
10591                      diag::note_not_found_by_two_phase_lookup)
10592           << R.getLookupName() << 0;
10593       } else if (SuggestedNamespaces.size() == 1) {
10594         SemaRef.Diag(Best->Function->getLocation(),
10595                      diag::note_not_found_by_two_phase_lookup)
10596           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10597       } else {
10598         // FIXME: It would be useful to list the associated namespaces here,
10599         // but the diagnostics infrastructure doesn't provide a way to produce
10600         // a localized representation of a list of items.
10601         SemaRef.Diag(Best->Function->getLocation(),
10602                      diag::note_not_found_by_two_phase_lookup)
10603           << R.getLookupName() << 2;
10604       }
10605 
10606       // Try to recover by calling this function.
10607       return true;
10608     }
10609 
10610     R.clear();
10611   }
10612 
10613   return false;
10614 }
10615 
10616 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10617 /// template, where the non-dependent operator was declared after the template
10618 /// was defined.
10619 ///
10620 /// Returns true if a viable candidate was found and a diagnostic was issued.
10621 static bool
10622 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10623                                SourceLocation OpLoc,
10624                                ArrayRef<Expr *> Args) {
10625   DeclarationName OpName =
10626     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10627   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10628   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10629                                 OverloadCandidateSet::CSK_Operator,
10630                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10631 }
10632 
10633 namespace {
10634 class BuildRecoveryCallExprRAII {
10635   Sema &SemaRef;
10636 public:
10637   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10638     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10639     SemaRef.IsBuildingRecoveryCallExpr = true;
10640   }
10641 
10642   ~BuildRecoveryCallExprRAII() {
10643     SemaRef.IsBuildingRecoveryCallExpr = false;
10644   }
10645 };
10646 
10647 }
10648 
10649 static std::unique_ptr<CorrectionCandidateCallback>
10650 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10651               bool HasTemplateArgs, bool AllowTypoCorrection) {
10652   if (!AllowTypoCorrection)
10653     return llvm::make_unique<NoTypoCorrectionCCC>();
10654   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10655                                                   HasTemplateArgs, ME);
10656 }
10657 
10658 /// Attempts to recover from a call where no functions were found.
10659 ///
10660 /// Returns true if new candidates were found.
10661 static ExprResult
10662 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10663                       UnresolvedLookupExpr *ULE,
10664                       SourceLocation LParenLoc,
10665                       MutableArrayRef<Expr *> Args,
10666                       SourceLocation RParenLoc,
10667                       bool EmptyLookup, bool AllowTypoCorrection) {
10668   // Do not try to recover if it is already building a recovery call.
10669   // This stops infinite loops for template instantiations like
10670   //
10671   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10672   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10673   //
10674   if (SemaRef.IsBuildingRecoveryCallExpr)
10675     return ExprError();
10676   BuildRecoveryCallExprRAII RCE(SemaRef);
10677 
10678   CXXScopeSpec SS;
10679   SS.Adopt(ULE->getQualifierLoc());
10680   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10681 
10682   TemplateArgumentListInfo TABuffer;
10683   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10684   if (ULE->hasExplicitTemplateArgs()) {
10685     ULE->copyTemplateArgumentsInto(TABuffer);
10686     ExplicitTemplateArgs = &TABuffer;
10687   }
10688 
10689   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10690                  Sema::LookupOrdinaryName);
10691   bool DoDiagnoseEmptyLookup = EmptyLookup;
10692   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10693                               OverloadCandidateSet::CSK_Normal,
10694                               ExplicitTemplateArgs, Args,
10695                               &DoDiagnoseEmptyLookup) &&
10696     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10697         S, SS, R,
10698         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10699                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10700         ExplicitTemplateArgs, Args)))
10701     return ExprError();
10702 
10703   assert(!R.empty() && "lookup results empty despite recovery");
10704 
10705   // Build an implicit member call if appropriate.  Just drop the
10706   // casts and such from the call, we don't really care.
10707   ExprResult NewFn = ExprError();
10708   if ((*R.begin())->isCXXClassMember())
10709     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10710                                                     ExplicitTemplateArgs, S);
10711   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10712     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10713                                         ExplicitTemplateArgs);
10714   else
10715     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10716 
10717   if (NewFn.isInvalid())
10718     return ExprError();
10719 
10720   // This shouldn't cause an infinite loop because we're giving it
10721   // an expression with viable lookup results, which should never
10722   // end up here.
10723   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10724                                MultiExprArg(Args.data(), Args.size()),
10725                                RParenLoc);
10726 }
10727 
10728 /// \brief Constructs and populates an OverloadedCandidateSet from
10729 /// the given function.
10730 /// \returns true when an the ExprResult output parameter has been set.
10731 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10732                                   UnresolvedLookupExpr *ULE,
10733                                   MultiExprArg Args,
10734                                   SourceLocation RParenLoc,
10735                                   OverloadCandidateSet *CandidateSet,
10736                                   ExprResult *Result) {
10737 #ifndef NDEBUG
10738   if (ULE->requiresADL()) {
10739     // To do ADL, we must have found an unqualified name.
10740     assert(!ULE->getQualifier() && "qualified name with ADL");
10741 
10742     // We don't perform ADL for implicit declarations of builtins.
10743     // Verify that this was correctly set up.
10744     FunctionDecl *F;
10745     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10746         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10747         F->getBuiltinID() && F->isImplicit())
10748       llvm_unreachable("performing ADL for builtin");
10749 
10750     // We don't perform ADL in C.
10751     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10752   }
10753 #endif
10754 
10755   UnbridgedCastsSet UnbridgedCasts;
10756   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10757     *Result = ExprError();
10758     return true;
10759   }
10760 
10761   // Add the functions denoted by the callee to the set of candidate
10762   // functions, including those from argument-dependent lookup.
10763   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10764 
10765   if (getLangOpts().MSVCCompat &&
10766       CurContext->isDependentContext() && !isSFINAEContext() &&
10767       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10768 
10769     OverloadCandidateSet::iterator Best;
10770     if (CandidateSet->empty() ||
10771         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10772             OR_No_Viable_Function) {
10773       // In Microsoft mode, if we are inside a template class member function then
10774       // create a type dependent CallExpr. The goal is to postpone name lookup
10775       // to instantiation time to be able to search into type dependent base
10776       // classes.
10777       CallExpr *CE = new (Context) CallExpr(
10778           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
10779       CE->setTypeDependent(true);
10780       *Result = CE;
10781       return true;
10782     }
10783   }
10784 
10785   if (CandidateSet->empty())
10786     return false;
10787 
10788   UnbridgedCasts.restore();
10789   return false;
10790 }
10791 
10792 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10793 /// the completed call expression. If overload resolution fails, emits
10794 /// diagnostics and returns ExprError()
10795 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10796                                            UnresolvedLookupExpr *ULE,
10797                                            SourceLocation LParenLoc,
10798                                            MultiExprArg Args,
10799                                            SourceLocation RParenLoc,
10800                                            Expr *ExecConfig,
10801                                            OverloadCandidateSet *CandidateSet,
10802                                            OverloadCandidateSet::iterator *Best,
10803                                            OverloadingResult OverloadResult,
10804                                            bool AllowTypoCorrection) {
10805   if (CandidateSet->empty())
10806     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10807                                  RParenLoc, /*EmptyLookup=*/true,
10808                                  AllowTypoCorrection);
10809 
10810   switch (OverloadResult) {
10811   case OR_Success: {
10812     FunctionDecl *FDecl = (*Best)->Function;
10813     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10814     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10815       return ExprError();
10816     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10817     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10818                                          ExecConfig);
10819   }
10820 
10821   case OR_No_Viable_Function: {
10822     // Try to recover by looking for viable functions which the user might
10823     // have meant to call.
10824     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10825                                                 Args, RParenLoc,
10826                                                 /*EmptyLookup=*/false,
10827                                                 AllowTypoCorrection);
10828     if (!Recovery.isInvalid())
10829       return Recovery;
10830 
10831     SemaRef.Diag(Fn->getLocStart(),
10832          diag::err_ovl_no_viable_function_in_call)
10833       << ULE->getName() << Fn->getSourceRange();
10834     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10835     break;
10836   }
10837 
10838   case OR_Ambiguous:
10839     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10840       << ULE->getName() << Fn->getSourceRange();
10841     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10842     break;
10843 
10844   case OR_Deleted: {
10845     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10846       << (*Best)->Function->isDeleted()
10847       << ULE->getName()
10848       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10849       << Fn->getSourceRange();
10850     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10851 
10852     // We emitted an error for the unvailable/deleted function call but keep
10853     // the call in the AST.
10854     FunctionDecl *FDecl = (*Best)->Function;
10855     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10856     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10857                                          ExecConfig);
10858   }
10859   }
10860 
10861   // Overload resolution failed.
10862   return ExprError();
10863 }
10864 
10865 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10866 /// (which eventually refers to the declaration Func) and the call
10867 /// arguments Args/NumArgs, attempt to resolve the function call down
10868 /// to a specific function. If overload resolution succeeds, returns
10869 /// the call expression produced by overload resolution.
10870 /// Otherwise, emits diagnostics and returns ExprError.
10871 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10872                                          UnresolvedLookupExpr *ULE,
10873                                          SourceLocation LParenLoc,
10874                                          MultiExprArg Args,
10875                                          SourceLocation RParenLoc,
10876                                          Expr *ExecConfig,
10877                                          bool AllowTypoCorrection) {
10878   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10879                                     OverloadCandidateSet::CSK_Normal);
10880   ExprResult result;
10881 
10882   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10883                              &result))
10884     return result;
10885 
10886   OverloadCandidateSet::iterator Best;
10887   OverloadingResult OverloadResult =
10888       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10889 
10890   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10891                                   RParenLoc, ExecConfig, &CandidateSet,
10892                                   &Best, OverloadResult,
10893                                   AllowTypoCorrection);
10894 }
10895 
10896 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10897   return Functions.size() > 1 ||
10898     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10899 }
10900 
10901 /// \brief Create a unary operation that may resolve to an overloaded
10902 /// operator.
10903 ///
10904 /// \param OpLoc The location of the operator itself (e.g., '*').
10905 ///
10906 /// \param OpcIn The UnaryOperator::Opcode that describes this
10907 /// operator.
10908 ///
10909 /// \param Fns The set of non-member functions that will be
10910 /// considered by overload resolution. The caller needs to build this
10911 /// set based on the context using, e.g.,
10912 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10913 /// set should not contain any member functions; those will be added
10914 /// by CreateOverloadedUnaryOp().
10915 ///
10916 /// \param Input The input argument.
10917 ExprResult
10918 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10919                               const UnresolvedSetImpl &Fns,
10920                               Expr *Input) {
10921   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10922 
10923   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10924   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10925   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10926   // TODO: provide better source location info.
10927   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10928 
10929   if (checkPlaceholderForOverload(*this, Input))
10930     return ExprError();
10931 
10932   Expr *Args[2] = { Input, nullptr };
10933   unsigned NumArgs = 1;
10934 
10935   // For post-increment and post-decrement, add the implicit '0' as
10936   // the second argument, so that we know this is a post-increment or
10937   // post-decrement.
10938   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10939     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10940     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10941                                      SourceLocation());
10942     NumArgs = 2;
10943   }
10944 
10945   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10946 
10947   if (Input->isTypeDependent()) {
10948     if (Fns.empty())
10949       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10950                                          VK_RValue, OK_Ordinary, OpLoc);
10951 
10952     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10953     UnresolvedLookupExpr *Fn
10954       = UnresolvedLookupExpr::Create(Context, NamingClass,
10955                                      NestedNameSpecifierLoc(), OpNameInfo,
10956                                      /*ADL*/ true, IsOverloaded(Fns),
10957                                      Fns.begin(), Fns.end());
10958     return new (Context)
10959         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10960                             VK_RValue, OpLoc, false);
10961   }
10962 
10963   // Build an empty overload set.
10964   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10965 
10966   // Add the candidates from the given function set.
10967   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
10968 
10969   // Add operator candidates that are member functions.
10970   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10971 
10972   // Add candidates from ADL.
10973   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10974                                        /*ExplicitTemplateArgs*/nullptr,
10975                                        CandidateSet);
10976 
10977   // Add builtin operator candidates.
10978   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10979 
10980   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10981 
10982   // Perform overload resolution.
10983   OverloadCandidateSet::iterator Best;
10984   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10985   case OR_Success: {
10986     // We found a built-in operator or an overloaded operator.
10987     FunctionDecl *FnDecl = Best->Function;
10988 
10989     if (FnDecl) {
10990       // We matched an overloaded operator. Build a call to that
10991       // operator.
10992 
10993       // Convert the arguments.
10994       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10995         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10996 
10997         ExprResult InputRes =
10998           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10999                                               Best->FoundDecl, Method);
11000         if (InputRes.isInvalid())
11001           return ExprError();
11002         Input = InputRes.get();
11003       } else {
11004         // Convert the arguments.
11005         ExprResult InputInit
11006           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11007                                                       Context,
11008                                                       FnDecl->getParamDecl(0)),
11009                                       SourceLocation(),
11010                                       Input);
11011         if (InputInit.isInvalid())
11012           return ExprError();
11013         Input = InputInit.get();
11014       }
11015 
11016       // Build the actual expression node.
11017       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11018                                                 HadMultipleCandidates, OpLoc);
11019       if (FnExpr.isInvalid())
11020         return ExprError();
11021 
11022       // Determine the result type.
11023       QualType ResultTy = FnDecl->getReturnType();
11024       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11025       ResultTy = ResultTy.getNonLValueExprType(Context);
11026 
11027       Args[0] = Input;
11028       CallExpr *TheCall =
11029         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11030                                           ResultTy, VK, OpLoc, false);
11031 
11032       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11033         return ExprError();
11034 
11035       return MaybeBindToTemporary(TheCall);
11036     } else {
11037       // We matched a built-in operator. Convert the arguments, then
11038       // break out so that we will build the appropriate built-in
11039       // operator node.
11040       ExprResult InputRes =
11041         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11042                                   Best->Conversions[0], AA_Passing);
11043       if (InputRes.isInvalid())
11044         return ExprError();
11045       Input = InputRes.get();
11046       break;
11047     }
11048   }
11049 
11050   case OR_No_Viable_Function:
11051     // This is an erroneous use of an operator which can be overloaded by
11052     // a non-member function. Check for non-member operators which were
11053     // defined too late to be candidates.
11054     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11055       // FIXME: Recover by calling the found function.
11056       return ExprError();
11057 
11058     // No viable function; fall through to handling this as a
11059     // built-in operator, which will produce an error message for us.
11060     break;
11061 
11062   case OR_Ambiguous:
11063     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11064         << UnaryOperator::getOpcodeStr(Opc)
11065         << Input->getType()
11066         << Input->getSourceRange();
11067     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11068                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11069     return ExprError();
11070 
11071   case OR_Deleted:
11072     Diag(OpLoc, diag::err_ovl_deleted_oper)
11073       << Best->Function->isDeleted()
11074       << UnaryOperator::getOpcodeStr(Opc)
11075       << getDeletedOrUnavailableSuffix(Best->Function)
11076       << Input->getSourceRange();
11077     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11078                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11079     return ExprError();
11080   }
11081 
11082   // Either we found no viable overloaded operator or we matched a
11083   // built-in operator. In either case, fall through to trying to
11084   // build a built-in operation.
11085   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11086 }
11087 
11088 /// \brief Create a binary operation that may resolve to an overloaded
11089 /// operator.
11090 ///
11091 /// \param OpLoc The location of the operator itself (e.g., '+').
11092 ///
11093 /// \param OpcIn The BinaryOperator::Opcode that describes this
11094 /// operator.
11095 ///
11096 /// \param Fns The set of non-member functions that will be
11097 /// considered by overload resolution. The caller needs to build this
11098 /// set based on the context using, e.g.,
11099 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11100 /// set should not contain any member functions; those will be added
11101 /// by CreateOverloadedBinOp().
11102 ///
11103 /// \param LHS Left-hand argument.
11104 /// \param RHS Right-hand argument.
11105 ExprResult
11106 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11107                             unsigned OpcIn,
11108                             const UnresolvedSetImpl &Fns,
11109                             Expr *LHS, Expr *RHS) {
11110   Expr *Args[2] = { LHS, RHS };
11111   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11112 
11113   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11114   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11115   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11116 
11117   // If either side is type-dependent, create an appropriate dependent
11118   // expression.
11119   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11120     if (Fns.empty()) {
11121       // If there are no functions to store, just build a dependent
11122       // BinaryOperator or CompoundAssignment.
11123       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11124         return new (Context) BinaryOperator(
11125             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11126             OpLoc, FPFeatures.fp_contract);
11127 
11128       return new (Context) CompoundAssignOperator(
11129           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11130           Context.DependentTy, Context.DependentTy, OpLoc,
11131           FPFeatures.fp_contract);
11132     }
11133 
11134     // FIXME: save results of ADL from here?
11135     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11136     // TODO: provide better source location info in DNLoc component.
11137     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11138     UnresolvedLookupExpr *Fn
11139       = UnresolvedLookupExpr::Create(Context, NamingClass,
11140                                      NestedNameSpecifierLoc(), OpNameInfo,
11141                                      /*ADL*/ true, IsOverloaded(Fns),
11142                                      Fns.begin(), Fns.end());
11143     return new (Context)
11144         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11145                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11146   }
11147 
11148   // Always do placeholder-like conversions on the RHS.
11149   if (checkPlaceholderForOverload(*this, Args[1]))
11150     return ExprError();
11151 
11152   // Do placeholder-like conversion on the LHS; note that we should
11153   // not get here with a PseudoObject LHS.
11154   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11155   if (checkPlaceholderForOverload(*this, Args[0]))
11156     return ExprError();
11157 
11158   // If this is the assignment operator, we only perform overload resolution
11159   // if the left-hand side is a class or enumeration type. This is actually
11160   // a hack. The standard requires that we do overload resolution between the
11161   // various built-in candidates, but as DR507 points out, this can lead to
11162   // problems. So we do it this way, which pretty much follows what GCC does.
11163   // Note that we go the traditional code path for compound assignment forms.
11164   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11165     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11166 
11167   // If this is the .* operator, which is not overloadable, just
11168   // create a built-in binary operator.
11169   if (Opc == BO_PtrMemD)
11170     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11171 
11172   // Build an empty overload set.
11173   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11174 
11175   // Add the candidates from the given function set.
11176   AddFunctionCandidates(Fns, Args, CandidateSet);
11177 
11178   // Add operator candidates that are member functions.
11179   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11180 
11181   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11182   // performed for an assignment operator (nor for operator[] nor operator->,
11183   // which don't get here).
11184   if (Opc != BO_Assign)
11185     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11186                                          /*ExplicitTemplateArgs*/ nullptr,
11187                                          CandidateSet);
11188 
11189   // Add builtin operator candidates.
11190   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11191 
11192   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11193 
11194   // Perform overload resolution.
11195   OverloadCandidateSet::iterator Best;
11196   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11197     case OR_Success: {
11198       // We found a built-in operator or an overloaded operator.
11199       FunctionDecl *FnDecl = Best->Function;
11200 
11201       if (FnDecl) {
11202         // We matched an overloaded operator. Build a call to that
11203         // operator.
11204 
11205         // Convert the arguments.
11206         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11207           // Best->Access is only meaningful for class members.
11208           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11209 
11210           ExprResult Arg1 =
11211             PerformCopyInitialization(
11212               InitializedEntity::InitializeParameter(Context,
11213                                                      FnDecl->getParamDecl(0)),
11214               SourceLocation(), Args[1]);
11215           if (Arg1.isInvalid())
11216             return ExprError();
11217 
11218           ExprResult Arg0 =
11219             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11220                                                 Best->FoundDecl, Method);
11221           if (Arg0.isInvalid())
11222             return ExprError();
11223           Args[0] = Arg0.getAs<Expr>();
11224           Args[1] = RHS = Arg1.getAs<Expr>();
11225         } else {
11226           // Convert the arguments.
11227           ExprResult Arg0 = PerformCopyInitialization(
11228             InitializedEntity::InitializeParameter(Context,
11229                                                    FnDecl->getParamDecl(0)),
11230             SourceLocation(), Args[0]);
11231           if (Arg0.isInvalid())
11232             return ExprError();
11233 
11234           ExprResult Arg1 =
11235             PerformCopyInitialization(
11236               InitializedEntity::InitializeParameter(Context,
11237                                                      FnDecl->getParamDecl(1)),
11238               SourceLocation(), Args[1]);
11239           if (Arg1.isInvalid())
11240             return ExprError();
11241           Args[0] = LHS = Arg0.getAs<Expr>();
11242           Args[1] = RHS = Arg1.getAs<Expr>();
11243         }
11244 
11245         // Build the actual expression node.
11246         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11247                                                   Best->FoundDecl,
11248                                                   HadMultipleCandidates, OpLoc);
11249         if (FnExpr.isInvalid())
11250           return ExprError();
11251 
11252         // Determine the result type.
11253         QualType ResultTy = FnDecl->getReturnType();
11254         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11255         ResultTy = ResultTy.getNonLValueExprType(Context);
11256 
11257         CXXOperatorCallExpr *TheCall =
11258           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11259                                             Args, ResultTy, VK, OpLoc,
11260                                             FPFeatures.fp_contract);
11261 
11262         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11263                                 FnDecl))
11264           return ExprError();
11265 
11266         ArrayRef<const Expr *> ArgsArray(Args, 2);
11267         // Cut off the implicit 'this'.
11268         if (isa<CXXMethodDecl>(FnDecl))
11269           ArgsArray = ArgsArray.slice(1);
11270 
11271         // Check for a self move.
11272         if (Op == OO_Equal)
11273           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11274 
11275         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11276                   TheCall->getSourceRange(), VariadicDoesNotApply);
11277 
11278         return MaybeBindToTemporary(TheCall);
11279       } else {
11280         // We matched a built-in operator. Convert the arguments, then
11281         // break out so that we will build the appropriate built-in
11282         // operator node.
11283         ExprResult ArgsRes0 =
11284           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11285                                     Best->Conversions[0], AA_Passing);
11286         if (ArgsRes0.isInvalid())
11287           return ExprError();
11288         Args[0] = ArgsRes0.get();
11289 
11290         ExprResult ArgsRes1 =
11291           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11292                                     Best->Conversions[1], AA_Passing);
11293         if (ArgsRes1.isInvalid())
11294           return ExprError();
11295         Args[1] = ArgsRes1.get();
11296         break;
11297       }
11298     }
11299 
11300     case OR_No_Viable_Function: {
11301       // C++ [over.match.oper]p9:
11302       //   If the operator is the operator , [...] and there are no
11303       //   viable functions, then the operator is assumed to be the
11304       //   built-in operator and interpreted according to clause 5.
11305       if (Opc == BO_Comma)
11306         break;
11307 
11308       // For class as left operand for assignment or compound assigment
11309       // operator do not fall through to handling in built-in, but report that
11310       // no overloaded assignment operator found
11311       ExprResult Result = ExprError();
11312       if (Args[0]->getType()->isRecordType() &&
11313           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11314         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11315              << BinaryOperator::getOpcodeStr(Opc)
11316              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11317         if (Args[0]->getType()->isIncompleteType()) {
11318           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11319             << Args[0]->getType()
11320             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11321         }
11322       } else {
11323         // This is an erroneous use of an operator which can be overloaded by
11324         // a non-member function. Check for non-member operators which were
11325         // defined too late to be candidates.
11326         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11327           // FIXME: Recover by calling the found function.
11328           return ExprError();
11329 
11330         // No viable function; try to create a built-in operation, which will
11331         // produce an error. Then, show the non-viable candidates.
11332         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11333       }
11334       assert(Result.isInvalid() &&
11335              "C++ binary operator overloading is missing candidates!");
11336       if (Result.isInvalid())
11337         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11338                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11339       return Result;
11340     }
11341 
11342     case OR_Ambiguous:
11343       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11344           << BinaryOperator::getOpcodeStr(Opc)
11345           << Args[0]->getType() << Args[1]->getType()
11346           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11347       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11348                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11349       return ExprError();
11350 
11351     case OR_Deleted:
11352       if (isImplicitlyDeleted(Best->Function)) {
11353         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11354         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11355           << Context.getRecordType(Method->getParent())
11356           << getSpecialMember(Method);
11357 
11358         // The user probably meant to call this special member. Just
11359         // explain why it's deleted.
11360         NoteDeletedFunction(Method);
11361         return ExprError();
11362       } else {
11363         Diag(OpLoc, diag::err_ovl_deleted_oper)
11364           << Best->Function->isDeleted()
11365           << BinaryOperator::getOpcodeStr(Opc)
11366           << getDeletedOrUnavailableSuffix(Best->Function)
11367           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11368       }
11369       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11370                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11371       return ExprError();
11372   }
11373 
11374   // We matched a built-in operator; build it.
11375   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11376 }
11377 
11378 ExprResult
11379 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11380                                          SourceLocation RLoc,
11381                                          Expr *Base, Expr *Idx) {
11382   Expr *Args[2] = { Base, Idx };
11383   DeclarationName OpName =
11384       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11385 
11386   // If either side is type-dependent, create an appropriate dependent
11387   // expression.
11388   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11389 
11390     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11391     // CHECKME: no 'operator' keyword?
11392     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11393     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11394     UnresolvedLookupExpr *Fn
11395       = UnresolvedLookupExpr::Create(Context, NamingClass,
11396                                      NestedNameSpecifierLoc(), OpNameInfo,
11397                                      /*ADL*/ true, /*Overloaded*/ false,
11398                                      UnresolvedSetIterator(),
11399                                      UnresolvedSetIterator());
11400     // Can't add any actual overloads yet
11401 
11402     return new (Context)
11403         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11404                             Context.DependentTy, VK_RValue, RLoc, false);
11405   }
11406 
11407   // Handle placeholders on both operands.
11408   if (checkPlaceholderForOverload(*this, Args[0]))
11409     return ExprError();
11410   if (checkPlaceholderForOverload(*this, Args[1]))
11411     return ExprError();
11412 
11413   // Build an empty overload set.
11414   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11415 
11416   // Subscript can only be overloaded as a member function.
11417 
11418   // Add operator candidates that are member functions.
11419   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11420 
11421   // Add builtin operator candidates.
11422   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11423 
11424   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11425 
11426   // Perform overload resolution.
11427   OverloadCandidateSet::iterator Best;
11428   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11429     case OR_Success: {
11430       // We found a built-in operator or an overloaded operator.
11431       FunctionDecl *FnDecl = Best->Function;
11432 
11433       if (FnDecl) {
11434         // We matched an overloaded operator. Build a call to that
11435         // operator.
11436 
11437         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11438 
11439         // Convert the arguments.
11440         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11441         ExprResult Arg0 =
11442           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11443                                               Best->FoundDecl, Method);
11444         if (Arg0.isInvalid())
11445           return ExprError();
11446         Args[0] = Arg0.get();
11447 
11448         // Convert the arguments.
11449         ExprResult InputInit
11450           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11451                                                       Context,
11452                                                       FnDecl->getParamDecl(0)),
11453                                       SourceLocation(),
11454                                       Args[1]);
11455         if (InputInit.isInvalid())
11456           return ExprError();
11457 
11458         Args[1] = InputInit.getAs<Expr>();
11459 
11460         // Build the actual expression node.
11461         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11462         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11463         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11464                                                   Best->FoundDecl,
11465                                                   HadMultipleCandidates,
11466                                                   OpLocInfo.getLoc(),
11467                                                   OpLocInfo.getInfo());
11468         if (FnExpr.isInvalid())
11469           return ExprError();
11470 
11471         // Determine the result type
11472         QualType ResultTy = FnDecl->getReturnType();
11473         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11474         ResultTy = ResultTy.getNonLValueExprType(Context);
11475 
11476         CXXOperatorCallExpr *TheCall =
11477           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11478                                             FnExpr.get(), Args,
11479                                             ResultTy, VK, RLoc,
11480                                             false);
11481 
11482         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11483           return ExprError();
11484 
11485         return MaybeBindToTemporary(TheCall);
11486       } else {
11487         // We matched a built-in operator. Convert the arguments, then
11488         // break out so that we will build the appropriate built-in
11489         // operator node.
11490         ExprResult ArgsRes0 =
11491           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11492                                     Best->Conversions[0], AA_Passing);
11493         if (ArgsRes0.isInvalid())
11494           return ExprError();
11495         Args[0] = ArgsRes0.get();
11496 
11497         ExprResult ArgsRes1 =
11498           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11499                                     Best->Conversions[1], AA_Passing);
11500         if (ArgsRes1.isInvalid())
11501           return ExprError();
11502         Args[1] = ArgsRes1.get();
11503 
11504         break;
11505       }
11506     }
11507 
11508     case OR_No_Viable_Function: {
11509       if (CandidateSet.empty())
11510         Diag(LLoc, diag::err_ovl_no_oper)
11511           << Args[0]->getType() << /*subscript*/ 0
11512           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11513       else
11514         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11515           << Args[0]->getType()
11516           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11517       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11518                                   "[]", LLoc);
11519       return ExprError();
11520     }
11521 
11522     case OR_Ambiguous:
11523       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11524           << "[]"
11525           << Args[0]->getType() << Args[1]->getType()
11526           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11527       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11528                                   "[]", LLoc);
11529       return ExprError();
11530 
11531     case OR_Deleted:
11532       Diag(LLoc, diag::err_ovl_deleted_oper)
11533         << Best->Function->isDeleted() << "[]"
11534         << getDeletedOrUnavailableSuffix(Best->Function)
11535         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11536       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11537                                   "[]", LLoc);
11538       return ExprError();
11539     }
11540 
11541   // We matched a built-in operator; build it.
11542   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11543 }
11544 
11545 /// BuildCallToMemberFunction - Build a call to a member
11546 /// function. MemExpr is the expression that refers to the member
11547 /// function (and includes the object parameter), Args/NumArgs are the
11548 /// arguments to the function call (not including the object
11549 /// parameter). The caller needs to validate that the member
11550 /// expression refers to a non-static member function or an overloaded
11551 /// member function.
11552 ExprResult
11553 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11554                                 SourceLocation LParenLoc,
11555                                 MultiExprArg Args,
11556                                 SourceLocation RParenLoc) {
11557   assert(MemExprE->getType() == Context.BoundMemberTy ||
11558          MemExprE->getType() == Context.OverloadTy);
11559 
11560   // Dig out the member expression. This holds both the object
11561   // argument and the member function we're referring to.
11562   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11563 
11564   // Determine whether this is a call to a pointer-to-member function.
11565   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11566     assert(op->getType() == Context.BoundMemberTy);
11567     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11568 
11569     QualType fnType =
11570       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11571 
11572     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11573     QualType resultType = proto->getCallResultType(Context);
11574     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11575 
11576     // Check that the object type isn't more qualified than the
11577     // member function we're calling.
11578     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11579 
11580     QualType objectType = op->getLHS()->getType();
11581     if (op->getOpcode() == BO_PtrMemI)
11582       objectType = objectType->castAs<PointerType>()->getPointeeType();
11583     Qualifiers objectQuals = objectType.getQualifiers();
11584 
11585     Qualifiers difference = objectQuals - funcQuals;
11586     difference.removeObjCGCAttr();
11587     difference.removeAddressSpace();
11588     if (difference) {
11589       std::string qualsString = difference.getAsString();
11590       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11591         << fnType.getUnqualifiedType()
11592         << qualsString
11593         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11594     }
11595 
11596     CXXMemberCallExpr *call
11597       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11598                                         resultType, valueKind, RParenLoc);
11599 
11600     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11601                             call, nullptr))
11602       return ExprError();
11603 
11604     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11605       return ExprError();
11606 
11607     if (CheckOtherCall(call, proto))
11608       return ExprError();
11609 
11610     return MaybeBindToTemporary(call);
11611   }
11612 
11613   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11614     return new (Context)
11615         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11616 
11617   UnbridgedCastsSet UnbridgedCasts;
11618   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11619     return ExprError();
11620 
11621   MemberExpr *MemExpr;
11622   CXXMethodDecl *Method = nullptr;
11623   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11624   NestedNameSpecifier *Qualifier = nullptr;
11625   if (isa<MemberExpr>(NakedMemExpr)) {
11626     MemExpr = cast<MemberExpr>(NakedMemExpr);
11627     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11628     FoundDecl = MemExpr->getFoundDecl();
11629     Qualifier = MemExpr->getQualifier();
11630     UnbridgedCasts.restore();
11631 
11632     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11633       Diag(MemExprE->getLocStart(),
11634            diag::err_ovl_no_viable_member_function_in_call)
11635           << Method << Method->getSourceRange();
11636       Diag(Method->getLocation(),
11637            diag::note_ovl_candidate_disabled_by_enable_if_attr)
11638           << Attr->getCond()->getSourceRange() << Attr->getMessage();
11639       return ExprError();
11640     }
11641   } else {
11642     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11643     Qualifier = UnresExpr->getQualifier();
11644 
11645     QualType ObjectType = UnresExpr->getBaseType();
11646     Expr::Classification ObjectClassification
11647       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11648                             : UnresExpr->getBase()->Classify(Context);
11649 
11650     // Add overload candidates
11651     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11652                                       OverloadCandidateSet::CSK_Normal);
11653 
11654     // FIXME: avoid copy.
11655     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11656     if (UnresExpr->hasExplicitTemplateArgs()) {
11657       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11658       TemplateArgs = &TemplateArgsBuffer;
11659     }
11660 
11661     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11662            E = UnresExpr->decls_end(); I != E; ++I) {
11663 
11664       NamedDecl *Func = *I;
11665       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11666       if (isa<UsingShadowDecl>(Func))
11667         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11668 
11669 
11670       // Microsoft supports direct constructor calls.
11671       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11672         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11673                              Args, CandidateSet);
11674       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11675         // If explicit template arguments were provided, we can't call a
11676         // non-template member function.
11677         if (TemplateArgs)
11678           continue;
11679 
11680         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11681                            ObjectClassification, Args, CandidateSet,
11682                            /*SuppressUserConversions=*/false);
11683       } else {
11684         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11685                                    I.getPair(), ActingDC, TemplateArgs,
11686                                    ObjectType,  ObjectClassification,
11687                                    Args, CandidateSet,
11688                                    /*SuppressUsedConversions=*/false);
11689       }
11690     }
11691 
11692     DeclarationName DeclName = UnresExpr->getMemberName();
11693 
11694     UnbridgedCasts.restore();
11695 
11696     OverloadCandidateSet::iterator Best;
11697     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11698                                             Best)) {
11699     case OR_Success:
11700       Method = cast<CXXMethodDecl>(Best->Function);
11701       FoundDecl = Best->FoundDecl;
11702       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11703       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11704         return ExprError();
11705       // If FoundDecl is different from Method (such as if one is a template
11706       // and the other a specialization), make sure DiagnoseUseOfDecl is
11707       // called on both.
11708       // FIXME: This would be more comprehensively addressed by modifying
11709       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11710       // being used.
11711       if (Method != FoundDecl.getDecl() &&
11712                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11713         return ExprError();
11714       break;
11715 
11716     case OR_No_Viable_Function:
11717       Diag(UnresExpr->getMemberLoc(),
11718            diag::err_ovl_no_viable_member_function_in_call)
11719         << DeclName << MemExprE->getSourceRange();
11720       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11721       // FIXME: Leaking incoming expressions!
11722       return ExprError();
11723 
11724     case OR_Ambiguous:
11725       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11726         << DeclName << MemExprE->getSourceRange();
11727       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11728       // FIXME: Leaking incoming expressions!
11729       return ExprError();
11730 
11731     case OR_Deleted:
11732       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11733         << Best->Function->isDeleted()
11734         << DeclName
11735         << getDeletedOrUnavailableSuffix(Best->Function)
11736         << MemExprE->getSourceRange();
11737       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11738       // FIXME: Leaking incoming expressions!
11739       return ExprError();
11740     }
11741 
11742     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11743 
11744     // If overload resolution picked a static member, build a
11745     // non-member call based on that function.
11746     if (Method->isStatic()) {
11747       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11748                                    RParenLoc);
11749     }
11750 
11751     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11752   }
11753 
11754   QualType ResultType = Method->getReturnType();
11755   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11756   ResultType = ResultType.getNonLValueExprType(Context);
11757 
11758   assert(Method && "Member call to something that isn't a method?");
11759   CXXMemberCallExpr *TheCall =
11760     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11761                                     ResultType, VK, RParenLoc);
11762 
11763   // (CUDA B.1): Check for invalid calls between targets.
11764   if (getLangOpts().CUDA) {
11765     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11766       if (CheckCUDATarget(Caller, Method)) {
11767         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11768             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11769             << IdentifyCUDATarget(Caller);
11770         return ExprError();
11771       }
11772     }
11773   }
11774 
11775   // Check for a valid return type.
11776   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11777                           TheCall, Method))
11778     return ExprError();
11779 
11780   // Convert the object argument (for a non-static member function call).
11781   // We only need to do this if there was actually an overload; otherwise
11782   // it was done at lookup.
11783   if (!Method->isStatic()) {
11784     ExprResult ObjectArg =
11785       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11786                                           FoundDecl, Method);
11787     if (ObjectArg.isInvalid())
11788       return ExprError();
11789     MemExpr->setBase(ObjectArg.get());
11790   }
11791 
11792   // Convert the rest of the arguments
11793   const FunctionProtoType *Proto =
11794     Method->getType()->getAs<FunctionProtoType>();
11795   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11796                               RParenLoc))
11797     return ExprError();
11798 
11799   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11800 
11801   if (CheckFunctionCall(Method, TheCall, Proto))
11802     return ExprError();
11803 
11804   if ((isa<CXXConstructorDecl>(CurContext) ||
11805        isa<CXXDestructorDecl>(CurContext)) &&
11806       TheCall->getMethodDecl()->isPure()) {
11807     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11808 
11809     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11810         MemExpr->performsVirtualDispatch(getLangOpts())) {
11811       Diag(MemExpr->getLocStart(),
11812            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11813         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11814         << MD->getParent()->getDeclName();
11815 
11816       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11817       if (getLangOpts().AppleKext)
11818         Diag(MemExpr->getLocStart(),
11819              diag::note_pure_qualified_call_kext)
11820              << MD->getParent()->getDeclName()
11821              << MD->getDeclName();
11822     }
11823   }
11824   return MaybeBindToTemporary(TheCall);
11825 }
11826 
11827 /// BuildCallToObjectOfClassType - Build a call to an object of class
11828 /// type (C++ [over.call.object]), which can end up invoking an
11829 /// overloaded function call operator (@c operator()) or performing a
11830 /// user-defined conversion on the object argument.
11831 ExprResult
11832 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11833                                    SourceLocation LParenLoc,
11834                                    MultiExprArg Args,
11835                                    SourceLocation RParenLoc) {
11836   if (checkPlaceholderForOverload(*this, Obj))
11837     return ExprError();
11838   ExprResult Object = Obj;
11839 
11840   UnbridgedCastsSet UnbridgedCasts;
11841   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11842     return ExprError();
11843 
11844   assert(Object.get()->getType()->isRecordType() &&
11845          "Requires object type argument");
11846   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11847 
11848   // C++ [over.call.object]p1:
11849   //  If the primary-expression E in the function call syntax
11850   //  evaluates to a class object of type "cv T", then the set of
11851   //  candidate functions includes at least the function call
11852   //  operators of T. The function call operators of T are obtained by
11853   //  ordinary lookup of the name operator() in the context of
11854   //  (E).operator().
11855   OverloadCandidateSet CandidateSet(LParenLoc,
11856                                     OverloadCandidateSet::CSK_Operator);
11857   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11858 
11859   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11860                           diag::err_incomplete_object_call, Object.get()))
11861     return true;
11862 
11863   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11864   LookupQualifiedName(R, Record->getDecl());
11865   R.suppressDiagnostics();
11866 
11867   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11868        Oper != OperEnd; ++Oper) {
11869     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11870                        Object.get()->Classify(Context),
11871                        Args, CandidateSet,
11872                        /*SuppressUserConversions=*/ false);
11873   }
11874 
11875   // C++ [over.call.object]p2:
11876   //   In addition, for each (non-explicit in C++0x) conversion function
11877   //   declared in T of the form
11878   //
11879   //        operator conversion-type-id () cv-qualifier;
11880   //
11881   //   where cv-qualifier is the same cv-qualification as, or a
11882   //   greater cv-qualification than, cv, and where conversion-type-id
11883   //   denotes the type "pointer to function of (P1,...,Pn) returning
11884   //   R", or the type "reference to pointer to function of
11885   //   (P1,...,Pn) returning R", or the type "reference to function
11886   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11887   //   is also considered as a candidate function. Similarly,
11888   //   surrogate call functions are added to the set of candidate
11889   //   functions for each conversion function declared in an
11890   //   accessible base class provided the function is not hidden
11891   //   within T by another intervening declaration.
11892   const auto &Conversions =
11893       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11894   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11895     NamedDecl *D = *I;
11896     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11897     if (isa<UsingShadowDecl>(D))
11898       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11899 
11900     // Skip over templated conversion functions; they aren't
11901     // surrogates.
11902     if (isa<FunctionTemplateDecl>(D))
11903       continue;
11904 
11905     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11906     if (!Conv->isExplicit()) {
11907       // Strip the reference type (if any) and then the pointer type (if
11908       // any) to get down to what might be a function type.
11909       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11910       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11911         ConvType = ConvPtrType->getPointeeType();
11912 
11913       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11914       {
11915         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11916                               Object.get(), Args, CandidateSet);
11917       }
11918     }
11919   }
11920 
11921   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11922 
11923   // Perform overload resolution.
11924   OverloadCandidateSet::iterator Best;
11925   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11926                              Best)) {
11927   case OR_Success:
11928     // Overload resolution succeeded; we'll build the appropriate call
11929     // below.
11930     break;
11931 
11932   case OR_No_Viable_Function:
11933     if (CandidateSet.empty())
11934       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11935         << Object.get()->getType() << /*call*/ 1
11936         << Object.get()->getSourceRange();
11937     else
11938       Diag(Object.get()->getLocStart(),
11939            diag::err_ovl_no_viable_object_call)
11940         << Object.get()->getType() << Object.get()->getSourceRange();
11941     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11942     break;
11943 
11944   case OR_Ambiguous:
11945     Diag(Object.get()->getLocStart(),
11946          diag::err_ovl_ambiguous_object_call)
11947       << Object.get()->getType() << Object.get()->getSourceRange();
11948     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11949     break;
11950 
11951   case OR_Deleted:
11952     Diag(Object.get()->getLocStart(),
11953          diag::err_ovl_deleted_object_call)
11954       << Best->Function->isDeleted()
11955       << Object.get()->getType()
11956       << getDeletedOrUnavailableSuffix(Best->Function)
11957       << Object.get()->getSourceRange();
11958     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11959     break;
11960   }
11961 
11962   if (Best == CandidateSet.end())
11963     return true;
11964 
11965   UnbridgedCasts.restore();
11966 
11967   if (Best->Function == nullptr) {
11968     // Since there is no function declaration, this is one of the
11969     // surrogate candidates. Dig out the conversion function.
11970     CXXConversionDecl *Conv
11971       = cast<CXXConversionDecl>(
11972                          Best->Conversions[0].UserDefined.ConversionFunction);
11973 
11974     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11975                               Best->FoundDecl);
11976     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11977       return ExprError();
11978     assert(Conv == Best->FoundDecl.getDecl() &&
11979              "Found Decl & conversion-to-functionptr should be same, right?!");
11980     // We selected one of the surrogate functions that converts the
11981     // object parameter to a function pointer. Perform the conversion
11982     // on the object argument, then let ActOnCallExpr finish the job.
11983 
11984     // Create an implicit member expr to refer to the conversion operator.
11985     // and then call it.
11986     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11987                                              Conv, HadMultipleCandidates);
11988     if (Call.isInvalid())
11989       return ExprError();
11990     // Record usage of conversion in an implicit cast.
11991     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11992                                     CK_UserDefinedConversion, Call.get(),
11993                                     nullptr, VK_RValue);
11994 
11995     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11996   }
11997 
11998   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11999 
12000   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12001   // that calls this method, using Object for the implicit object
12002   // parameter and passing along the remaining arguments.
12003   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12004 
12005   // An error diagnostic has already been printed when parsing the declaration.
12006   if (Method->isInvalidDecl())
12007     return ExprError();
12008 
12009   const FunctionProtoType *Proto =
12010     Method->getType()->getAs<FunctionProtoType>();
12011 
12012   unsigned NumParams = Proto->getNumParams();
12013 
12014   DeclarationNameInfo OpLocInfo(
12015                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12016   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12017   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12018                                            HadMultipleCandidates,
12019                                            OpLocInfo.getLoc(),
12020                                            OpLocInfo.getInfo());
12021   if (NewFn.isInvalid())
12022     return true;
12023 
12024   // Build the full argument list for the method call (the implicit object
12025   // parameter is placed at the beginning of the list).
12026   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12027   MethodArgs[0] = Object.get();
12028   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12029 
12030   // Once we've built TheCall, all of the expressions are properly
12031   // owned.
12032   QualType ResultTy = Method->getReturnType();
12033   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12034   ResultTy = ResultTy.getNonLValueExprType(Context);
12035 
12036   CXXOperatorCallExpr *TheCall = new (Context)
12037       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12038                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12039                           ResultTy, VK, RParenLoc, false);
12040   MethodArgs.reset();
12041 
12042   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12043     return true;
12044 
12045   // We may have default arguments. If so, we need to allocate more
12046   // slots in the call for them.
12047   if (Args.size() < NumParams)
12048     TheCall->setNumArgs(Context, NumParams + 1);
12049 
12050   bool IsError = false;
12051 
12052   // Initialize the implicit object parameter.
12053   ExprResult ObjRes =
12054     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12055                                         Best->FoundDecl, Method);
12056   if (ObjRes.isInvalid())
12057     IsError = true;
12058   else
12059     Object = ObjRes;
12060   TheCall->setArg(0, Object.get());
12061 
12062   // Check the argument types.
12063   for (unsigned i = 0; i != NumParams; i++) {
12064     Expr *Arg;
12065     if (i < Args.size()) {
12066       Arg = Args[i];
12067 
12068       // Pass the argument.
12069 
12070       ExprResult InputInit
12071         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12072                                                     Context,
12073                                                     Method->getParamDecl(i)),
12074                                     SourceLocation(), Arg);
12075 
12076       IsError |= InputInit.isInvalid();
12077       Arg = InputInit.getAs<Expr>();
12078     } else {
12079       ExprResult DefArg
12080         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12081       if (DefArg.isInvalid()) {
12082         IsError = true;
12083         break;
12084       }
12085 
12086       Arg = DefArg.getAs<Expr>();
12087     }
12088 
12089     TheCall->setArg(i + 1, Arg);
12090   }
12091 
12092   // If this is a variadic call, handle args passed through "...".
12093   if (Proto->isVariadic()) {
12094     // Promote the arguments (C99 6.5.2.2p7).
12095     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12096       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12097                                                         nullptr);
12098       IsError |= Arg.isInvalid();
12099       TheCall->setArg(i + 1, Arg.get());
12100     }
12101   }
12102 
12103   if (IsError) return true;
12104 
12105   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12106 
12107   if (CheckFunctionCall(Method, TheCall, Proto))
12108     return true;
12109 
12110   return MaybeBindToTemporary(TheCall);
12111 }
12112 
12113 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12114 ///  (if one exists), where @c Base is an expression of class type and
12115 /// @c Member is the name of the member we're trying to find.
12116 ExprResult
12117 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12118                                bool *NoArrowOperatorFound) {
12119   assert(Base->getType()->isRecordType() &&
12120          "left-hand side must have class type");
12121 
12122   if (checkPlaceholderForOverload(*this, Base))
12123     return ExprError();
12124 
12125   SourceLocation Loc = Base->getExprLoc();
12126 
12127   // C++ [over.ref]p1:
12128   //
12129   //   [...] An expression x->m is interpreted as (x.operator->())->m
12130   //   for a class object x of type T if T::operator->() exists and if
12131   //   the operator is selected as the best match function by the
12132   //   overload resolution mechanism (13.3).
12133   DeclarationName OpName =
12134     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12135   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12136   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12137 
12138   if (RequireCompleteType(Loc, Base->getType(),
12139                           diag::err_typecheck_incomplete_tag, Base))
12140     return ExprError();
12141 
12142   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12143   LookupQualifiedName(R, BaseRecord->getDecl());
12144   R.suppressDiagnostics();
12145 
12146   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12147        Oper != OperEnd; ++Oper) {
12148     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12149                        None, CandidateSet, /*SuppressUserConversions=*/false);
12150   }
12151 
12152   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12153 
12154   // Perform overload resolution.
12155   OverloadCandidateSet::iterator Best;
12156   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12157   case OR_Success:
12158     // Overload resolution succeeded; we'll build the call below.
12159     break;
12160 
12161   case OR_No_Viable_Function:
12162     if (CandidateSet.empty()) {
12163       QualType BaseType = Base->getType();
12164       if (NoArrowOperatorFound) {
12165         // Report this specific error to the caller instead of emitting a
12166         // diagnostic, as requested.
12167         *NoArrowOperatorFound = true;
12168         return ExprError();
12169       }
12170       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12171         << BaseType << Base->getSourceRange();
12172       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12173         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12174           << FixItHint::CreateReplacement(OpLoc, ".");
12175       }
12176     } else
12177       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12178         << "operator->" << Base->getSourceRange();
12179     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12180     return ExprError();
12181 
12182   case OR_Ambiguous:
12183     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12184       << "->" << Base->getType() << Base->getSourceRange();
12185     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12186     return ExprError();
12187 
12188   case OR_Deleted:
12189     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12190       << Best->Function->isDeleted()
12191       << "->"
12192       << getDeletedOrUnavailableSuffix(Best->Function)
12193       << Base->getSourceRange();
12194     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12195     return ExprError();
12196   }
12197 
12198   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12199 
12200   // Convert the object parameter.
12201   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12202   ExprResult BaseResult =
12203     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12204                                         Best->FoundDecl, Method);
12205   if (BaseResult.isInvalid())
12206     return ExprError();
12207   Base = BaseResult.get();
12208 
12209   // Build the operator call.
12210   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12211                                             HadMultipleCandidates, OpLoc);
12212   if (FnExpr.isInvalid())
12213     return ExprError();
12214 
12215   QualType ResultTy = Method->getReturnType();
12216   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12217   ResultTy = ResultTy.getNonLValueExprType(Context);
12218   CXXOperatorCallExpr *TheCall =
12219     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12220                                       Base, ResultTy, VK, OpLoc, false);
12221 
12222   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12223           return ExprError();
12224 
12225   return MaybeBindToTemporary(TheCall);
12226 }
12227 
12228 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12229 /// a literal operator described by the provided lookup results.
12230 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12231                                           DeclarationNameInfo &SuffixInfo,
12232                                           ArrayRef<Expr*> Args,
12233                                           SourceLocation LitEndLoc,
12234                                        TemplateArgumentListInfo *TemplateArgs) {
12235   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12236 
12237   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12238                                     OverloadCandidateSet::CSK_Normal);
12239   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12240                         /*SuppressUserConversions=*/true);
12241 
12242   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12243 
12244   // Perform overload resolution. This will usually be trivial, but might need
12245   // to perform substitutions for a literal operator template.
12246   OverloadCandidateSet::iterator Best;
12247   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12248   case OR_Success:
12249   case OR_Deleted:
12250     break;
12251 
12252   case OR_No_Viable_Function:
12253     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12254       << R.getLookupName();
12255     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12256     return ExprError();
12257 
12258   case OR_Ambiguous:
12259     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12260     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12261     return ExprError();
12262   }
12263 
12264   FunctionDecl *FD = Best->Function;
12265   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12266                                         HadMultipleCandidates,
12267                                         SuffixInfo.getLoc(),
12268                                         SuffixInfo.getInfo());
12269   if (Fn.isInvalid())
12270     return true;
12271 
12272   // Check the argument types. This should almost always be a no-op, except
12273   // that array-to-pointer decay is applied to string literals.
12274   Expr *ConvArgs[2];
12275   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12276     ExprResult InputInit = PerformCopyInitialization(
12277       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12278       SourceLocation(), Args[ArgIdx]);
12279     if (InputInit.isInvalid())
12280       return true;
12281     ConvArgs[ArgIdx] = InputInit.get();
12282   }
12283 
12284   QualType ResultTy = FD->getReturnType();
12285   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12286   ResultTy = ResultTy.getNonLValueExprType(Context);
12287 
12288   UserDefinedLiteral *UDL =
12289     new (Context) UserDefinedLiteral(Context, Fn.get(),
12290                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12291                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12292 
12293   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12294     return ExprError();
12295 
12296   if (CheckFunctionCall(FD, UDL, nullptr))
12297     return ExprError();
12298 
12299   return MaybeBindToTemporary(UDL);
12300 }
12301 
12302 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12303 /// given LookupResult is non-empty, it is assumed to describe a member which
12304 /// will be invoked. Otherwise, the function will be found via argument
12305 /// dependent lookup.
12306 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12307 /// otherwise CallExpr is set to ExprError() and some non-success value
12308 /// is returned.
12309 Sema::ForRangeStatus
12310 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12311                                 SourceLocation RangeLoc, VarDecl *Decl,
12312                                 BeginEndFunction BEF,
12313                                 const DeclarationNameInfo &NameInfo,
12314                                 LookupResult &MemberLookup,
12315                                 OverloadCandidateSet *CandidateSet,
12316                                 Expr *Range, ExprResult *CallExpr) {
12317   CandidateSet->clear();
12318   if (!MemberLookup.empty()) {
12319     ExprResult MemberRef =
12320         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12321                                  /*IsPtr=*/false, CXXScopeSpec(),
12322                                  /*TemplateKWLoc=*/SourceLocation(),
12323                                  /*FirstQualifierInScope=*/nullptr,
12324                                  MemberLookup,
12325                                  /*TemplateArgs=*/nullptr, S);
12326     if (MemberRef.isInvalid()) {
12327       *CallExpr = ExprError();
12328       Diag(Range->getLocStart(), diag::note_in_for_range)
12329           << RangeLoc << BEF << Range->getType();
12330       return FRS_DiagnosticIssued;
12331     }
12332     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12333     if (CallExpr->isInvalid()) {
12334       *CallExpr = ExprError();
12335       Diag(Range->getLocStart(), diag::note_in_for_range)
12336           << RangeLoc << BEF << Range->getType();
12337       return FRS_DiagnosticIssued;
12338     }
12339   } else {
12340     UnresolvedSet<0> FoundNames;
12341     UnresolvedLookupExpr *Fn =
12342       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12343                                    NestedNameSpecifierLoc(), NameInfo,
12344                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12345                                    FoundNames.begin(), FoundNames.end());
12346 
12347     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12348                                                     CandidateSet, CallExpr);
12349     if (CandidateSet->empty() || CandidateSetError) {
12350       *CallExpr = ExprError();
12351       return FRS_NoViableFunction;
12352     }
12353     OverloadCandidateSet::iterator Best;
12354     OverloadingResult OverloadResult =
12355         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12356 
12357     if (OverloadResult == OR_No_Viable_Function) {
12358       *CallExpr = ExprError();
12359       return FRS_NoViableFunction;
12360     }
12361     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12362                                          Loc, nullptr, CandidateSet, &Best,
12363                                          OverloadResult,
12364                                          /*AllowTypoCorrection=*/false);
12365     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12366       *CallExpr = ExprError();
12367       Diag(Range->getLocStart(), diag::note_in_for_range)
12368           << RangeLoc << BEF << Range->getType();
12369       return FRS_DiagnosticIssued;
12370     }
12371   }
12372   return FRS_Success;
12373 }
12374 
12375 
12376 /// FixOverloadedFunctionReference - E is an expression that refers to
12377 /// a C++ overloaded function (possibly with some parentheses and
12378 /// perhaps a '&' around it). We have resolved the overloaded function
12379 /// to the function declaration Fn, so patch up the expression E to
12380 /// refer (possibly indirectly) to Fn. Returns the new expr.
12381 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12382                                            FunctionDecl *Fn) {
12383   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12384     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12385                                                    Found, Fn);
12386     if (SubExpr == PE->getSubExpr())
12387       return PE;
12388 
12389     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12390   }
12391 
12392   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12393     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12394                                                    Found, Fn);
12395     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12396                                SubExpr->getType()) &&
12397            "Implicit cast type cannot be determined from overload");
12398     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12399     if (SubExpr == ICE->getSubExpr())
12400       return ICE;
12401 
12402     return ImplicitCastExpr::Create(Context, ICE->getType(),
12403                                     ICE->getCastKind(),
12404                                     SubExpr, nullptr,
12405                                     ICE->getValueKind());
12406   }
12407 
12408   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12409     assert(UnOp->getOpcode() == UO_AddrOf &&
12410            "Can only take the address of an overloaded function");
12411     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12412       if (Method->isStatic()) {
12413         // Do nothing: static member functions aren't any different
12414         // from non-member functions.
12415       } else {
12416         // Fix the subexpression, which really has to be an
12417         // UnresolvedLookupExpr holding an overloaded member function
12418         // or template.
12419         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12420                                                        Found, Fn);
12421         if (SubExpr == UnOp->getSubExpr())
12422           return UnOp;
12423 
12424         assert(isa<DeclRefExpr>(SubExpr)
12425                && "fixed to something other than a decl ref");
12426         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12427                && "fixed to a member ref with no nested name qualifier");
12428 
12429         // We have taken the address of a pointer to member
12430         // function. Perform the computation here so that we get the
12431         // appropriate pointer to member type.
12432         QualType ClassType
12433           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12434         QualType MemPtrType
12435           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12436 
12437         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12438                                            VK_RValue, OK_Ordinary,
12439                                            UnOp->getOperatorLoc());
12440       }
12441     }
12442     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12443                                                    Found, Fn);
12444     if (SubExpr == UnOp->getSubExpr())
12445       return UnOp;
12446 
12447     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12448                                      Context.getPointerType(SubExpr->getType()),
12449                                        VK_RValue, OK_Ordinary,
12450                                        UnOp->getOperatorLoc());
12451   }
12452 
12453   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12454     // FIXME: avoid copy.
12455     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12456     if (ULE->hasExplicitTemplateArgs()) {
12457       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12458       TemplateArgs = &TemplateArgsBuffer;
12459     }
12460 
12461     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12462                                            ULE->getQualifierLoc(),
12463                                            ULE->getTemplateKeywordLoc(),
12464                                            Fn,
12465                                            /*enclosing*/ false, // FIXME?
12466                                            ULE->getNameLoc(),
12467                                            Fn->getType(),
12468                                            VK_LValue,
12469                                            Found.getDecl(),
12470                                            TemplateArgs);
12471     MarkDeclRefReferenced(DRE);
12472     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12473     return DRE;
12474   }
12475 
12476   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12477     // FIXME: avoid copy.
12478     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12479     if (MemExpr->hasExplicitTemplateArgs()) {
12480       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12481       TemplateArgs = &TemplateArgsBuffer;
12482     }
12483 
12484     Expr *Base;
12485 
12486     // If we're filling in a static method where we used to have an
12487     // implicit member access, rewrite to a simple decl ref.
12488     if (MemExpr->isImplicitAccess()) {
12489       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12490         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12491                                                MemExpr->getQualifierLoc(),
12492                                                MemExpr->getTemplateKeywordLoc(),
12493                                                Fn,
12494                                                /*enclosing*/ false,
12495                                                MemExpr->getMemberLoc(),
12496                                                Fn->getType(),
12497                                                VK_LValue,
12498                                                Found.getDecl(),
12499                                                TemplateArgs);
12500         MarkDeclRefReferenced(DRE);
12501         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12502         return DRE;
12503       } else {
12504         SourceLocation Loc = MemExpr->getMemberLoc();
12505         if (MemExpr->getQualifier())
12506           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12507         CheckCXXThisCapture(Loc);
12508         Base = new (Context) CXXThisExpr(Loc,
12509                                          MemExpr->getBaseType(),
12510                                          /*isImplicit=*/true);
12511       }
12512     } else
12513       Base = MemExpr->getBase();
12514 
12515     ExprValueKind valueKind;
12516     QualType type;
12517     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12518       valueKind = VK_LValue;
12519       type = Fn->getType();
12520     } else {
12521       valueKind = VK_RValue;
12522       type = Context.BoundMemberTy;
12523     }
12524 
12525     MemberExpr *ME = MemberExpr::Create(
12526         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12527         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12528         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12529         OK_Ordinary);
12530     ME->setHadMultipleCandidates(true);
12531     MarkMemberReferenced(ME);
12532     return ME;
12533   }
12534 
12535   llvm_unreachable("Invalid reference to overloaded function");
12536 }
12537 
12538 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12539                                                 DeclAccessPair Found,
12540                                                 FunctionDecl *Fn) {
12541   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12542 }
12543