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     // If either declaration was introduced by a using declaration,
900     // we'll need to use slightly different rules for matching.
901     // Essentially, these rules are the normal rules, except that
902     // function templates hide function templates with different
903     // return types or template parameter lists.
904     bool UseMemberUsingDeclRules =
905       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906       !New->getFriendObjectKind();
907 
908     if (FunctionDecl *OldF = OldD->getAsFunction()) {
909       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
910         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
911           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
912           continue;
913         }
914 
915         if (!isa<FunctionTemplateDecl>(OldD) &&
916             !shouldLinkPossiblyHiddenDecl(*I, New))
917           continue;
918 
919         Match = *I;
920         return Ovl_Match;
921       }
922     } else if (isa<UsingDecl>(OldD)) {
923       // We can overload with these, which can show up when doing
924       // redeclaration checks for UsingDecls.
925       assert(Old.getLookupKind() == LookupUsingDeclName);
926     } else if (isa<TagDecl>(OldD)) {
927       // We can always overload with tags by hiding them.
928     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
929       // Optimistically assume that an unresolved using decl will
930       // overload; if it doesn't, we'll have to diagnose during
931       // template instantiation.
932     } else {
933       // (C++ 13p1):
934       //   Only function declarations can be overloaded; object and type
935       //   declarations cannot be overloaded.
936       Match = *I;
937       return Ovl_NonFunction;
938     }
939   }
940 
941   return Ovl_Overload;
942 }
943 
944 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
945                       bool UseUsingDeclRules) {
946   // C++ [basic.start.main]p2: This function shall not be overloaded.
947   if (New->isMain())
948     return false;
949 
950   // MSVCRT user defined entry points cannot be overloaded.
951   if (New->isMSVCRTEntryPoint())
952     return false;
953 
954   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
955   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
956 
957   // C++ [temp.fct]p2:
958   //   A function template can be overloaded with other function templates
959   //   and with normal (non-template) functions.
960   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
961     return true;
962 
963   // Is the function New an overload of the function Old?
964   QualType OldQType = Context.getCanonicalType(Old->getType());
965   QualType NewQType = Context.getCanonicalType(New->getType());
966 
967   // Compare the signatures (C++ 1.3.10) of the two functions to
968   // determine whether they are overloads. If we find any mismatch
969   // in the signature, they are overloads.
970 
971   // If either of these functions is a K&R-style function (no
972   // prototype), then we consider them to have matching signatures.
973   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
974       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
975     return false;
976 
977   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
979 
980   // The signature of a function includes the types of its
981   // parameters (C++ 1.3.10), which includes the presence or absence
982   // of the ellipsis; see C++ DR 357).
983   if (OldQType != NewQType &&
984       (OldType->getNumParams() != NewType->getNumParams() ||
985        OldType->isVariadic() != NewType->isVariadic() ||
986        !FunctionParamTypesAreEqual(OldType, NewType)))
987     return true;
988 
989   // C++ [temp.over.link]p4:
990   //   The signature of a function template consists of its function
991   //   signature, its return type and its template parameter list. The names
992   //   of the template parameters are significant only for establishing the
993   //   relationship between the template parameters and the rest of the
994   //   signature.
995   //
996   // We check the return type and template parameter lists for function
997   // templates first; the remaining checks follow.
998   //
999   // However, we don't consider either of these when deciding whether
1000   // a member introduced by a shadow declaration is hidden.
1001   if (!UseUsingDeclRules && NewTemplate &&
1002       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003                                        OldTemplate->getTemplateParameters(),
1004                                        false, TPL_TemplateMatch) ||
1005        OldType->getReturnType() != NewType->getReturnType()))
1006     return true;
1007 
1008   // If the function is a class member, its signature includes the
1009   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1010   //
1011   // As part of this, also check whether one of the member functions
1012   // is static, in which case they are not overloads (C++
1013   // 13.1p2). While not part of the definition of the signature,
1014   // this check is important to determine whether these functions
1015   // can be overloaded.
1016   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1018   if (OldMethod && NewMethod &&
1019       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1020     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1021       if (!UseUsingDeclRules &&
1022           (OldMethod->getRefQualifier() == RQ_None ||
1023            NewMethod->getRefQualifier() == RQ_None)) {
1024         // C++0x [over.load]p2:
1025         //   - Member function declarations with the same name and the same
1026         //     parameter-type-list as well as member function template
1027         //     declarations with the same name, the same parameter-type-list, and
1028         //     the same template parameter lists cannot be overloaded if any of
1029         //     them, but not all, have a ref-qualifier (8.3.5).
1030         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1031           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1032         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1033       }
1034       return true;
1035     }
1036 
1037     // We may not have applied the implicit const for a constexpr member
1038     // function yet (because we haven't yet resolved whether this is a static
1039     // or non-static member function). Add it now, on the assumption that this
1040     // is a redeclaration of OldMethod.
1041     unsigned OldQuals = OldMethod->getTypeQualifiers();
1042     unsigned NewQuals = NewMethod->getTypeQualifiers();
1043     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1044         !isa<CXXConstructorDecl>(NewMethod))
1045       NewQuals |= Qualifiers::Const;
1046 
1047     // We do not allow overloading based off of '__restrict'.
1048     OldQuals &= ~Qualifiers::Restrict;
1049     NewQuals &= ~Qualifiers::Restrict;
1050     if (OldQuals != NewQuals)
1051       return true;
1052   }
1053 
1054   // enable_if attributes are an order-sensitive part of the signature.
1055   for (specific_attr_iterator<EnableIfAttr>
1056          NewI = New->specific_attr_begin<EnableIfAttr>(),
1057          NewE = New->specific_attr_end<EnableIfAttr>(),
1058          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1059          OldE = Old->specific_attr_end<EnableIfAttr>();
1060        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1061     if (NewI == NewE || OldI == OldE)
1062       return true;
1063     llvm::FoldingSetNodeID NewID, OldID;
1064     NewI->getCond()->Profile(NewID, Context, true);
1065     OldI->getCond()->Profile(OldID, Context, true);
1066     if (NewID != OldID)
1067       return true;
1068   }
1069 
1070   // The signatures match; this is not an overload.
1071   return false;
1072 }
1073 
1074 /// \brief Checks availability of the function depending on the current
1075 /// function context. Inside an unavailable function, unavailability is ignored.
1076 ///
1077 /// \returns true if \arg FD is unavailable and current context is inside
1078 /// an available function, false otherwise.
1079 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1080   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1081 }
1082 
1083 /// \brief Tries a user-defined conversion from From to ToType.
1084 ///
1085 /// Produces an implicit conversion sequence for when a standard conversion
1086 /// is not an option. See TryImplicitConversion for more information.
1087 static ImplicitConversionSequence
1088 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1089                          bool SuppressUserConversions,
1090                          bool AllowExplicit,
1091                          bool InOverloadResolution,
1092                          bool CStyle,
1093                          bool AllowObjCWritebackConversion,
1094                          bool AllowObjCConversionOnExplicit) {
1095   ImplicitConversionSequence ICS;
1096 
1097   if (SuppressUserConversions) {
1098     // We're not in the case above, so there is no conversion that
1099     // we can perform.
1100     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1101     return ICS;
1102   }
1103 
1104   // Attempt user-defined conversion.
1105   OverloadCandidateSet Conversions(From->getExprLoc(),
1106                                    OverloadCandidateSet::CSK_Normal);
1107   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108                                   Conversions, AllowExplicit,
1109                                   AllowObjCConversionOnExplicit)) {
1110   case OR_Success:
1111   case OR_Deleted:
1112     ICS.setUserDefined();
1113     ICS.UserDefined.Before.setAsIdentityConversion();
1114     // C++ [over.ics.user]p4:
1115     //   A conversion of an expression of class type to the same class
1116     //   type is given Exact Match rank, and a conversion of an
1117     //   expression of class type to a base class of that type is
1118     //   given Conversion rank, in spite of the fact that a copy
1119     //   constructor (i.e., a user-defined conversion function) is
1120     //   called for those cases.
1121     if (CXXConstructorDecl *Constructor
1122           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1123       QualType FromCanon
1124         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1125       QualType ToCanon
1126         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1127       if (Constructor->isCopyConstructor() &&
1128           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1129         // Turn this into a "standard" conversion sequence, so that it
1130         // gets ranked with standard conversion sequences.
1131         ICS.setStandard();
1132         ICS.Standard.setAsIdentityConversion();
1133         ICS.Standard.setFromType(From->getType());
1134         ICS.Standard.setAllToTypes(ToType);
1135         ICS.Standard.CopyConstructor = Constructor;
1136         if (ToCanon != FromCanon)
1137           ICS.Standard.Second = ICK_Derived_To_Base;
1138       }
1139     }
1140     break;
1141 
1142   case OR_Ambiguous:
1143     ICS.setAmbiguous();
1144     ICS.Ambiguous.setFromType(From->getType());
1145     ICS.Ambiguous.setToType(ToType);
1146     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1147          Cand != Conversions.end(); ++Cand)
1148       if (Cand->Viable)
1149         ICS.Ambiguous.addConversion(Cand->Function);
1150     break;
1151 
1152     // Fall through.
1153   case OR_No_Viable_Function:
1154     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1155     break;
1156   }
1157 
1158   return ICS;
1159 }
1160 
1161 /// TryImplicitConversion - Attempt to perform an implicit conversion
1162 /// from the given expression (Expr) to the given type (ToType). This
1163 /// function returns an implicit conversion sequence that can be used
1164 /// to perform the initialization. Given
1165 ///
1166 ///   void f(float f);
1167 ///   void g(int i) { f(i); }
1168 ///
1169 /// this routine would produce an implicit conversion sequence to
1170 /// describe the initialization of f from i, which will be a standard
1171 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1172 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1173 //
1174 /// Note that this routine only determines how the conversion can be
1175 /// performed; it does not actually perform the conversion. As such,
1176 /// it will not produce any diagnostics if no conversion is available,
1177 /// but will instead return an implicit conversion sequence of kind
1178 /// "BadConversion".
1179 ///
1180 /// If @p SuppressUserConversions, then user-defined conversions are
1181 /// not permitted.
1182 /// If @p AllowExplicit, then explicit user-defined conversions are
1183 /// permitted.
1184 ///
1185 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1186 /// writeback conversion, which allows __autoreleasing id* parameters to
1187 /// be initialized with __strong id* or __weak id* arguments.
1188 static ImplicitConversionSequence
1189 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190                       bool SuppressUserConversions,
1191                       bool AllowExplicit,
1192                       bool InOverloadResolution,
1193                       bool CStyle,
1194                       bool AllowObjCWritebackConversion,
1195                       bool AllowObjCConversionOnExplicit) {
1196   ImplicitConversionSequence ICS;
1197   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1198                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1199     ICS.setStandard();
1200     return ICS;
1201   }
1202 
1203   if (!S.getLangOpts().CPlusPlus) {
1204     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1205     return ICS;
1206   }
1207 
1208   // C++ [over.ics.user]p4:
1209   //   A conversion of an expression of class type to the same class
1210   //   type is given Exact Match rank, and a conversion of an
1211   //   expression of class type to a base class of that type is
1212   //   given Conversion rank, in spite of the fact that a copy/move
1213   //   constructor (i.e., a user-defined conversion function) is
1214   //   called for those cases.
1215   QualType FromType = From->getType();
1216   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1217       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218        S.IsDerivedFrom(FromType, ToType))) {
1219     ICS.setStandard();
1220     ICS.Standard.setAsIdentityConversion();
1221     ICS.Standard.setFromType(FromType);
1222     ICS.Standard.setAllToTypes(ToType);
1223 
1224     // We don't actually check at this point whether there is a valid
1225     // copy/move constructor, since overloading just assumes that it
1226     // exists. When we actually perform initialization, we'll find the
1227     // appropriate constructor to copy the returned object, if needed.
1228     ICS.Standard.CopyConstructor = nullptr;
1229 
1230     // Determine whether this is considered a derived-to-base conversion.
1231     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1232       ICS.Standard.Second = ICK_Derived_To_Base;
1233 
1234     return ICS;
1235   }
1236 
1237   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238                                   AllowExplicit, InOverloadResolution, CStyle,
1239                                   AllowObjCWritebackConversion,
1240                                   AllowObjCConversionOnExplicit);
1241 }
1242 
1243 ImplicitConversionSequence
1244 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1245                             bool SuppressUserConversions,
1246                             bool AllowExplicit,
1247                             bool InOverloadResolution,
1248                             bool CStyle,
1249                             bool AllowObjCWritebackConversion) {
1250   return ::TryImplicitConversion(*this, From, ToType,
1251                                  SuppressUserConversions, AllowExplicit,
1252                                  InOverloadResolution, CStyle,
1253                                  AllowObjCWritebackConversion,
1254                                  /*AllowObjCConversionOnExplicit=*/false);
1255 }
1256 
1257 /// PerformImplicitConversion - Perform an implicit conversion of the
1258 /// expression From to the type ToType. Returns the
1259 /// converted expression. Flavor is the kind of conversion we're
1260 /// performing, used in the error message. If @p AllowExplicit,
1261 /// explicit user-defined conversions are permitted.
1262 ExprResult
1263 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1264                                 AssignmentAction Action, bool AllowExplicit) {
1265   ImplicitConversionSequence ICS;
1266   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1267 }
1268 
1269 ExprResult
1270 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1271                                 AssignmentAction Action, bool AllowExplicit,
1272                                 ImplicitConversionSequence& ICS) {
1273   if (checkPlaceholderForOverload(*this, From))
1274     return ExprError();
1275 
1276   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277   bool AllowObjCWritebackConversion
1278     = getLangOpts().ObjCAutoRefCount &&
1279       (Action == AA_Passing || Action == AA_Sending);
1280   if (getLangOpts().ObjC1)
1281     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282                                       ToType, From->getType(), From);
1283   ICS = ::TryImplicitConversion(*this, From, ToType,
1284                                 /*SuppressUserConversions=*/false,
1285                                 AllowExplicit,
1286                                 /*InOverloadResolution=*/false,
1287                                 /*CStyle=*/false,
1288                                 AllowObjCWritebackConversion,
1289                                 /*AllowObjCConversionOnExplicit=*/false);
1290   return PerformImplicitConversion(From, ToType, ICS, Action);
1291 }
1292 
1293 /// \brief Determine whether the conversion from FromType to ToType is a valid
1294 /// conversion that strips "noreturn" off the nested function type.
1295 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296                                 QualType &ResultTy) {
1297   if (Context.hasSameUnqualifiedType(FromType, ToType))
1298     return false;
1299 
1300   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1301   // where F adds one of the following at most once:
1302   //   - a pointer
1303   //   - a member pointer
1304   //   - a block pointer
1305   CanQualType CanTo = Context.getCanonicalType(ToType);
1306   CanQualType CanFrom = Context.getCanonicalType(FromType);
1307   Type::TypeClass TyClass = CanTo->getTypeClass();
1308   if (TyClass != CanFrom->getTypeClass()) return false;
1309   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1310     if (TyClass == Type::Pointer) {
1311       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1312       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1313     } else if (TyClass == Type::BlockPointer) {
1314       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1315       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1316     } else if (TyClass == Type::MemberPointer) {
1317       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1318       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1319     } else {
1320       return false;
1321     }
1322 
1323     TyClass = CanTo->getTypeClass();
1324     if (TyClass != CanFrom->getTypeClass()) return false;
1325     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1326       return false;
1327   }
1328 
1329   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1330   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1331   if (!EInfo.getNoReturn()) return false;
1332 
1333   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1334   assert(QualType(FromFn, 0).isCanonical());
1335   if (QualType(FromFn, 0) != CanTo) return false;
1336 
1337   ResultTy = ToType;
1338   return true;
1339 }
1340 
1341 /// \brief Determine whether the conversion from FromType to ToType is a valid
1342 /// vector conversion.
1343 ///
1344 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1345 /// conversion.
1346 static bool IsVectorConversion(Sema &S, QualType FromType,
1347                                QualType ToType, ImplicitConversionKind &ICK) {
1348   // We need at least one of these types to be a vector type to have a vector
1349   // conversion.
1350   if (!ToType->isVectorType() && !FromType->isVectorType())
1351     return false;
1352 
1353   // Identical types require no conversions.
1354   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1355     return false;
1356 
1357   // There are no conversions between extended vector types, only identity.
1358   if (ToType->isExtVectorType()) {
1359     // There are no conversions between extended vector types other than the
1360     // identity conversion.
1361     if (FromType->isExtVectorType())
1362       return false;
1363 
1364     // Vector splat from any arithmetic type to a vector.
1365     if (FromType->isArithmeticType()) {
1366       ICK = ICK_Vector_Splat;
1367       return true;
1368     }
1369   }
1370 
1371   // We can perform the conversion between vector types in the following cases:
1372   // 1)vector types are equivalent AltiVec and GCC vector types
1373   // 2)lax vector conversions are permitted and the vector types are of the
1374   //   same size
1375   if (ToType->isVectorType() && FromType->isVectorType()) {
1376     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377         S.isLaxVectorConversion(FromType, ToType)) {
1378       ICK = ICK_Vector_Conversion;
1379       return true;
1380     }
1381   }
1382 
1383   return false;
1384 }
1385 
1386 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387                                 bool InOverloadResolution,
1388                                 StandardConversionSequence &SCS,
1389                                 bool CStyle);
1390 
1391 /// IsStandardConversion - Determines whether there is a standard
1392 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1393 /// expression From to the type ToType. Standard conversion sequences
1394 /// only consider non-class types; for conversions that involve class
1395 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1396 /// contain the standard conversion sequence required to perform this
1397 /// conversion and this routine will return true. Otherwise, this
1398 /// routine will return false and the value of SCS is unspecified.
1399 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400                                  bool InOverloadResolution,
1401                                  StandardConversionSequence &SCS,
1402                                  bool CStyle,
1403                                  bool AllowObjCWritebackConversion) {
1404   QualType FromType = From->getType();
1405 
1406   // Standard conversions (C++ [conv])
1407   SCS.setAsIdentityConversion();
1408   SCS.IncompatibleObjC = false;
1409   SCS.setFromType(FromType);
1410   SCS.CopyConstructor = nullptr;
1411 
1412   // There are no standard conversions for class types in C++, so
1413   // abort early. When overloading in C, however, we do permit
1414   if (FromType->isRecordType() || ToType->isRecordType()) {
1415     if (S.getLangOpts().CPlusPlus)
1416       return false;
1417 
1418     // When we're overloading in C, we allow, as standard conversions,
1419   }
1420 
1421   // The first conversion can be an lvalue-to-rvalue conversion,
1422   // array-to-pointer conversion, or function-to-pointer conversion
1423   // (C++ 4p1).
1424 
1425   if (FromType == S.Context.OverloadTy) {
1426     DeclAccessPair AccessPair;
1427     if (FunctionDecl *Fn
1428           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1429                                                  AccessPair)) {
1430       // We were able to resolve the address of the overloaded function,
1431       // so we can convert to the type of that function.
1432       FromType = Fn->getType();
1433       SCS.setFromType(FromType);
1434 
1435       // we can sometimes resolve &foo<int> regardless of ToType, so check
1436       // if the type matches (identity) or we are converting to bool
1437       if (!S.Context.hasSameUnqualifiedType(
1438                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1439         QualType resultTy;
1440         // if the function type matches except for [[noreturn]], it's ok
1441         if (!S.IsNoReturnConversion(FromType,
1442               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1443           // otherwise, only a boolean conversion is standard
1444           if (!ToType->isBooleanType())
1445             return false;
1446       }
1447 
1448       // Check if the "from" expression is taking the address of an overloaded
1449       // function and recompute the FromType accordingly. Take advantage of the
1450       // fact that non-static member functions *must* have such an address-of
1451       // expression.
1452       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1453       if (Method && !Method->isStatic()) {
1454         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1455                "Non-unary operator on non-static member address");
1456         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1457                == UO_AddrOf &&
1458                "Non-address-of operator on non-static member address");
1459         const Type *ClassType
1460           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1461         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1462       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1464                UO_AddrOf &&
1465                "Non-address-of operator for overloaded function expression");
1466         FromType = S.Context.getPointerType(FromType);
1467       }
1468 
1469       // Check that we've computed the proper type after overload resolution.
1470       assert(S.Context.hasSameType(
1471         FromType,
1472         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1473     } else {
1474       return false;
1475     }
1476   }
1477   // Lvalue-to-rvalue conversion (C++11 4.1):
1478   //   A glvalue (3.10) of a non-function, non-array type T can
1479   //   be converted to a prvalue.
1480   bool argIsLValue = From->isGLValue();
1481   if (argIsLValue &&
1482       !FromType->isFunctionType() && !FromType->isArrayType() &&
1483       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1484     SCS.First = ICK_Lvalue_To_Rvalue;
1485 
1486     // C11 6.3.2.1p2:
1487     //   ... if the lvalue has atomic type, the value has the non-atomic version
1488     //   of the type of the lvalue ...
1489     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1490       FromType = Atomic->getValueType();
1491 
1492     // If T is a non-class type, the type of the rvalue is the
1493     // cv-unqualified version of T. Otherwise, the type of the rvalue
1494     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1495     // just strip the qualifiers because they don't matter.
1496     FromType = FromType.getUnqualifiedType();
1497   } else if (FromType->isArrayType()) {
1498     // Array-to-pointer conversion (C++ 4.2)
1499     SCS.First = ICK_Array_To_Pointer;
1500 
1501     // An lvalue or rvalue of type "array of N T" or "array of unknown
1502     // bound of T" can be converted to an rvalue of type "pointer to
1503     // T" (C++ 4.2p1).
1504     FromType = S.Context.getArrayDecayedType(FromType);
1505 
1506     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1507       // This conversion is deprecated in C++03 (D.4)
1508       SCS.DeprecatedStringLiteralToCharPtr = true;
1509 
1510       // For the purpose of ranking in overload resolution
1511       // (13.3.3.1.1), this conversion is considered an
1512       // array-to-pointer conversion followed by a qualification
1513       // conversion (4.4). (C++ 4.2p2)
1514       SCS.Second = ICK_Identity;
1515       SCS.Third = ICK_Qualification;
1516       SCS.QualificationIncludesObjCLifetime = false;
1517       SCS.setAllToTypes(FromType);
1518       return true;
1519     }
1520   } else if (FromType->isFunctionType() && argIsLValue) {
1521     // Function-to-pointer conversion (C++ 4.3).
1522     SCS.First = ICK_Function_To_Pointer;
1523 
1524     // An lvalue of function type T can be converted to an rvalue of
1525     // type "pointer to T." The result is a pointer to the
1526     // function. (C++ 4.3p1).
1527     FromType = S.Context.getPointerType(FromType);
1528   } else {
1529     // We don't require any conversions for the first step.
1530     SCS.First = ICK_Identity;
1531   }
1532   SCS.setToType(0, FromType);
1533 
1534   // The second conversion can be an integral promotion, floating
1535   // point promotion, integral conversion, floating point conversion,
1536   // floating-integral conversion, pointer conversion,
1537   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1538   // For overloading in C, this can also be a "compatible-type"
1539   // conversion.
1540   bool IncompatibleObjC = false;
1541   ImplicitConversionKind SecondICK = ICK_Identity;
1542   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1543     // The unqualified versions of the types are the same: there's no
1544     // conversion to do.
1545     SCS.Second = ICK_Identity;
1546   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1547     // Integral promotion (C++ 4.5).
1548     SCS.Second = ICK_Integral_Promotion;
1549     FromType = ToType.getUnqualifiedType();
1550   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1551     // Floating point promotion (C++ 4.6).
1552     SCS.Second = ICK_Floating_Promotion;
1553     FromType = ToType.getUnqualifiedType();
1554   } else if (S.IsComplexPromotion(FromType, ToType)) {
1555     // Complex promotion (Clang extension)
1556     SCS.Second = ICK_Complex_Promotion;
1557     FromType = ToType.getUnqualifiedType();
1558   } else if (ToType->isBooleanType() &&
1559              (FromType->isArithmeticType() ||
1560               FromType->isAnyPointerType() ||
1561               FromType->isBlockPointerType() ||
1562               FromType->isMemberPointerType() ||
1563               FromType->isNullPtrType())) {
1564     // Boolean conversions (C++ 4.12).
1565     SCS.Second = ICK_Boolean_Conversion;
1566     FromType = S.Context.BoolTy;
1567   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1568              ToType->isIntegralType(S.Context)) {
1569     // Integral conversions (C++ 4.7).
1570     SCS.Second = ICK_Integral_Conversion;
1571     FromType = ToType.getUnqualifiedType();
1572   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1573     // Complex conversions (C99 6.3.1.6)
1574     SCS.Second = ICK_Complex_Conversion;
1575     FromType = ToType.getUnqualifiedType();
1576   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1578     // Complex-real conversions (C99 6.3.1.7)
1579     SCS.Second = ICK_Complex_Real;
1580     FromType = ToType.getUnqualifiedType();
1581   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1582     // Floating point conversions (C++ 4.8).
1583     SCS.Second = ICK_Floating_Conversion;
1584     FromType = ToType.getUnqualifiedType();
1585   } else if ((FromType->isRealFloatingType() &&
1586               ToType->isIntegralType(S.Context)) ||
1587              (FromType->isIntegralOrUnscopedEnumerationType() &&
1588               ToType->isRealFloatingType())) {
1589     // Floating-integral conversions (C++ 4.9).
1590     SCS.Second = ICK_Floating_Integral;
1591     FromType = ToType.getUnqualifiedType();
1592   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1593     SCS.Second = ICK_Block_Pointer_Conversion;
1594   } else if (AllowObjCWritebackConversion &&
1595              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1596     SCS.Second = ICK_Writeback_Conversion;
1597   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598                                    FromType, IncompatibleObjC)) {
1599     // Pointer conversions (C++ 4.10).
1600     SCS.Second = ICK_Pointer_Conversion;
1601     SCS.IncompatibleObjC = IncompatibleObjC;
1602     FromType = FromType.getUnqualifiedType();
1603   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1604                                          InOverloadResolution, FromType)) {
1605     // Pointer to member conversions (4.11).
1606     SCS.Second = ICK_Pointer_Member;
1607   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1608     SCS.Second = SecondICK;
1609     FromType = ToType.getUnqualifiedType();
1610   } else if (!S.getLangOpts().CPlusPlus &&
1611              S.Context.typesAreCompatible(ToType, FromType)) {
1612     // Compatible conversions (Clang extension for C function overloading)
1613     SCS.Second = ICK_Compatible_Conversion;
1614     FromType = ToType.getUnqualifiedType();
1615   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1616     // Treat a conversion that strips "noreturn" as an identity conversion.
1617     SCS.Second = ICK_NoReturn_Adjustment;
1618   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1619                                              InOverloadResolution,
1620                                              SCS, CStyle)) {
1621     SCS.Second = ICK_TransparentUnionConversion;
1622     FromType = ToType;
1623   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1624                                  CStyle)) {
1625     // tryAtomicConversion has updated the standard conversion sequence
1626     // appropriately.
1627     return true;
1628   } else if (ToType->isEventT() &&
1629              From->isIntegerConstantExpr(S.getASTContext()) &&
1630              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1631     SCS.Second = ICK_Zero_Event_Conversion;
1632     FromType = ToType;
1633   } else {
1634     // No second conversion required.
1635     SCS.Second = ICK_Identity;
1636   }
1637   SCS.setToType(1, FromType);
1638 
1639   QualType CanonFrom;
1640   QualType CanonTo;
1641   // The third conversion can be a qualification conversion (C++ 4p1).
1642   bool ObjCLifetimeConversion;
1643   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644                                   ObjCLifetimeConversion)) {
1645     SCS.Third = ICK_Qualification;
1646     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1647     FromType = ToType;
1648     CanonFrom = S.Context.getCanonicalType(FromType);
1649     CanonTo = S.Context.getCanonicalType(ToType);
1650   } else {
1651     // No conversion required
1652     SCS.Third = ICK_Identity;
1653 
1654     // C++ [over.best.ics]p6:
1655     //   [...] Any difference in top-level cv-qualification is
1656     //   subsumed by the initialization itself and does not constitute
1657     //   a conversion. [...]
1658     CanonFrom = S.Context.getCanonicalType(FromType);
1659     CanonTo = S.Context.getCanonicalType(ToType);
1660     if (CanonFrom.getLocalUnqualifiedType()
1661                                        == CanonTo.getLocalUnqualifiedType() &&
1662         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1663       FromType = ToType;
1664       CanonFrom = CanonTo;
1665     }
1666   }
1667   SCS.setToType(2, FromType);
1668 
1669   // If we have not converted the argument type to the parameter type,
1670   // this is a bad conversion sequence.
1671   if (CanonFrom != CanonTo)
1672     return false;
1673 
1674   return true;
1675 }
1676 
1677 static bool
1678 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1679                                      QualType &ToType,
1680                                      bool InOverloadResolution,
1681                                      StandardConversionSequence &SCS,
1682                                      bool CStyle) {
1683 
1684   const RecordType *UT = ToType->getAsUnionType();
1685   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1686     return false;
1687   // The field to initialize within the transparent union.
1688   RecordDecl *UD = UT->getDecl();
1689   // It's compatible if the expression matches any of the fields.
1690   for (const auto *it : UD->fields()) {
1691     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692                              CStyle, /*ObjCWritebackConversion=*/false)) {
1693       ToType = it->getType();
1694       return true;
1695     }
1696   }
1697   return false;
1698 }
1699 
1700 /// IsIntegralPromotion - Determines whether the conversion from the
1701 /// expression From (whose potentially-adjusted type is FromType) to
1702 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1703 /// sets PromotedType to the promoted type.
1704 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1705   const BuiltinType *To = ToType->getAs<BuiltinType>();
1706   // All integers are built-in.
1707   if (!To) {
1708     return false;
1709   }
1710 
1711   // An rvalue of type char, signed char, unsigned char, short int, or
1712   // unsigned short int can be converted to an rvalue of type int if
1713   // int can represent all the values of the source type; otherwise,
1714   // the source rvalue can be converted to an rvalue of type unsigned
1715   // int (C++ 4.5p1).
1716   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717       !FromType->isEnumeralType()) {
1718     if (// We can promote any signed, promotable integer type to an int
1719         (FromType->isSignedIntegerType() ||
1720          // We can promote any unsigned integer type whose size is
1721          // less than int to an int.
1722          (!FromType->isSignedIntegerType() &&
1723           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1724       return To->getKind() == BuiltinType::Int;
1725     }
1726 
1727     return To->getKind() == BuiltinType::UInt;
1728   }
1729 
1730   // C++11 [conv.prom]p3:
1731   //   A prvalue of an unscoped enumeration type whose underlying type is not
1732   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1733   //   following types that can represent all the values of the enumeration
1734   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1735   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1736   //   long long int. If none of the types in that list can represent all the
1737   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1738   //   type can be converted to an rvalue a prvalue of the extended integer type
1739   //   with lowest integer conversion rank (4.13) greater than the rank of long
1740   //   long in which all the values of the enumeration can be represented. If
1741   //   there are two such extended types, the signed one is chosen.
1742   // C++11 [conv.prom]p4:
1743   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1744   //   can be converted to a prvalue of its underlying type. Moreover, if
1745   //   integral promotion can be applied to its underlying type, a prvalue of an
1746   //   unscoped enumeration type whose underlying type is fixed can also be
1747   //   converted to a prvalue of the promoted underlying type.
1748   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1749     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1750     // provided for a scoped enumeration.
1751     if (FromEnumType->getDecl()->isScoped())
1752       return false;
1753 
1754     // We can perform an integral promotion to the underlying type of the enum,
1755     // even if that's not the promoted type.
1756     if (FromEnumType->getDecl()->isFixed()) {
1757       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1758       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1759              IsIntegralPromotion(From, Underlying, ToType);
1760     }
1761 
1762     // We have already pre-calculated the promotion type, so this is trivial.
1763     if (ToType->isIntegerType() &&
1764         !RequireCompleteType(From->getLocStart(), FromType, 0))
1765       return Context.hasSameUnqualifiedType(ToType,
1766                                 FromEnumType->getDecl()->getPromotionType());
1767   }
1768 
1769   // C++0x [conv.prom]p2:
1770   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1771   //   to an rvalue a prvalue of the first of the following types that can
1772   //   represent all the values of its underlying type: int, unsigned int,
1773   //   long int, unsigned long int, long long int, or unsigned long long int.
1774   //   If none of the types in that list can represent all the values of its
1775   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1776   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1777   //   type.
1778   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1779       ToType->isIntegerType()) {
1780     // Determine whether the type we're converting from is signed or
1781     // unsigned.
1782     bool FromIsSigned = FromType->isSignedIntegerType();
1783     uint64_t FromSize = Context.getTypeSize(FromType);
1784 
1785     // The types we'll try to promote to, in the appropriate
1786     // order. Try each of these types.
1787     QualType PromoteTypes[6] = {
1788       Context.IntTy, Context.UnsignedIntTy,
1789       Context.LongTy, Context.UnsignedLongTy ,
1790       Context.LongLongTy, Context.UnsignedLongLongTy
1791     };
1792     for (int Idx = 0; Idx < 6; ++Idx) {
1793       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1794       if (FromSize < ToSize ||
1795           (FromSize == ToSize &&
1796            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1797         // We found the type that we can promote to. If this is the
1798         // type we wanted, we have a promotion. Otherwise, no
1799         // promotion.
1800         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1801       }
1802     }
1803   }
1804 
1805   // An rvalue for an integral bit-field (9.6) can be converted to an
1806   // rvalue of type int if int can represent all the values of the
1807   // bit-field; otherwise, it can be converted to unsigned int if
1808   // unsigned int can represent all the values of the bit-field. If
1809   // the bit-field is larger yet, no integral promotion applies to
1810   // it. If the bit-field has an enumerated type, it is treated as any
1811   // other value of that type for promotion purposes (C++ 4.5p3).
1812   // FIXME: We should delay checking of bit-fields until we actually perform the
1813   // conversion.
1814   using llvm::APSInt;
1815   if (From)
1816     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1817       APSInt BitWidth;
1818       if (FromType->isIntegralType(Context) &&
1819           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1820         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1821         ToSize = Context.getTypeSize(ToType);
1822 
1823         // Are we promoting to an int from a bitfield that fits in an int?
1824         if (BitWidth < ToSize ||
1825             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1826           return To->getKind() == BuiltinType::Int;
1827         }
1828 
1829         // Are we promoting to an unsigned int from an unsigned bitfield
1830         // that fits into an unsigned int?
1831         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1832           return To->getKind() == BuiltinType::UInt;
1833         }
1834 
1835         return false;
1836       }
1837     }
1838 
1839   // An rvalue of type bool can be converted to an rvalue of type int,
1840   // with false becoming zero and true becoming one (C++ 4.5p4).
1841   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1842     return true;
1843   }
1844 
1845   return false;
1846 }
1847 
1848 /// IsFloatingPointPromotion - Determines whether the conversion from
1849 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1850 /// returns true and sets PromotedType to the promoted type.
1851 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1852   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1853     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1854       /// An rvalue of type float can be converted to an rvalue of type
1855       /// double. (C++ 4.6p1).
1856       if (FromBuiltin->getKind() == BuiltinType::Float &&
1857           ToBuiltin->getKind() == BuiltinType::Double)
1858         return true;
1859 
1860       // C99 6.3.1.5p1:
1861       //   When a float is promoted to double or long double, or a
1862       //   double is promoted to long double [...].
1863       if (!getLangOpts().CPlusPlus &&
1864           (FromBuiltin->getKind() == BuiltinType::Float ||
1865            FromBuiltin->getKind() == BuiltinType::Double) &&
1866           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1867         return true;
1868 
1869       // Half can be promoted to float.
1870       if (!getLangOpts().NativeHalfType &&
1871            FromBuiltin->getKind() == BuiltinType::Half &&
1872           ToBuiltin->getKind() == BuiltinType::Float)
1873         return true;
1874     }
1875 
1876   return false;
1877 }
1878 
1879 /// \brief Determine if a conversion is a complex promotion.
1880 ///
1881 /// A complex promotion is defined as a complex -> complex conversion
1882 /// where the conversion between the underlying real types is a
1883 /// floating-point or integral promotion.
1884 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1885   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1886   if (!FromComplex)
1887     return false;
1888 
1889   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1890   if (!ToComplex)
1891     return false;
1892 
1893   return IsFloatingPointPromotion(FromComplex->getElementType(),
1894                                   ToComplex->getElementType()) ||
1895     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1896                         ToComplex->getElementType());
1897 }
1898 
1899 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1900 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1901 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1902 /// if non-empty, will be a pointer to ToType that may or may not have
1903 /// the right set of qualifiers on its pointee.
1904 ///
1905 static QualType
1906 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1907                                    QualType ToPointee, QualType ToType,
1908                                    ASTContext &Context,
1909                                    bool StripObjCLifetime = false) {
1910   assert((FromPtr->getTypeClass() == Type::Pointer ||
1911           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1912          "Invalid similarly-qualified pointer type");
1913 
1914   /// Conversions to 'id' subsume cv-qualifier conversions.
1915   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1916     return ToType.getUnqualifiedType();
1917 
1918   QualType CanonFromPointee
1919     = Context.getCanonicalType(FromPtr->getPointeeType());
1920   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1921   Qualifiers Quals = CanonFromPointee.getQualifiers();
1922 
1923   if (StripObjCLifetime)
1924     Quals.removeObjCLifetime();
1925 
1926   // Exact qualifier match -> return the pointer type we're converting to.
1927   if (CanonToPointee.getLocalQualifiers() == Quals) {
1928     // ToType is exactly what we need. Return it.
1929     if (!ToType.isNull())
1930       return ToType.getUnqualifiedType();
1931 
1932     // Build a pointer to ToPointee. It has the right qualifiers
1933     // already.
1934     if (isa<ObjCObjectPointerType>(ToType))
1935       return Context.getObjCObjectPointerType(ToPointee);
1936     return Context.getPointerType(ToPointee);
1937   }
1938 
1939   // Just build a canonical type that has the right qualifiers.
1940   QualType QualifiedCanonToPointee
1941     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1942 
1943   if (isa<ObjCObjectPointerType>(ToType))
1944     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1945   return Context.getPointerType(QualifiedCanonToPointee);
1946 }
1947 
1948 static bool isNullPointerConstantForConversion(Expr *Expr,
1949                                                bool InOverloadResolution,
1950                                                ASTContext &Context) {
1951   // Handle value-dependent integral null pointer constants correctly.
1952   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1953   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1954       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1955     return !InOverloadResolution;
1956 
1957   return Expr->isNullPointerConstant(Context,
1958                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1959                                         : Expr::NPC_ValueDependentIsNull);
1960 }
1961 
1962 /// IsPointerConversion - Determines whether the conversion of the
1963 /// expression From, which has the (possibly adjusted) type FromType,
1964 /// can be converted to the type ToType via a pointer conversion (C++
1965 /// 4.10). If so, returns true and places the converted type (that
1966 /// might differ from ToType in its cv-qualifiers at some level) into
1967 /// ConvertedType.
1968 ///
1969 /// This routine also supports conversions to and from block pointers
1970 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1971 /// pointers to interfaces. FIXME: Once we've determined the
1972 /// appropriate overloading rules for Objective-C, we may want to
1973 /// split the Objective-C checks into a different routine; however,
1974 /// GCC seems to consider all of these conversions to be pointer
1975 /// conversions, so for now they live here. IncompatibleObjC will be
1976 /// set if the conversion is an allowed Objective-C conversion that
1977 /// should result in a warning.
1978 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1979                                bool InOverloadResolution,
1980                                QualType& ConvertedType,
1981                                bool &IncompatibleObjC) {
1982   IncompatibleObjC = false;
1983   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1984                               IncompatibleObjC))
1985     return true;
1986 
1987   // Conversion from a null pointer constant to any Objective-C pointer type.
1988   if (ToType->isObjCObjectPointerType() &&
1989       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1990     ConvertedType = ToType;
1991     return true;
1992   }
1993 
1994   // Blocks: Block pointers can be converted to void*.
1995   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1996       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1997     ConvertedType = ToType;
1998     return true;
1999   }
2000   // Blocks: A null pointer constant can be converted to a block
2001   // pointer type.
2002   if (ToType->isBlockPointerType() &&
2003       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2004     ConvertedType = ToType;
2005     return true;
2006   }
2007 
2008   // If the left-hand-side is nullptr_t, the right side can be a null
2009   // pointer constant.
2010   if (ToType->isNullPtrType() &&
2011       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2012     ConvertedType = ToType;
2013     return true;
2014   }
2015 
2016   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2017   if (!ToTypePtr)
2018     return false;
2019 
2020   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2021   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2022     ConvertedType = ToType;
2023     return true;
2024   }
2025 
2026   // Beyond this point, both types need to be pointers
2027   // , including objective-c pointers.
2028   QualType ToPointeeType = ToTypePtr->getPointeeType();
2029   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2030       !getLangOpts().ObjCAutoRefCount) {
2031     ConvertedType = BuildSimilarlyQualifiedPointerType(
2032                                       FromType->getAs<ObjCObjectPointerType>(),
2033                                                        ToPointeeType,
2034                                                        ToType, Context);
2035     return true;
2036   }
2037   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2038   if (!FromTypePtr)
2039     return false;
2040 
2041   QualType FromPointeeType = FromTypePtr->getPointeeType();
2042 
2043   // If the unqualified pointee types are the same, this can't be a
2044   // pointer conversion, so don't do all of the work below.
2045   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2046     return false;
2047 
2048   // An rvalue of type "pointer to cv T," where T is an object type,
2049   // can be converted to an rvalue of type "pointer to cv void" (C++
2050   // 4.10p2).
2051   if (FromPointeeType->isIncompleteOrObjectType() &&
2052       ToPointeeType->isVoidType()) {
2053     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2054                                                        ToPointeeType,
2055                                                        ToType, Context,
2056                                                    /*StripObjCLifetime=*/true);
2057     return true;
2058   }
2059 
2060   // MSVC allows implicit function to void* type conversion.
2061   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2062       ToPointeeType->isVoidType()) {
2063     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2064                                                        ToPointeeType,
2065                                                        ToType, Context);
2066     return true;
2067   }
2068 
2069   // When we're overloading in C, we allow a special kind of pointer
2070   // conversion for compatible-but-not-identical pointee types.
2071   if (!getLangOpts().CPlusPlus &&
2072       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2073     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2074                                                        ToPointeeType,
2075                                                        ToType, Context);
2076     return true;
2077   }
2078 
2079   // C++ [conv.ptr]p3:
2080   //
2081   //   An rvalue of type "pointer to cv D," where D is a class type,
2082   //   can be converted to an rvalue of type "pointer to cv B," where
2083   //   B is a base class (clause 10) of D. If B is an inaccessible
2084   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2085   //   necessitates this conversion is ill-formed. The result of the
2086   //   conversion is a pointer to the base class sub-object of the
2087   //   derived class object. The null pointer value is converted to
2088   //   the null pointer value of the destination type.
2089   //
2090   // Note that we do not check for ambiguity or inaccessibility
2091   // here. That is handled by CheckPointerConversion.
2092   if (getLangOpts().CPlusPlus &&
2093       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2094       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2095       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2096       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2097     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2098                                                        ToPointeeType,
2099                                                        ToType, Context);
2100     return true;
2101   }
2102 
2103   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2104       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2105     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2106                                                        ToPointeeType,
2107                                                        ToType, Context);
2108     return true;
2109   }
2110 
2111   return false;
2112 }
2113 
2114 /// \brief Adopt the given qualifiers for the given type.
2115 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2116   Qualifiers TQs = T.getQualifiers();
2117 
2118   // Check whether qualifiers already match.
2119   if (TQs == Qs)
2120     return T;
2121 
2122   if (Qs.compatiblyIncludes(TQs))
2123     return Context.getQualifiedType(T, Qs);
2124 
2125   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2126 }
2127 
2128 /// isObjCPointerConversion - Determines whether this is an
2129 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2130 /// with the same arguments and return values.
2131 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2132                                    QualType& ConvertedType,
2133                                    bool &IncompatibleObjC) {
2134   if (!getLangOpts().ObjC1)
2135     return false;
2136 
2137   // The set of qualifiers on the type we're converting from.
2138   Qualifiers FromQualifiers = FromType.getQualifiers();
2139 
2140   // First, we handle all conversions on ObjC object pointer types.
2141   const ObjCObjectPointerType* ToObjCPtr =
2142     ToType->getAs<ObjCObjectPointerType>();
2143   const ObjCObjectPointerType *FromObjCPtr =
2144     FromType->getAs<ObjCObjectPointerType>();
2145 
2146   if (ToObjCPtr && FromObjCPtr) {
2147     // If the pointee types are the same (ignoring qualifications),
2148     // then this is not a pointer conversion.
2149     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2150                                        FromObjCPtr->getPointeeType()))
2151       return false;
2152 
2153     // Check for compatible
2154     // Objective C++: We're able to convert between "id" or "Class" and a
2155     // pointer to any interface (in both directions).
2156     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2157       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2158       return true;
2159     }
2160     // Conversions with Objective-C's id<...>.
2161     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2162          ToObjCPtr->isObjCQualifiedIdType()) &&
2163         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2164                                                   /*compare=*/false)) {
2165       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2166       return true;
2167     }
2168     // Objective C++: We're able to convert from a pointer to an
2169     // interface to a pointer to a different interface.
2170     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2171       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2172       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2173       if (getLangOpts().CPlusPlus && LHS && RHS &&
2174           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2175                                                 FromObjCPtr->getPointeeType()))
2176         return false;
2177       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2178                                                    ToObjCPtr->getPointeeType(),
2179                                                          ToType, Context);
2180       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2181       return true;
2182     }
2183 
2184     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2185       // Okay: this is some kind of implicit downcast of Objective-C
2186       // interfaces, which is permitted. However, we're going to
2187       // complain about it.
2188       IncompatibleObjC = true;
2189       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2190                                                    ToObjCPtr->getPointeeType(),
2191                                                          ToType, Context);
2192       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2193       return true;
2194     }
2195   }
2196   // Beyond this point, both types need to be C pointers or block pointers.
2197   QualType ToPointeeType;
2198   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2199     ToPointeeType = ToCPtr->getPointeeType();
2200   else if (const BlockPointerType *ToBlockPtr =
2201             ToType->getAs<BlockPointerType>()) {
2202     // Objective C++: We're able to convert from a pointer to any object
2203     // to a block pointer type.
2204     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2205       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2206       return true;
2207     }
2208     ToPointeeType = ToBlockPtr->getPointeeType();
2209   }
2210   else if (FromType->getAs<BlockPointerType>() &&
2211            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2212     // Objective C++: We're able to convert from a block pointer type to a
2213     // pointer to any object.
2214     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2215     return true;
2216   }
2217   else
2218     return false;
2219 
2220   QualType FromPointeeType;
2221   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2222     FromPointeeType = FromCPtr->getPointeeType();
2223   else if (const BlockPointerType *FromBlockPtr =
2224            FromType->getAs<BlockPointerType>())
2225     FromPointeeType = FromBlockPtr->getPointeeType();
2226   else
2227     return false;
2228 
2229   // If we have pointers to pointers, recursively check whether this
2230   // is an Objective-C conversion.
2231   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2232       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2233                               IncompatibleObjC)) {
2234     // We always complain about this conversion.
2235     IncompatibleObjC = true;
2236     ConvertedType = Context.getPointerType(ConvertedType);
2237     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2238     return true;
2239   }
2240   // Allow conversion of pointee being objective-c pointer to another one;
2241   // as in I* to id.
2242   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2243       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2244       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2245                               IncompatibleObjC)) {
2246 
2247     ConvertedType = Context.getPointerType(ConvertedType);
2248     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2249     return true;
2250   }
2251 
2252   // If we have pointers to functions or blocks, check whether the only
2253   // differences in the argument and result types are in Objective-C
2254   // pointer conversions. If so, we permit the conversion (but
2255   // complain about it).
2256   const FunctionProtoType *FromFunctionType
2257     = FromPointeeType->getAs<FunctionProtoType>();
2258   const FunctionProtoType *ToFunctionType
2259     = ToPointeeType->getAs<FunctionProtoType>();
2260   if (FromFunctionType && ToFunctionType) {
2261     // If the function types are exactly the same, this isn't an
2262     // Objective-C pointer conversion.
2263     if (Context.getCanonicalType(FromPointeeType)
2264           == Context.getCanonicalType(ToPointeeType))
2265       return false;
2266 
2267     // Perform the quick checks that will tell us whether these
2268     // function types are obviously different.
2269     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2270         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2271         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2272       return false;
2273 
2274     bool HasObjCConversion = false;
2275     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2276         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2277       // Okay, the types match exactly. Nothing to do.
2278     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2279                                        ToFunctionType->getReturnType(),
2280                                        ConvertedType, IncompatibleObjC)) {
2281       // Okay, we have an Objective-C pointer conversion.
2282       HasObjCConversion = true;
2283     } else {
2284       // Function types are too different. Abort.
2285       return false;
2286     }
2287 
2288     // Check argument types.
2289     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2290          ArgIdx != NumArgs; ++ArgIdx) {
2291       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2292       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2293       if (Context.getCanonicalType(FromArgType)
2294             == Context.getCanonicalType(ToArgType)) {
2295         // Okay, the types match exactly. Nothing to do.
2296       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2297                                          ConvertedType, IncompatibleObjC)) {
2298         // Okay, we have an Objective-C pointer conversion.
2299         HasObjCConversion = true;
2300       } else {
2301         // Argument types are too different. Abort.
2302         return false;
2303       }
2304     }
2305 
2306     if (HasObjCConversion) {
2307       // We had an Objective-C conversion. Allow this pointer
2308       // conversion, but complain about it.
2309       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2310       IncompatibleObjC = true;
2311       return true;
2312     }
2313   }
2314 
2315   return false;
2316 }
2317 
2318 /// \brief Determine whether this is an Objective-C writeback conversion,
2319 /// used for parameter passing when performing automatic reference counting.
2320 ///
2321 /// \param FromType The type we're converting form.
2322 ///
2323 /// \param ToType The type we're converting to.
2324 ///
2325 /// \param ConvertedType The type that will be produced after applying
2326 /// this conversion.
2327 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2328                                      QualType &ConvertedType) {
2329   if (!getLangOpts().ObjCAutoRefCount ||
2330       Context.hasSameUnqualifiedType(FromType, ToType))
2331     return false;
2332 
2333   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2334   QualType ToPointee;
2335   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2336     ToPointee = ToPointer->getPointeeType();
2337   else
2338     return false;
2339 
2340   Qualifiers ToQuals = ToPointee.getQualifiers();
2341   if (!ToPointee->isObjCLifetimeType() ||
2342       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2343       !ToQuals.withoutObjCLifetime().empty())
2344     return false;
2345 
2346   // Argument must be a pointer to __strong to __weak.
2347   QualType FromPointee;
2348   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2349     FromPointee = FromPointer->getPointeeType();
2350   else
2351     return false;
2352 
2353   Qualifiers FromQuals = FromPointee.getQualifiers();
2354   if (!FromPointee->isObjCLifetimeType() ||
2355       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2356        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2357     return false;
2358 
2359   // Make sure that we have compatible qualifiers.
2360   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2361   if (!ToQuals.compatiblyIncludes(FromQuals))
2362     return false;
2363 
2364   // Remove qualifiers from the pointee type we're converting from; they
2365   // aren't used in the compatibility check belong, and we'll be adding back
2366   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2367   FromPointee = FromPointee.getUnqualifiedType();
2368 
2369   // The unqualified form of the pointee types must be compatible.
2370   ToPointee = ToPointee.getUnqualifiedType();
2371   bool IncompatibleObjC;
2372   if (Context.typesAreCompatible(FromPointee, ToPointee))
2373     FromPointee = ToPointee;
2374   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2375                                     IncompatibleObjC))
2376     return false;
2377 
2378   /// \brief Construct the type we're converting to, which is a pointer to
2379   /// __autoreleasing pointee.
2380   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2381   ConvertedType = Context.getPointerType(FromPointee);
2382   return true;
2383 }
2384 
2385 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2386                                     QualType& ConvertedType) {
2387   QualType ToPointeeType;
2388   if (const BlockPointerType *ToBlockPtr =
2389         ToType->getAs<BlockPointerType>())
2390     ToPointeeType = ToBlockPtr->getPointeeType();
2391   else
2392     return false;
2393 
2394   QualType FromPointeeType;
2395   if (const BlockPointerType *FromBlockPtr =
2396       FromType->getAs<BlockPointerType>())
2397     FromPointeeType = FromBlockPtr->getPointeeType();
2398   else
2399     return false;
2400   // We have pointer to blocks, check whether the only
2401   // differences in the argument and result types are in Objective-C
2402   // pointer conversions. If so, we permit the conversion.
2403 
2404   const FunctionProtoType *FromFunctionType
2405     = FromPointeeType->getAs<FunctionProtoType>();
2406   const FunctionProtoType *ToFunctionType
2407     = ToPointeeType->getAs<FunctionProtoType>();
2408 
2409   if (!FromFunctionType || !ToFunctionType)
2410     return false;
2411 
2412   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2413     return true;
2414 
2415   // Perform the quick checks that will tell us whether these
2416   // function types are obviously different.
2417   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2418       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2419     return false;
2420 
2421   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2422   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2423   if (FromEInfo != ToEInfo)
2424     return false;
2425 
2426   bool IncompatibleObjC = false;
2427   if (Context.hasSameType(FromFunctionType->getReturnType(),
2428                           ToFunctionType->getReturnType())) {
2429     // Okay, the types match exactly. Nothing to do.
2430   } else {
2431     QualType RHS = FromFunctionType->getReturnType();
2432     QualType LHS = ToFunctionType->getReturnType();
2433     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2434         !RHS.hasQualifiers() && LHS.hasQualifiers())
2435        LHS = LHS.getUnqualifiedType();
2436 
2437      if (Context.hasSameType(RHS,LHS)) {
2438        // OK exact match.
2439      } else if (isObjCPointerConversion(RHS, LHS,
2440                                         ConvertedType, IncompatibleObjC)) {
2441      if (IncompatibleObjC)
2442        return false;
2443      // Okay, we have an Objective-C pointer conversion.
2444      }
2445      else
2446        return false;
2447    }
2448 
2449    // Check argument types.
2450    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2451         ArgIdx != NumArgs; ++ArgIdx) {
2452      IncompatibleObjC = false;
2453      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2454      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2455      if (Context.hasSameType(FromArgType, ToArgType)) {
2456        // Okay, the types match exactly. Nothing to do.
2457      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2458                                         ConvertedType, IncompatibleObjC)) {
2459        if (IncompatibleObjC)
2460          return false;
2461        // Okay, we have an Objective-C pointer conversion.
2462      } else
2463        // Argument types are too different. Abort.
2464        return false;
2465    }
2466    if (LangOpts.ObjCAutoRefCount &&
2467        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2468                                                     ToFunctionType))
2469      return false;
2470 
2471    ConvertedType = ToType;
2472    return true;
2473 }
2474 
2475 enum {
2476   ft_default,
2477   ft_different_class,
2478   ft_parameter_arity,
2479   ft_parameter_mismatch,
2480   ft_return_type,
2481   ft_qualifer_mismatch
2482 };
2483 
2484 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2485 /// function types.  Catches different number of parameter, mismatch in
2486 /// parameter types, and different return types.
2487 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2488                                       QualType FromType, QualType ToType) {
2489   // If either type is not valid, include no extra info.
2490   if (FromType.isNull() || ToType.isNull()) {
2491     PDiag << ft_default;
2492     return;
2493   }
2494 
2495   // Get the function type from the pointers.
2496   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2497     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2498                             *ToMember = ToType->getAs<MemberPointerType>();
2499     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2500       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2501             << QualType(FromMember->getClass(), 0);
2502       return;
2503     }
2504     FromType = FromMember->getPointeeType();
2505     ToType = ToMember->getPointeeType();
2506   }
2507 
2508   if (FromType->isPointerType())
2509     FromType = FromType->getPointeeType();
2510   if (ToType->isPointerType())
2511     ToType = ToType->getPointeeType();
2512 
2513   // Remove references.
2514   FromType = FromType.getNonReferenceType();
2515   ToType = ToType.getNonReferenceType();
2516 
2517   // Don't print extra info for non-specialized template functions.
2518   if (FromType->isInstantiationDependentType() &&
2519       !FromType->getAs<TemplateSpecializationType>()) {
2520     PDiag << ft_default;
2521     return;
2522   }
2523 
2524   // No extra info for same types.
2525   if (Context.hasSameType(FromType, ToType)) {
2526     PDiag << ft_default;
2527     return;
2528   }
2529 
2530   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2531                           *ToFunction = ToType->getAs<FunctionProtoType>();
2532 
2533   // Both types need to be function types.
2534   if (!FromFunction || !ToFunction) {
2535     PDiag << ft_default;
2536     return;
2537   }
2538 
2539   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2540     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2541           << FromFunction->getNumParams();
2542     return;
2543   }
2544 
2545   // Handle different parameter types.
2546   unsigned ArgPos;
2547   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2548     PDiag << ft_parameter_mismatch << ArgPos + 1
2549           << ToFunction->getParamType(ArgPos)
2550           << FromFunction->getParamType(ArgPos);
2551     return;
2552   }
2553 
2554   // Handle different return type.
2555   if (!Context.hasSameType(FromFunction->getReturnType(),
2556                            ToFunction->getReturnType())) {
2557     PDiag << ft_return_type << ToFunction->getReturnType()
2558           << FromFunction->getReturnType();
2559     return;
2560   }
2561 
2562   unsigned FromQuals = FromFunction->getTypeQuals(),
2563            ToQuals = ToFunction->getTypeQuals();
2564   if (FromQuals != ToQuals) {
2565     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2566     return;
2567   }
2568 
2569   // Unable to find a difference, so add no extra info.
2570   PDiag << ft_default;
2571 }
2572 
2573 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2574 /// for equality of their argument types. Caller has already checked that
2575 /// they have same number of arguments.  If the parameters are different,
2576 /// ArgPos will have the parameter index of the first different parameter.
2577 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2578                                       const FunctionProtoType *NewType,
2579                                       unsigned *ArgPos) {
2580   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2581                                               N = NewType->param_type_begin(),
2582                                               E = OldType->param_type_end();
2583        O && (O != E); ++O, ++N) {
2584     if (!Context.hasSameType(O->getUnqualifiedType(),
2585                              N->getUnqualifiedType())) {
2586       if (ArgPos)
2587         *ArgPos = O - OldType->param_type_begin();
2588       return false;
2589     }
2590   }
2591   return true;
2592 }
2593 
2594 /// CheckPointerConversion - Check the pointer conversion from the
2595 /// expression From to the type ToType. This routine checks for
2596 /// ambiguous or inaccessible derived-to-base pointer
2597 /// conversions for which IsPointerConversion has already returned
2598 /// true. It returns true and produces a diagnostic if there was an
2599 /// error, or returns false otherwise.
2600 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2601                                   CastKind &Kind,
2602                                   CXXCastPath& BasePath,
2603                                   bool IgnoreBaseAccess) {
2604   QualType FromType = From->getType();
2605   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2606 
2607   Kind = CK_BitCast;
2608 
2609   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2610       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2611       Expr::NPCK_ZeroExpression) {
2612     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2613       DiagRuntimeBehavior(From->getExprLoc(), From,
2614                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2615                             << ToType << From->getSourceRange());
2616     else if (!isUnevaluatedContext())
2617       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2618         << ToType << From->getSourceRange();
2619   }
2620   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2621     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2622       QualType FromPointeeType = FromPtrType->getPointeeType(),
2623                ToPointeeType   = ToPtrType->getPointeeType();
2624 
2625       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2626           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2627         // We must have a derived-to-base conversion. Check an
2628         // ambiguous or inaccessible conversion.
2629         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2630                                          From->getExprLoc(),
2631                                          From->getSourceRange(), &BasePath,
2632                                          IgnoreBaseAccess))
2633           return true;
2634 
2635         // The conversion was successful.
2636         Kind = CK_DerivedToBase;
2637       }
2638     }
2639   } else if (const ObjCObjectPointerType *ToPtrType =
2640                ToType->getAs<ObjCObjectPointerType>()) {
2641     if (const ObjCObjectPointerType *FromPtrType =
2642           FromType->getAs<ObjCObjectPointerType>()) {
2643       // Objective-C++ conversions are always okay.
2644       // FIXME: We should have a different class of conversions for the
2645       // Objective-C++ implicit conversions.
2646       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2647         return false;
2648     } else if (FromType->isBlockPointerType()) {
2649       Kind = CK_BlockPointerToObjCPointerCast;
2650     } else {
2651       Kind = CK_CPointerToObjCPointerCast;
2652     }
2653   } else if (ToType->isBlockPointerType()) {
2654     if (!FromType->isBlockPointerType())
2655       Kind = CK_AnyPointerToBlockPointerCast;
2656   }
2657 
2658   // We shouldn't fall into this case unless it's valid for other
2659   // reasons.
2660   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2661     Kind = CK_NullToPointer;
2662 
2663   return false;
2664 }
2665 
2666 /// IsMemberPointerConversion - Determines whether the conversion of the
2667 /// expression From, which has the (possibly adjusted) type FromType, can be
2668 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2669 /// If so, returns true and places the converted type (that might differ from
2670 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2671 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2672                                      QualType ToType,
2673                                      bool InOverloadResolution,
2674                                      QualType &ConvertedType) {
2675   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2676   if (!ToTypePtr)
2677     return false;
2678 
2679   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2680   if (From->isNullPointerConstant(Context,
2681                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2682                                         : Expr::NPC_ValueDependentIsNull)) {
2683     ConvertedType = ToType;
2684     return true;
2685   }
2686 
2687   // Otherwise, both types have to be member pointers.
2688   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2689   if (!FromTypePtr)
2690     return false;
2691 
2692   // A pointer to member of B can be converted to a pointer to member of D,
2693   // where D is derived from B (C++ 4.11p2).
2694   QualType FromClass(FromTypePtr->getClass(), 0);
2695   QualType ToClass(ToTypePtr->getClass(), 0);
2696 
2697   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2698       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2699       IsDerivedFrom(ToClass, FromClass)) {
2700     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2701                                                  ToClass.getTypePtr());
2702     return true;
2703   }
2704 
2705   return false;
2706 }
2707 
2708 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2709 /// expression From to the type ToType. This routine checks for ambiguous or
2710 /// virtual or inaccessible base-to-derived member pointer conversions
2711 /// for which IsMemberPointerConversion has already returned true. It returns
2712 /// true and produces a diagnostic if there was an error, or returns false
2713 /// otherwise.
2714 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2715                                         CastKind &Kind,
2716                                         CXXCastPath &BasePath,
2717                                         bool IgnoreBaseAccess) {
2718   QualType FromType = From->getType();
2719   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2720   if (!FromPtrType) {
2721     // This must be a null pointer to member pointer conversion
2722     assert(From->isNullPointerConstant(Context,
2723                                        Expr::NPC_ValueDependentIsNull) &&
2724            "Expr must be null pointer constant!");
2725     Kind = CK_NullToMemberPointer;
2726     return false;
2727   }
2728 
2729   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2730   assert(ToPtrType && "No member pointer cast has a target type "
2731                       "that is not a member pointer.");
2732 
2733   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2734   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2735 
2736   // FIXME: What about dependent types?
2737   assert(FromClass->isRecordType() && "Pointer into non-class.");
2738   assert(ToClass->isRecordType() && "Pointer into non-class.");
2739 
2740   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2741                      /*DetectVirtual=*/true);
2742   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2743   assert(DerivationOkay &&
2744          "Should not have been called if derivation isn't OK.");
2745   (void)DerivationOkay;
2746 
2747   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2748                                   getUnqualifiedType())) {
2749     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2750     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2751       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2752     return true;
2753   }
2754 
2755   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2756     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2757       << FromClass << ToClass << QualType(VBase, 0)
2758       << From->getSourceRange();
2759     return true;
2760   }
2761 
2762   if (!IgnoreBaseAccess)
2763     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2764                          Paths.front(),
2765                          diag::err_downcast_from_inaccessible_base);
2766 
2767   // Must be a base to derived member conversion.
2768   BuildBasePathArray(Paths, BasePath);
2769   Kind = CK_BaseToDerivedMemberPointer;
2770   return false;
2771 }
2772 
2773 /// Determine whether the lifetime conversion between the two given
2774 /// qualifiers sets is nontrivial.
2775 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2776                                                Qualifiers ToQuals) {
2777   // Converting anything to const __unsafe_unretained is trivial.
2778   if (ToQuals.hasConst() &&
2779       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2780     return false;
2781 
2782   return true;
2783 }
2784 
2785 /// IsQualificationConversion - Determines whether the conversion from
2786 /// an rvalue of type FromType to ToType is a qualification conversion
2787 /// (C++ 4.4).
2788 ///
2789 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2790 /// when the qualification conversion involves a change in the Objective-C
2791 /// object lifetime.
2792 bool
2793 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2794                                 bool CStyle, bool &ObjCLifetimeConversion) {
2795   FromType = Context.getCanonicalType(FromType);
2796   ToType = Context.getCanonicalType(ToType);
2797   ObjCLifetimeConversion = false;
2798 
2799   // If FromType and ToType are the same type, this is not a
2800   // qualification conversion.
2801   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2802     return false;
2803 
2804   // (C++ 4.4p4):
2805   //   A conversion can add cv-qualifiers at levels other than the first
2806   //   in multi-level pointers, subject to the following rules: [...]
2807   bool PreviousToQualsIncludeConst = true;
2808   bool UnwrappedAnyPointer = false;
2809   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2810     // Within each iteration of the loop, we check the qualifiers to
2811     // determine if this still looks like a qualification
2812     // conversion. Then, if all is well, we unwrap one more level of
2813     // pointers or pointers-to-members and do it all again
2814     // until there are no more pointers or pointers-to-members left to
2815     // unwrap.
2816     UnwrappedAnyPointer = true;
2817 
2818     Qualifiers FromQuals = FromType.getQualifiers();
2819     Qualifiers ToQuals = ToType.getQualifiers();
2820 
2821     // Objective-C ARC:
2822     //   Check Objective-C lifetime conversions.
2823     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2824         UnwrappedAnyPointer) {
2825       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2826         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2827           ObjCLifetimeConversion = true;
2828         FromQuals.removeObjCLifetime();
2829         ToQuals.removeObjCLifetime();
2830       } else {
2831         // Qualification conversions cannot cast between different
2832         // Objective-C lifetime qualifiers.
2833         return false;
2834       }
2835     }
2836 
2837     // Allow addition/removal of GC attributes but not changing GC attributes.
2838     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2839         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2840       FromQuals.removeObjCGCAttr();
2841       ToQuals.removeObjCGCAttr();
2842     }
2843 
2844     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2845     //      2,j, and similarly for volatile.
2846     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2847       return false;
2848 
2849     //   -- if the cv 1,j and cv 2,j are different, then const is in
2850     //      every cv for 0 < k < j.
2851     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2852         && !PreviousToQualsIncludeConst)
2853       return false;
2854 
2855     // Keep track of whether all prior cv-qualifiers in the "to" type
2856     // include const.
2857     PreviousToQualsIncludeConst
2858       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2859   }
2860 
2861   // We are left with FromType and ToType being the pointee types
2862   // after unwrapping the original FromType and ToType the same number
2863   // of types. If we unwrapped any pointers, and if FromType and
2864   // ToType have the same unqualified type (since we checked
2865   // qualifiers above), then this is a qualification conversion.
2866   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2867 }
2868 
2869 /// \brief - Determine whether this is a conversion from a scalar type to an
2870 /// atomic type.
2871 ///
2872 /// If successful, updates \c SCS's second and third steps in the conversion
2873 /// sequence to finish the conversion.
2874 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2875                                 bool InOverloadResolution,
2876                                 StandardConversionSequence &SCS,
2877                                 bool CStyle) {
2878   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2879   if (!ToAtomic)
2880     return false;
2881 
2882   StandardConversionSequence InnerSCS;
2883   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2884                             InOverloadResolution, InnerSCS,
2885                             CStyle, /*AllowObjCWritebackConversion=*/false))
2886     return false;
2887 
2888   SCS.Second = InnerSCS.Second;
2889   SCS.setToType(1, InnerSCS.getToType(1));
2890   SCS.Third = InnerSCS.Third;
2891   SCS.QualificationIncludesObjCLifetime
2892     = InnerSCS.QualificationIncludesObjCLifetime;
2893   SCS.setToType(2, InnerSCS.getToType(2));
2894   return true;
2895 }
2896 
2897 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2898                                               CXXConstructorDecl *Constructor,
2899                                               QualType Type) {
2900   const FunctionProtoType *CtorType =
2901       Constructor->getType()->getAs<FunctionProtoType>();
2902   if (CtorType->getNumParams() > 0) {
2903     QualType FirstArg = CtorType->getParamType(0);
2904     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2905       return true;
2906   }
2907   return false;
2908 }
2909 
2910 static OverloadingResult
2911 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2912                                        CXXRecordDecl *To,
2913                                        UserDefinedConversionSequence &User,
2914                                        OverloadCandidateSet &CandidateSet,
2915                                        bool AllowExplicit) {
2916   DeclContext::lookup_result R = S.LookupConstructors(To);
2917   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2918        Con != ConEnd; ++Con) {
2919     NamedDecl *D = *Con;
2920     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2921 
2922     // Find the constructor (which may be a template).
2923     CXXConstructorDecl *Constructor = nullptr;
2924     FunctionTemplateDecl *ConstructorTmpl
2925       = dyn_cast<FunctionTemplateDecl>(D);
2926     if (ConstructorTmpl)
2927       Constructor
2928         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2929     else
2930       Constructor = cast<CXXConstructorDecl>(D);
2931 
2932     bool Usable = !Constructor->isInvalidDecl() &&
2933                   S.isInitListConstructor(Constructor) &&
2934                   (AllowExplicit || !Constructor->isExplicit());
2935     if (Usable) {
2936       // If the first argument is (a reference to) the target type,
2937       // suppress conversions.
2938       bool SuppressUserConversions =
2939           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2940       if (ConstructorTmpl)
2941         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2942                                        /*ExplicitArgs*/ nullptr,
2943                                        From, CandidateSet,
2944                                        SuppressUserConversions);
2945       else
2946         S.AddOverloadCandidate(Constructor, FoundDecl,
2947                                From, CandidateSet,
2948                                SuppressUserConversions);
2949     }
2950   }
2951 
2952   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2953 
2954   OverloadCandidateSet::iterator Best;
2955   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2956   case OR_Success: {
2957     // Record the standard conversion we used and the conversion function.
2958     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2959     QualType ThisType = Constructor->getThisType(S.Context);
2960     // Initializer lists don't have conversions as such.
2961     User.Before.setAsIdentityConversion();
2962     User.HadMultipleCandidates = HadMultipleCandidates;
2963     User.ConversionFunction = Constructor;
2964     User.FoundConversionFunction = Best->FoundDecl;
2965     User.After.setAsIdentityConversion();
2966     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2967     User.After.setAllToTypes(ToType);
2968     return OR_Success;
2969   }
2970 
2971   case OR_No_Viable_Function:
2972     return OR_No_Viable_Function;
2973   case OR_Deleted:
2974     return OR_Deleted;
2975   case OR_Ambiguous:
2976     return OR_Ambiguous;
2977   }
2978 
2979   llvm_unreachable("Invalid OverloadResult!");
2980 }
2981 
2982 /// Determines whether there is a user-defined conversion sequence
2983 /// (C++ [over.ics.user]) that converts expression From to the type
2984 /// ToType. If such a conversion exists, User will contain the
2985 /// user-defined conversion sequence that performs such a conversion
2986 /// and this routine will return true. Otherwise, this routine returns
2987 /// false and User is unspecified.
2988 ///
2989 /// \param AllowExplicit  true if the conversion should consider C++0x
2990 /// "explicit" conversion functions as well as non-explicit conversion
2991 /// functions (C++0x [class.conv.fct]p2).
2992 ///
2993 /// \param AllowObjCConversionOnExplicit true if the conversion should
2994 /// allow an extra Objective-C pointer conversion on uses of explicit
2995 /// constructors. Requires \c AllowExplicit to also be set.
2996 static OverloadingResult
2997 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2998                         UserDefinedConversionSequence &User,
2999                         OverloadCandidateSet &CandidateSet,
3000                         bool AllowExplicit,
3001                         bool AllowObjCConversionOnExplicit) {
3002   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3003 
3004   // Whether we will only visit constructors.
3005   bool ConstructorsOnly = false;
3006 
3007   // If the type we are conversion to is a class type, enumerate its
3008   // constructors.
3009   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3010     // C++ [over.match.ctor]p1:
3011     //   When objects of class type are direct-initialized (8.5), or
3012     //   copy-initialized from an expression of the same or a
3013     //   derived class type (8.5), overload resolution selects the
3014     //   constructor. [...] For copy-initialization, the candidate
3015     //   functions are all the converting constructors (12.3.1) of
3016     //   that class. The argument list is the expression-list within
3017     //   the parentheses of the initializer.
3018     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3019         (From->getType()->getAs<RecordType>() &&
3020          S.IsDerivedFrom(From->getType(), ToType)))
3021       ConstructorsOnly = true;
3022 
3023     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3024     // RequireCompleteType may have returned true due to some invalid decl
3025     // during template instantiation, but ToType may be complete enough now
3026     // to try to recover.
3027     if (ToType->isIncompleteType()) {
3028       // We're not going to find any constructors.
3029     } else if (CXXRecordDecl *ToRecordDecl
3030                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3031 
3032       Expr **Args = &From;
3033       unsigned NumArgs = 1;
3034       bool ListInitializing = false;
3035       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3036         // But first, see if there is an init-list-constructor that will work.
3037         OverloadingResult Result = IsInitializerListConstructorConversion(
3038             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3039         if (Result != OR_No_Viable_Function)
3040           return Result;
3041         // Never mind.
3042         CandidateSet.clear();
3043 
3044         // If we're list-initializing, we pass the individual elements as
3045         // arguments, not the entire list.
3046         Args = InitList->getInits();
3047         NumArgs = InitList->getNumInits();
3048         ListInitializing = true;
3049       }
3050 
3051       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3052       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3053            Con != ConEnd; ++Con) {
3054         NamedDecl *D = *Con;
3055         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3056 
3057         // Find the constructor (which may be a template).
3058         CXXConstructorDecl *Constructor = nullptr;
3059         FunctionTemplateDecl *ConstructorTmpl
3060           = dyn_cast<FunctionTemplateDecl>(D);
3061         if (ConstructorTmpl)
3062           Constructor
3063             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3064         else
3065           Constructor = cast<CXXConstructorDecl>(D);
3066 
3067         bool Usable = !Constructor->isInvalidDecl();
3068         if (ListInitializing)
3069           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3070         else
3071           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3072         if (Usable) {
3073           bool SuppressUserConversions = !ConstructorsOnly;
3074           if (SuppressUserConversions && ListInitializing) {
3075             SuppressUserConversions = false;
3076             if (NumArgs == 1) {
3077               // If the first argument is (a reference to) the target type,
3078               // suppress conversions.
3079               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3080                                                 S.Context, Constructor, ToType);
3081             }
3082           }
3083           if (ConstructorTmpl)
3084             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3085                                            /*ExplicitArgs*/ nullptr,
3086                                            llvm::makeArrayRef(Args, NumArgs),
3087                                            CandidateSet, SuppressUserConversions);
3088           else
3089             // Allow one user-defined conversion when user specifies a
3090             // From->ToType conversion via an static cast (c-style, etc).
3091             S.AddOverloadCandidate(Constructor, FoundDecl,
3092                                    llvm::makeArrayRef(Args, NumArgs),
3093                                    CandidateSet, SuppressUserConversions);
3094         }
3095       }
3096     }
3097   }
3098 
3099   // Enumerate conversion functions, if we're allowed to.
3100   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3101   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3102     // No conversion functions from incomplete types.
3103   } else if (const RecordType *FromRecordType
3104                                    = From->getType()->getAs<RecordType>()) {
3105     if (CXXRecordDecl *FromRecordDecl
3106          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3107       // Add all of the conversion functions as candidates.
3108       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3109       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3110         DeclAccessPair FoundDecl = I.getPair();
3111         NamedDecl *D = FoundDecl.getDecl();
3112         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3113         if (isa<UsingShadowDecl>(D))
3114           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3115 
3116         CXXConversionDecl *Conv;
3117         FunctionTemplateDecl *ConvTemplate;
3118         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3119           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3120         else
3121           Conv = cast<CXXConversionDecl>(D);
3122 
3123         if (AllowExplicit || !Conv->isExplicit()) {
3124           if (ConvTemplate)
3125             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3126                                              ActingContext, From, ToType,
3127                                              CandidateSet,
3128                                              AllowObjCConversionOnExplicit);
3129           else
3130             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3131                                      From, ToType, CandidateSet,
3132                                      AllowObjCConversionOnExplicit);
3133         }
3134       }
3135     }
3136   }
3137 
3138   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3139 
3140   OverloadCandidateSet::iterator Best;
3141   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3142                                                         Best, true)) {
3143   case OR_Success:
3144   case OR_Deleted:
3145     // Record the standard conversion we used and the conversion function.
3146     if (CXXConstructorDecl *Constructor
3147           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3148       // C++ [over.ics.user]p1:
3149       //   If the user-defined conversion is specified by a
3150       //   constructor (12.3.1), the initial standard conversion
3151       //   sequence converts the source type to the type required by
3152       //   the argument of the constructor.
3153       //
3154       QualType ThisType = Constructor->getThisType(S.Context);
3155       if (isa<InitListExpr>(From)) {
3156         // Initializer lists don't have conversions as such.
3157         User.Before.setAsIdentityConversion();
3158       } else {
3159         if (Best->Conversions[0].isEllipsis())
3160           User.EllipsisConversion = true;
3161         else {
3162           User.Before = Best->Conversions[0].Standard;
3163           User.EllipsisConversion = false;
3164         }
3165       }
3166       User.HadMultipleCandidates = HadMultipleCandidates;
3167       User.ConversionFunction = Constructor;
3168       User.FoundConversionFunction = Best->FoundDecl;
3169       User.After.setAsIdentityConversion();
3170       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3171       User.After.setAllToTypes(ToType);
3172       return Result;
3173     }
3174     if (CXXConversionDecl *Conversion
3175                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3176       // C++ [over.ics.user]p1:
3177       //
3178       //   [...] If the user-defined conversion is specified by a
3179       //   conversion function (12.3.2), the initial standard
3180       //   conversion sequence converts the source type to the
3181       //   implicit object parameter of the conversion function.
3182       User.Before = Best->Conversions[0].Standard;
3183       User.HadMultipleCandidates = HadMultipleCandidates;
3184       User.ConversionFunction = Conversion;
3185       User.FoundConversionFunction = Best->FoundDecl;
3186       User.EllipsisConversion = false;
3187 
3188       // C++ [over.ics.user]p2:
3189       //   The second standard conversion sequence converts the
3190       //   result of the user-defined conversion to the target type
3191       //   for the sequence. Since an implicit conversion sequence
3192       //   is an initialization, the special rules for
3193       //   initialization by user-defined conversion apply when
3194       //   selecting the best user-defined conversion for a
3195       //   user-defined conversion sequence (see 13.3.3 and
3196       //   13.3.3.1).
3197       User.After = Best->FinalConversion;
3198       return Result;
3199     }
3200     llvm_unreachable("Not a constructor or conversion function?");
3201 
3202   case OR_No_Viable_Function:
3203     return OR_No_Viable_Function;
3204 
3205   case OR_Ambiguous:
3206     return OR_Ambiguous;
3207   }
3208 
3209   llvm_unreachable("Invalid OverloadResult!");
3210 }
3211 
3212 bool
3213 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3214   ImplicitConversionSequence ICS;
3215   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3216                                     OverloadCandidateSet::CSK_Normal);
3217   OverloadingResult OvResult =
3218     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3219                             CandidateSet, false, false);
3220   if (OvResult == OR_Ambiguous)
3221     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3222         << From->getType() << ToType << From->getSourceRange();
3223   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3224     if (!RequireCompleteType(From->getLocStart(), ToType,
3225                              diag::err_typecheck_nonviable_condition_incomplete,
3226                              From->getType(), From->getSourceRange()))
3227       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3228           << From->getType() << From->getSourceRange() << ToType;
3229   } else
3230     return false;
3231   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3232   return true;
3233 }
3234 
3235 /// \brief Compare the user-defined conversion functions or constructors
3236 /// of two user-defined conversion sequences to determine whether any ordering
3237 /// is possible.
3238 static ImplicitConversionSequence::CompareKind
3239 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3240                            FunctionDecl *Function2) {
3241   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3242     return ImplicitConversionSequence::Indistinguishable;
3243 
3244   // Objective-C++:
3245   //   If both conversion functions are implicitly-declared conversions from
3246   //   a lambda closure type to a function pointer and a block pointer,
3247   //   respectively, always prefer the conversion to a function pointer,
3248   //   because the function pointer is more lightweight and is more likely
3249   //   to keep code working.
3250   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3251   if (!Conv1)
3252     return ImplicitConversionSequence::Indistinguishable;
3253 
3254   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3255   if (!Conv2)
3256     return ImplicitConversionSequence::Indistinguishable;
3257 
3258   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3259     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3260     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3261     if (Block1 != Block2)
3262       return Block1 ? ImplicitConversionSequence::Worse
3263                     : ImplicitConversionSequence::Better;
3264   }
3265 
3266   return ImplicitConversionSequence::Indistinguishable;
3267 }
3268 
3269 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3270     const ImplicitConversionSequence &ICS) {
3271   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3272          (ICS.isUserDefined() &&
3273           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3274 }
3275 
3276 /// CompareImplicitConversionSequences - Compare two implicit
3277 /// conversion sequences to determine whether one is better than the
3278 /// other or if they are indistinguishable (C++ 13.3.3.2).
3279 static ImplicitConversionSequence::CompareKind
3280 CompareImplicitConversionSequences(Sema &S,
3281                                    const ImplicitConversionSequence& ICS1,
3282                                    const ImplicitConversionSequence& ICS2)
3283 {
3284   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3285   // conversion sequences (as defined in 13.3.3.1)
3286   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3287   //      conversion sequence than a user-defined conversion sequence or
3288   //      an ellipsis conversion sequence, and
3289   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3290   //      conversion sequence than an ellipsis conversion sequence
3291   //      (13.3.3.1.3).
3292   //
3293   // C++0x [over.best.ics]p10:
3294   //   For the purpose of ranking implicit conversion sequences as
3295   //   described in 13.3.3.2, the ambiguous conversion sequence is
3296   //   treated as a user-defined sequence that is indistinguishable
3297   //   from any other user-defined conversion sequence.
3298 
3299   // String literal to 'char *' conversion has been deprecated in C++03. It has
3300   // been removed from C++11. We still accept this conversion, if it happens at
3301   // the best viable function. Otherwise, this conversion is considered worse
3302   // than ellipsis conversion. Consider this as an extension; this is not in the
3303   // standard. For example:
3304   //
3305   // int &f(...);    // #1
3306   // void f(char*);  // #2
3307   // void g() { int &r = f("foo"); }
3308   //
3309   // In C++03, we pick #2 as the best viable function.
3310   // In C++11, we pick #1 as the best viable function, because ellipsis
3311   // conversion is better than string-literal to char* conversion (since there
3312   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3313   // convert arguments, #2 would be the best viable function in C++11.
3314   // If the best viable function has this conversion, a warning will be issued
3315   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3316 
3317   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3318       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3319       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3320     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3321                ? ImplicitConversionSequence::Worse
3322                : ImplicitConversionSequence::Better;
3323 
3324   if (ICS1.getKindRank() < ICS2.getKindRank())
3325     return ImplicitConversionSequence::Better;
3326   if (ICS2.getKindRank() < ICS1.getKindRank())
3327     return ImplicitConversionSequence::Worse;
3328 
3329   // The following checks require both conversion sequences to be of
3330   // the same kind.
3331   if (ICS1.getKind() != ICS2.getKind())
3332     return ImplicitConversionSequence::Indistinguishable;
3333 
3334   ImplicitConversionSequence::CompareKind Result =
3335       ImplicitConversionSequence::Indistinguishable;
3336 
3337   // Two implicit conversion sequences of the same form are
3338   // indistinguishable conversion sequences unless one of the
3339   // following rules apply: (C++ 13.3.3.2p3):
3340 
3341   // List-initialization sequence L1 is a better conversion sequence than
3342   // list-initialization sequence L2 if:
3343   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3344   //   if not that,
3345   // - L1 converts to type “array of N1 T”, L2 converts to type “array of N2 T”,
3346   //   and N1 is smaller than N2.,
3347   // even if one of the other rules in this paragraph would otherwise apply.
3348   if (!ICS1.isBad()) {
3349     if (ICS1.isStdInitializerListElement() &&
3350         !ICS2.isStdInitializerListElement())
3351       return ImplicitConversionSequence::Better;
3352     if (!ICS1.isStdInitializerListElement() &&
3353         ICS2.isStdInitializerListElement())
3354       return ImplicitConversionSequence::Worse;
3355   }
3356 
3357   if (ICS1.isStandard())
3358     // Standard conversion sequence S1 is a better conversion sequence than
3359     // standard conversion sequence S2 if [...]
3360     Result = CompareStandardConversionSequences(S,
3361                                                 ICS1.Standard, ICS2.Standard);
3362   else if (ICS1.isUserDefined()) {
3363     // User-defined conversion sequence U1 is a better conversion
3364     // sequence than another user-defined conversion sequence U2 if
3365     // they contain the same user-defined conversion function or
3366     // constructor and if the second standard conversion sequence of
3367     // U1 is better than the second standard conversion sequence of
3368     // U2 (C++ 13.3.3.2p3).
3369     if (ICS1.UserDefined.ConversionFunction ==
3370           ICS2.UserDefined.ConversionFunction)
3371       Result = CompareStandardConversionSequences(S,
3372                                                   ICS1.UserDefined.After,
3373                                                   ICS2.UserDefined.After);
3374     else
3375       Result = compareConversionFunctions(S,
3376                                           ICS1.UserDefined.ConversionFunction,
3377                                           ICS2.UserDefined.ConversionFunction);
3378   }
3379 
3380   return Result;
3381 }
3382 
3383 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3384   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3385     Qualifiers Quals;
3386     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3387     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3388   }
3389 
3390   return Context.hasSameUnqualifiedType(T1, T2);
3391 }
3392 
3393 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3394 // determine if one is a proper subset of the other.
3395 static ImplicitConversionSequence::CompareKind
3396 compareStandardConversionSubsets(ASTContext &Context,
3397                                  const StandardConversionSequence& SCS1,
3398                                  const StandardConversionSequence& SCS2) {
3399   ImplicitConversionSequence::CompareKind Result
3400     = ImplicitConversionSequence::Indistinguishable;
3401 
3402   // the identity conversion sequence is considered to be a subsequence of
3403   // any non-identity conversion sequence
3404   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3405     return ImplicitConversionSequence::Better;
3406   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3407     return ImplicitConversionSequence::Worse;
3408 
3409   if (SCS1.Second != SCS2.Second) {
3410     if (SCS1.Second == ICK_Identity)
3411       Result = ImplicitConversionSequence::Better;
3412     else if (SCS2.Second == ICK_Identity)
3413       Result = ImplicitConversionSequence::Worse;
3414     else
3415       return ImplicitConversionSequence::Indistinguishable;
3416   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3417     return ImplicitConversionSequence::Indistinguishable;
3418 
3419   if (SCS1.Third == SCS2.Third) {
3420     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3421                              : ImplicitConversionSequence::Indistinguishable;
3422   }
3423 
3424   if (SCS1.Third == ICK_Identity)
3425     return Result == ImplicitConversionSequence::Worse
3426              ? ImplicitConversionSequence::Indistinguishable
3427              : ImplicitConversionSequence::Better;
3428 
3429   if (SCS2.Third == ICK_Identity)
3430     return Result == ImplicitConversionSequence::Better
3431              ? ImplicitConversionSequence::Indistinguishable
3432              : ImplicitConversionSequence::Worse;
3433 
3434   return ImplicitConversionSequence::Indistinguishable;
3435 }
3436 
3437 /// \brief Determine whether one of the given reference bindings is better
3438 /// than the other based on what kind of bindings they are.
3439 static bool
3440 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3441                              const StandardConversionSequence &SCS2) {
3442   // C++0x [over.ics.rank]p3b4:
3443   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3444   //      implicit object parameter of a non-static member function declared
3445   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3446   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3447   //      lvalue reference to a function lvalue and S2 binds an rvalue
3448   //      reference*.
3449   //
3450   // FIXME: Rvalue references. We're going rogue with the above edits,
3451   // because the semantics in the current C++0x working paper (N3225 at the
3452   // time of this writing) break the standard definition of std::forward
3453   // and std::reference_wrapper when dealing with references to functions.
3454   // Proposed wording changes submitted to CWG for consideration.
3455   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3456       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3457     return false;
3458 
3459   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3460           SCS2.IsLvalueReference) ||
3461          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3462           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3463 }
3464 
3465 /// CompareStandardConversionSequences - Compare two standard
3466 /// conversion sequences to determine whether one is better than the
3467 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3468 static ImplicitConversionSequence::CompareKind
3469 CompareStandardConversionSequences(Sema &S,
3470                                    const StandardConversionSequence& SCS1,
3471                                    const StandardConversionSequence& SCS2)
3472 {
3473   // Standard conversion sequence S1 is a better conversion sequence
3474   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3475 
3476   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3477   //     sequences in the canonical form defined by 13.3.3.1.1,
3478   //     excluding any Lvalue Transformation; the identity conversion
3479   //     sequence is considered to be a subsequence of any
3480   //     non-identity conversion sequence) or, if not that,
3481   if (ImplicitConversionSequence::CompareKind CK
3482         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3483     return CK;
3484 
3485   //  -- the rank of S1 is better than the rank of S2 (by the rules
3486   //     defined below), or, if not that,
3487   ImplicitConversionRank Rank1 = SCS1.getRank();
3488   ImplicitConversionRank Rank2 = SCS2.getRank();
3489   if (Rank1 < Rank2)
3490     return ImplicitConversionSequence::Better;
3491   else if (Rank2 < Rank1)
3492     return ImplicitConversionSequence::Worse;
3493 
3494   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3495   // are indistinguishable unless one of the following rules
3496   // applies:
3497 
3498   //   A conversion that is not a conversion of a pointer, or
3499   //   pointer to member, to bool is better than another conversion
3500   //   that is such a conversion.
3501   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3502     return SCS2.isPointerConversionToBool()
3503              ? ImplicitConversionSequence::Better
3504              : ImplicitConversionSequence::Worse;
3505 
3506   // C++ [over.ics.rank]p4b2:
3507   //
3508   //   If class B is derived directly or indirectly from class A,
3509   //   conversion of B* to A* is better than conversion of B* to
3510   //   void*, and conversion of A* to void* is better than conversion
3511   //   of B* to void*.
3512   bool SCS1ConvertsToVoid
3513     = SCS1.isPointerConversionToVoidPointer(S.Context);
3514   bool SCS2ConvertsToVoid
3515     = SCS2.isPointerConversionToVoidPointer(S.Context);
3516   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3517     // Exactly one of the conversion sequences is a conversion to
3518     // a void pointer; it's the worse conversion.
3519     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3520                               : ImplicitConversionSequence::Worse;
3521   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3522     // Neither conversion sequence converts to a void pointer; compare
3523     // their derived-to-base conversions.
3524     if (ImplicitConversionSequence::CompareKind DerivedCK
3525           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3526       return DerivedCK;
3527   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3528              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3529     // Both conversion sequences are conversions to void
3530     // pointers. Compare the source types to determine if there's an
3531     // inheritance relationship in their sources.
3532     QualType FromType1 = SCS1.getFromType();
3533     QualType FromType2 = SCS2.getFromType();
3534 
3535     // Adjust the types we're converting from via the array-to-pointer
3536     // conversion, if we need to.
3537     if (SCS1.First == ICK_Array_To_Pointer)
3538       FromType1 = S.Context.getArrayDecayedType(FromType1);
3539     if (SCS2.First == ICK_Array_To_Pointer)
3540       FromType2 = S.Context.getArrayDecayedType(FromType2);
3541 
3542     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3543     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3544 
3545     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3546       return ImplicitConversionSequence::Better;
3547     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3548       return ImplicitConversionSequence::Worse;
3549 
3550     // Objective-C++: If one interface is more specific than the
3551     // other, it is the better one.
3552     const ObjCObjectPointerType* FromObjCPtr1
3553       = FromType1->getAs<ObjCObjectPointerType>();
3554     const ObjCObjectPointerType* FromObjCPtr2
3555       = FromType2->getAs<ObjCObjectPointerType>();
3556     if (FromObjCPtr1 && FromObjCPtr2) {
3557       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3558                                                           FromObjCPtr2);
3559       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3560                                                            FromObjCPtr1);
3561       if (AssignLeft != AssignRight) {
3562         return AssignLeft? ImplicitConversionSequence::Better
3563                          : ImplicitConversionSequence::Worse;
3564       }
3565     }
3566   }
3567 
3568   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3569   // bullet 3).
3570   if (ImplicitConversionSequence::CompareKind QualCK
3571         = CompareQualificationConversions(S, SCS1, SCS2))
3572     return QualCK;
3573 
3574   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3575     // Check for a better reference binding based on the kind of bindings.
3576     if (isBetterReferenceBindingKind(SCS1, SCS2))
3577       return ImplicitConversionSequence::Better;
3578     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3579       return ImplicitConversionSequence::Worse;
3580 
3581     // C++ [over.ics.rank]p3b4:
3582     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3583     //      which the references refer are the same type except for
3584     //      top-level cv-qualifiers, and the type to which the reference
3585     //      initialized by S2 refers is more cv-qualified than the type
3586     //      to which the reference initialized by S1 refers.
3587     QualType T1 = SCS1.getToType(2);
3588     QualType T2 = SCS2.getToType(2);
3589     T1 = S.Context.getCanonicalType(T1);
3590     T2 = S.Context.getCanonicalType(T2);
3591     Qualifiers T1Quals, T2Quals;
3592     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3593     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3594     if (UnqualT1 == UnqualT2) {
3595       // Objective-C++ ARC: If the references refer to objects with different
3596       // lifetimes, prefer bindings that don't change lifetime.
3597       if (SCS1.ObjCLifetimeConversionBinding !=
3598                                           SCS2.ObjCLifetimeConversionBinding) {
3599         return SCS1.ObjCLifetimeConversionBinding
3600                                            ? ImplicitConversionSequence::Worse
3601                                            : ImplicitConversionSequence::Better;
3602       }
3603 
3604       // If the type is an array type, promote the element qualifiers to the
3605       // type for comparison.
3606       if (isa<ArrayType>(T1) && T1Quals)
3607         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3608       if (isa<ArrayType>(T2) && T2Quals)
3609         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3610       if (T2.isMoreQualifiedThan(T1))
3611         return ImplicitConversionSequence::Better;
3612       else if (T1.isMoreQualifiedThan(T2))
3613         return ImplicitConversionSequence::Worse;
3614     }
3615   }
3616 
3617   // In Microsoft mode, prefer an integral conversion to a
3618   // floating-to-integral conversion if the integral conversion
3619   // is between types of the same size.
3620   // For example:
3621   // void f(float);
3622   // void f(int);
3623   // int main {
3624   //    long a;
3625   //    f(a);
3626   // }
3627   // Here, MSVC will call f(int) instead of generating a compile error
3628   // as clang will do in standard mode.
3629   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3630       SCS2.Second == ICK_Floating_Integral &&
3631       S.Context.getTypeSize(SCS1.getFromType()) ==
3632           S.Context.getTypeSize(SCS1.getToType(2)))
3633     return ImplicitConversionSequence::Better;
3634 
3635   return ImplicitConversionSequence::Indistinguishable;
3636 }
3637 
3638 /// CompareQualificationConversions - Compares two standard conversion
3639 /// sequences to determine whether they can be ranked based on their
3640 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3641 static ImplicitConversionSequence::CompareKind
3642 CompareQualificationConversions(Sema &S,
3643                                 const StandardConversionSequence& SCS1,
3644                                 const StandardConversionSequence& SCS2) {
3645   // C++ 13.3.3.2p3:
3646   //  -- S1 and S2 differ only in their qualification conversion and
3647   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3648   //     cv-qualification signature of type T1 is a proper subset of
3649   //     the cv-qualification signature of type T2, and S1 is not the
3650   //     deprecated string literal array-to-pointer conversion (4.2).
3651   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3652       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3653     return ImplicitConversionSequence::Indistinguishable;
3654 
3655   // FIXME: the example in the standard doesn't use a qualification
3656   // conversion (!)
3657   QualType T1 = SCS1.getToType(2);
3658   QualType T2 = SCS2.getToType(2);
3659   T1 = S.Context.getCanonicalType(T1);
3660   T2 = S.Context.getCanonicalType(T2);
3661   Qualifiers T1Quals, T2Quals;
3662   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3663   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3664 
3665   // If the types are the same, we won't learn anything by unwrapped
3666   // them.
3667   if (UnqualT1 == UnqualT2)
3668     return ImplicitConversionSequence::Indistinguishable;
3669 
3670   // If the type is an array type, promote the element qualifiers to the type
3671   // for comparison.
3672   if (isa<ArrayType>(T1) && T1Quals)
3673     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3674   if (isa<ArrayType>(T2) && T2Quals)
3675     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3676 
3677   ImplicitConversionSequence::CompareKind Result
3678     = ImplicitConversionSequence::Indistinguishable;
3679 
3680   // Objective-C++ ARC:
3681   //   Prefer qualification conversions not involving a change in lifetime
3682   //   to qualification conversions that do not change lifetime.
3683   if (SCS1.QualificationIncludesObjCLifetime !=
3684                                       SCS2.QualificationIncludesObjCLifetime) {
3685     Result = SCS1.QualificationIncludesObjCLifetime
3686                ? ImplicitConversionSequence::Worse
3687                : ImplicitConversionSequence::Better;
3688   }
3689 
3690   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3691     // Within each iteration of the loop, we check the qualifiers to
3692     // determine if this still looks like a qualification
3693     // conversion. Then, if all is well, we unwrap one more level of
3694     // pointers or pointers-to-members and do it all again
3695     // until there are no more pointers or pointers-to-members left
3696     // to unwrap. This essentially mimics what
3697     // IsQualificationConversion does, but here we're checking for a
3698     // strict subset of qualifiers.
3699     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3700       // The qualifiers are the same, so this doesn't tell us anything
3701       // about how the sequences rank.
3702       ;
3703     else if (T2.isMoreQualifiedThan(T1)) {
3704       // T1 has fewer qualifiers, so it could be the better sequence.
3705       if (Result == ImplicitConversionSequence::Worse)
3706         // Neither has qualifiers that are a subset of the other's
3707         // qualifiers.
3708         return ImplicitConversionSequence::Indistinguishable;
3709 
3710       Result = ImplicitConversionSequence::Better;
3711     } else if (T1.isMoreQualifiedThan(T2)) {
3712       // T2 has fewer qualifiers, so it could be the better sequence.
3713       if (Result == ImplicitConversionSequence::Better)
3714         // Neither has qualifiers that are a subset of the other's
3715         // qualifiers.
3716         return ImplicitConversionSequence::Indistinguishable;
3717 
3718       Result = ImplicitConversionSequence::Worse;
3719     } else {
3720       // Qualifiers are disjoint.
3721       return ImplicitConversionSequence::Indistinguishable;
3722     }
3723 
3724     // If the types after this point are equivalent, we're done.
3725     if (S.Context.hasSameUnqualifiedType(T1, T2))
3726       break;
3727   }
3728 
3729   // Check that the winning standard conversion sequence isn't using
3730   // the deprecated string literal array to pointer conversion.
3731   switch (Result) {
3732   case ImplicitConversionSequence::Better:
3733     if (SCS1.DeprecatedStringLiteralToCharPtr)
3734       Result = ImplicitConversionSequence::Indistinguishable;
3735     break;
3736 
3737   case ImplicitConversionSequence::Indistinguishable:
3738     break;
3739 
3740   case ImplicitConversionSequence::Worse:
3741     if (SCS2.DeprecatedStringLiteralToCharPtr)
3742       Result = ImplicitConversionSequence::Indistinguishable;
3743     break;
3744   }
3745 
3746   return Result;
3747 }
3748 
3749 /// CompareDerivedToBaseConversions - Compares two standard conversion
3750 /// sequences to determine whether they can be ranked based on their
3751 /// various kinds of derived-to-base conversions (C++
3752 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3753 /// conversions between Objective-C interface types.
3754 static ImplicitConversionSequence::CompareKind
3755 CompareDerivedToBaseConversions(Sema &S,
3756                                 const StandardConversionSequence& SCS1,
3757                                 const StandardConversionSequence& SCS2) {
3758   QualType FromType1 = SCS1.getFromType();
3759   QualType ToType1 = SCS1.getToType(1);
3760   QualType FromType2 = SCS2.getFromType();
3761   QualType ToType2 = SCS2.getToType(1);
3762 
3763   // Adjust the types we're converting from via the array-to-pointer
3764   // conversion, if we need to.
3765   if (SCS1.First == ICK_Array_To_Pointer)
3766     FromType1 = S.Context.getArrayDecayedType(FromType1);
3767   if (SCS2.First == ICK_Array_To_Pointer)
3768     FromType2 = S.Context.getArrayDecayedType(FromType2);
3769 
3770   // Canonicalize all of the types.
3771   FromType1 = S.Context.getCanonicalType(FromType1);
3772   ToType1 = S.Context.getCanonicalType(ToType1);
3773   FromType2 = S.Context.getCanonicalType(FromType2);
3774   ToType2 = S.Context.getCanonicalType(ToType2);
3775 
3776   // C++ [over.ics.rank]p4b3:
3777   //
3778   //   If class B is derived directly or indirectly from class A and
3779   //   class C is derived directly or indirectly from B,
3780   //
3781   // Compare based on pointer conversions.
3782   if (SCS1.Second == ICK_Pointer_Conversion &&
3783       SCS2.Second == ICK_Pointer_Conversion &&
3784       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3785       FromType1->isPointerType() && FromType2->isPointerType() &&
3786       ToType1->isPointerType() && ToType2->isPointerType()) {
3787     QualType FromPointee1
3788       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3789     QualType ToPointee1
3790       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3791     QualType FromPointee2
3792       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3793     QualType ToPointee2
3794       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3795 
3796     //   -- conversion of C* to B* is better than conversion of C* to A*,
3797     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3798       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3799         return ImplicitConversionSequence::Better;
3800       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3801         return ImplicitConversionSequence::Worse;
3802     }
3803 
3804     //   -- conversion of B* to A* is better than conversion of C* to A*,
3805     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3806       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3807         return ImplicitConversionSequence::Better;
3808       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3809         return ImplicitConversionSequence::Worse;
3810     }
3811   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3812              SCS2.Second == ICK_Pointer_Conversion) {
3813     const ObjCObjectPointerType *FromPtr1
3814       = FromType1->getAs<ObjCObjectPointerType>();
3815     const ObjCObjectPointerType *FromPtr2
3816       = FromType2->getAs<ObjCObjectPointerType>();
3817     const ObjCObjectPointerType *ToPtr1
3818       = ToType1->getAs<ObjCObjectPointerType>();
3819     const ObjCObjectPointerType *ToPtr2
3820       = ToType2->getAs<ObjCObjectPointerType>();
3821 
3822     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3823       // Apply the same conversion ranking rules for Objective-C pointer types
3824       // that we do for C++ pointers to class types. However, we employ the
3825       // Objective-C pseudo-subtyping relationship used for assignment of
3826       // Objective-C pointer types.
3827       bool FromAssignLeft
3828         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3829       bool FromAssignRight
3830         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3831       bool ToAssignLeft
3832         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3833       bool ToAssignRight
3834         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3835 
3836       // A conversion to an a non-id object pointer type or qualified 'id'
3837       // type is better than a conversion to 'id'.
3838       if (ToPtr1->isObjCIdType() &&
3839           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3840         return ImplicitConversionSequence::Worse;
3841       if (ToPtr2->isObjCIdType() &&
3842           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3843         return ImplicitConversionSequence::Better;
3844 
3845       // A conversion to a non-id object pointer type is better than a
3846       // conversion to a qualified 'id' type
3847       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3848         return ImplicitConversionSequence::Worse;
3849       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3850         return ImplicitConversionSequence::Better;
3851 
3852       // A conversion to an a non-Class object pointer type or qualified 'Class'
3853       // type is better than a conversion to 'Class'.
3854       if (ToPtr1->isObjCClassType() &&
3855           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3856         return ImplicitConversionSequence::Worse;
3857       if (ToPtr2->isObjCClassType() &&
3858           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3859         return ImplicitConversionSequence::Better;
3860 
3861       // A conversion to a non-Class object pointer type is better than a
3862       // conversion to a qualified 'Class' type.
3863       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3864         return ImplicitConversionSequence::Worse;
3865       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3866         return ImplicitConversionSequence::Better;
3867 
3868       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3869       if (S.Context.hasSameType(FromType1, FromType2) &&
3870           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3871           (ToAssignLeft != ToAssignRight))
3872         return ToAssignLeft? ImplicitConversionSequence::Worse
3873                            : ImplicitConversionSequence::Better;
3874 
3875       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3876       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3877           (FromAssignLeft != FromAssignRight))
3878         return FromAssignLeft? ImplicitConversionSequence::Better
3879         : ImplicitConversionSequence::Worse;
3880     }
3881   }
3882 
3883   // Ranking of member-pointer types.
3884   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3885       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3886       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3887     const MemberPointerType * FromMemPointer1 =
3888                                         FromType1->getAs<MemberPointerType>();
3889     const MemberPointerType * ToMemPointer1 =
3890                                           ToType1->getAs<MemberPointerType>();
3891     const MemberPointerType * FromMemPointer2 =
3892                                           FromType2->getAs<MemberPointerType>();
3893     const MemberPointerType * ToMemPointer2 =
3894                                           ToType2->getAs<MemberPointerType>();
3895     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3896     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3897     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3898     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3899     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3900     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3901     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3902     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3903     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3904     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3905       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3906         return ImplicitConversionSequence::Worse;
3907       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3908         return ImplicitConversionSequence::Better;
3909     }
3910     // conversion of B::* to C::* is better than conversion of A::* to C::*
3911     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3912       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3913         return ImplicitConversionSequence::Better;
3914       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3915         return ImplicitConversionSequence::Worse;
3916     }
3917   }
3918 
3919   if (SCS1.Second == ICK_Derived_To_Base) {
3920     //   -- conversion of C to B is better than conversion of C to A,
3921     //   -- binding of an expression of type C to a reference of type
3922     //      B& is better than binding an expression of type C to a
3923     //      reference of type A&,
3924     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3925         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3926       if (S.IsDerivedFrom(ToType1, ToType2))
3927         return ImplicitConversionSequence::Better;
3928       else if (S.IsDerivedFrom(ToType2, ToType1))
3929         return ImplicitConversionSequence::Worse;
3930     }
3931 
3932     //   -- conversion of B to A is better than conversion of C to A.
3933     //   -- binding of an expression of type B to a reference of type
3934     //      A& is better than binding an expression of type C to a
3935     //      reference of type A&,
3936     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3937         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3938       if (S.IsDerivedFrom(FromType2, FromType1))
3939         return ImplicitConversionSequence::Better;
3940       else if (S.IsDerivedFrom(FromType1, FromType2))
3941         return ImplicitConversionSequence::Worse;
3942     }
3943   }
3944 
3945   return ImplicitConversionSequence::Indistinguishable;
3946 }
3947 
3948 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3949 /// C++ class.
3950 static bool isTypeValid(QualType T) {
3951   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3952     return !Record->isInvalidDecl();
3953 
3954   return true;
3955 }
3956 
3957 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3958 /// determine whether they are reference-related,
3959 /// reference-compatible, reference-compatible with added
3960 /// qualification, or incompatible, for use in C++ initialization by
3961 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3962 /// type, and the first type (T1) is the pointee type of the reference
3963 /// type being initialized.
3964 Sema::ReferenceCompareResult
3965 Sema::CompareReferenceRelationship(SourceLocation Loc,
3966                                    QualType OrigT1, QualType OrigT2,
3967                                    bool &DerivedToBase,
3968                                    bool &ObjCConversion,
3969                                    bool &ObjCLifetimeConversion) {
3970   assert(!OrigT1->isReferenceType() &&
3971     "T1 must be the pointee type of the reference type");
3972   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3973 
3974   QualType T1 = Context.getCanonicalType(OrigT1);
3975   QualType T2 = Context.getCanonicalType(OrigT2);
3976   Qualifiers T1Quals, T2Quals;
3977   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3978   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3979 
3980   // C++ [dcl.init.ref]p4:
3981   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3982   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3983   //   T1 is a base class of T2.
3984   DerivedToBase = false;
3985   ObjCConversion = false;
3986   ObjCLifetimeConversion = false;
3987   if (UnqualT1 == UnqualT2) {
3988     // Nothing to do.
3989   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3990              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3991              IsDerivedFrom(UnqualT2, UnqualT1))
3992     DerivedToBase = true;
3993   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3994            UnqualT2->isObjCObjectOrInterfaceType() &&
3995            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3996     ObjCConversion = true;
3997   else
3998     return Ref_Incompatible;
3999 
4000   // At this point, we know that T1 and T2 are reference-related (at
4001   // least).
4002 
4003   // If the type is an array type, promote the element qualifiers to the type
4004   // for comparison.
4005   if (isa<ArrayType>(T1) && T1Quals)
4006     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4007   if (isa<ArrayType>(T2) && T2Quals)
4008     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4009 
4010   // C++ [dcl.init.ref]p4:
4011   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4012   //   reference-related to T2 and cv1 is the same cv-qualification
4013   //   as, or greater cv-qualification than, cv2. For purposes of
4014   //   overload resolution, cases for which cv1 is greater
4015   //   cv-qualification than cv2 are identified as
4016   //   reference-compatible with added qualification (see 13.3.3.2).
4017   //
4018   // Note that we also require equivalence of Objective-C GC and address-space
4019   // qualifiers when performing these computations, so that e.g., an int in
4020   // address space 1 is not reference-compatible with an int in address
4021   // space 2.
4022   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4023       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4024     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4025       ObjCLifetimeConversion = true;
4026 
4027     T1Quals.removeObjCLifetime();
4028     T2Quals.removeObjCLifetime();
4029   }
4030 
4031   if (T1Quals == T2Quals)
4032     return Ref_Compatible;
4033   else if (T1Quals.compatiblyIncludes(T2Quals))
4034     return Ref_Compatible_With_Added_Qualification;
4035   else
4036     return Ref_Related;
4037 }
4038 
4039 /// \brief Look for a user-defined conversion to an value reference-compatible
4040 ///        with DeclType. Return true if something definite is found.
4041 static bool
4042 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4043                          QualType DeclType, SourceLocation DeclLoc,
4044                          Expr *Init, QualType T2, bool AllowRvalues,
4045                          bool AllowExplicit) {
4046   assert(T2->isRecordType() && "Can only find conversions of record types.");
4047   CXXRecordDecl *T2RecordDecl
4048     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4049 
4050   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4051   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4052   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4053     NamedDecl *D = *I;
4054     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4055     if (isa<UsingShadowDecl>(D))
4056       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4057 
4058     FunctionTemplateDecl *ConvTemplate
4059       = dyn_cast<FunctionTemplateDecl>(D);
4060     CXXConversionDecl *Conv;
4061     if (ConvTemplate)
4062       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4063     else
4064       Conv = cast<CXXConversionDecl>(D);
4065 
4066     // If this is an explicit conversion, and we're not allowed to consider
4067     // explicit conversions, skip it.
4068     if (!AllowExplicit && Conv->isExplicit())
4069       continue;
4070 
4071     if (AllowRvalues) {
4072       bool DerivedToBase = false;
4073       bool ObjCConversion = false;
4074       bool ObjCLifetimeConversion = false;
4075 
4076       // If we are initializing an rvalue reference, don't permit conversion
4077       // functions that return lvalues.
4078       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4079         const ReferenceType *RefType
4080           = Conv->getConversionType()->getAs<LValueReferenceType>();
4081         if (RefType && !RefType->getPointeeType()->isFunctionType())
4082           continue;
4083       }
4084 
4085       if (!ConvTemplate &&
4086           S.CompareReferenceRelationship(
4087             DeclLoc,
4088             Conv->getConversionType().getNonReferenceType()
4089               .getUnqualifiedType(),
4090             DeclType.getNonReferenceType().getUnqualifiedType(),
4091             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4092           Sema::Ref_Incompatible)
4093         continue;
4094     } else {
4095       // If the conversion function doesn't return a reference type,
4096       // it can't be considered for this conversion. An rvalue reference
4097       // is only acceptable if its referencee is a function type.
4098 
4099       const ReferenceType *RefType =
4100         Conv->getConversionType()->getAs<ReferenceType>();
4101       if (!RefType ||
4102           (!RefType->isLValueReferenceType() &&
4103            !RefType->getPointeeType()->isFunctionType()))
4104         continue;
4105     }
4106 
4107     if (ConvTemplate)
4108       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4109                                        Init, DeclType, CandidateSet,
4110                                        /*AllowObjCConversionOnExplicit=*/false);
4111     else
4112       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4113                                DeclType, CandidateSet,
4114                                /*AllowObjCConversionOnExplicit=*/false);
4115   }
4116 
4117   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4118 
4119   OverloadCandidateSet::iterator Best;
4120   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4121   case OR_Success:
4122     // C++ [over.ics.ref]p1:
4123     //
4124     //   [...] If the parameter binds directly to the result of
4125     //   applying a conversion function to the argument
4126     //   expression, the implicit conversion sequence is a
4127     //   user-defined conversion sequence (13.3.3.1.2), with the
4128     //   second standard conversion sequence either an identity
4129     //   conversion or, if the conversion function returns an
4130     //   entity of a type that is a derived class of the parameter
4131     //   type, a derived-to-base Conversion.
4132     if (!Best->FinalConversion.DirectBinding)
4133       return false;
4134 
4135     ICS.setUserDefined();
4136     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4137     ICS.UserDefined.After = Best->FinalConversion;
4138     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4139     ICS.UserDefined.ConversionFunction = Best->Function;
4140     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4141     ICS.UserDefined.EllipsisConversion = false;
4142     assert(ICS.UserDefined.After.ReferenceBinding &&
4143            ICS.UserDefined.After.DirectBinding &&
4144            "Expected a direct reference binding!");
4145     return true;
4146 
4147   case OR_Ambiguous:
4148     ICS.setAmbiguous();
4149     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4150          Cand != CandidateSet.end(); ++Cand)
4151       if (Cand->Viable)
4152         ICS.Ambiguous.addConversion(Cand->Function);
4153     return true;
4154 
4155   case OR_No_Viable_Function:
4156   case OR_Deleted:
4157     // There was no suitable conversion, or we found a deleted
4158     // conversion; continue with other checks.
4159     return false;
4160   }
4161 
4162   llvm_unreachable("Invalid OverloadResult!");
4163 }
4164 
4165 /// \brief Compute an implicit conversion sequence for reference
4166 /// initialization.
4167 static ImplicitConversionSequence
4168 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4169                  SourceLocation DeclLoc,
4170                  bool SuppressUserConversions,
4171                  bool AllowExplicit) {
4172   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4173 
4174   // Most paths end in a failed conversion.
4175   ImplicitConversionSequence ICS;
4176   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4177 
4178   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4179   QualType T2 = Init->getType();
4180 
4181   // If the initializer is the address of an overloaded function, try
4182   // to resolve the overloaded function. If all goes well, T2 is the
4183   // type of the resulting function.
4184   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4185     DeclAccessPair Found;
4186     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4187                                                                 false, Found))
4188       T2 = Fn->getType();
4189   }
4190 
4191   // Compute some basic properties of the types and the initializer.
4192   bool isRValRef = DeclType->isRValueReferenceType();
4193   bool DerivedToBase = false;
4194   bool ObjCConversion = false;
4195   bool ObjCLifetimeConversion = false;
4196   Expr::Classification InitCategory = Init->Classify(S.Context);
4197   Sema::ReferenceCompareResult RefRelationship
4198     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4199                                      ObjCConversion, ObjCLifetimeConversion);
4200 
4201 
4202   // C++0x [dcl.init.ref]p5:
4203   //   A reference to type "cv1 T1" is initialized by an expression
4204   //   of type "cv2 T2" as follows:
4205 
4206   //     -- If reference is an lvalue reference and the initializer expression
4207   if (!isRValRef) {
4208     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4209     //        reference-compatible with "cv2 T2," or
4210     //
4211     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4212     if (InitCategory.isLValue() &&
4213         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4214       // C++ [over.ics.ref]p1:
4215       //   When a parameter of reference type binds directly (8.5.3)
4216       //   to an argument expression, the implicit conversion sequence
4217       //   is the identity conversion, unless the argument expression
4218       //   has a type that is a derived class of the parameter type,
4219       //   in which case the implicit conversion sequence is a
4220       //   derived-to-base Conversion (13.3.3.1).
4221       ICS.setStandard();
4222       ICS.Standard.First = ICK_Identity;
4223       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4224                          : ObjCConversion? ICK_Compatible_Conversion
4225                          : ICK_Identity;
4226       ICS.Standard.Third = ICK_Identity;
4227       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4228       ICS.Standard.setToType(0, T2);
4229       ICS.Standard.setToType(1, T1);
4230       ICS.Standard.setToType(2, T1);
4231       ICS.Standard.ReferenceBinding = true;
4232       ICS.Standard.DirectBinding = true;
4233       ICS.Standard.IsLvalueReference = !isRValRef;
4234       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4235       ICS.Standard.BindsToRvalue = false;
4236       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4237       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4238       ICS.Standard.CopyConstructor = nullptr;
4239       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4240 
4241       // Nothing more to do: the inaccessibility/ambiguity check for
4242       // derived-to-base conversions is suppressed when we're
4243       // computing the implicit conversion sequence (C++
4244       // [over.best.ics]p2).
4245       return ICS;
4246     }
4247 
4248     //       -- has a class type (i.e., T2 is a class type), where T1 is
4249     //          not reference-related to T2, and can be implicitly
4250     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4251     //          is reference-compatible with "cv3 T3" 92) (this
4252     //          conversion is selected by enumerating the applicable
4253     //          conversion functions (13.3.1.6) and choosing the best
4254     //          one through overload resolution (13.3)),
4255     if (!SuppressUserConversions && T2->isRecordType() &&
4256         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4257         RefRelationship == Sema::Ref_Incompatible) {
4258       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4259                                    Init, T2, /*AllowRvalues=*/false,
4260                                    AllowExplicit))
4261         return ICS;
4262     }
4263   }
4264 
4265   //     -- Otherwise, the reference shall be an lvalue reference to a
4266   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4267   //        shall be an rvalue reference.
4268   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4269     return ICS;
4270 
4271   //       -- If the initializer expression
4272   //
4273   //            -- is an xvalue, class prvalue, array prvalue or function
4274   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4275   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4276       (InitCategory.isXValue() ||
4277       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4278       (InitCategory.isLValue() && T2->isFunctionType()))) {
4279     ICS.setStandard();
4280     ICS.Standard.First = ICK_Identity;
4281     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4282                       : ObjCConversion? ICK_Compatible_Conversion
4283                       : ICK_Identity;
4284     ICS.Standard.Third = ICK_Identity;
4285     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4286     ICS.Standard.setToType(0, T2);
4287     ICS.Standard.setToType(1, T1);
4288     ICS.Standard.setToType(2, T1);
4289     ICS.Standard.ReferenceBinding = true;
4290     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4291     // binding unless we're binding to a class prvalue.
4292     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4293     // allow the use of rvalue references in C++98/03 for the benefit of
4294     // standard library implementors; therefore, we need the xvalue check here.
4295     ICS.Standard.DirectBinding =
4296       S.getLangOpts().CPlusPlus11 ||
4297       !(InitCategory.isPRValue() || T2->isRecordType());
4298     ICS.Standard.IsLvalueReference = !isRValRef;
4299     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4300     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4301     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4302     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4303     ICS.Standard.CopyConstructor = nullptr;
4304     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4305     return ICS;
4306   }
4307 
4308   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4309   //               reference-related to T2, and can be implicitly converted to
4310   //               an xvalue, class prvalue, or function lvalue of type
4311   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4312   //               "cv3 T3",
4313   //
4314   //          then the reference is bound to the value of the initializer
4315   //          expression in the first case and to the result of the conversion
4316   //          in the second case (or, in either case, to an appropriate base
4317   //          class subobject).
4318   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4319       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4320       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4321                                Init, T2, /*AllowRvalues=*/true,
4322                                AllowExplicit)) {
4323     // In the second case, if the reference is an rvalue reference
4324     // and the second standard conversion sequence of the
4325     // user-defined conversion sequence includes an lvalue-to-rvalue
4326     // conversion, the program is ill-formed.
4327     if (ICS.isUserDefined() && isRValRef &&
4328         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4329       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4330 
4331     return ICS;
4332   }
4333 
4334   // A temporary of function type cannot be created; don't even try.
4335   if (T1->isFunctionType())
4336     return ICS;
4337 
4338   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4339   //          initialized from the initializer expression using the
4340   //          rules for a non-reference copy initialization (8.5). The
4341   //          reference is then bound to the temporary. If T1 is
4342   //          reference-related to T2, cv1 must be the same
4343   //          cv-qualification as, or greater cv-qualification than,
4344   //          cv2; otherwise, the program is ill-formed.
4345   if (RefRelationship == Sema::Ref_Related) {
4346     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4347     // we would be reference-compatible or reference-compatible with
4348     // added qualification. But that wasn't the case, so the reference
4349     // initialization fails.
4350     //
4351     // Note that we only want to check address spaces and cvr-qualifiers here.
4352     // ObjC GC and lifetime qualifiers aren't important.
4353     Qualifiers T1Quals = T1.getQualifiers();
4354     Qualifiers T2Quals = T2.getQualifiers();
4355     T1Quals.removeObjCGCAttr();
4356     T1Quals.removeObjCLifetime();
4357     T2Quals.removeObjCGCAttr();
4358     T2Quals.removeObjCLifetime();
4359     if (!T1Quals.compatiblyIncludes(T2Quals))
4360       return ICS;
4361   }
4362 
4363   // If at least one of the types is a class type, the types are not
4364   // related, and we aren't allowed any user conversions, the
4365   // reference binding fails. This case is important for breaking
4366   // recursion, since TryImplicitConversion below will attempt to
4367   // create a temporary through the use of a copy constructor.
4368   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4369       (T1->isRecordType() || T2->isRecordType()))
4370     return ICS;
4371 
4372   // If T1 is reference-related to T2 and the reference is an rvalue
4373   // reference, the initializer expression shall not be an lvalue.
4374   if (RefRelationship >= Sema::Ref_Related &&
4375       isRValRef && Init->Classify(S.Context).isLValue())
4376     return ICS;
4377 
4378   // C++ [over.ics.ref]p2:
4379   //   When a parameter of reference type is not bound directly to
4380   //   an argument expression, the conversion sequence is the one
4381   //   required to convert the argument expression to the
4382   //   underlying type of the reference according to
4383   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4384   //   to copy-initializing a temporary of the underlying type with
4385   //   the argument expression. Any difference in top-level
4386   //   cv-qualification is subsumed by the initialization itself
4387   //   and does not constitute a conversion.
4388   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4389                               /*AllowExplicit=*/false,
4390                               /*InOverloadResolution=*/false,
4391                               /*CStyle=*/false,
4392                               /*AllowObjCWritebackConversion=*/false,
4393                               /*AllowObjCConversionOnExplicit=*/false);
4394 
4395   // Of course, that's still a reference binding.
4396   if (ICS.isStandard()) {
4397     ICS.Standard.ReferenceBinding = true;
4398     ICS.Standard.IsLvalueReference = !isRValRef;
4399     ICS.Standard.BindsToFunctionLvalue = false;
4400     ICS.Standard.BindsToRvalue = true;
4401     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4402     ICS.Standard.ObjCLifetimeConversionBinding = false;
4403   } else if (ICS.isUserDefined()) {
4404     const ReferenceType *LValRefType =
4405         ICS.UserDefined.ConversionFunction->getReturnType()
4406             ->getAs<LValueReferenceType>();
4407 
4408     // C++ [over.ics.ref]p3:
4409     //   Except for an implicit object parameter, for which see 13.3.1, a
4410     //   standard conversion sequence cannot be formed if it requires [...]
4411     //   binding an rvalue reference to an lvalue other than a function
4412     //   lvalue.
4413     // Note that the function case is not possible here.
4414     if (DeclType->isRValueReferenceType() && LValRefType) {
4415       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4416       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4417       // reference to an rvalue!
4418       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4419       return ICS;
4420     }
4421 
4422     ICS.UserDefined.Before.setAsIdentityConversion();
4423     ICS.UserDefined.After.ReferenceBinding = true;
4424     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4425     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4426     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4427     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4428     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4429   }
4430 
4431   return ICS;
4432 }
4433 
4434 static ImplicitConversionSequence
4435 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4436                       bool SuppressUserConversions,
4437                       bool InOverloadResolution,
4438                       bool AllowObjCWritebackConversion,
4439                       bool AllowExplicit = false);
4440 
4441 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4442 /// initializer list From.
4443 static ImplicitConversionSequence
4444 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4445                   bool SuppressUserConversions,
4446                   bool InOverloadResolution,
4447                   bool AllowObjCWritebackConversion) {
4448   // C++11 [over.ics.list]p1:
4449   //   When an argument is an initializer list, it is not an expression and
4450   //   special rules apply for converting it to a parameter type.
4451 
4452   ImplicitConversionSequence Result;
4453   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4454 
4455   // We need a complete type for what follows. Incomplete types can never be
4456   // initialized from init lists.
4457   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4458     return Result;
4459 
4460   // Per DR1467:
4461   //   If the parameter type is a class X and the initializer list has a single
4462   //   element of type cv U, where U is X or a class derived from X, the
4463   //   implicit conversion sequence is the one required to convert the element
4464   //   to the parameter type.
4465   //
4466   //   Otherwise, if the parameter type is a character array [... ]
4467   //   and the initializer list has a single element that is an
4468   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4469   //   implicit conversion sequence is the identity conversion.
4470   if (From->getNumInits() == 1) {
4471     if (ToType->isRecordType()) {
4472       QualType InitType = From->getInit(0)->getType();
4473       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4474           S.IsDerivedFrom(InitType, ToType))
4475         return TryCopyInitialization(S, From->getInit(0), ToType,
4476                                      SuppressUserConversions,
4477                                      InOverloadResolution,
4478                                      AllowObjCWritebackConversion);
4479     }
4480     // FIXME: Check the other conditions here: array of character type,
4481     // initializer is a string literal.
4482     if (ToType->isArrayType()) {
4483       InitializedEntity Entity =
4484         InitializedEntity::InitializeParameter(S.Context, ToType,
4485                                                /*Consumed=*/false);
4486       if (S.CanPerformCopyInitialization(Entity, From)) {
4487         Result.setStandard();
4488         Result.Standard.setAsIdentityConversion();
4489         Result.Standard.setFromType(ToType);
4490         Result.Standard.setAllToTypes(ToType);
4491         return Result;
4492       }
4493     }
4494   }
4495 
4496   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4497   // C++11 [over.ics.list]p2:
4498   //   If the parameter type is std::initializer_list<X> or "array of X" and
4499   //   all the elements can be implicitly converted to X, the implicit
4500   //   conversion sequence is the worst conversion necessary to convert an
4501   //   element of the list to X.
4502   //
4503   // C++14 [over.ics.list]p3:
4504   //   Otherwise, if the parameter type is “array of N X”, if the initializer
4505   //   list has exactly N elements or if it has fewer than N elements and X is
4506   //   default-constructible, and if all the elements of the initializer list
4507   //   can be implicitly converted to X, the implicit conversion sequence is
4508   //   the worst conversion necessary to convert an element of the list to X.
4509   //
4510   // FIXME: We're missing a lot of these checks.
4511   bool toStdInitializerList = false;
4512   QualType X;
4513   if (ToType->isArrayType())
4514     X = S.Context.getAsArrayType(ToType)->getElementType();
4515   else
4516     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4517   if (!X.isNull()) {
4518     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4519       Expr *Init = From->getInit(i);
4520       ImplicitConversionSequence ICS =
4521           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4522                                 InOverloadResolution,
4523                                 AllowObjCWritebackConversion);
4524       // If a single element isn't convertible, fail.
4525       if (ICS.isBad()) {
4526         Result = ICS;
4527         break;
4528       }
4529       // Otherwise, look for the worst conversion.
4530       if (Result.isBad() ||
4531           CompareImplicitConversionSequences(S, ICS, Result) ==
4532               ImplicitConversionSequence::Worse)
4533         Result = ICS;
4534     }
4535 
4536     // For an empty list, we won't have computed any conversion sequence.
4537     // Introduce the identity conversion sequence.
4538     if (From->getNumInits() == 0) {
4539       Result.setStandard();
4540       Result.Standard.setAsIdentityConversion();
4541       Result.Standard.setFromType(ToType);
4542       Result.Standard.setAllToTypes(ToType);
4543     }
4544 
4545     Result.setStdInitializerListElement(toStdInitializerList);
4546     return Result;
4547   }
4548 
4549   // C++14 [over.ics.list]p4:
4550   // C++11 [over.ics.list]p3:
4551   //   Otherwise, if the parameter is a non-aggregate class X and overload
4552   //   resolution chooses a single best constructor [...] the implicit
4553   //   conversion sequence is a user-defined conversion sequence. If multiple
4554   //   constructors are viable but none is better than the others, the
4555   //   implicit conversion sequence is a user-defined conversion sequence.
4556   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4557     // This function can deal with initializer lists.
4558     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4559                                     /*AllowExplicit=*/false,
4560                                     InOverloadResolution, /*CStyle=*/false,
4561                                     AllowObjCWritebackConversion,
4562                                     /*AllowObjCConversionOnExplicit=*/false);
4563   }
4564 
4565   // C++14 [over.ics.list]p5:
4566   // C++11 [over.ics.list]p4:
4567   //   Otherwise, if the parameter has an aggregate type which can be
4568   //   initialized from the initializer list [...] the implicit conversion
4569   //   sequence is a user-defined conversion sequence.
4570   if (ToType->isAggregateType()) {
4571     // Type is an aggregate, argument is an init list. At this point it comes
4572     // down to checking whether the initialization works.
4573     // FIXME: Find out whether this parameter is consumed or not.
4574     InitializedEntity Entity =
4575         InitializedEntity::InitializeParameter(S.Context, ToType,
4576                                                /*Consumed=*/false);
4577     if (S.CanPerformCopyInitialization(Entity, From)) {
4578       Result.setUserDefined();
4579       Result.UserDefined.Before.setAsIdentityConversion();
4580       // Initializer lists don't have a type.
4581       Result.UserDefined.Before.setFromType(QualType());
4582       Result.UserDefined.Before.setAllToTypes(QualType());
4583 
4584       Result.UserDefined.After.setAsIdentityConversion();
4585       Result.UserDefined.After.setFromType(ToType);
4586       Result.UserDefined.After.setAllToTypes(ToType);
4587       Result.UserDefined.ConversionFunction = nullptr;
4588     }
4589     return Result;
4590   }
4591 
4592   // C++14 [over.ics.list]p6:
4593   // C++11 [over.ics.list]p5:
4594   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4595   if (ToType->isReferenceType()) {
4596     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4597     // mention initializer lists in any way. So we go by what list-
4598     // initialization would do and try to extrapolate from that.
4599 
4600     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4601 
4602     // If the initializer list has a single element that is reference-related
4603     // to the parameter type, we initialize the reference from that.
4604     if (From->getNumInits() == 1) {
4605       Expr *Init = From->getInit(0);
4606 
4607       QualType T2 = Init->getType();
4608 
4609       // If the initializer is the address of an overloaded function, try
4610       // to resolve the overloaded function. If all goes well, T2 is the
4611       // type of the resulting function.
4612       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4613         DeclAccessPair Found;
4614         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4615                                    Init, ToType, false, Found))
4616           T2 = Fn->getType();
4617       }
4618 
4619       // Compute some basic properties of the types and the initializer.
4620       bool dummy1 = false;
4621       bool dummy2 = false;
4622       bool dummy3 = false;
4623       Sema::ReferenceCompareResult RefRelationship
4624         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4625                                          dummy2, dummy3);
4626 
4627       if (RefRelationship >= Sema::Ref_Related) {
4628         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4629                                 SuppressUserConversions,
4630                                 /*AllowExplicit=*/false);
4631       }
4632     }
4633 
4634     // Otherwise, we bind the reference to a temporary created from the
4635     // initializer list.
4636     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4637                                InOverloadResolution,
4638                                AllowObjCWritebackConversion);
4639     if (Result.isFailure())
4640       return Result;
4641     assert(!Result.isEllipsis() &&
4642            "Sub-initialization cannot result in ellipsis conversion.");
4643 
4644     // Can we even bind to a temporary?
4645     if (ToType->isRValueReferenceType() ||
4646         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4647       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4648                                             Result.UserDefined.After;
4649       SCS.ReferenceBinding = true;
4650       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4651       SCS.BindsToRvalue = true;
4652       SCS.BindsToFunctionLvalue = false;
4653       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4654       SCS.ObjCLifetimeConversionBinding = false;
4655     } else
4656       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4657                     From, ToType);
4658     return Result;
4659   }
4660 
4661   // C++14 [over.ics.list]p7:
4662   // C++11 [over.ics.list]p6:
4663   //   Otherwise, if the parameter type is not a class:
4664   if (!ToType->isRecordType()) {
4665     //    - if the initializer list has one element that is not itself an
4666     //      initializer list, the implicit conversion sequence is the one
4667     //      required to convert the element to the parameter type.
4668     unsigned NumInits = From->getNumInits();
4669     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4670       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4671                                      SuppressUserConversions,
4672                                      InOverloadResolution,
4673                                      AllowObjCWritebackConversion);
4674     //    - if the initializer list has no elements, the implicit conversion
4675     //      sequence is the identity conversion.
4676     else if (NumInits == 0) {
4677       Result.setStandard();
4678       Result.Standard.setAsIdentityConversion();
4679       Result.Standard.setFromType(ToType);
4680       Result.Standard.setAllToTypes(ToType);
4681     }
4682     return Result;
4683   }
4684 
4685   // C++14 [over.ics.list]p8:
4686   // C++11 [over.ics.list]p7:
4687   //   In all cases other than those enumerated above, no conversion is possible
4688   return Result;
4689 }
4690 
4691 /// TryCopyInitialization - Try to copy-initialize a value of type
4692 /// ToType from the expression From. Return the implicit conversion
4693 /// sequence required to pass this argument, which may be a bad
4694 /// conversion sequence (meaning that the argument cannot be passed to
4695 /// a parameter of this type). If @p SuppressUserConversions, then we
4696 /// do not permit any user-defined conversion sequences.
4697 static ImplicitConversionSequence
4698 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4699                       bool SuppressUserConversions,
4700                       bool InOverloadResolution,
4701                       bool AllowObjCWritebackConversion,
4702                       bool AllowExplicit) {
4703   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4704     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4705                              InOverloadResolution,AllowObjCWritebackConversion);
4706 
4707   if (ToType->isReferenceType())
4708     return TryReferenceInit(S, From, ToType,
4709                             /*FIXME:*/From->getLocStart(),
4710                             SuppressUserConversions,
4711                             AllowExplicit);
4712 
4713   return TryImplicitConversion(S, From, ToType,
4714                                SuppressUserConversions,
4715                                /*AllowExplicit=*/false,
4716                                InOverloadResolution,
4717                                /*CStyle=*/false,
4718                                AllowObjCWritebackConversion,
4719                                /*AllowObjCConversionOnExplicit=*/false);
4720 }
4721 
4722 static bool TryCopyInitialization(const CanQualType FromQTy,
4723                                   const CanQualType ToQTy,
4724                                   Sema &S,
4725                                   SourceLocation Loc,
4726                                   ExprValueKind FromVK) {
4727   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4728   ImplicitConversionSequence ICS =
4729     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4730 
4731   return !ICS.isBad();
4732 }
4733 
4734 /// TryObjectArgumentInitialization - Try to initialize the object
4735 /// parameter of the given member function (@c Method) from the
4736 /// expression @p From.
4737 static ImplicitConversionSequence
4738 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4739                                 Expr::Classification FromClassification,
4740                                 CXXMethodDecl *Method,
4741                                 CXXRecordDecl *ActingContext) {
4742   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4743   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4744   //                 const volatile object.
4745   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4746     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4747   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4748 
4749   // Set up the conversion sequence as a "bad" conversion, to allow us
4750   // to exit early.
4751   ImplicitConversionSequence ICS;
4752 
4753   // We need to have an object of class type.
4754   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4755     FromType = PT->getPointeeType();
4756 
4757     // When we had a pointer, it's implicitly dereferenced, so we
4758     // better have an lvalue.
4759     assert(FromClassification.isLValue());
4760   }
4761 
4762   assert(FromType->isRecordType());
4763 
4764   // C++0x [over.match.funcs]p4:
4765   //   For non-static member functions, the type of the implicit object
4766   //   parameter is
4767   //
4768   //     - "lvalue reference to cv X" for functions declared without a
4769   //        ref-qualifier or with the & ref-qualifier
4770   //     - "rvalue reference to cv X" for functions declared with the &&
4771   //        ref-qualifier
4772   //
4773   // where X is the class of which the function is a member and cv is the
4774   // cv-qualification on the member function declaration.
4775   //
4776   // However, when finding an implicit conversion sequence for the argument, we
4777   // are not allowed to create temporaries or perform user-defined conversions
4778   // (C++ [over.match.funcs]p5). We perform a simplified version of
4779   // reference binding here, that allows class rvalues to bind to
4780   // non-constant references.
4781 
4782   // First check the qualifiers.
4783   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4784   if (ImplicitParamType.getCVRQualifiers()
4785                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4786       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4787     ICS.setBad(BadConversionSequence::bad_qualifiers,
4788                FromType, ImplicitParamType);
4789     return ICS;
4790   }
4791 
4792   // Check that we have either the same type or a derived type. It
4793   // affects the conversion rank.
4794   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4795   ImplicitConversionKind SecondKind;
4796   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4797     SecondKind = ICK_Identity;
4798   } else if (S.IsDerivedFrom(FromType, ClassType))
4799     SecondKind = ICK_Derived_To_Base;
4800   else {
4801     ICS.setBad(BadConversionSequence::unrelated_class,
4802                FromType, ImplicitParamType);
4803     return ICS;
4804   }
4805 
4806   // Check the ref-qualifier.
4807   switch (Method->getRefQualifier()) {
4808   case RQ_None:
4809     // Do nothing; we don't care about lvalueness or rvalueness.
4810     break;
4811 
4812   case RQ_LValue:
4813     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4814       // non-const lvalue reference cannot bind to an rvalue
4815       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4816                  ImplicitParamType);
4817       return ICS;
4818     }
4819     break;
4820 
4821   case RQ_RValue:
4822     if (!FromClassification.isRValue()) {
4823       // rvalue reference cannot bind to an lvalue
4824       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4825                  ImplicitParamType);
4826       return ICS;
4827     }
4828     break;
4829   }
4830 
4831   // Success. Mark this as a reference binding.
4832   ICS.setStandard();
4833   ICS.Standard.setAsIdentityConversion();
4834   ICS.Standard.Second = SecondKind;
4835   ICS.Standard.setFromType(FromType);
4836   ICS.Standard.setAllToTypes(ImplicitParamType);
4837   ICS.Standard.ReferenceBinding = true;
4838   ICS.Standard.DirectBinding = true;
4839   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4840   ICS.Standard.BindsToFunctionLvalue = false;
4841   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4842   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4843     = (Method->getRefQualifier() == RQ_None);
4844   return ICS;
4845 }
4846 
4847 /// PerformObjectArgumentInitialization - Perform initialization of
4848 /// the implicit object parameter for the given Method with the given
4849 /// expression.
4850 ExprResult
4851 Sema::PerformObjectArgumentInitialization(Expr *From,
4852                                           NestedNameSpecifier *Qualifier,
4853                                           NamedDecl *FoundDecl,
4854                                           CXXMethodDecl *Method) {
4855   QualType FromRecordType, DestType;
4856   QualType ImplicitParamRecordType  =
4857     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4858 
4859   Expr::Classification FromClassification;
4860   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4861     FromRecordType = PT->getPointeeType();
4862     DestType = Method->getThisType(Context);
4863     FromClassification = Expr::Classification::makeSimpleLValue();
4864   } else {
4865     FromRecordType = From->getType();
4866     DestType = ImplicitParamRecordType;
4867     FromClassification = From->Classify(Context);
4868   }
4869 
4870   // Note that we always use the true parent context when performing
4871   // the actual argument initialization.
4872   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4873       *this, From->getType(), FromClassification, Method, Method->getParent());
4874   if (ICS.isBad()) {
4875     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4876       Qualifiers FromQs = FromRecordType.getQualifiers();
4877       Qualifiers ToQs = DestType.getQualifiers();
4878       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4879       if (CVR) {
4880         Diag(From->getLocStart(),
4881              diag::err_member_function_call_bad_cvr)
4882           << Method->getDeclName() << FromRecordType << (CVR - 1)
4883           << From->getSourceRange();
4884         Diag(Method->getLocation(), diag::note_previous_decl)
4885           << Method->getDeclName();
4886         return ExprError();
4887       }
4888     }
4889 
4890     return Diag(From->getLocStart(),
4891                 diag::err_implicit_object_parameter_init)
4892        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4893   }
4894 
4895   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4896     ExprResult FromRes =
4897       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4898     if (FromRes.isInvalid())
4899       return ExprError();
4900     From = FromRes.get();
4901   }
4902 
4903   if (!Context.hasSameType(From->getType(), DestType))
4904     From = ImpCastExprToType(From, DestType, CK_NoOp,
4905                              From->getValueKind()).get();
4906   return From;
4907 }
4908 
4909 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4910 /// expression From to bool (C++0x [conv]p3).
4911 static ImplicitConversionSequence
4912 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4913   return TryImplicitConversion(S, From, S.Context.BoolTy,
4914                                /*SuppressUserConversions=*/false,
4915                                /*AllowExplicit=*/true,
4916                                /*InOverloadResolution=*/false,
4917                                /*CStyle=*/false,
4918                                /*AllowObjCWritebackConversion=*/false,
4919                                /*AllowObjCConversionOnExplicit=*/false);
4920 }
4921 
4922 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4923 /// of the expression From to bool (C++0x [conv]p3).
4924 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4925   if (checkPlaceholderForOverload(*this, From))
4926     return ExprError();
4927 
4928   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4929   if (!ICS.isBad())
4930     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4931 
4932   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4933     return Diag(From->getLocStart(),
4934                 diag::err_typecheck_bool_condition)
4935                   << From->getType() << From->getSourceRange();
4936   return ExprError();
4937 }
4938 
4939 /// Check that the specified conversion is permitted in a converted constant
4940 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4941 /// is acceptable.
4942 static bool CheckConvertedConstantConversions(Sema &S,
4943                                               StandardConversionSequence &SCS) {
4944   // Since we know that the target type is an integral or unscoped enumeration
4945   // type, most conversion kinds are impossible. All possible First and Third
4946   // conversions are fine.
4947   switch (SCS.Second) {
4948   case ICK_Identity:
4949   case ICK_NoReturn_Adjustment:
4950   case ICK_Integral_Promotion:
4951   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4952     return true;
4953 
4954   case ICK_Boolean_Conversion:
4955     // Conversion from an integral or unscoped enumeration type to bool is
4956     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4957     // conversion, so we allow it in a converted constant expression.
4958     //
4959     // FIXME: Per core issue 1407, we should not allow this, but that breaks
4960     // a lot of popular code. We should at least add a warning for this
4961     // (non-conforming) extension.
4962     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4963            SCS.getToType(2)->isBooleanType();
4964 
4965   case ICK_Pointer_Conversion:
4966   case ICK_Pointer_Member:
4967     // C++1z: null pointer conversions and null member pointer conversions are
4968     // only permitted if the source type is std::nullptr_t.
4969     return SCS.getFromType()->isNullPtrType();
4970 
4971   case ICK_Floating_Promotion:
4972   case ICK_Complex_Promotion:
4973   case ICK_Floating_Conversion:
4974   case ICK_Complex_Conversion:
4975   case ICK_Floating_Integral:
4976   case ICK_Compatible_Conversion:
4977   case ICK_Derived_To_Base:
4978   case ICK_Vector_Conversion:
4979   case ICK_Vector_Splat:
4980   case ICK_Complex_Real:
4981   case ICK_Block_Pointer_Conversion:
4982   case ICK_TransparentUnionConversion:
4983   case ICK_Writeback_Conversion:
4984   case ICK_Zero_Event_Conversion:
4985     return false;
4986 
4987   case ICK_Lvalue_To_Rvalue:
4988   case ICK_Array_To_Pointer:
4989   case ICK_Function_To_Pointer:
4990     llvm_unreachable("found a first conversion kind in Second");
4991 
4992   case ICK_Qualification:
4993     llvm_unreachable("found a third conversion kind in Second");
4994 
4995   case ICK_Num_Conversion_Kinds:
4996     break;
4997   }
4998 
4999   llvm_unreachable("unknown conversion kind");
5000 }
5001 
5002 /// CheckConvertedConstantExpression - Check that the expression From is a
5003 /// converted constant expression of type T, perform the conversion and produce
5004 /// the converted expression, per C++11 [expr.const]p3.
5005 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5006                                                    QualType T, APValue &Value,
5007                                                    Sema::CCEKind CCE,
5008                                                    bool RequireInt) {
5009   assert(S.getLangOpts().CPlusPlus11 &&
5010          "converted constant expression outside C++11");
5011 
5012   if (checkPlaceholderForOverload(S, From))
5013     return ExprError();
5014 
5015   // C++1z [expr.const]p3:
5016   //  A converted constant expression of type T is an expression,
5017   //  implicitly converted to type T, where the converted
5018   //  expression is a constant expression and the implicit conversion
5019   //  sequence contains only [... list of conversions ...].
5020   ImplicitConversionSequence ICS =
5021     TryCopyInitialization(S, From, T,
5022                           /*SuppressUserConversions=*/false,
5023                           /*InOverloadResolution=*/false,
5024                           /*AllowObjcWritebackConversion=*/false,
5025                           /*AllowExplicit=*/false);
5026   StandardConversionSequence *SCS = nullptr;
5027   switch (ICS.getKind()) {
5028   case ImplicitConversionSequence::StandardConversion:
5029     SCS = &ICS.Standard;
5030     break;
5031   case ImplicitConversionSequence::UserDefinedConversion:
5032     // We are converting to a non-class type, so the Before sequence
5033     // must be trivial.
5034     SCS = &ICS.UserDefined.After;
5035     break;
5036   case ImplicitConversionSequence::AmbiguousConversion:
5037   case ImplicitConversionSequence::BadConversion:
5038     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5039       return S.Diag(From->getLocStart(),
5040                     diag::err_typecheck_converted_constant_expression)
5041                 << From->getType() << From->getSourceRange() << T;
5042     return ExprError();
5043 
5044   case ImplicitConversionSequence::EllipsisConversion:
5045     llvm_unreachable("ellipsis conversion in converted constant expression");
5046   }
5047 
5048   // Check that we would only use permitted conversions.
5049   if (!CheckConvertedConstantConversions(S, *SCS)) {
5050     return S.Diag(From->getLocStart(),
5051                   diag::err_typecheck_converted_constant_expression_disallowed)
5052              << From->getType() << From->getSourceRange() << T;
5053   }
5054   // [...] and where the reference binding (if any) binds directly.
5055   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5056     return S.Diag(From->getLocStart(),
5057                   diag::err_typecheck_converted_constant_expression_indirect)
5058              << From->getType() << From->getSourceRange() << T;
5059   }
5060 
5061   ExprResult Result =
5062       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5063   if (Result.isInvalid())
5064     return Result;
5065 
5066   // Check for a narrowing implicit conversion.
5067   APValue PreNarrowingValue;
5068   QualType PreNarrowingType;
5069   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5070                                 PreNarrowingType)) {
5071   case NK_Variable_Narrowing:
5072     // Implicit conversion to a narrower type, and the value is not a constant
5073     // expression. We'll diagnose this in a moment.
5074   case NK_Not_Narrowing:
5075     break;
5076 
5077   case NK_Constant_Narrowing:
5078     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5079       << CCE << /*Constant*/1
5080       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5081     break;
5082 
5083   case NK_Type_Narrowing:
5084     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5085       << CCE << /*Constant*/0 << From->getType() << T;
5086     break;
5087   }
5088 
5089   // Check the expression is a constant expression.
5090   SmallVector<PartialDiagnosticAt, 8> Notes;
5091   Expr::EvalResult Eval;
5092   Eval.Diag = &Notes;
5093 
5094   if ((T->isReferenceType()
5095            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5096            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5097       (RequireInt && !Eval.Val.isInt())) {
5098     // The expression can't be folded, so we can't keep it at this position in
5099     // the AST.
5100     Result = ExprError();
5101   } else {
5102     Value = Eval.Val;
5103 
5104     if (Notes.empty()) {
5105       // It's a constant expression.
5106       return Result;
5107     }
5108   }
5109 
5110   // It's not a constant expression. Produce an appropriate diagnostic.
5111   if (Notes.size() == 1 &&
5112       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5113     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5114   else {
5115     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5116       << CCE << From->getSourceRange();
5117     for (unsigned I = 0; I < Notes.size(); ++I)
5118       S.Diag(Notes[I].first, Notes[I].second);
5119   }
5120   return ExprError();
5121 }
5122 
5123 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5124                                                   APValue &Value, CCEKind CCE) {
5125   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5126 }
5127 
5128 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5129                                                   llvm::APSInt &Value,
5130                                                   CCEKind CCE) {
5131   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5132 
5133   APValue V;
5134   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5135   if (!R.isInvalid())
5136     Value = V.getInt();
5137   return R;
5138 }
5139 
5140 
5141 /// dropPointerConversions - If the given standard conversion sequence
5142 /// involves any pointer conversions, remove them.  This may change
5143 /// the result type of the conversion sequence.
5144 static void dropPointerConversion(StandardConversionSequence &SCS) {
5145   if (SCS.Second == ICK_Pointer_Conversion) {
5146     SCS.Second = ICK_Identity;
5147     SCS.Third = ICK_Identity;
5148     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5149   }
5150 }
5151 
5152 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5153 /// convert the expression From to an Objective-C pointer type.
5154 static ImplicitConversionSequence
5155 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5156   // Do an implicit conversion to 'id'.
5157   QualType Ty = S.Context.getObjCIdType();
5158   ImplicitConversionSequence ICS
5159     = TryImplicitConversion(S, From, Ty,
5160                             // FIXME: Are these flags correct?
5161                             /*SuppressUserConversions=*/false,
5162                             /*AllowExplicit=*/true,
5163                             /*InOverloadResolution=*/false,
5164                             /*CStyle=*/false,
5165                             /*AllowObjCWritebackConversion=*/false,
5166                             /*AllowObjCConversionOnExplicit=*/true);
5167 
5168   // Strip off any final conversions to 'id'.
5169   switch (ICS.getKind()) {
5170   case ImplicitConversionSequence::BadConversion:
5171   case ImplicitConversionSequence::AmbiguousConversion:
5172   case ImplicitConversionSequence::EllipsisConversion:
5173     break;
5174 
5175   case ImplicitConversionSequence::UserDefinedConversion:
5176     dropPointerConversion(ICS.UserDefined.After);
5177     break;
5178 
5179   case ImplicitConversionSequence::StandardConversion:
5180     dropPointerConversion(ICS.Standard);
5181     break;
5182   }
5183 
5184   return ICS;
5185 }
5186 
5187 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5188 /// conversion of the expression From to an Objective-C pointer type.
5189 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5190   if (checkPlaceholderForOverload(*this, From))
5191     return ExprError();
5192 
5193   QualType Ty = Context.getObjCIdType();
5194   ImplicitConversionSequence ICS =
5195     TryContextuallyConvertToObjCPointer(*this, From);
5196   if (!ICS.isBad())
5197     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5198   return ExprError();
5199 }
5200 
5201 /// Determine whether the provided type is an integral type, or an enumeration
5202 /// type of a permitted flavor.
5203 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5204   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5205                                  : T->isIntegralOrUnscopedEnumerationType();
5206 }
5207 
5208 static ExprResult
5209 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5210                             Sema::ContextualImplicitConverter &Converter,
5211                             QualType T, UnresolvedSetImpl &ViableConversions) {
5212 
5213   if (Converter.Suppress)
5214     return ExprError();
5215 
5216   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5217   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5218     CXXConversionDecl *Conv =
5219         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5220     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5221     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5222   }
5223   return From;
5224 }
5225 
5226 static bool
5227 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5228                            Sema::ContextualImplicitConverter &Converter,
5229                            QualType T, bool HadMultipleCandidates,
5230                            UnresolvedSetImpl &ExplicitConversions) {
5231   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5232     DeclAccessPair Found = ExplicitConversions[0];
5233     CXXConversionDecl *Conversion =
5234         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5235 
5236     // The user probably meant to invoke the given explicit
5237     // conversion; use it.
5238     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5239     std::string TypeStr;
5240     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5241 
5242     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5243         << FixItHint::CreateInsertion(From->getLocStart(),
5244                                       "static_cast<" + TypeStr + ">(")
5245         << FixItHint::CreateInsertion(
5246                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5247     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5248 
5249     // If we aren't in a SFINAE context, build a call to the
5250     // explicit conversion function.
5251     if (SemaRef.isSFINAEContext())
5252       return true;
5253 
5254     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5255     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5256                                                        HadMultipleCandidates);
5257     if (Result.isInvalid())
5258       return true;
5259     // Record usage of conversion in an implicit cast.
5260     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5261                                     CK_UserDefinedConversion, Result.get(),
5262                                     nullptr, Result.get()->getValueKind());
5263   }
5264   return false;
5265 }
5266 
5267 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5268                              Sema::ContextualImplicitConverter &Converter,
5269                              QualType T, bool HadMultipleCandidates,
5270                              DeclAccessPair &Found) {
5271   CXXConversionDecl *Conversion =
5272       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5273   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5274 
5275   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5276   if (!Converter.SuppressConversion) {
5277     if (SemaRef.isSFINAEContext())
5278       return true;
5279 
5280     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5281         << From->getSourceRange();
5282   }
5283 
5284   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5285                                                      HadMultipleCandidates);
5286   if (Result.isInvalid())
5287     return true;
5288   // Record usage of conversion in an implicit cast.
5289   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5290                                   CK_UserDefinedConversion, Result.get(),
5291                                   nullptr, Result.get()->getValueKind());
5292   return false;
5293 }
5294 
5295 static ExprResult finishContextualImplicitConversion(
5296     Sema &SemaRef, SourceLocation Loc, Expr *From,
5297     Sema::ContextualImplicitConverter &Converter) {
5298   if (!Converter.match(From->getType()) && !Converter.Suppress)
5299     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5300         << From->getSourceRange();
5301 
5302   return SemaRef.DefaultLvalueConversion(From);
5303 }
5304 
5305 static void
5306 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5307                                   UnresolvedSetImpl &ViableConversions,
5308                                   OverloadCandidateSet &CandidateSet) {
5309   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5310     DeclAccessPair FoundDecl = ViableConversions[I];
5311     NamedDecl *D = FoundDecl.getDecl();
5312     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5313     if (isa<UsingShadowDecl>(D))
5314       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5315 
5316     CXXConversionDecl *Conv;
5317     FunctionTemplateDecl *ConvTemplate;
5318     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5319       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5320     else
5321       Conv = cast<CXXConversionDecl>(D);
5322 
5323     if (ConvTemplate)
5324       SemaRef.AddTemplateConversionCandidate(
5325         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5326         /*AllowObjCConversionOnExplicit=*/false);
5327     else
5328       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5329                                      ToType, CandidateSet,
5330                                      /*AllowObjCConversionOnExplicit=*/false);
5331   }
5332 }
5333 
5334 /// \brief Attempt to convert the given expression to a type which is accepted
5335 /// by the given converter.
5336 ///
5337 /// This routine will attempt to convert an expression of class type to a
5338 /// type accepted by the specified converter. In C++11 and before, the class
5339 /// must have a single non-explicit conversion function converting to a matching
5340 /// type. In C++1y, there can be multiple such conversion functions, but only
5341 /// one target type.
5342 ///
5343 /// \param Loc The source location of the construct that requires the
5344 /// conversion.
5345 ///
5346 /// \param From The expression we're converting from.
5347 ///
5348 /// \param Converter Used to control and diagnose the conversion process.
5349 ///
5350 /// \returns The expression, converted to an integral or enumeration type if
5351 /// successful.
5352 ExprResult Sema::PerformContextualImplicitConversion(
5353     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5354   // We can't perform any more checking for type-dependent expressions.
5355   if (From->isTypeDependent())
5356     return From;
5357 
5358   // Process placeholders immediately.
5359   if (From->hasPlaceholderType()) {
5360     ExprResult result = CheckPlaceholderExpr(From);
5361     if (result.isInvalid())
5362       return result;
5363     From = result.get();
5364   }
5365 
5366   // If the expression already has a matching type, we're golden.
5367   QualType T = From->getType();
5368   if (Converter.match(T))
5369     return DefaultLvalueConversion(From);
5370 
5371   // FIXME: Check for missing '()' if T is a function type?
5372 
5373   // We can only perform contextual implicit conversions on objects of class
5374   // type.
5375   const RecordType *RecordTy = T->getAs<RecordType>();
5376   if (!RecordTy || !getLangOpts().CPlusPlus) {
5377     if (!Converter.Suppress)
5378       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5379     return From;
5380   }
5381 
5382   // We must have a complete class type.
5383   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5384     ContextualImplicitConverter &Converter;
5385     Expr *From;
5386 
5387     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5388         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5389 
5390     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5391       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5392     }
5393   } IncompleteDiagnoser(Converter, From);
5394 
5395   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5396     return From;
5397 
5398   // Look for a conversion to an integral or enumeration type.
5399   UnresolvedSet<4>
5400       ViableConversions; // These are *potentially* viable in C++1y.
5401   UnresolvedSet<4> ExplicitConversions;
5402   const auto &Conversions =
5403       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5404 
5405   bool HadMultipleCandidates =
5406       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5407 
5408   // To check that there is only one target type, in C++1y:
5409   QualType ToType;
5410   bool HasUniqueTargetType = true;
5411 
5412   // Collect explicit or viable (potentially in C++1y) conversions.
5413   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5414     NamedDecl *D = (*I)->getUnderlyingDecl();
5415     CXXConversionDecl *Conversion;
5416     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5417     if (ConvTemplate) {
5418       if (getLangOpts().CPlusPlus14)
5419         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5420       else
5421         continue; // C++11 does not consider conversion operator templates(?).
5422     } else
5423       Conversion = cast<CXXConversionDecl>(D);
5424 
5425     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5426            "Conversion operator templates are considered potentially "
5427            "viable in C++1y");
5428 
5429     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5430     if (Converter.match(CurToType) || ConvTemplate) {
5431 
5432       if (Conversion->isExplicit()) {
5433         // FIXME: For C++1y, do we need this restriction?
5434         // cf. diagnoseNoViableConversion()
5435         if (!ConvTemplate)
5436           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5437       } else {
5438         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5439           if (ToType.isNull())
5440             ToType = CurToType.getUnqualifiedType();
5441           else if (HasUniqueTargetType &&
5442                    (CurToType.getUnqualifiedType() != ToType))
5443             HasUniqueTargetType = false;
5444         }
5445         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5446       }
5447     }
5448   }
5449 
5450   if (getLangOpts().CPlusPlus14) {
5451     // C++1y [conv]p6:
5452     // ... An expression e of class type E appearing in such a context
5453     // is said to be contextually implicitly converted to a specified
5454     // type T and is well-formed if and only if e can be implicitly
5455     // converted to a type T that is determined as follows: E is searched
5456     // for conversion functions whose return type is cv T or reference to
5457     // cv T such that T is allowed by the context. There shall be
5458     // exactly one such T.
5459 
5460     // If no unique T is found:
5461     if (ToType.isNull()) {
5462       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5463                                      HadMultipleCandidates,
5464                                      ExplicitConversions))
5465         return ExprError();
5466       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5467     }
5468 
5469     // If more than one unique Ts are found:
5470     if (!HasUniqueTargetType)
5471       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5472                                          ViableConversions);
5473 
5474     // If one unique T is found:
5475     // First, build a candidate set from the previously recorded
5476     // potentially viable conversions.
5477     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5478     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5479                                       CandidateSet);
5480 
5481     // Then, perform overload resolution over the candidate set.
5482     OverloadCandidateSet::iterator Best;
5483     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5484     case OR_Success: {
5485       // Apply this conversion.
5486       DeclAccessPair Found =
5487           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5488       if (recordConversion(*this, Loc, From, Converter, T,
5489                            HadMultipleCandidates, Found))
5490         return ExprError();
5491       break;
5492     }
5493     case OR_Ambiguous:
5494       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5495                                          ViableConversions);
5496     case OR_No_Viable_Function:
5497       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5498                                      HadMultipleCandidates,
5499                                      ExplicitConversions))
5500         return ExprError();
5501     // fall through 'OR_Deleted' case.
5502     case OR_Deleted:
5503       // We'll complain below about a non-integral condition type.
5504       break;
5505     }
5506   } else {
5507     switch (ViableConversions.size()) {
5508     case 0: {
5509       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5510                                      HadMultipleCandidates,
5511                                      ExplicitConversions))
5512         return ExprError();
5513 
5514       // We'll complain below about a non-integral condition type.
5515       break;
5516     }
5517     case 1: {
5518       // Apply this conversion.
5519       DeclAccessPair Found = ViableConversions[0];
5520       if (recordConversion(*this, Loc, From, Converter, T,
5521                            HadMultipleCandidates, Found))
5522         return ExprError();
5523       break;
5524     }
5525     default:
5526       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5527                                          ViableConversions);
5528     }
5529   }
5530 
5531   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5532 }
5533 
5534 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5535 /// an acceptable non-member overloaded operator for a call whose
5536 /// arguments have types T1 (and, if non-empty, T2). This routine
5537 /// implements the check in C++ [over.match.oper]p3b2 concerning
5538 /// enumeration types.
5539 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5540                                                    FunctionDecl *Fn,
5541                                                    ArrayRef<Expr *> Args) {
5542   QualType T1 = Args[0]->getType();
5543   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5544 
5545   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5546     return true;
5547 
5548   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5549     return true;
5550 
5551   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5552   if (Proto->getNumParams() < 1)
5553     return false;
5554 
5555   if (T1->isEnumeralType()) {
5556     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5557     if (Context.hasSameUnqualifiedType(T1, ArgType))
5558       return true;
5559   }
5560 
5561   if (Proto->getNumParams() < 2)
5562     return false;
5563 
5564   if (!T2.isNull() && T2->isEnumeralType()) {
5565     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5566     if (Context.hasSameUnqualifiedType(T2, ArgType))
5567       return true;
5568   }
5569 
5570   return false;
5571 }
5572 
5573 /// AddOverloadCandidate - Adds the given function to the set of
5574 /// candidate functions, using the given function call arguments.  If
5575 /// @p SuppressUserConversions, then don't allow user-defined
5576 /// conversions via constructors or conversion operators.
5577 ///
5578 /// \param PartialOverloading true if we are performing "partial" overloading
5579 /// based on an incomplete set of function arguments. This feature is used by
5580 /// code completion.
5581 void
5582 Sema::AddOverloadCandidate(FunctionDecl *Function,
5583                            DeclAccessPair FoundDecl,
5584                            ArrayRef<Expr *> Args,
5585                            OverloadCandidateSet &CandidateSet,
5586                            bool SuppressUserConversions,
5587                            bool PartialOverloading,
5588                            bool AllowExplicit) {
5589   const FunctionProtoType *Proto
5590     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5591   assert(Proto && "Functions without a prototype cannot be overloaded");
5592   assert(!Function->getDescribedFunctionTemplate() &&
5593          "Use AddTemplateOverloadCandidate for function templates");
5594 
5595   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5596     if (!isa<CXXConstructorDecl>(Method)) {
5597       // If we get here, it's because we're calling a member function
5598       // that is named without a member access expression (e.g.,
5599       // "this->f") that was either written explicitly or created
5600       // implicitly. This can happen with a qualified call to a member
5601       // function, e.g., X::f(). We use an empty type for the implied
5602       // object argument (C++ [over.call.func]p3), and the acting context
5603       // is irrelevant.
5604       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5605                          QualType(), Expr::Classification::makeSimpleLValue(),
5606                          Args, CandidateSet, SuppressUserConversions,
5607                          PartialOverloading);
5608       return;
5609     }
5610     // We treat a constructor like a non-member function, since its object
5611     // argument doesn't participate in overload resolution.
5612   }
5613 
5614   if (!CandidateSet.isNewCandidate(Function))
5615     return;
5616 
5617   // C++ [over.match.oper]p3:
5618   //   if no operand has a class type, only those non-member functions in the
5619   //   lookup set that have a first parameter of type T1 or "reference to
5620   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5621   //   is a right operand) a second parameter of type T2 or "reference to
5622   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5623   //   candidate functions.
5624   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5625       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5626     return;
5627 
5628   // C++11 [class.copy]p11: [DR1402]
5629   //   A defaulted move constructor that is defined as deleted is ignored by
5630   //   overload resolution.
5631   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5632   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5633       Constructor->isMoveConstructor())
5634     return;
5635 
5636   // Overload resolution is always an unevaluated context.
5637   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5638 
5639   // Add this candidate
5640   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5641   Candidate.FoundDecl = FoundDecl;
5642   Candidate.Function = Function;
5643   Candidate.Viable = true;
5644   Candidate.IsSurrogate = false;
5645   Candidate.IgnoreObjectArgument = false;
5646   Candidate.ExplicitCallArguments = Args.size();
5647 
5648   if (Constructor) {
5649     // C++ [class.copy]p3:
5650     //   A member function template is never instantiated to perform the copy
5651     //   of a class object to an object of its class type.
5652     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5653     if (Args.size() == 1 &&
5654         Constructor->isSpecializationCopyingObject() &&
5655         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5656          IsDerivedFrom(Args[0]->getType(), ClassType))) {
5657       Candidate.Viable = false;
5658       Candidate.FailureKind = ovl_fail_illegal_constructor;
5659       return;
5660     }
5661   }
5662 
5663   unsigned NumParams = Proto->getNumParams();
5664 
5665   // (C++ 13.3.2p2): A candidate function having fewer than m
5666   // parameters is viable only if it has an ellipsis in its parameter
5667   // list (8.3.5).
5668   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5669       !Proto->isVariadic()) {
5670     Candidate.Viable = false;
5671     Candidate.FailureKind = ovl_fail_too_many_arguments;
5672     return;
5673   }
5674 
5675   // (C++ 13.3.2p2): A candidate function having more than m parameters
5676   // is viable only if the (m+1)st parameter has a default argument
5677   // (8.3.6). For the purposes of overload resolution, the
5678   // parameter list is truncated on the right, so that there are
5679   // exactly m parameters.
5680   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5681   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5682     // Not enough arguments.
5683     Candidate.Viable = false;
5684     Candidate.FailureKind = ovl_fail_too_few_arguments;
5685     return;
5686   }
5687 
5688   // (CUDA B.1): Check for invalid calls between targets.
5689   if (getLangOpts().CUDA)
5690     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5691       // Skip the check for callers that are implicit members, because in this
5692       // case we may not yet know what the member's target is; the target is
5693       // inferred for the member automatically, based on the bases and fields of
5694       // the class.
5695       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5696         Candidate.Viable = false;
5697         Candidate.FailureKind = ovl_fail_bad_target;
5698         return;
5699       }
5700 
5701   // Determine the implicit conversion sequences for each of the
5702   // arguments.
5703   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5704     if (ArgIdx < NumParams) {
5705       // (C++ 13.3.2p3): for F to be a viable function, there shall
5706       // exist for each argument an implicit conversion sequence
5707       // (13.3.3.1) that converts that argument to the corresponding
5708       // parameter of F.
5709       QualType ParamType = Proto->getParamType(ArgIdx);
5710       Candidate.Conversions[ArgIdx]
5711         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5712                                 SuppressUserConversions,
5713                                 /*InOverloadResolution=*/true,
5714                                 /*AllowObjCWritebackConversion=*/
5715                                   getLangOpts().ObjCAutoRefCount,
5716                                 AllowExplicit);
5717       if (Candidate.Conversions[ArgIdx].isBad()) {
5718         Candidate.Viable = false;
5719         Candidate.FailureKind = ovl_fail_bad_conversion;
5720         return;
5721       }
5722     } else {
5723       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5724       // argument for which there is no corresponding parameter is
5725       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5726       Candidate.Conversions[ArgIdx].setEllipsis();
5727     }
5728   }
5729 
5730   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5731     Candidate.Viable = false;
5732     Candidate.FailureKind = ovl_fail_enable_if;
5733     Candidate.DeductionFailure.Data = FailedAttr;
5734     return;
5735   }
5736 }
5737 
5738 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5739                                        bool IsInstance) {
5740   SmallVector<ObjCMethodDecl*, 4> Methods;
5741   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5742     return nullptr;
5743 
5744   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5745     bool Match = true;
5746     ObjCMethodDecl *Method = Methods[b];
5747     unsigned NumNamedArgs = Sel.getNumArgs();
5748     // Method might have more arguments than selector indicates. This is due
5749     // to addition of c-style arguments in method.
5750     if (Method->param_size() > NumNamedArgs)
5751       NumNamedArgs = Method->param_size();
5752     if (Args.size() < NumNamedArgs)
5753       continue;
5754 
5755     for (unsigned i = 0; i < NumNamedArgs; i++) {
5756       // We can't do any type-checking on a type-dependent argument.
5757       if (Args[i]->isTypeDependent()) {
5758         Match = false;
5759         break;
5760       }
5761 
5762       ParmVarDecl *param = Method->parameters()[i];
5763       Expr *argExpr = Args[i];
5764       assert(argExpr && "SelectBestMethod(): missing expression");
5765 
5766       // Strip the unbridged-cast placeholder expression off unless it's
5767       // a consumed argument.
5768       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5769           !param->hasAttr<CFConsumedAttr>())
5770         argExpr = stripARCUnbridgedCast(argExpr);
5771 
5772       // If the parameter is __unknown_anytype, move on to the next method.
5773       if (param->getType() == Context.UnknownAnyTy) {
5774         Match = false;
5775         break;
5776       }
5777 
5778       ImplicitConversionSequence ConversionState
5779         = TryCopyInitialization(*this, argExpr, param->getType(),
5780                                 /*SuppressUserConversions*/false,
5781                                 /*InOverloadResolution=*/true,
5782                                 /*AllowObjCWritebackConversion=*/
5783                                 getLangOpts().ObjCAutoRefCount,
5784                                 /*AllowExplicit*/false);
5785         if (ConversionState.isBad()) {
5786           Match = false;
5787           break;
5788         }
5789     }
5790     // Promote additional arguments to variadic methods.
5791     if (Match && Method->isVariadic()) {
5792       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5793         if (Args[i]->isTypeDependent()) {
5794           Match = false;
5795           break;
5796         }
5797         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5798                                                           nullptr);
5799         if (Arg.isInvalid()) {
5800           Match = false;
5801           break;
5802         }
5803       }
5804     } else {
5805       // Check for extra arguments to non-variadic methods.
5806       if (Args.size() != NumNamedArgs)
5807         Match = false;
5808       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5809         // Special case when selectors have no argument. In this case, select
5810         // one with the most general result type of 'id'.
5811         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5812           QualType ReturnT = Methods[b]->getReturnType();
5813           if (ReturnT->isObjCIdType())
5814             return Methods[b];
5815         }
5816       }
5817     }
5818 
5819     if (Match)
5820       return Method;
5821   }
5822   return nullptr;
5823 }
5824 
5825 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5826 
5827 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5828                                   bool MissingImplicitThis) {
5829   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5830   // we need to find the first failing one.
5831   if (!Function->hasAttrs())
5832     return nullptr;
5833   AttrVec Attrs = Function->getAttrs();
5834   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5835                                        IsNotEnableIfAttr);
5836   if (Attrs.begin() == E)
5837     return nullptr;
5838   std::reverse(Attrs.begin(), E);
5839 
5840   SFINAETrap Trap(*this);
5841 
5842   // Convert the arguments.
5843   SmallVector<Expr *, 16> ConvertedArgs;
5844   bool InitializationFailed = false;
5845   bool ContainsValueDependentExpr = false;
5846   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5847     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5848         !cast<CXXMethodDecl>(Function)->isStatic() &&
5849         !isa<CXXConstructorDecl>(Function)) {
5850       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5851       ExprResult R =
5852         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5853                                             Method, Method);
5854       if (R.isInvalid()) {
5855         InitializationFailed = true;
5856         break;
5857       }
5858       ContainsValueDependentExpr |= R.get()->isValueDependent();
5859       ConvertedArgs.push_back(R.get());
5860     } else {
5861       ExprResult R =
5862         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5863                                                 Context,
5864                                                 Function->getParamDecl(i)),
5865                                   SourceLocation(),
5866                                   Args[i]);
5867       if (R.isInvalid()) {
5868         InitializationFailed = true;
5869         break;
5870       }
5871       ContainsValueDependentExpr |= R.get()->isValueDependent();
5872       ConvertedArgs.push_back(R.get());
5873     }
5874   }
5875 
5876   if (InitializationFailed || Trap.hasErrorOccurred())
5877     return cast<EnableIfAttr>(Attrs[0]);
5878 
5879   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5880     APValue Result;
5881     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5882     if (EIA->getCond()->isValueDependent()) {
5883       // Don't even try now, we'll examine it after instantiation.
5884       continue;
5885     }
5886 
5887     if (!EIA->getCond()->EvaluateWithSubstitution(
5888             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5889       if (!ContainsValueDependentExpr)
5890         return EIA;
5891     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5892       return EIA;
5893     }
5894   }
5895   return nullptr;
5896 }
5897 
5898 /// \brief Add all of the function declarations in the given function set to
5899 /// the overload candidate set.
5900 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5901                                  ArrayRef<Expr *> Args,
5902                                  OverloadCandidateSet& CandidateSet,
5903                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5904                                  bool SuppressUserConversions,
5905                                  bool PartialOverloading) {
5906   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5907     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5908     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5909       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5910         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5911                            cast<CXXMethodDecl>(FD)->getParent(),
5912                            Args[0]->getType(), Args[0]->Classify(Context),
5913                            Args.slice(1), CandidateSet,
5914                            SuppressUserConversions, PartialOverloading);
5915       else
5916         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5917                              SuppressUserConversions, PartialOverloading);
5918     } else {
5919       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5920       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5921           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5922         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5923                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5924                                    ExplicitTemplateArgs,
5925                                    Args[0]->getType(),
5926                                    Args[0]->Classify(Context), Args.slice(1),
5927                                    CandidateSet, SuppressUserConversions,
5928                                    PartialOverloading);
5929       else
5930         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5931                                      ExplicitTemplateArgs, Args,
5932                                      CandidateSet, SuppressUserConversions,
5933                                      PartialOverloading);
5934     }
5935   }
5936 }
5937 
5938 /// AddMethodCandidate - Adds a named decl (which is some kind of
5939 /// method) as a method candidate to the given overload set.
5940 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5941                               QualType ObjectType,
5942                               Expr::Classification ObjectClassification,
5943                               ArrayRef<Expr *> Args,
5944                               OverloadCandidateSet& CandidateSet,
5945                               bool SuppressUserConversions) {
5946   NamedDecl *Decl = FoundDecl.getDecl();
5947   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5948 
5949   if (isa<UsingShadowDecl>(Decl))
5950     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5951 
5952   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5953     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5954            "Expected a member function template");
5955     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5956                                /*ExplicitArgs*/ nullptr,
5957                                ObjectType, ObjectClassification,
5958                                Args, CandidateSet,
5959                                SuppressUserConversions);
5960   } else {
5961     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5962                        ObjectType, ObjectClassification,
5963                        Args,
5964                        CandidateSet, SuppressUserConversions);
5965   }
5966 }
5967 
5968 /// AddMethodCandidate - Adds the given C++ member function to the set
5969 /// of candidate functions, using the given function call arguments
5970 /// and the object argument (@c Object). For example, in a call
5971 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5972 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5973 /// allow user-defined conversions via constructors or conversion
5974 /// operators.
5975 void
5976 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5977                          CXXRecordDecl *ActingContext, QualType ObjectType,
5978                          Expr::Classification ObjectClassification,
5979                          ArrayRef<Expr *> Args,
5980                          OverloadCandidateSet &CandidateSet,
5981                          bool SuppressUserConversions,
5982                          bool PartialOverloading) {
5983   const FunctionProtoType *Proto
5984     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5985   assert(Proto && "Methods without a prototype cannot be overloaded");
5986   assert(!isa<CXXConstructorDecl>(Method) &&
5987          "Use AddOverloadCandidate for constructors");
5988 
5989   if (!CandidateSet.isNewCandidate(Method))
5990     return;
5991 
5992   // C++11 [class.copy]p23: [DR1402]
5993   //   A defaulted move assignment operator that is defined as deleted is
5994   //   ignored by overload resolution.
5995   if (Method->isDefaulted() && Method->isDeleted() &&
5996       Method->isMoveAssignmentOperator())
5997     return;
5998 
5999   // Overload resolution is always an unevaluated context.
6000   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6001 
6002   // Add this candidate
6003   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6004   Candidate.FoundDecl = FoundDecl;
6005   Candidate.Function = Method;
6006   Candidate.IsSurrogate = false;
6007   Candidate.IgnoreObjectArgument = false;
6008   Candidate.ExplicitCallArguments = Args.size();
6009 
6010   unsigned NumParams = Proto->getNumParams();
6011 
6012   // (C++ 13.3.2p2): A candidate function having fewer than m
6013   // parameters is viable only if it has an ellipsis in its parameter
6014   // list (8.3.5).
6015   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6016       !Proto->isVariadic()) {
6017     Candidate.Viable = false;
6018     Candidate.FailureKind = ovl_fail_too_many_arguments;
6019     return;
6020   }
6021 
6022   // (C++ 13.3.2p2): A candidate function having more than m parameters
6023   // is viable only if the (m+1)st parameter has a default argument
6024   // (8.3.6). For the purposes of overload resolution, the
6025   // parameter list is truncated on the right, so that there are
6026   // exactly m parameters.
6027   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6028   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6029     // Not enough arguments.
6030     Candidate.Viable = false;
6031     Candidate.FailureKind = ovl_fail_too_few_arguments;
6032     return;
6033   }
6034 
6035   Candidate.Viable = true;
6036 
6037   if (Method->isStatic() || ObjectType.isNull())
6038     // The implicit object argument is ignored.
6039     Candidate.IgnoreObjectArgument = true;
6040   else {
6041     // Determine the implicit conversion sequence for the object
6042     // parameter.
6043     Candidate.Conversions[0]
6044       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6045                                         Method, ActingContext);
6046     if (Candidate.Conversions[0].isBad()) {
6047       Candidate.Viable = false;
6048       Candidate.FailureKind = ovl_fail_bad_conversion;
6049       return;
6050     }
6051   }
6052 
6053   // (CUDA B.1): Check for invalid calls between targets.
6054   if (getLangOpts().CUDA)
6055     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6056       if (CheckCUDATarget(Caller, Method)) {
6057         Candidate.Viable = false;
6058         Candidate.FailureKind = ovl_fail_bad_target;
6059         return;
6060       }
6061 
6062   // Determine the implicit conversion sequences for each of the
6063   // arguments.
6064   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6065     if (ArgIdx < NumParams) {
6066       // (C++ 13.3.2p3): for F to be a viable function, there shall
6067       // exist for each argument an implicit conversion sequence
6068       // (13.3.3.1) that converts that argument to the corresponding
6069       // parameter of F.
6070       QualType ParamType = Proto->getParamType(ArgIdx);
6071       Candidate.Conversions[ArgIdx + 1]
6072         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6073                                 SuppressUserConversions,
6074                                 /*InOverloadResolution=*/true,
6075                                 /*AllowObjCWritebackConversion=*/
6076                                   getLangOpts().ObjCAutoRefCount);
6077       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6078         Candidate.Viable = false;
6079         Candidate.FailureKind = ovl_fail_bad_conversion;
6080         return;
6081       }
6082     } else {
6083       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6084       // argument for which there is no corresponding parameter is
6085       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6086       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6087     }
6088   }
6089 
6090   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6091     Candidate.Viable = false;
6092     Candidate.FailureKind = ovl_fail_enable_if;
6093     Candidate.DeductionFailure.Data = FailedAttr;
6094     return;
6095   }
6096 }
6097 
6098 /// \brief Add a C++ member function template as a candidate to the candidate
6099 /// set, using template argument deduction to produce an appropriate member
6100 /// function template specialization.
6101 void
6102 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6103                                  DeclAccessPair FoundDecl,
6104                                  CXXRecordDecl *ActingContext,
6105                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6106                                  QualType ObjectType,
6107                                  Expr::Classification ObjectClassification,
6108                                  ArrayRef<Expr *> Args,
6109                                  OverloadCandidateSet& CandidateSet,
6110                                  bool SuppressUserConversions,
6111                                  bool PartialOverloading) {
6112   if (!CandidateSet.isNewCandidate(MethodTmpl))
6113     return;
6114 
6115   // C++ [over.match.funcs]p7:
6116   //   In each case where a candidate is a function template, candidate
6117   //   function template specializations are generated using template argument
6118   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6119   //   candidate functions in the usual way.113) A given name can refer to one
6120   //   or more function templates and also to a set of overloaded non-template
6121   //   functions. In such a case, the candidate functions generated from each
6122   //   function template are combined with the set of non-template candidate
6123   //   functions.
6124   TemplateDeductionInfo Info(CandidateSet.getLocation());
6125   FunctionDecl *Specialization = nullptr;
6126   if (TemplateDeductionResult Result
6127       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6128                                 Specialization, Info, PartialOverloading)) {
6129     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6130     Candidate.FoundDecl = FoundDecl;
6131     Candidate.Function = MethodTmpl->getTemplatedDecl();
6132     Candidate.Viable = false;
6133     Candidate.FailureKind = ovl_fail_bad_deduction;
6134     Candidate.IsSurrogate = false;
6135     Candidate.IgnoreObjectArgument = false;
6136     Candidate.ExplicitCallArguments = Args.size();
6137     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6138                                                           Info);
6139     return;
6140   }
6141 
6142   // Add the function template specialization produced by template argument
6143   // deduction as a candidate.
6144   assert(Specialization && "Missing member function template specialization?");
6145   assert(isa<CXXMethodDecl>(Specialization) &&
6146          "Specialization is not a member function?");
6147   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6148                      ActingContext, ObjectType, ObjectClassification, Args,
6149                      CandidateSet, SuppressUserConversions, PartialOverloading);
6150 }
6151 
6152 /// \brief Add a C++ function template specialization as a candidate
6153 /// in the candidate set, using template argument deduction to produce
6154 /// an appropriate function template specialization.
6155 void
6156 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6157                                    DeclAccessPair FoundDecl,
6158                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6159                                    ArrayRef<Expr *> Args,
6160                                    OverloadCandidateSet& CandidateSet,
6161                                    bool SuppressUserConversions,
6162                                    bool PartialOverloading) {
6163   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6164     return;
6165 
6166   // C++ [over.match.funcs]p7:
6167   //   In each case where a candidate is a function template, candidate
6168   //   function template specializations are generated using template argument
6169   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6170   //   candidate functions in the usual way.113) A given name can refer to one
6171   //   or more function templates and also to a set of overloaded non-template
6172   //   functions. In such a case, the candidate functions generated from each
6173   //   function template are combined with the set of non-template candidate
6174   //   functions.
6175   TemplateDeductionInfo Info(CandidateSet.getLocation());
6176   FunctionDecl *Specialization = nullptr;
6177   if (TemplateDeductionResult Result
6178         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6179                                   Specialization, Info, PartialOverloading)) {
6180     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6181     Candidate.FoundDecl = FoundDecl;
6182     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6183     Candidate.Viable = false;
6184     Candidate.FailureKind = ovl_fail_bad_deduction;
6185     Candidate.IsSurrogate = false;
6186     Candidate.IgnoreObjectArgument = false;
6187     Candidate.ExplicitCallArguments = Args.size();
6188     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6189                                                           Info);
6190     return;
6191   }
6192 
6193   // Add the function template specialization produced by template argument
6194   // deduction as a candidate.
6195   assert(Specialization && "Missing function template specialization?");
6196   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6197                        SuppressUserConversions, PartialOverloading);
6198 }
6199 
6200 /// Determine whether this is an allowable conversion from the result
6201 /// of an explicit conversion operator to the expected type, per C++
6202 /// [over.match.conv]p1 and [over.match.ref]p1.
6203 ///
6204 /// \param ConvType The return type of the conversion function.
6205 ///
6206 /// \param ToType The type we are converting to.
6207 ///
6208 /// \param AllowObjCPointerConversion Allow a conversion from one
6209 /// Objective-C pointer to another.
6210 ///
6211 /// \returns true if the conversion is allowable, false otherwise.
6212 static bool isAllowableExplicitConversion(Sema &S,
6213                                           QualType ConvType, QualType ToType,
6214                                           bool AllowObjCPointerConversion) {
6215   QualType ToNonRefType = ToType.getNonReferenceType();
6216 
6217   // Easy case: the types are the same.
6218   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6219     return true;
6220 
6221   // Allow qualification conversions.
6222   bool ObjCLifetimeConversion;
6223   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6224                                   ObjCLifetimeConversion))
6225     return true;
6226 
6227   // If we're not allowed to consider Objective-C pointer conversions,
6228   // we're done.
6229   if (!AllowObjCPointerConversion)
6230     return false;
6231 
6232   // Is this an Objective-C pointer conversion?
6233   bool IncompatibleObjC = false;
6234   QualType ConvertedType;
6235   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6236                                    IncompatibleObjC);
6237 }
6238 
6239 /// AddConversionCandidate - Add a C++ conversion function as a
6240 /// candidate in the candidate set (C++ [over.match.conv],
6241 /// C++ [over.match.copy]). From is the expression we're converting from,
6242 /// and ToType is the type that we're eventually trying to convert to
6243 /// (which may or may not be the same type as the type that the
6244 /// conversion function produces).
6245 void
6246 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6247                              DeclAccessPair FoundDecl,
6248                              CXXRecordDecl *ActingContext,
6249                              Expr *From, QualType ToType,
6250                              OverloadCandidateSet& CandidateSet,
6251                              bool AllowObjCConversionOnExplicit) {
6252   assert(!Conversion->getDescribedFunctionTemplate() &&
6253          "Conversion function templates use AddTemplateConversionCandidate");
6254   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6255   if (!CandidateSet.isNewCandidate(Conversion))
6256     return;
6257 
6258   // If the conversion function has an undeduced return type, trigger its
6259   // deduction now.
6260   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6261     if (DeduceReturnType(Conversion, From->getExprLoc()))
6262       return;
6263     ConvType = Conversion->getConversionType().getNonReferenceType();
6264   }
6265 
6266   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6267   // operator is only a candidate if its return type is the target type or
6268   // can be converted to the target type with a qualification conversion.
6269   if (Conversion->isExplicit() &&
6270       !isAllowableExplicitConversion(*this, ConvType, ToType,
6271                                      AllowObjCConversionOnExplicit))
6272     return;
6273 
6274   // Overload resolution is always an unevaluated context.
6275   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6276 
6277   // Add this candidate
6278   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6279   Candidate.FoundDecl = FoundDecl;
6280   Candidate.Function = Conversion;
6281   Candidate.IsSurrogate = false;
6282   Candidate.IgnoreObjectArgument = false;
6283   Candidate.FinalConversion.setAsIdentityConversion();
6284   Candidate.FinalConversion.setFromType(ConvType);
6285   Candidate.FinalConversion.setAllToTypes(ToType);
6286   Candidate.Viable = true;
6287   Candidate.ExplicitCallArguments = 1;
6288 
6289   // C++ [over.match.funcs]p4:
6290   //   For conversion functions, the function is considered to be a member of
6291   //   the class of the implicit implied object argument for the purpose of
6292   //   defining the type of the implicit object parameter.
6293   //
6294   // Determine the implicit conversion sequence for the implicit
6295   // object parameter.
6296   QualType ImplicitParamType = From->getType();
6297   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6298     ImplicitParamType = FromPtrType->getPointeeType();
6299   CXXRecordDecl *ConversionContext
6300     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6301 
6302   Candidate.Conversions[0]
6303     = TryObjectArgumentInitialization(*this, From->getType(),
6304                                       From->Classify(Context),
6305                                       Conversion, ConversionContext);
6306 
6307   if (Candidate.Conversions[0].isBad()) {
6308     Candidate.Viable = false;
6309     Candidate.FailureKind = ovl_fail_bad_conversion;
6310     return;
6311   }
6312 
6313   // We won't go through a user-defined type conversion function to convert a
6314   // derived to base as such conversions are given Conversion Rank. They only
6315   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6316   QualType FromCanon
6317     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6318   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6319   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6320     Candidate.Viable = false;
6321     Candidate.FailureKind = ovl_fail_trivial_conversion;
6322     return;
6323   }
6324 
6325   // To determine what the conversion from the result of calling the
6326   // conversion function to the type we're eventually trying to
6327   // convert to (ToType), we need to synthesize a call to the
6328   // conversion function and attempt copy initialization from it. This
6329   // makes sure that we get the right semantics with respect to
6330   // lvalues/rvalues and the type. Fortunately, we can allocate this
6331   // call on the stack and we don't need its arguments to be
6332   // well-formed.
6333   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6334                             VK_LValue, From->getLocStart());
6335   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6336                                 Context.getPointerType(Conversion->getType()),
6337                                 CK_FunctionToPointerDecay,
6338                                 &ConversionRef, VK_RValue);
6339 
6340   QualType ConversionType = Conversion->getConversionType();
6341   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6342     Candidate.Viable = false;
6343     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6344     return;
6345   }
6346 
6347   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6348 
6349   // Note that it is safe to allocate CallExpr on the stack here because
6350   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6351   // allocator).
6352   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6353   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6354                 From->getLocStart());
6355   ImplicitConversionSequence ICS =
6356     TryCopyInitialization(*this, &Call, ToType,
6357                           /*SuppressUserConversions=*/true,
6358                           /*InOverloadResolution=*/false,
6359                           /*AllowObjCWritebackConversion=*/false);
6360 
6361   switch (ICS.getKind()) {
6362   case ImplicitConversionSequence::StandardConversion:
6363     Candidate.FinalConversion = ICS.Standard;
6364 
6365     // C++ [over.ics.user]p3:
6366     //   If the user-defined conversion is specified by a specialization of a
6367     //   conversion function template, the second standard conversion sequence
6368     //   shall have exact match rank.
6369     if (Conversion->getPrimaryTemplate() &&
6370         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6371       Candidate.Viable = false;
6372       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6373       return;
6374     }
6375 
6376     // C++0x [dcl.init.ref]p5:
6377     //    In the second case, if the reference is an rvalue reference and
6378     //    the second standard conversion sequence of the user-defined
6379     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6380     //    program is ill-formed.
6381     if (ToType->isRValueReferenceType() &&
6382         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6383       Candidate.Viable = false;
6384       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6385       return;
6386     }
6387     break;
6388 
6389   case ImplicitConversionSequence::BadConversion:
6390     Candidate.Viable = false;
6391     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6392     return;
6393 
6394   default:
6395     llvm_unreachable(
6396            "Can only end up with a standard conversion sequence or failure");
6397   }
6398 
6399   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6400     Candidate.Viable = false;
6401     Candidate.FailureKind = ovl_fail_enable_if;
6402     Candidate.DeductionFailure.Data = FailedAttr;
6403     return;
6404   }
6405 }
6406 
6407 /// \brief Adds a conversion function template specialization
6408 /// candidate to the overload set, using template argument deduction
6409 /// to deduce the template arguments of the conversion function
6410 /// template from the type that we are converting to (C++
6411 /// [temp.deduct.conv]).
6412 void
6413 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6414                                      DeclAccessPair FoundDecl,
6415                                      CXXRecordDecl *ActingDC,
6416                                      Expr *From, QualType ToType,
6417                                      OverloadCandidateSet &CandidateSet,
6418                                      bool AllowObjCConversionOnExplicit) {
6419   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6420          "Only conversion function templates permitted here");
6421 
6422   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6423     return;
6424 
6425   TemplateDeductionInfo Info(CandidateSet.getLocation());
6426   CXXConversionDecl *Specialization = nullptr;
6427   if (TemplateDeductionResult Result
6428         = DeduceTemplateArguments(FunctionTemplate, ToType,
6429                                   Specialization, Info)) {
6430     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6431     Candidate.FoundDecl = FoundDecl;
6432     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6433     Candidate.Viable = false;
6434     Candidate.FailureKind = ovl_fail_bad_deduction;
6435     Candidate.IsSurrogate = false;
6436     Candidate.IgnoreObjectArgument = false;
6437     Candidate.ExplicitCallArguments = 1;
6438     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6439                                                           Info);
6440     return;
6441   }
6442 
6443   // Add the conversion function template specialization produced by
6444   // template argument deduction as a candidate.
6445   assert(Specialization && "Missing function template specialization?");
6446   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6447                          CandidateSet, AllowObjCConversionOnExplicit);
6448 }
6449 
6450 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6451 /// converts the given @c Object to a function pointer via the
6452 /// conversion function @c Conversion, and then attempts to call it
6453 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6454 /// the type of function that we'll eventually be calling.
6455 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6456                                  DeclAccessPair FoundDecl,
6457                                  CXXRecordDecl *ActingContext,
6458                                  const FunctionProtoType *Proto,
6459                                  Expr *Object,
6460                                  ArrayRef<Expr *> Args,
6461                                  OverloadCandidateSet& CandidateSet) {
6462   if (!CandidateSet.isNewCandidate(Conversion))
6463     return;
6464 
6465   // Overload resolution is always an unevaluated context.
6466   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6467 
6468   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6469   Candidate.FoundDecl = FoundDecl;
6470   Candidate.Function = nullptr;
6471   Candidate.Surrogate = Conversion;
6472   Candidate.Viable = true;
6473   Candidate.IsSurrogate = true;
6474   Candidate.IgnoreObjectArgument = false;
6475   Candidate.ExplicitCallArguments = Args.size();
6476 
6477   // Determine the implicit conversion sequence for the implicit
6478   // object parameter.
6479   ImplicitConversionSequence ObjectInit
6480     = TryObjectArgumentInitialization(*this, Object->getType(),
6481                                       Object->Classify(Context),
6482                                       Conversion, ActingContext);
6483   if (ObjectInit.isBad()) {
6484     Candidate.Viable = false;
6485     Candidate.FailureKind = ovl_fail_bad_conversion;
6486     Candidate.Conversions[0] = ObjectInit;
6487     return;
6488   }
6489 
6490   // The first conversion is actually a user-defined conversion whose
6491   // first conversion is ObjectInit's standard conversion (which is
6492   // effectively a reference binding). Record it as such.
6493   Candidate.Conversions[0].setUserDefined();
6494   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6495   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6496   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6497   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6498   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6499   Candidate.Conversions[0].UserDefined.After
6500     = Candidate.Conversions[0].UserDefined.Before;
6501   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6502 
6503   // Find the
6504   unsigned NumParams = Proto->getNumParams();
6505 
6506   // (C++ 13.3.2p2): A candidate function having fewer than m
6507   // parameters is viable only if it has an ellipsis in its parameter
6508   // list (8.3.5).
6509   if (Args.size() > NumParams && !Proto->isVariadic()) {
6510     Candidate.Viable = false;
6511     Candidate.FailureKind = ovl_fail_too_many_arguments;
6512     return;
6513   }
6514 
6515   // Function types don't have any default arguments, so just check if
6516   // we have enough arguments.
6517   if (Args.size() < NumParams) {
6518     // Not enough arguments.
6519     Candidate.Viable = false;
6520     Candidate.FailureKind = ovl_fail_too_few_arguments;
6521     return;
6522   }
6523 
6524   // Determine the implicit conversion sequences for each of the
6525   // arguments.
6526   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6527     if (ArgIdx < NumParams) {
6528       // (C++ 13.3.2p3): for F to be a viable function, there shall
6529       // exist for each argument an implicit conversion sequence
6530       // (13.3.3.1) that converts that argument to the corresponding
6531       // parameter of F.
6532       QualType ParamType = Proto->getParamType(ArgIdx);
6533       Candidate.Conversions[ArgIdx + 1]
6534         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6535                                 /*SuppressUserConversions=*/false,
6536                                 /*InOverloadResolution=*/false,
6537                                 /*AllowObjCWritebackConversion=*/
6538                                   getLangOpts().ObjCAutoRefCount);
6539       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6540         Candidate.Viable = false;
6541         Candidate.FailureKind = ovl_fail_bad_conversion;
6542         return;
6543       }
6544     } else {
6545       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6546       // argument for which there is no corresponding parameter is
6547       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6548       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6549     }
6550   }
6551 
6552   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6553     Candidate.Viable = false;
6554     Candidate.FailureKind = ovl_fail_enable_if;
6555     Candidate.DeductionFailure.Data = FailedAttr;
6556     return;
6557   }
6558 }
6559 
6560 /// \brief Add overload candidates for overloaded operators that are
6561 /// member functions.
6562 ///
6563 /// Add the overloaded operator candidates that are member functions
6564 /// for the operator Op that was used in an operator expression such
6565 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6566 /// CandidateSet will store the added overload candidates. (C++
6567 /// [over.match.oper]).
6568 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6569                                        SourceLocation OpLoc,
6570                                        ArrayRef<Expr *> Args,
6571                                        OverloadCandidateSet& CandidateSet,
6572                                        SourceRange OpRange) {
6573   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6574 
6575   // C++ [over.match.oper]p3:
6576   //   For a unary operator @ with an operand of a type whose
6577   //   cv-unqualified version is T1, and for a binary operator @ with
6578   //   a left operand of a type whose cv-unqualified version is T1 and
6579   //   a right operand of a type whose cv-unqualified version is T2,
6580   //   three sets of candidate functions, designated member
6581   //   candidates, non-member candidates and built-in candidates, are
6582   //   constructed as follows:
6583   QualType T1 = Args[0]->getType();
6584 
6585   //     -- If T1 is a complete class type or a class currently being
6586   //        defined, the set of member candidates is the result of the
6587   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6588   //        the set of member candidates is empty.
6589   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6590     // Complete the type if it can be completed.
6591     RequireCompleteType(OpLoc, T1, 0);
6592     // If the type is neither complete nor being defined, bail out now.
6593     if (!T1Rec->getDecl()->getDefinition())
6594       return;
6595 
6596     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6597     LookupQualifiedName(Operators, T1Rec->getDecl());
6598     Operators.suppressDiagnostics();
6599 
6600     for (LookupResult::iterator Oper = Operators.begin(),
6601                              OperEnd = Operators.end();
6602          Oper != OperEnd;
6603          ++Oper)
6604       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6605                          Args[0]->Classify(Context),
6606                          Args.slice(1),
6607                          CandidateSet,
6608                          /* SuppressUserConversions = */ false);
6609   }
6610 }
6611 
6612 /// AddBuiltinCandidate - Add a candidate for a built-in
6613 /// operator. ResultTy and ParamTys are the result and parameter types
6614 /// of the built-in candidate, respectively. Args and NumArgs are the
6615 /// arguments being passed to the candidate. IsAssignmentOperator
6616 /// should be true when this built-in candidate is an assignment
6617 /// operator. NumContextualBoolArguments is the number of arguments
6618 /// (at the beginning of the argument list) that will be contextually
6619 /// converted to bool.
6620 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6621                                ArrayRef<Expr *> Args,
6622                                OverloadCandidateSet& CandidateSet,
6623                                bool IsAssignmentOperator,
6624                                unsigned NumContextualBoolArguments) {
6625   // Overload resolution is always an unevaluated context.
6626   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6627 
6628   // Add this candidate
6629   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6630   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6631   Candidate.Function = nullptr;
6632   Candidate.IsSurrogate = false;
6633   Candidate.IgnoreObjectArgument = false;
6634   Candidate.BuiltinTypes.ResultTy = ResultTy;
6635   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6636     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6637 
6638   // Determine the implicit conversion sequences for each of the
6639   // arguments.
6640   Candidate.Viable = true;
6641   Candidate.ExplicitCallArguments = Args.size();
6642   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6643     // C++ [over.match.oper]p4:
6644     //   For the built-in assignment operators, conversions of the
6645     //   left operand are restricted as follows:
6646     //     -- no temporaries are introduced to hold the left operand, and
6647     //     -- no user-defined conversions are applied to the left
6648     //        operand to achieve a type match with the left-most
6649     //        parameter of a built-in candidate.
6650     //
6651     // We block these conversions by turning off user-defined
6652     // conversions, since that is the only way that initialization of
6653     // a reference to a non-class type can occur from something that
6654     // is not of the same type.
6655     if (ArgIdx < NumContextualBoolArguments) {
6656       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6657              "Contextual conversion to bool requires bool type");
6658       Candidate.Conversions[ArgIdx]
6659         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6660     } else {
6661       Candidate.Conversions[ArgIdx]
6662         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6663                                 ArgIdx == 0 && IsAssignmentOperator,
6664                                 /*InOverloadResolution=*/false,
6665                                 /*AllowObjCWritebackConversion=*/
6666                                   getLangOpts().ObjCAutoRefCount);
6667     }
6668     if (Candidate.Conversions[ArgIdx].isBad()) {
6669       Candidate.Viable = false;
6670       Candidate.FailureKind = ovl_fail_bad_conversion;
6671       break;
6672     }
6673   }
6674 }
6675 
6676 namespace {
6677 
6678 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6679 /// candidate operator functions for built-in operators (C++
6680 /// [over.built]). The types are separated into pointer types and
6681 /// enumeration types.
6682 class BuiltinCandidateTypeSet  {
6683   /// TypeSet - A set of types.
6684   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6685 
6686   /// PointerTypes - The set of pointer types that will be used in the
6687   /// built-in candidates.
6688   TypeSet PointerTypes;
6689 
6690   /// MemberPointerTypes - The set of member pointer types that will be
6691   /// used in the built-in candidates.
6692   TypeSet MemberPointerTypes;
6693 
6694   /// EnumerationTypes - The set of enumeration types that will be
6695   /// used in the built-in candidates.
6696   TypeSet EnumerationTypes;
6697 
6698   /// \brief The set of vector types that will be used in the built-in
6699   /// candidates.
6700   TypeSet VectorTypes;
6701 
6702   /// \brief A flag indicating non-record types are viable candidates
6703   bool HasNonRecordTypes;
6704 
6705   /// \brief A flag indicating whether either arithmetic or enumeration types
6706   /// were present in the candidate set.
6707   bool HasArithmeticOrEnumeralTypes;
6708 
6709   /// \brief A flag indicating whether the nullptr type was present in the
6710   /// candidate set.
6711   bool HasNullPtrType;
6712 
6713   /// Sema - The semantic analysis instance where we are building the
6714   /// candidate type set.
6715   Sema &SemaRef;
6716 
6717   /// Context - The AST context in which we will build the type sets.
6718   ASTContext &Context;
6719 
6720   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6721                                                const Qualifiers &VisibleQuals);
6722   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6723 
6724 public:
6725   /// iterator - Iterates through the types that are part of the set.
6726   typedef TypeSet::iterator iterator;
6727 
6728   BuiltinCandidateTypeSet(Sema &SemaRef)
6729     : HasNonRecordTypes(false),
6730       HasArithmeticOrEnumeralTypes(false),
6731       HasNullPtrType(false),
6732       SemaRef(SemaRef),
6733       Context(SemaRef.Context) { }
6734 
6735   void AddTypesConvertedFrom(QualType Ty,
6736                              SourceLocation Loc,
6737                              bool AllowUserConversions,
6738                              bool AllowExplicitConversions,
6739                              const Qualifiers &VisibleTypeConversionsQuals);
6740 
6741   /// pointer_begin - First pointer type found;
6742   iterator pointer_begin() { return PointerTypes.begin(); }
6743 
6744   /// pointer_end - Past the last pointer type found;
6745   iterator pointer_end() { return PointerTypes.end(); }
6746 
6747   /// member_pointer_begin - First member pointer type found;
6748   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6749 
6750   /// member_pointer_end - Past the last member pointer type found;
6751   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6752 
6753   /// enumeration_begin - First enumeration type found;
6754   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6755 
6756   /// enumeration_end - Past the last enumeration type found;
6757   iterator enumeration_end() { return EnumerationTypes.end(); }
6758 
6759   iterator vector_begin() { return VectorTypes.begin(); }
6760   iterator vector_end() { return VectorTypes.end(); }
6761 
6762   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6763   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6764   bool hasNullPtrType() const { return HasNullPtrType; }
6765 };
6766 
6767 } // end anonymous namespace
6768 
6769 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6770 /// the set of pointer types along with any more-qualified variants of
6771 /// that type. For example, if @p Ty is "int const *", this routine
6772 /// will add "int const *", "int const volatile *", "int const
6773 /// restrict *", and "int const volatile restrict *" to the set of
6774 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6775 /// false otherwise.
6776 ///
6777 /// FIXME: what to do about extended qualifiers?
6778 bool
6779 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6780                                              const Qualifiers &VisibleQuals) {
6781 
6782   // Insert this type.
6783   if (!PointerTypes.insert(Ty).second)
6784     return false;
6785 
6786   QualType PointeeTy;
6787   const PointerType *PointerTy = Ty->getAs<PointerType>();
6788   bool buildObjCPtr = false;
6789   if (!PointerTy) {
6790     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6791     PointeeTy = PTy->getPointeeType();
6792     buildObjCPtr = true;
6793   } else {
6794     PointeeTy = PointerTy->getPointeeType();
6795   }
6796 
6797   // Don't add qualified variants of arrays. For one, they're not allowed
6798   // (the qualifier would sink to the element type), and for another, the
6799   // only overload situation where it matters is subscript or pointer +- int,
6800   // and those shouldn't have qualifier variants anyway.
6801   if (PointeeTy->isArrayType())
6802     return true;
6803 
6804   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6805   bool hasVolatile = VisibleQuals.hasVolatile();
6806   bool hasRestrict = VisibleQuals.hasRestrict();
6807 
6808   // Iterate through all strict supersets of BaseCVR.
6809   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6810     if ((CVR | BaseCVR) != CVR) continue;
6811     // Skip over volatile if no volatile found anywhere in the types.
6812     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6813 
6814     // Skip over restrict if no restrict found anywhere in the types, or if
6815     // the type cannot be restrict-qualified.
6816     if ((CVR & Qualifiers::Restrict) &&
6817         (!hasRestrict ||
6818          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6819       continue;
6820 
6821     // Build qualified pointee type.
6822     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6823 
6824     // Build qualified pointer type.
6825     QualType QPointerTy;
6826     if (!buildObjCPtr)
6827       QPointerTy = Context.getPointerType(QPointeeTy);
6828     else
6829       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6830 
6831     // Insert qualified pointer type.
6832     PointerTypes.insert(QPointerTy);
6833   }
6834 
6835   return true;
6836 }
6837 
6838 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6839 /// to the set of pointer types along with any more-qualified variants of
6840 /// that type. For example, if @p Ty is "int const *", this routine
6841 /// will add "int const *", "int const volatile *", "int const
6842 /// restrict *", and "int const volatile restrict *" to the set of
6843 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6844 /// false otherwise.
6845 ///
6846 /// FIXME: what to do about extended qualifiers?
6847 bool
6848 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6849     QualType Ty) {
6850   // Insert this type.
6851   if (!MemberPointerTypes.insert(Ty).second)
6852     return false;
6853 
6854   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6855   assert(PointerTy && "type was not a member pointer type!");
6856 
6857   QualType PointeeTy = PointerTy->getPointeeType();
6858   // Don't add qualified variants of arrays. For one, they're not allowed
6859   // (the qualifier would sink to the element type), and for another, the
6860   // only overload situation where it matters is subscript or pointer +- int,
6861   // and those shouldn't have qualifier variants anyway.
6862   if (PointeeTy->isArrayType())
6863     return true;
6864   const Type *ClassTy = PointerTy->getClass();
6865 
6866   // Iterate through all strict supersets of the pointee type's CVR
6867   // qualifiers.
6868   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6869   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6870     if ((CVR | BaseCVR) != CVR) continue;
6871 
6872     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6873     MemberPointerTypes.insert(
6874       Context.getMemberPointerType(QPointeeTy, ClassTy));
6875   }
6876 
6877   return true;
6878 }
6879 
6880 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6881 /// Ty can be implicit converted to the given set of @p Types. We're
6882 /// primarily interested in pointer types and enumeration types. We also
6883 /// take member pointer types, for the conditional operator.
6884 /// AllowUserConversions is true if we should look at the conversion
6885 /// functions of a class type, and AllowExplicitConversions if we
6886 /// should also include the explicit conversion functions of a class
6887 /// type.
6888 void
6889 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6890                                                SourceLocation Loc,
6891                                                bool AllowUserConversions,
6892                                                bool AllowExplicitConversions,
6893                                                const Qualifiers &VisibleQuals) {
6894   // Only deal with canonical types.
6895   Ty = Context.getCanonicalType(Ty);
6896 
6897   // Look through reference types; they aren't part of the type of an
6898   // expression for the purposes of conversions.
6899   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6900     Ty = RefTy->getPointeeType();
6901 
6902   // If we're dealing with an array type, decay to the pointer.
6903   if (Ty->isArrayType())
6904     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6905 
6906   // Otherwise, we don't care about qualifiers on the type.
6907   Ty = Ty.getLocalUnqualifiedType();
6908 
6909   // Flag if we ever add a non-record type.
6910   const RecordType *TyRec = Ty->getAs<RecordType>();
6911   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6912 
6913   // Flag if we encounter an arithmetic type.
6914   HasArithmeticOrEnumeralTypes =
6915     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6916 
6917   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6918     PointerTypes.insert(Ty);
6919   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6920     // Insert our type, and its more-qualified variants, into the set
6921     // of types.
6922     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6923       return;
6924   } else if (Ty->isMemberPointerType()) {
6925     // Member pointers are far easier, since the pointee can't be converted.
6926     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6927       return;
6928   } else if (Ty->isEnumeralType()) {
6929     HasArithmeticOrEnumeralTypes = true;
6930     EnumerationTypes.insert(Ty);
6931   } else if (Ty->isVectorType()) {
6932     // We treat vector types as arithmetic types in many contexts as an
6933     // extension.
6934     HasArithmeticOrEnumeralTypes = true;
6935     VectorTypes.insert(Ty);
6936   } else if (Ty->isNullPtrType()) {
6937     HasNullPtrType = true;
6938   } else if (AllowUserConversions && TyRec) {
6939     // No conversion functions in incomplete types.
6940     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6941       return;
6942 
6943     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6944     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6945       if (isa<UsingShadowDecl>(D))
6946         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6947 
6948       // Skip conversion function templates; they don't tell us anything
6949       // about which builtin types we can convert to.
6950       if (isa<FunctionTemplateDecl>(D))
6951         continue;
6952 
6953       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6954       if (AllowExplicitConversions || !Conv->isExplicit()) {
6955         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6956                               VisibleQuals);
6957       }
6958     }
6959   }
6960 }
6961 
6962 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6963 /// the volatile- and non-volatile-qualified assignment operators for the
6964 /// given type to the candidate set.
6965 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6966                                                    QualType T,
6967                                                    ArrayRef<Expr *> Args,
6968                                     OverloadCandidateSet &CandidateSet) {
6969   QualType ParamTypes[2];
6970 
6971   // T& operator=(T&, T)
6972   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6973   ParamTypes[1] = T;
6974   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6975                         /*IsAssignmentOperator=*/true);
6976 
6977   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6978     // volatile T& operator=(volatile T&, T)
6979     ParamTypes[0]
6980       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6981     ParamTypes[1] = T;
6982     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6983                           /*IsAssignmentOperator=*/true);
6984   }
6985 }
6986 
6987 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6988 /// if any, found in visible type conversion functions found in ArgExpr's type.
6989 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6990     Qualifiers VRQuals;
6991     const RecordType *TyRec;
6992     if (const MemberPointerType *RHSMPType =
6993         ArgExpr->getType()->getAs<MemberPointerType>())
6994       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6995     else
6996       TyRec = ArgExpr->getType()->getAs<RecordType>();
6997     if (!TyRec) {
6998       // Just to be safe, assume the worst case.
6999       VRQuals.addVolatile();
7000       VRQuals.addRestrict();
7001       return VRQuals;
7002     }
7003 
7004     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7005     if (!ClassDecl->hasDefinition())
7006       return VRQuals;
7007 
7008     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7009       if (isa<UsingShadowDecl>(D))
7010         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7011       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7012         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7013         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7014           CanTy = ResTypeRef->getPointeeType();
7015         // Need to go down the pointer/mempointer chain and add qualifiers
7016         // as see them.
7017         bool done = false;
7018         while (!done) {
7019           if (CanTy.isRestrictQualified())
7020             VRQuals.addRestrict();
7021           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7022             CanTy = ResTypePtr->getPointeeType();
7023           else if (const MemberPointerType *ResTypeMPtr =
7024                 CanTy->getAs<MemberPointerType>())
7025             CanTy = ResTypeMPtr->getPointeeType();
7026           else
7027             done = true;
7028           if (CanTy.isVolatileQualified())
7029             VRQuals.addVolatile();
7030           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7031             return VRQuals;
7032         }
7033       }
7034     }
7035     return VRQuals;
7036 }
7037 
7038 namespace {
7039 
7040 /// \brief Helper class to manage the addition of builtin operator overload
7041 /// candidates. It provides shared state and utility methods used throughout
7042 /// the process, as well as a helper method to add each group of builtin
7043 /// operator overloads from the standard to a candidate set.
7044 class BuiltinOperatorOverloadBuilder {
7045   // Common instance state available to all overload candidate addition methods.
7046   Sema &S;
7047   ArrayRef<Expr *> Args;
7048   Qualifiers VisibleTypeConversionsQuals;
7049   bool HasArithmeticOrEnumeralCandidateType;
7050   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7051   OverloadCandidateSet &CandidateSet;
7052 
7053   // Define some constants used to index and iterate over the arithemetic types
7054   // provided via the getArithmeticType() method below.
7055   // The "promoted arithmetic types" are the arithmetic
7056   // types are that preserved by promotion (C++ [over.built]p2).
7057   static const unsigned FirstIntegralType = 3;
7058   static const unsigned LastIntegralType = 20;
7059   static const unsigned FirstPromotedIntegralType = 3,
7060                         LastPromotedIntegralType = 11;
7061   static const unsigned FirstPromotedArithmeticType = 0,
7062                         LastPromotedArithmeticType = 11;
7063   static const unsigned NumArithmeticTypes = 20;
7064 
7065   /// \brief Get the canonical type for a given arithmetic type index.
7066   CanQualType getArithmeticType(unsigned index) {
7067     assert(index < NumArithmeticTypes);
7068     static CanQualType ASTContext::* const
7069       ArithmeticTypes[NumArithmeticTypes] = {
7070       // Start of promoted types.
7071       &ASTContext::FloatTy,
7072       &ASTContext::DoubleTy,
7073       &ASTContext::LongDoubleTy,
7074 
7075       // Start of integral types.
7076       &ASTContext::IntTy,
7077       &ASTContext::LongTy,
7078       &ASTContext::LongLongTy,
7079       &ASTContext::Int128Ty,
7080       &ASTContext::UnsignedIntTy,
7081       &ASTContext::UnsignedLongTy,
7082       &ASTContext::UnsignedLongLongTy,
7083       &ASTContext::UnsignedInt128Ty,
7084       // End of promoted types.
7085 
7086       &ASTContext::BoolTy,
7087       &ASTContext::CharTy,
7088       &ASTContext::WCharTy,
7089       &ASTContext::Char16Ty,
7090       &ASTContext::Char32Ty,
7091       &ASTContext::SignedCharTy,
7092       &ASTContext::ShortTy,
7093       &ASTContext::UnsignedCharTy,
7094       &ASTContext::UnsignedShortTy,
7095       // End of integral types.
7096       // FIXME: What about complex? What about half?
7097     };
7098     return S.Context.*ArithmeticTypes[index];
7099   }
7100 
7101   /// \brief Gets the canonical type resulting from the usual arithemetic
7102   /// converions for the given arithmetic types.
7103   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7104     // Accelerator table for performing the usual arithmetic conversions.
7105     // The rules are basically:
7106     //   - if either is floating-point, use the wider floating-point
7107     //   - if same signedness, use the higher rank
7108     //   - if same size, use unsigned of the higher rank
7109     //   - use the larger type
7110     // These rules, together with the axiom that higher ranks are
7111     // never smaller, are sufficient to precompute all of these results
7112     // *except* when dealing with signed types of higher rank.
7113     // (we could precompute SLL x UI for all known platforms, but it's
7114     // better not to make any assumptions).
7115     // We assume that int128 has a higher rank than long long on all platforms.
7116     enum PromotedType {
7117             Dep=-1,
7118             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7119     };
7120     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7121                                         [LastPromotedArithmeticType] = {
7122 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7123 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7124 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7125 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7126 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7127 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7128 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7129 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7130 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7131 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7132 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7133     };
7134 
7135     assert(L < LastPromotedArithmeticType);
7136     assert(R < LastPromotedArithmeticType);
7137     int Idx = ConversionsTable[L][R];
7138 
7139     // Fast path: the table gives us a concrete answer.
7140     if (Idx != Dep) return getArithmeticType(Idx);
7141 
7142     // Slow path: we need to compare widths.
7143     // An invariant is that the signed type has higher rank.
7144     CanQualType LT = getArithmeticType(L),
7145                 RT = getArithmeticType(R);
7146     unsigned LW = S.Context.getIntWidth(LT),
7147              RW = S.Context.getIntWidth(RT);
7148 
7149     // If they're different widths, use the signed type.
7150     if (LW > RW) return LT;
7151     else if (LW < RW) return RT;
7152 
7153     // Otherwise, use the unsigned type of the signed type's rank.
7154     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7155     assert(L == SLL || R == SLL);
7156     return S.Context.UnsignedLongLongTy;
7157   }
7158 
7159   /// \brief Helper method to factor out the common pattern of adding overloads
7160   /// for '++' and '--' builtin operators.
7161   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7162                                            bool HasVolatile,
7163                                            bool HasRestrict) {
7164     QualType ParamTypes[2] = {
7165       S.Context.getLValueReferenceType(CandidateTy),
7166       S.Context.IntTy
7167     };
7168 
7169     // Non-volatile version.
7170     if (Args.size() == 1)
7171       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7172     else
7173       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7174 
7175     // Use a heuristic to reduce number of builtin candidates in the set:
7176     // add volatile version only if there are conversions to a volatile type.
7177     if (HasVolatile) {
7178       ParamTypes[0] =
7179         S.Context.getLValueReferenceType(
7180           S.Context.getVolatileType(CandidateTy));
7181       if (Args.size() == 1)
7182         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7183       else
7184         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7185     }
7186 
7187     // Add restrict version only if there are conversions to a restrict type
7188     // and our candidate type is a non-restrict-qualified pointer.
7189     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7190         !CandidateTy.isRestrictQualified()) {
7191       ParamTypes[0]
7192         = S.Context.getLValueReferenceType(
7193             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7194       if (Args.size() == 1)
7195         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7196       else
7197         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7198 
7199       if (HasVolatile) {
7200         ParamTypes[0]
7201           = S.Context.getLValueReferenceType(
7202               S.Context.getCVRQualifiedType(CandidateTy,
7203                                             (Qualifiers::Volatile |
7204                                              Qualifiers::Restrict)));
7205         if (Args.size() == 1)
7206           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7207         else
7208           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7209       }
7210     }
7211 
7212   }
7213 
7214 public:
7215   BuiltinOperatorOverloadBuilder(
7216     Sema &S, ArrayRef<Expr *> Args,
7217     Qualifiers VisibleTypeConversionsQuals,
7218     bool HasArithmeticOrEnumeralCandidateType,
7219     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7220     OverloadCandidateSet &CandidateSet)
7221     : S(S), Args(Args),
7222       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7223       HasArithmeticOrEnumeralCandidateType(
7224         HasArithmeticOrEnumeralCandidateType),
7225       CandidateTypes(CandidateTypes),
7226       CandidateSet(CandidateSet) {
7227     // Validate some of our static helper constants in debug builds.
7228     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7229            "Invalid first promoted integral type");
7230     assert(getArithmeticType(LastPromotedIntegralType - 1)
7231              == S.Context.UnsignedInt128Ty &&
7232            "Invalid last promoted integral type");
7233     assert(getArithmeticType(FirstPromotedArithmeticType)
7234              == S.Context.FloatTy &&
7235            "Invalid first promoted arithmetic type");
7236     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7237              == S.Context.UnsignedInt128Ty &&
7238            "Invalid last promoted arithmetic type");
7239   }
7240 
7241   // C++ [over.built]p3:
7242   //
7243   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7244   //   is either volatile or empty, there exist candidate operator
7245   //   functions of the form
7246   //
7247   //       VQ T&      operator++(VQ T&);
7248   //       T          operator++(VQ T&, int);
7249   //
7250   // C++ [over.built]p4:
7251   //
7252   //   For every pair (T, VQ), where T is an arithmetic type other
7253   //   than bool, and VQ is either volatile or empty, there exist
7254   //   candidate operator functions of the form
7255   //
7256   //       VQ T&      operator--(VQ T&);
7257   //       T          operator--(VQ T&, int);
7258   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7259     if (!HasArithmeticOrEnumeralCandidateType)
7260       return;
7261 
7262     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7263          Arith < NumArithmeticTypes; ++Arith) {
7264       addPlusPlusMinusMinusStyleOverloads(
7265         getArithmeticType(Arith),
7266         VisibleTypeConversionsQuals.hasVolatile(),
7267         VisibleTypeConversionsQuals.hasRestrict());
7268     }
7269   }
7270 
7271   // C++ [over.built]p5:
7272   //
7273   //   For every pair (T, VQ), where T is a cv-qualified or
7274   //   cv-unqualified object type, and VQ is either volatile or
7275   //   empty, there exist candidate operator functions of the form
7276   //
7277   //       T*VQ&      operator++(T*VQ&);
7278   //       T*VQ&      operator--(T*VQ&);
7279   //       T*         operator++(T*VQ&, int);
7280   //       T*         operator--(T*VQ&, int);
7281   void addPlusPlusMinusMinusPointerOverloads() {
7282     for (BuiltinCandidateTypeSet::iterator
7283               Ptr = CandidateTypes[0].pointer_begin(),
7284            PtrEnd = CandidateTypes[0].pointer_end();
7285          Ptr != PtrEnd; ++Ptr) {
7286       // Skip pointer types that aren't pointers to object types.
7287       if (!(*Ptr)->getPointeeType()->isObjectType())
7288         continue;
7289 
7290       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7291         (!(*Ptr).isVolatileQualified() &&
7292          VisibleTypeConversionsQuals.hasVolatile()),
7293         (!(*Ptr).isRestrictQualified() &&
7294          VisibleTypeConversionsQuals.hasRestrict()));
7295     }
7296   }
7297 
7298   // C++ [over.built]p6:
7299   //   For every cv-qualified or cv-unqualified object type T, there
7300   //   exist candidate operator functions of the form
7301   //
7302   //       T&         operator*(T*);
7303   //
7304   // C++ [over.built]p7:
7305   //   For every function type T that does not have cv-qualifiers or a
7306   //   ref-qualifier, there exist candidate operator functions of the form
7307   //       T&         operator*(T*);
7308   void addUnaryStarPointerOverloads() {
7309     for (BuiltinCandidateTypeSet::iterator
7310               Ptr = CandidateTypes[0].pointer_begin(),
7311            PtrEnd = CandidateTypes[0].pointer_end();
7312          Ptr != PtrEnd; ++Ptr) {
7313       QualType ParamTy = *Ptr;
7314       QualType PointeeTy = ParamTy->getPointeeType();
7315       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7316         continue;
7317 
7318       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7319         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7320           continue;
7321 
7322       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7323                             &ParamTy, Args, CandidateSet);
7324     }
7325   }
7326 
7327   // C++ [over.built]p9:
7328   //  For every promoted arithmetic type T, there exist candidate
7329   //  operator functions of the form
7330   //
7331   //       T         operator+(T);
7332   //       T         operator-(T);
7333   void addUnaryPlusOrMinusArithmeticOverloads() {
7334     if (!HasArithmeticOrEnumeralCandidateType)
7335       return;
7336 
7337     for (unsigned Arith = FirstPromotedArithmeticType;
7338          Arith < LastPromotedArithmeticType; ++Arith) {
7339       QualType ArithTy = getArithmeticType(Arith);
7340       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7341     }
7342 
7343     // Extension: We also add these operators for vector types.
7344     for (BuiltinCandidateTypeSet::iterator
7345               Vec = CandidateTypes[0].vector_begin(),
7346            VecEnd = CandidateTypes[0].vector_end();
7347          Vec != VecEnd; ++Vec) {
7348       QualType VecTy = *Vec;
7349       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7350     }
7351   }
7352 
7353   // C++ [over.built]p8:
7354   //   For every type T, there exist candidate operator functions of
7355   //   the form
7356   //
7357   //       T*         operator+(T*);
7358   void addUnaryPlusPointerOverloads() {
7359     for (BuiltinCandidateTypeSet::iterator
7360               Ptr = CandidateTypes[0].pointer_begin(),
7361            PtrEnd = CandidateTypes[0].pointer_end();
7362          Ptr != PtrEnd; ++Ptr) {
7363       QualType ParamTy = *Ptr;
7364       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7365     }
7366   }
7367 
7368   // C++ [over.built]p10:
7369   //   For every promoted integral type T, there exist candidate
7370   //   operator functions of the form
7371   //
7372   //        T         operator~(T);
7373   void addUnaryTildePromotedIntegralOverloads() {
7374     if (!HasArithmeticOrEnumeralCandidateType)
7375       return;
7376 
7377     for (unsigned Int = FirstPromotedIntegralType;
7378          Int < LastPromotedIntegralType; ++Int) {
7379       QualType IntTy = getArithmeticType(Int);
7380       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7381     }
7382 
7383     // Extension: We also add this operator for vector types.
7384     for (BuiltinCandidateTypeSet::iterator
7385               Vec = CandidateTypes[0].vector_begin(),
7386            VecEnd = CandidateTypes[0].vector_end();
7387          Vec != VecEnd; ++Vec) {
7388       QualType VecTy = *Vec;
7389       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7390     }
7391   }
7392 
7393   // C++ [over.match.oper]p16:
7394   //   For every pointer to member type T, there exist candidate operator
7395   //   functions of the form
7396   //
7397   //        bool operator==(T,T);
7398   //        bool operator!=(T,T);
7399   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7400     /// Set of (canonical) types that we've already handled.
7401     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7402 
7403     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7404       for (BuiltinCandidateTypeSet::iterator
7405                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7406              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7407            MemPtr != MemPtrEnd;
7408            ++MemPtr) {
7409         // Don't add the same builtin candidate twice.
7410         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7411           continue;
7412 
7413         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7414         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7415       }
7416     }
7417   }
7418 
7419   // C++ [over.built]p15:
7420   //
7421   //   For every T, where T is an enumeration type, a pointer type, or
7422   //   std::nullptr_t, there exist candidate operator functions of the form
7423   //
7424   //        bool       operator<(T, T);
7425   //        bool       operator>(T, T);
7426   //        bool       operator<=(T, T);
7427   //        bool       operator>=(T, T);
7428   //        bool       operator==(T, T);
7429   //        bool       operator!=(T, T);
7430   void addRelationalPointerOrEnumeralOverloads() {
7431     // C++ [over.match.oper]p3:
7432     //   [...]the built-in candidates include all of the candidate operator
7433     //   functions defined in 13.6 that, compared to the given operator, [...]
7434     //   do not have the same parameter-type-list as any non-template non-member
7435     //   candidate.
7436     //
7437     // Note that in practice, this only affects enumeration types because there
7438     // aren't any built-in candidates of record type, and a user-defined operator
7439     // must have an operand of record or enumeration type. Also, the only other
7440     // overloaded operator with enumeration arguments, operator=,
7441     // cannot be overloaded for enumeration types, so this is the only place
7442     // where we must suppress candidates like this.
7443     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7444       UserDefinedBinaryOperators;
7445 
7446     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7447       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7448           CandidateTypes[ArgIdx].enumeration_end()) {
7449         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7450                                          CEnd = CandidateSet.end();
7451              C != CEnd; ++C) {
7452           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7453             continue;
7454 
7455           if (C->Function->isFunctionTemplateSpecialization())
7456             continue;
7457 
7458           QualType FirstParamType =
7459             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7460           QualType SecondParamType =
7461             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7462 
7463           // Skip if either parameter isn't of enumeral type.
7464           if (!FirstParamType->isEnumeralType() ||
7465               !SecondParamType->isEnumeralType())
7466             continue;
7467 
7468           // Add this operator to the set of known user-defined operators.
7469           UserDefinedBinaryOperators.insert(
7470             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7471                            S.Context.getCanonicalType(SecondParamType)));
7472         }
7473       }
7474     }
7475 
7476     /// Set of (canonical) types that we've already handled.
7477     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7478 
7479     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7480       for (BuiltinCandidateTypeSet::iterator
7481                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7482              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7483            Ptr != PtrEnd; ++Ptr) {
7484         // Don't add the same builtin candidate twice.
7485         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7486           continue;
7487 
7488         QualType ParamTypes[2] = { *Ptr, *Ptr };
7489         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7490       }
7491       for (BuiltinCandidateTypeSet::iterator
7492                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7493              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7494            Enum != EnumEnd; ++Enum) {
7495         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7496 
7497         // Don't add the same builtin candidate twice, or if a user defined
7498         // candidate exists.
7499         if (!AddedTypes.insert(CanonType).second ||
7500             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7501                                                             CanonType)))
7502           continue;
7503 
7504         QualType ParamTypes[2] = { *Enum, *Enum };
7505         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7506       }
7507 
7508       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7509         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7510         if (AddedTypes.insert(NullPtrTy).second &&
7511             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7512                                                              NullPtrTy))) {
7513           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7514           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7515                                 CandidateSet);
7516         }
7517       }
7518     }
7519   }
7520 
7521   // C++ [over.built]p13:
7522   //
7523   //   For every cv-qualified or cv-unqualified object type T
7524   //   there exist candidate operator functions of the form
7525   //
7526   //      T*         operator+(T*, ptrdiff_t);
7527   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7528   //      T*         operator-(T*, ptrdiff_t);
7529   //      T*         operator+(ptrdiff_t, T*);
7530   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7531   //
7532   // C++ [over.built]p14:
7533   //
7534   //   For every T, where T is a pointer to object type, there
7535   //   exist candidate operator functions of the form
7536   //
7537   //      ptrdiff_t  operator-(T, T);
7538   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7539     /// Set of (canonical) types that we've already handled.
7540     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7541 
7542     for (int Arg = 0; Arg < 2; ++Arg) {
7543       QualType AsymetricParamTypes[2] = {
7544         S.Context.getPointerDiffType(),
7545         S.Context.getPointerDiffType(),
7546       };
7547       for (BuiltinCandidateTypeSet::iterator
7548                 Ptr = CandidateTypes[Arg].pointer_begin(),
7549              PtrEnd = CandidateTypes[Arg].pointer_end();
7550            Ptr != PtrEnd; ++Ptr) {
7551         QualType PointeeTy = (*Ptr)->getPointeeType();
7552         if (!PointeeTy->isObjectType())
7553           continue;
7554 
7555         AsymetricParamTypes[Arg] = *Ptr;
7556         if (Arg == 0 || Op == OO_Plus) {
7557           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7558           // T* operator+(ptrdiff_t, T*);
7559           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7560         }
7561         if (Op == OO_Minus) {
7562           // ptrdiff_t operator-(T, T);
7563           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7564             continue;
7565 
7566           QualType ParamTypes[2] = { *Ptr, *Ptr };
7567           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7568                                 Args, CandidateSet);
7569         }
7570       }
7571     }
7572   }
7573 
7574   // C++ [over.built]p12:
7575   //
7576   //   For every pair of promoted arithmetic types L and R, there
7577   //   exist candidate operator functions of the form
7578   //
7579   //        LR         operator*(L, R);
7580   //        LR         operator/(L, R);
7581   //        LR         operator+(L, R);
7582   //        LR         operator-(L, R);
7583   //        bool       operator<(L, R);
7584   //        bool       operator>(L, R);
7585   //        bool       operator<=(L, R);
7586   //        bool       operator>=(L, R);
7587   //        bool       operator==(L, R);
7588   //        bool       operator!=(L, R);
7589   //
7590   //   where LR is the result of the usual arithmetic conversions
7591   //   between types L and R.
7592   //
7593   // C++ [over.built]p24:
7594   //
7595   //   For every pair of promoted arithmetic types L and R, there exist
7596   //   candidate operator functions of the form
7597   //
7598   //        LR       operator?(bool, L, R);
7599   //
7600   //   where LR is the result of the usual arithmetic conversions
7601   //   between types L and R.
7602   // Our candidates ignore the first parameter.
7603   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7604     if (!HasArithmeticOrEnumeralCandidateType)
7605       return;
7606 
7607     for (unsigned Left = FirstPromotedArithmeticType;
7608          Left < LastPromotedArithmeticType; ++Left) {
7609       for (unsigned Right = FirstPromotedArithmeticType;
7610            Right < LastPromotedArithmeticType; ++Right) {
7611         QualType LandR[2] = { getArithmeticType(Left),
7612                               getArithmeticType(Right) };
7613         QualType Result =
7614           isComparison ? S.Context.BoolTy
7615                        : getUsualArithmeticConversions(Left, Right);
7616         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7617       }
7618     }
7619 
7620     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7621     // conditional operator for vector types.
7622     for (BuiltinCandidateTypeSet::iterator
7623               Vec1 = CandidateTypes[0].vector_begin(),
7624            Vec1End = CandidateTypes[0].vector_end();
7625          Vec1 != Vec1End; ++Vec1) {
7626       for (BuiltinCandidateTypeSet::iterator
7627                 Vec2 = CandidateTypes[1].vector_begin(),
7628              Vec2End = CandidateTypes[1].vector_end();
7629            Vec2 != Vec2End; ++Vec2) {
7630         QualType LandR[2] = { *Vec1, *Vec2 };
7631         QualType Result = S.Context.BoolTy;
7632         if (!isComparison) {
7633           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7634             Result = *Vec1;
7635           else
7636             Result = *Vec2;
7637         }
7638 
7639         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7640       }
7641     }
7642   }
7643 
7644   // C++ [over.built]p17:
7645   //
7646   //   For every pair of promoted integral types L and R, there
7647   //   exist candidate operator functions of the form
7648   //
7649   //      LR         operator%(L, R);
7650   //      LR         operator&(L, R);
7651   //      LR         operator^(L, R);
7652   //      LR         operator|(L, R);
7653   //      L          operator<<(L, R);
7654   //      L          operator>>(L, R);
7655   //
7656   //   where LR is the result of the usual arithmetic conversions
7657   //   between types L and R.
7658   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7659     if (!HasArithmeticOrEnumeralCandidateType)
7660       return;
7661 
7662     for (unsigned Left = FirstPromotedIntegralType;
7663          Left < LastPromotedIntegralType; ++Left) {
7664       for (unsigned Right = FirstPromotedIntegralType;
7665            Right < LastPromotedIntegralType; ++Right) {
7666         QualType LandR[2] = { getArithmeticType(Left),
7667                               getArithmeticType(Right) };
7668         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7669             ? LandR[0]
7670             : getUsualArithmeticConversions(Left, Right);
7671         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7672       }
7673     }
7674   }
7675 
7676   // C++ [over.built]p20:
7677   //
7678   //   For every pair (T, VQ), where T is an enumeration or
7679   //   pointer to member type and VQ is either volatile or
7680   //   empty, there exist candidate operator functions of the form
7681   //
7682   //        VQ T&      operator=(VQ T&, T);
7683   void addAssignmentMemberPointerOrEnumeralOverloads() {
7684     /// Set of (canonical) types that we've already handled.
7685     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7686 
7687     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7688       for (BuiltinCandidateTypeSet::iterator
7689                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7690              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7691            Enum != EnumEnd; ++Enum) {
7692         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7693           continue;
7694 
7695         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7696       }
7697 
7698       for (BuiltinCandidateTypeSet::iterator
7699                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7700              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7701            MemPtr != MemPtrEnd; ++MemPtr) {
7702         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7703           continue;
7704 
7705         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7706       }
7707     }
7708   }
7709 
7710   // C++ [over.built]p19:
7711   //
7712   //   For every pair (T, VQ), where T is any type and VQ is either
7713   //   volatile or empty, there exist candidate operator functions
7714   //   of the form
7715   //
7716   //        T*VQ&      operator=(T*VQ&, T*);
7717   //
7718   // C++ [over.built]p21:
7719   //
7720   //   For every pair (T, VQ), where T is a cv-qualified or
7721   //   cv-unqualified object type and VQ is either volatile or
7722   //   empty, there exist candidate operator functions of the form
7723   //
7724   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7725   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7726   void addAssignmentPointerOverloads(bool isEqualOp) {
7727     /// Set of (canonical) types that we've already handled.
7728     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7729 
7730     for (BuiltinCandidateTypeSet::iterator
7731               Ptr = CandidateTypes[0].pointer_begin(),
7732            PtrEnd = CandidateTypes[0].pointer_end();
7733          Ptr != PtrEnd; ++Ptr) {
7734       // If this is operator=, keep track of the builtin candidates we added.
7735       if (isEqualOp)
7736         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7737       else if (!(*Ptr)->getPointeeType()->isObjectType())
7738         continue;
7739 
7740       // non-volatile version
7741       QualType ParamTypes[2] = {
7742         S.Context.getLValueReferenceType(*Ptr),
7743         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7744       };
7745       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7746                             /*IsAssigmentOperator=*/ isEqualOp);
7747 
7748       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7749                           VisibleTypeConversionsQuals.hasVolatile();
7750       if (NeedVolatile) {
7751         // volatile version
7752         ParamTypes[0] =
7753           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7754         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7755                               /*IsAssigmentOperator=*/isEqualOp);
7756       }
7757 
7758       if (!(*Ptr).isRestrictQualified() &&
7759           VisibleTypeConversionsQuals.hasRestrict()) {
7760         // restrict version
7761         ParamTypes[0]
7762           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7763         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7764                               /*IsAssigmentOperator=*/isEqualOp);
7765 
7766         if (NeedVolatile) {
7767           // volatile restrict version
7768           ParamTypes[0]
7769             = S.Context.getLValueReferenceType(
7770                 S.Context.getCVRQualifiedType(*Ptr,
7771                                               (Qualifiers::Volatile |
7772                                                Qualifiers::Restrict)));
7773           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7774                                 /*IsAssigmentOperator=*/isEqualOp);
7775         }
7776       }
7777     }
7778 
7779     if (isEqualOp) {
7780       for (BuiltinCandidateTypeSet::iterator
7781                 Ptr = CandidateTypes[1].pointer_begin(),
7782              PtrEnd = CandidateTypes[1].pointer_end();
7783            Ptr != PtrEnd; ++Ptr) {
7784         // Make sure we don't add the same candidate twice.
7785         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7786           continue;
7787 
7788         QualType ParamTypes[2] = {
7789           S.Context.getLValueReferenceType(*Ptr),
7790           *Ptr,
7791         };
7792 
7793         // non-volatile version
7794         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7795                               /*IsAssigmentOperator=*/true);
7796 
7797         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7798                            VisibleTypeConversionsQuals.hasVolatile();
7799         if (NeedVolatile) {
7800           // volatile version
7801           ParamTypes[0] =
7802             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7803           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7804                                 /*IsAssigmentOperator=*/true);
7805         }
7806 
7807         if (!(*Ptr).isRestrictQualified() &&
7808             VisibleTypeConversionsQuals.hasRestrict()) {
7809           // restrict version
7810           ParamTypes[0]
7811             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7812           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7813                                 /*IsAssigmentOperator=*/true);
7814 
7815           if (NeedVolatile) {
7816             // volatile restrict version
7817             ParamTypes[0]
7818               = S.Context.getLValueReferenceType(
7819                   S.Context.getCVRQualifiedType(*Ptr,
7820                                                 (Qualifiers::Volatile |
7821                                                  Qualifiers::Restrict)));
7822             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7823                                   /*IsAssigmentOperator=*/true);
7824           }
7825         }
7826       }
7827     }
7828   }
7829 
7830   // C++ [over.built]p18:
7831   //
7832   //   For every triple (L, VQ, R), where L is an arithmetic type,
7833   //   VQ is either volatile or empty, and R is a promoted
7834   //   arithmetic type, there exist candidate operator functions of
7835   //   the form
7836   //
7837   //        VQ L&      operator=(VQ L&, R);
7838   //        VQ L&      operator*=(VQ L&, R);
7839   //        VQ L&      operator/=(VQ L&, R);
7840   //        VQ L&      operator+=(VQ L&, R);
7841   //        VQ L&      operator-=(VQ L&, R);
7842   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7843     if (!HasArithmeticOrEnumeralCandidateType)
7844       return;
7845 
7846     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7847       for (unsigned Right = FirstPromotedArithmeticType;
7848            Right < LastPromotedArithmeticType; ++Right) {
7849         QualType ParamTypes[2];
7850         ParamTypes[1] = getArithmeticType(Right);
7851 
7852         // Add this built-in operator as a candidate (VQ is empty).
7853         ParamTypes[0] =
7854           S.Context.getLValueReferenceType(getArithmeticType(Left));
7855         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7856                               /*IsAssigmentOperator=*/isEqualOp);
7857 
7858         // Add this built-in operator as a candidate (VQ is 'volatile').
7859         if (VisibleTypeConversionsQuals.hasVolatile()) {
7860           ParamTypes[0] =
7861             S.Context.getVolatileType(getArithmeticType(Left));
7862           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7863           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7864                                 /*IsAssigmentOperator=*/isEqualOp);
7865         }
7866       }
7867     }
7868 
7869     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7870     for (BuiltinCandidateTypeSet::iterator
7871               Vec1 = CandidateTypes[0].vector_begin(),
7872            Vec1End = CandidateTypes[0].vector_end();
7873          Vec1 != Vec1End; ++Vec1) {
7874       for (BuiltinCandidateTypeSet::iterator
7875                 Vec2 = CandidateTypes[1].vector_begin(),
7876              Vec2End = CandidateTypes[1].vector_end();
7877            Vec2 != Vec2End; ++Vec2) {
7878         QualType ParamTypes[2];
7879         ParamTypes[1] = *Vec2;
7880         // Add this built-in operator as a candidate (VQ is empty).
7881         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7882         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7883                               /*IsAssigmentOperator=*/isEqualOp);
7884 
7885         // Add this built-in operator as a candidate (VQ is 'volatile').
7886         if (VisibleTypeConversionsQuals.hasVolatile()) {
7887           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7888           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7889           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7890                                 /*IsAssigmentOperator=*/isEqualOp);
7891         }
7892       }
7893     }
7894   }
7895 
7896   // C++ [over.built]p22:
7897   //
7898   //   For every triple (L, VQ, R), where L is an integral type, VQ
7899   //   is either volatile or empty, and R is a promoted integral
7900   //   type, there exist candidate operator functions of the form
7901   //
7902   //        VQ L&       operator%=(VQ L&, R);
7903   //        VQ L&       operator<<=(VQ L&, R);
7904   //        VQ L&       operator>>=(VQ L&, R);
7905   //        VQ L&       operator&=(VQ L&, R);
7906   //        VQ L&       operator^=(VQ L&, R);
7907   //        VQ L&       operator|=(VQ L&, R);
7908   void addAssignmentIntegralOverloads() {
7909     if (!HasArithmeticOrEnumeralCandidateType)
7910       return;
7911 
7912     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7913       for (unsigned Right = FirstPromotedIntegralType;
7914            Right < LastPromotedIntegralType; ++Right) {
7915         QualType ParamTypes[2];
7916         ParamTypes[1] = getArithmeticType(Right);
7917 
7918         // Add this built-in operator as a candidate (VQ is empty).
7919         ParamTypes[0] =
7920           S.Context.getLValueReferenceType(getArithmeticType(Left));
7921         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7922         if (VisibleTypeConversionsQuals.hasVolatile()) {
7923           // Add this built-in operator as a candidate (VQ is 'volatile').
7924           ParamTypes[0] = getArithmeticType(Left);
7925           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7926           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7927           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7928         }
7929       }
7930     }
7931   }
7932 
7933   // C++ [over.operator]p23:
7934   //
7935   //   There also exist candidate operator functions of the form
7936   //
7937   //        bool        operator!(bool);
7938   //        bool        operator&&(bool, bool);
7939   //        bool        operator||(bool, bool);
7940   void addExclaimOverload() {
7941     QualType ParamTy = S.Context.BoolTy;
7942     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7943                           /*IsAssignmentOperator=*/false,
7944                           /*NumContextualBoolArguments=*/1);
7945   }
7946   void addAmpAmpOrPipePipeOverload() {
7947     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7948     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7949                           /*IsAssignmentOperator=*/false,
7950                           /*NumContextualBoolArguments=*/2);
7951   }
7952 
7953   // C++ [over.built]p13:
7954   //
7955   //   For every cv-qualified or cv-unqualified object type T there
7956   //   exist candidate operator functions of the form
7957   //
7958   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7959   //        T&         operator[](T*, ptrdiff_t);
7960   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7961   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7962   //        T&         operator[](ptrdiff_t, T*);
7963   void addSubscriptOverloads() {
7964     for (BuiltinCandidateTypeSet::iterator
7965               Ptr = CandidateTypes[0].pointer_begin(),
7966            PtrEnd = CandidateTypes[0].pointer_end();
7967          Ptr != PtrEnd; ++Ptr) {
7968       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7969       QualType PointeeType = (*Ptr)->getPointeeType();
7970       if (!PointeeType->isObjectType())
7971         continue;
7972 
7973       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7974 
7975       // T& operator[](T*, ptrdiff_t)
7976       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7977     }
7978 
7979     for (BuiltinCandidateTypeSet::iterator
7980               Ptr = CandidateTypes[1].pointer_begin(),
7981            PtrEnd = CandidateTypes[1].pointer_end();
7982          Ptr != PtrEnd; ++Ptr) {
7983       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7984       QualType PointeeType = (*Ptr)->getPointeeType();
7985       if (!PointeeType->isObjectType())
7986         continue;
7987 
7988       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7989 
7990       // T& operator[](ptrdiff_t, T*)
7991       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7992     }
7993   }
7994 
7995   // C++ [over.built]p11:
7996   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7997   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7998   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7999   //    there exist candidate operator functions of the form
8000   //
8001   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8002   //
8003   //    where CV12 is the union of CV1 and CV2.
8004   void addArrowStarOverloads() {
8005     for (BuiltinCandidateTypeSet::iterator
8006              Ptr = CandidateTypes[0].pointer_begin(),
8007            PtrEnd = CandidateTypes[0].pointer_end();
8008          Ptr != PtrEnd; ++Ptr) {
8009       QualType C1Ty = (*Ptr);
8010       QualType C1;
8011       QualifierCollector Q1;
8012       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8013       if (!isa<RecordType>(C1))
8014         continue;
8015       // heuristic to reduce number of builtin candidates in the set.
8016       // Add volatile/restrict version only if there are conversions to a
8017       // volatile/restrict type.
8018       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8019         continue;
8020       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8021         continue;
8022       for (BuiltinCandidateTypeSet::iterator
8023                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8024              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8025            MemPtr != MemPtrEnd; ++MemPtr) {
8026         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8027         QualType C2 = QualType(mptr->getClass(), 0);
8028         C2 = C2.getUnqualifiedType();
8029         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8030           break;
8031         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8032         // build CV12 T&
8033         QualType T = mptr->getPointeeType();
8034         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8035             T.isVolatileQualified())
8036           continue;
8037         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8038             T.isRestrictQualified())
8039           continue;
8040         T = Q1.apply(S.Context, T);
8041         QualType ResultTy = S.Context.getLValueReferenceType(T);
8042         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8043       }
8044     }
8045   }
8046 
8047   // Note that we don't consider the first argument, since it has been
8048   // contextually converted to bool long ago. The candidates below are
8049   // therefore added as binary.
8050   //
8051   // C++ [over.built]p25:
8052   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8053   //   enumeration type, there exist candidate operator functions of the form
8054   //
8055   //        T        operator?(bool, T, T);
8056   //
8057   void addConditionalOperatorOverloads() {
8058     /// Set of (canonical) types that we've already handled.
8059     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8060 
8061     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8062       for (BuiltinCandidateTypeSet::iterator
8063                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8064              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8065            Ptr != PtrEnd; ++Ptr) {
8066         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8067           continue;
8068 
8069         QualType ParamTypes[2] = { *Ptr, *Ptr };
8070         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8071       }
8072 
8073       for (BuiltinCandidateTypeSet::iterator
8074                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8075              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8076            MemPtr != MemPtrEnd; ++MemPtr) {
8077         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8078           continue;
8079 
8080         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8081         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8082       }
8083 
8084       if (S.getLangOpts().CPlusPlus11) {
8085         for (BuiltinCandidateTypeSet::iterator
8086                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8087                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8088              Enum != EnumEnd; ++Enum) {
8089           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8090             continue;
8091 
8092           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8093             continue;
8094 
8095           QualType ParamTypes[2] = { *Enum, *Enum };
8096           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8097         }
8098       }
8099     }
8100   }
8101 };
8102 
8103 } // end anonymous namespace
8104 
8105 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8106 /// operator overloads to the candidate set (C++ [over.built]), based
8107 /// on the operator @p Op and the arguments given. For example, if the
8108 /// operator is a binary '+', this routine might add "int
8109 /// operator+(int, int)" to cover integer addition.
8110 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8111                                         SourceLocation OpLoc,
8112                                         ArrayRef<Expr *> Args,
8113                                         OverloadCandidateSet &CandidateSet) {
8114   // Find all of the types that the arguments can convert to, but only
8115   // if the operator we're looking at has built-in operator candidates
8116   // that make use of these types. Also record whether we encounter non-record
8117   // candidate types or either arithmetic or enumeral candidate types.
8118   Qualifiers VisibleTypeConversionsQuals;
8119   VisibleTypeConversionsQuals.addConst();
8120   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8121     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8122 
8123   bool HasNonRecordCandidateType = false;
8124   bool HasArithmeticOrEnumeralCandidateType = false;
8125   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8126   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8127     CandidateTypes.emplace_back(*this);
8128     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8129                                                  OpLoc,
8130                                                  true,
8131                                                  (Op == OO_Exclaim ||
8132                                                   Op == OO_AmpAmp ||
8133                                                   Op == OO_PipePipe),
8134                                                  VisibleTypeConversionsQuals);
8135     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8136         CandidateTypes[ArgIdx].hasNonRecordTypes();
8137     HasArithmeticOrEnumeralCandidateType =
8138         HasArithmeticOrEnumeralCandidateType ||
8139         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8140   }
8141 
8142   // Exit early when no non-record types have been added to the candidate set
8143   // for any of the arguments to the operator.
8144   //
8145   // We can't exit early for !, ||, or &&, since there we have always have
8146   // 'bool' overloads.
8147   if (!HasNonRecordCandidateType &&
8148       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8149     return;
8150 
8151   // Setup an object to manage the common state for building overloads.
8152   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8153                                            VisibleTypeConversionsQuals,
8154                                            HasArithmeticOrEnumeralCandidateType,
8155                                            CandidateTypes, CandidateSet);
8156 
8157   // Dispatch over the operation to add in only those overloads which apply.
8158   switch (Op) {
8159   case OO_None:
8160   case NUM_OVERLOADED_OPERATORS:
8161     llvm_unreachable("Expected an overloaded operator");
8162 
8163   case OO_New:
8164   case OO_Delete:
8165   case OO_Array_New:
8166   case OO_Array_Delete:
8167   case OO_Call:
8168     llvm_unreachable(
8169                     "Special operators don't use AddBuiltinOperatorCandidates");
8170 
8171   case OO_Comma:
8172   case OO_Arrow:
8173     // C++ [over.match.oper]p3:
8174     //   -- For the operator ',', the unary operator '&', or the
8175     //      operator '->', the built-in candidates set is empty.
8176     break;
8177 
8178   case OO_Plus: // '+' is either unary or binary
8179     if (Args.size() == 1)
8180       OpBuilder.addUnaryPlusPointerOverloads();
8181     // Fall through.
8182 
8183   case OO_Minus: // '-' is either unary or binary
8184     if (Args.size() == 1) {
8185       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8186     } else {
8187       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8188       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8189     }
8190     break;
8191 
8192   case OO_Star: // '*' is either unary or binary
8193     if (Args.size() == 1)
8194       OpBuilder.addUnaryStarPointerOverloads();
8195     else
8196       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8197     break;
8198 
8199   case OO_Slash:
8200     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8201     break;
8202 
8203   case OO_PlusPlus:
8204   case OO_MinusMinus:
8205     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8206     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8207     break;
8208 
8209   case OO_EqualEqual:
8210   case OO_ExclaimEqual:
8211     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8212     // Fall through.
8213 
8214   case OO_Less:
8215   case OO_Greater:
8216   case OO_LessEqual:
8217   case OO_GreaterEqual:
8218     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8219     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8220     break;
8221 
8222   case OO_Percent:
8223   case OO_Caret:
8224   case OO_Pipe:
8225   case OO_LessLess:
8226   case OO_GreaterGreater:
8227     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8228     break;
8229 
8230   case OO_Amp: // '&' is either unary or binary
8231     if (Args.size() == 1)
8232       // C++ [over.match.oper]p3:
8233       //   -- For the operator ',', the unary operator '&', or the
8234       //      operator '->', the built-in candidates set is empty.
8235       break;
8236 
8237     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8238     break;
8239 
8240   case OO_Tilde:
8241     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8242     break;
8243 
8244   case OO_Equal:
8245     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8246     // Fall through.
8247 
8248   case OO_PlusEqual:
8249   case OO_MinusEqual:
8250     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8251     // Fall through.
8252 
8253   case OO_StarEqual:
8254   case OO_SlashEqual:
8255     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8256     break;
8257 
8258   case OO_PercentEqual:
8259   case OO_LessLessEqual:
8260   case OO_GreaterGreaterEqual:
8261   case OO_AmpEqual:
8262   case OO_CaretEqual:
8263   case OO_PipeEqual:
8264     OpBuilder.addAssignmentIntegralOverloads();
8265     break;
8266 
8267   case OO_Exclaim:
8268     OpBuilder.addExclaimOverload();
8269     break;
8270 
8271   case OO_AmpAmp:
8272   case OO_PipePipe:
8273     OpBuilder.addAmpAmpOrPipePipeOverload();
8274     break;
8275 
8276   case OO_Subscript:
8277     OpBuilder.addSubscriptOverloads();
8278     break;
8279 
8280   case OO_ArrowStar:
8281     OpBuilder.addArrowStarOverloads();
8282     break;
8283 
8284   case OO_Conditional:
8285     OpBuilder.addConditionalOperatorOverloads();
8286     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8287     break;
8288   }
8289 }
8290 
8291 /// \brief Add function candidates found via argument-dependent lookup
8292 /// to the set of overloading candidates.
8293 ///
8294 /// This routine performs argument-dependent name lookup based on the
8295 /// given function name (which may also be an operator name) and adds
8296 /// all of the overload candidates found by ADL to the overload
8297 /// candidate set (C++ [basic.lookup.argdep]).
8298 void
8299 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8300                                            SourceLocation Loc,
8301                                            ArrayRef<Expr *> Args,
8302                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8303                                            OverloadCandidateSet& CandidateSet,
8304                                            bool PartialOverloading) {
8305   ADLResult Fns;
8306 
8307   // FIXME: This approach for uniquing ADL results (and removing
8308   // redundant candidates from the set) relies on pointer-equality,
8309   // which means we need to key off the canonical decl.  However,
8310   // always going back to the canonical decl might not get us the
8311   // right set of default arguments.  What default arguments are
8312   // we supposed to consider on ADL candidates, anyway?
8313 
8314   // FIXME: Pass in the explicit template arguments?
8315   ArgumentDependentLookup(Name, Loc, Args, Fns);
8316 
8317   // Erase all of the candidates we already knew about.
8318   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8319                                    CandEnd = CandidateSet.end();
8320        Cand != CandEnd; ++Cand)
8321     if (Cand->Function) {
8322       Fns.erase(Cand->Function);
8323       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8324         Fns.erase(FunTmpl);
8325     }
8326 
8327   // For each of the ADL candidates we found, add it to the overload
8328   // set.
8329   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8330     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8331     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8332       if (ExplicitTemplateArgs)
8333         continue;
8334 
8335       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8336                            PartialOverloading);
8337     } else
8338       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8339                                    FoundDecl, ExplicitTemplateArgs,
8340                                    Args, CandidateSet, PartialOverloading);
8341   }
8342 }
8343 
8344 /// isBetterOverloadCandidate - Determines whether the first overload
8345 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8346 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8347                                       const OverloadCandidate &Cand2,
8348                                       SourceLocation Loc,
8349                                       bool UserDefinedConversion) {
8350   // Define viable functions to be better candidates than non-viable
8351   // functions.
8352   if (!Cand2.Viable)
8353     return Cand1.Viable;
8354   else if (!Cand1.Viable)
8355     return false;
8356 
8357   // C++ [over.match.best]p1:
8358   //
8359   //   -- if F is a static member function, ICS1(F) is defined such
8360   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8361   //      any function G, and, symmetrically, ICS1(G) is neither
8362   //      better nor worse than ICS1(F).
8363   unsigned StartArg = 0;
8364   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8365     StartArg = 1;
8366 
8367   // C++ [over.match.best]p1:
8368   //   A viable function F1 is defined to be a better function than another
8369   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8370   //   conversion sequence than ICSi(F2), and then...
8371   unsigned NumArgs = Cand1.NumConversions;
8372   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8373   bool HasBetterConversion = false;
8374   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8375     switch (CompareImplicitConversionSequences(S,
8376                                                Cand1.Conversions[ArgIdx],
8377                                                Cand2.Conversions[ArgIdx])) {
8378     case ImplicitConversionSequence::Better:
8379       // Cand1 has a better conversion sequence.
8380       HasBetterConversion = true;
8381       break;
8382 
8383     case ImplicitConversionSequence::Worse:
8384       // Cand1 can't be better than Cand2.
8385       return false;
8386 
8387     case ImplicitConversionSequence::Indistinguishable:
8388       // Do nothing.
8389       break;
8390     }
8391   }
8392 
8393   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8394   //       ICSj(F2), or, if not that,
8395   if (HasBetterConversion)
8396     return true;
8397 
8398   //   -- the context is an initialization by user-defined conversion
8399   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8400   //      from the return type of F1 to the destination type (i.e.,
8401   //      the type of the entity being initialized) is a better
8402   //      conversion sequence than the standard conversion sequence
8403   //      from the return type of F2 to the destination type.
8404   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8405       isa<CXXConversionDecl>(Cand1.Function) &&
8406       isa<CXXConversionDecl>(Cand2.Function)) {
8407     // First check whether we prefer one of the conversion functions over the
8408     // other. This only distinguishes the results in non-standard, extension
8409     // cases such as the conversion from a lambda closure type to a function
8410     // pointer or block.
8411     ImplicitConversionSequence::CompareKind Result =
8412         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8413     if (Result == ImplicitConversionSequence::Indistinguishable)
8414       Result = CompareStandardConversionSequences(S,
8415                                                   Cand1.FinalConversion,
8416                                                   Cand2.FinalConversion);
8417 
8418     if (Result != ImplicitConversionSequence::Indistinguishable)
8419       return Result == ImplicitConversionSequence::Better;
8420 
8421     // FIXME: Compare kind of reference binding if conversion functions
8422     // convert to a reference type used in direct reference binding, per
8423     // C++14 [over.match.best]p1 section 2 bullet 3.
8424   }
8425 
8426   //    -- F1 is a non-template function and F2 is a function template
8427   //       specialization, or, if not that,
8428   bool Cand1IsSpecialization = Cand1.Function &&
8429                                Cand1.Function->getPrimaryTemplate();
8430   bool Cand2IsSpecialization = Cand2.Function &&
8431                                Cand2.Function->getPrimaryTemplate();
8432   if (Cand1IsSpecialization != Cand2IsSpecialization)
8433     return Cand2IsSpecialization;
8434 
8435   //   -- F1 and F2 are function template specializations, and the function
8436   //      template for F1 is more specialized than the template for F2
8437   //      according to the partial ordering rules described in 14.5.5.2, or,
8438   //      if not that,
8439   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8440     if (FunctionTemplateDecl *BetterTemplate
8441           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8442                                          Cand2.Function->getPrimaryTemplate(),
8443                                          Loc,
8444                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8445                                                              : TPOC_Call,
8446                                          Cand1.ExplicitCallArguments,
8447                                          Cand2.ExplicitCallArguments))
8448       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8449   }
8450 
8451   // Check for enable_if value-based overload resolution.
8452   if (Cand1.Function && Cand2.Function &&
8453       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8454        Cand2.Function->hasAttr<EnableIfAttr>())) {
8455     // FIXME: The next several lines are just
8456     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8457     // instead of reverse order which is how they're stored in the AST.
8458     AttrVec Cand1Attrs;
8459     if (Cand1.Function->hasAttrs()) {
8460       Cand1Attrs = Cand1.Function->getAttrs();
8461       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8462                                       IsNotEnableIfAttr),
8463                        Cand1Attrs.end());
8464       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8465     }
8466 
8467     AttrVec Cand2Attrs;
8468     if (Cand2.Function->hasAttrs()) {
8469       Cand2Attrs = Cand2.Function->getAttrs();
8470       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8471                                       IsNotEnableIfAttr),
8472                        Cand2Attrs.end());
8473       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8474     }
8475 
8476     // Candidate 1 is better if it has strictly more attributes and
8477     // the common sequence is identical.
8478     if (Cand1Attrs.size() <= Cand2Attrs.size())
8479       return false;
8480 
8481     auto Cand1I = Cand1Attrs.begin();
8482     for (auto &Cand2A : Cand2Attrs) {
8483       auto &Cand1A = *Cand1I++;
8484       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8485       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8486                                                      S.getASTContext(), true);
8487       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8488                                                      S.getASTContext(), true);
8489       if (Cand1ID != Cand2ID)
8490         return false;
8491     }
8492 
8493     return true;
8494   }
8495 
8496   return false;
8497 }
8498 
8499 /// \brief Computes the best viable function (C++ 13.3.3)
8500 /// within an overload candidate set.
8501 ///
8502 /// \param Loc The location of the function name (or operator symbol) for
8503 /// which overload resolution occurs.
8504 ///
8505 /// \param Best If overload resolution was successful or found a deleted
8506 /// function, \p Best points to the candidate function found.
8507 ///
8508 /// \returns The result of overload resolution.
8509 OverloadingResult
8510 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8511                                          iterator &Best,
8512                                          bool UserDefinedConversion) {
8513   // Find the best viable function.
8514   Best = end();
8515   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8516     if (Cand->Viable)
8517       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8518                                                      UserDefinedConversion))
8519         Best = Cand;
8520   }
8521 
8522   // If we didn't find any viable functions, abort.
8523   if (Best == end())
8524     return OR_No_Viable_Function;
8525 
8526   // Make sure that this function is better than every other viable
8527   // function. If not, we have an ambiguity.
8528   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8529     if (Cand->Viable &&
8530         Cand != Best &&
8531         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8532                                    UserDefinedConversion)) {
8533       Best = end();
8534       return OR_Ambiguous;
8535     }
8536   }
8537 
8538   // Best is the best viable function.
8539   if (Best->Function &&
8540       (Best->Function->isDeleted() ||
8541        S.isFunctionConsideredUnavailable(Best->Function)))
8542     return OR_Deleted;
8543 
8544   return OR_Success;
8545 }
8546 
8547 namespace {
8548 
8549 enum OverloadCandidateKind {
8550   oc_function,
8551   oc_method,
8552   oc_constructor,
8553   oc_function_template,
8554   oc_method_template,
8555   oc_constructor_template,
8556   oc_implicit_default_constructor,
8557   oc_implicit_copy_constructor,
8558   oc_implicit_move_constructor,
8559   oc_implicit_copy_assignment,
8560   oc_implicit_move_assignment,
8561   oc_implicit_inherited_constructor
8562 };
8563 
8564 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8565                                                 FunctionDecl *Fn,
8566                                                 std::string &Description) {
8567   bool isTemplate = false;
8568 
8569   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8570     isTemplate = true;
8571     Description = S.getTemplateArgumentBindingsText(
8572       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8573   }
8574 
8575   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8576     if (!Ctor->isImplicit())
8577       return isTemplate ? oc_constructor_template : oc_constructor;
8578 
8579     if (Ctor->getInheritedConstructor())
8580       return oc_implicit_inherited_constructor;
8581 
8582     if (Ctor->isDefaultConstructor())
8583       return oc_implicit_default_constructor;
8584 
8585     if (Ctor->isMoveConstructor())
8586       return oc_implicit_move_constructor;
8587 
8588     assert(Ctor->isCopyConstructor() &&
8589            "unexpected sort of implicit constructor");
8590     return oc_implicit_copy_constructor;
8591   }
8592 
8593   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8594     // This actually gets spelled 'candidate function' for now, but
8595     // it doesn't hurt to split it out.
8596     if (!Meth->isImplicit())
8597       return isTemplate ? oc_method_template : oc_method;
8598 
8599     if (Meth->isMoveAssignmentOperator())
8600       return oc_implicit_move_assignment;
8601 
8602     if (Meth->isCopyAssignmentOperator())
8603       return oc_implicit_copy_assignment;
8604 
8605     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8606     return oc_method;
8607   }
8608 
8609   return isTemplate ? oc_function_template : oc_function;
8610 }
8611 
8612 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8613   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8614   if (!Ctor) return;
8615 
8616   Ctor = Ctor->getInheritedConstructor();
8617   if (!Ctor) return;
8618 
8619   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8620 }
8621 
8622 } // end anonymous namespace
8623 
8624 // Notes the location of an overload candidate.
8625 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8626   std::string FnDesc;
8627   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8628   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8629                              << (unsigned) K << FnDesc;
8630   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8631   Diag(Fn->getLocation(), PD);
8632   MaybeEmitInheritedConstructorNote(*this, Fn);
8633 }
8634 
8635 // Notes the location of all overload candidates designated through
8636 // OverloadedExpr
8637 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8638   assert(OverloadedExpr->getType() == Context.OverloadTy);
8639 
8640   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8641   OverloadExpr *OvlExpr = Ovl.Expression;
8642 
8643   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8644                             IEnd = OvlExpr->decls_end();
8645        I != IEnd; ++I) {
8646     if (FunctionTemplateDecl *FunTmpl =
8647                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8648       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8649     } else if (FunctionDecl *Fun
8650                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8651       NoteOverloadCandidate(Fun, DestType);
8652     }
8653   }
8654 }
8655 
8656 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8657 /// "lead" diagnostic; it will be given two arguments, the source and
8658 /// target types of the conversion.
8659 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8660                                  Sema &S,
8661                                  SourceLocation CaretLoc,
8662                                  const PartialDiagnostic &PDiag) const {
8663   S.Diag(CaretLoc, PDiag)
8664     << Ambiguous.getFromType() << Ambiguous.getToType();
8665   // FIXME: The note limiting machinery is borrowed from
8666   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8667   // refactoring here.
8668   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8669   unsigned CandsShown = 0;
8670   AmbiguousConversionSequence::const_iterator I, E;
8671   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8672     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8673       break;
8674     ++CandsShown;
8675     S.NoteOverloadCandidate(*I);
8676   }
8677   if (I != E)
8678     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8679 }
8680 
8681 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8682                                   unsigned I) {
8683   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8684   assert(Conv.isBad());
8685   assert(Cand->Function && "for now, candidate must be a function");
8686   FunctionDecl *Fn = Cand->Function;
8687 
8688   // There's a conversion slot for the object argument if this is a
8689   // non-constructor method.  Note that 'I' corresponds the
8690   // conversion-slot index.
8691   bool isObjectArgument = false;
8692   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8693     if (I == 0)
8694       isObjectArgument = true;
8695     else
8696       I--;
8697   }
8698 
8699   std::string FnDesc;
8700   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8701 
8702   Expr *FromExpr = Conv.Bad.FromExpr;
8703   QualType FromTy = Conv.Bad.getFromType();
8704   QualType ToTy = Conv.Bad.getToType();
8705 
8706   if (FromTy == S.Context.OverloadTy) {
8707     assert(FromExpr && "overload set argument came from implicit argument?");
8708     Expr *E = FromExpr->IgnoreParens();
8709     if (isa<UnaryOperator>(E))
8710       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8711     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8712 
8713     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8714       << (unsigned) FnKind << FnDesc
8715       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8716       << ToTy << Name << I+1;
8717     MaybeEmitInheritedConstructorNote(S, Fn);
8718     return;
8719   }
8720 
8721   // Do some hand-waving analysis to see if the non-viability is due
8722   // to a qualifier mismatch.
8723   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8724   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8725   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8726     CToTy = RT->getPointeeType();
8727   else {
8728     // TODO: detect and diagnose the full richness of const mismatches.
8729     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8730       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8731         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8732   }
8733 
8734   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8735       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8736     Qualifiers FromQs = CFromTy.getQualifiers();
8737     Qualifiers ToQs = CToTy.getQualifiers();
8738 
8739     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8740       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8741         << (unsigned) FnKind << FnDesc
8742         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8743         << FromTy
8744         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8745         << (unsigned) isObjectArgument << I+1;
8746       MaybeEmitInheritedConstructorNote(S, Fn);
8747       return;
8748     }
8749 
8750     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8751       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8752         << (unsigned) FnKind << FnDesc
8753         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8754         << FromTy
8755         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8756         << (unsigned) isObjectArgument << I+1;
8757       MaybeEmitInheritedConstructorNote(S, Fn);
8758       return;
8759     }
8760 
8761     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8762       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8763       << (unsigned) FnKind << FnDesc
8764       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8765       << FromTy
8766       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8767       << (unsigned) isObjectArgument << I+1;
8768       MaybeEmitInheritedConstructorNote(S, Fn);
8769       return;
8770     }
8771 
8772     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8773     assert(CVR && "unexpected qualifiers mismatch");
8774 
8775     if (isObjectArgument) {
8776       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8777         << (unsigned) FnKind << FnDesc
8778         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8779         << FromTy << (CVR - 1);
8780     } else {
8781       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8782         << (unsigned) FnKind << FnDesc
8783         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8784         << FromTy << (CVR - 1) << I+1;
8785     }
8786     MaybeEmitInheritedConstructorNote(S, Fn);
8787     return;
8788   }
8789 
8790   // Special diagnostic for failure to convert an initializer list, since
8791   // telling the user that it has type void is not useful.
8792   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8793     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8794       << (unsigned) FnKind << FnDesc
8795       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8796       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8797     MaybeEmitInheritedConstructorNote(S, Fn);
8798     return;
8799   }
8800 
8801   // Diagnose references or pointers to incomplete types differently,
8802   // since it's far from impossible that the incompleteness triggered
8803   // the failure.
8804   QualType TempFromTy = FromTy.getNonReferenceType();
8805   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8806     TempFromTy = PTy->getPointeeType();
8807   if (TempFromTy->isIncompleteType()) {
8808     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
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 base -> derived pointer conversions.
8817   unsigned BaseToDerivedConversion = 0;
8818   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8819     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8820       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8821                                                FromPtrTy->getPointeeType()) &&
8822           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8823           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8824           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8825                           FromPtrTy->getPointeeType()))
8826         BaseToDerivedConversion = 1;
8827     }
8828   } else if (const ObjCObjectPointerType *FromPtrTy
8829                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8830     if (const ObjCObjectPointerType *ToPtrTy
8831                                         = ToTy->getAs<ObjCObjectPointerType>())
8832       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8833         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8834           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8835                                                 FromPtrTy->getPointeeType()) &&
8836               FromIface->isSuperClassOf(ToIface))
8837             BaseToDerivedConversion = 2;
8838   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8839     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8840         !FromTy->isIncompleteType() &&
8841         !ToRefTy->getPointeeType()->isIncompleteType() &&
8842         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8843       BaseToDerivedConversion = 3;
8844     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8845                ToTy.getNonReferenceType().getCanonicalType() ==
8846                FromTy.getNonReferenceType().getCanonicalType()) {
8847       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8848         << (unsigned) FnKind << FnDesc
8849         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8850         << (unsigned) isObjectArgument << I + 1;
8851       MaybeEmitInheritedConstructorNote(S, Fn);
8852       return;
8853     }
8854   }
8855 
8856   if (BaseToDerivedConversion) {
8857     S.Diag(Fn->getLocation(),
8858            diag::note_ovl_candidate_bad_base_to_derived_conv)
8859       << (unsigned) FnKind << FnDesc
8860       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8861       << (BaseToDerivedConversion - 1)
8862       << FromTy << ToTy << I+1;
8863     MaybeEmitInheritedConstructorNote(S, Fn);
8864     return;
8865   }
8866 
8867   if (isa<ObjCObjectPointerType>(CFromTy) &&
8868       isa<PointerType>(CToTy)) {
8869       Qualifiers FromQs = CFromTy.getQualifiers();
8870       Qualifiers ToQs = CToTy.getQualifiers();
8871       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8872         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8873         << (unsigned) FnKind << FnDesc
8874         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8875         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8876         MaybeEmitInheritedConstructorNote(S, Fn);
8877         return;
8878       }
8879   }
8880 
8881   // Emit the generic diagnostic and, optionally, add the hints to it.
8882   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8883   FDiag << (unsigned) FnKind << FnDesc
8884     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8885     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8886     << (unsigned) (Cand->Fix.Kind);
8887 
8888   // If we can fix the conversion, suggest the FixIts.
8889   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8890        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8891     FDiag << *HI;
8892   S.Diag(Fn->getLocation(), FDiag);
8893 
8894   MaybeEmitInheritedConstructorNote(S, Fn);
8895 }
8896 
8897 /// Additional arity mismatch diagnosis specific to a function overload
8898 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8899 /// over a candidate in any candidate set.
8900 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8901                                unsigned NumArgs) {
8902   FunctionDecl *Fn = Cand->Function;
8903   unsigned MinParams = Fn->getMinRequiredArguments();
8904 
8905   // With invalid overloaded operators, it's possible that we think we
8906   // have an arity mismatch when in fact it looks like we have the
8907   // right number of arguments, because only overloaded operators have
8908   // the weird behavior of overloading member and non-member functions.
8909   // Just don't report anything.
8910   if (Fn->isInvalidDecl() &&
8911       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8912     return true;
8913 
8914   if (NumArgs < MinParams) {
8915     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8916            (Cand->FailureKind == ovl_fail_bad_deduction &&
8917             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8918   } else {
8919     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8920            (Cand->FailureKind == ovl_fail_bad_deduction &&
8921             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8922   }
8923 
8924   return false;
8925 }
8926 
8927 /// General arity mismatch diagnosis over a candidate in a candidate set.
8928 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8929   assert(isa<FunctionDecl>(D) &&
8930       "The templated declaration should at least be a function"
8931       " when diagnosing bad template argument deduction due to too many"
8932       " or too few arguments");
8933 
8934   FunctionDecl *Fn = cast<FunctionDecl>(D);
8935 
8936   // TODO: treat calls to a missing default constructor as a special case
8937   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8938   unsigned MinParams = Fn->getMinRequiredArguments();
8939 
8940   // at least / at most / exactly
8941   unsigned mode, modeCount;
8942   if (NumFormalArgs < MinParams) {
8943     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8944         FnTy->isTemplateVariadic())
8945       mode = 0; // "at least"
8946     else
8947       mode = 2; // "exactly"
8948     modeCount = MinParams;
8949   } else {
8950     if (MinParams != FnTy->getNumParams())
8951       mode = 1; // "at most"
8952     else
8953       mode = 2; // "exactly"
8954     modeCount = FnTy->getNumParams();
8955   }
8956 
8957   std::string Description;
8958   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8959 
8960   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8961     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8962       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8963       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8964   else
8965     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8966       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8967       << mode << modeCount << NumFormalArgs;
8968   MaybeEmitInheritedConstructorNote(S, Fn);
8969 }
8970 
8971 /// Arity mismatch diagnosis specific to a function overload candidate.
8972 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8973                                   unsigned NumFormalArgs) {
8974   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8975     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8976 }
8977 
8978 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8979   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8980     return FD->getDescribedFunctionTemplate();
8981   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8982     return RD->getDescribedClassTemplate();
8983 
8984   llvm_unreachable("Unsupported: Getting the described template declaration"
8985                    " for bad deduction diagnosis");
8986 }
8987 
8988 /// Diagnose a failed template-argument deduction.
8989 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8990                                  DeductionFailureInfo &DeductionFailure,
8991                                  unsigned NumArgs) {
8992   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8993   NamedDecl *ParamD;
8994   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8995   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8996   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8997   switch (DeductionFailure.Result) {
8998   case Sema::TDK_Success:
8999     llvm_unreachable("TDK_success while diagnosing bad deduction");
9000 
9001   case Sema::TDK_Incomplete: {
9002     assert(ParamD && "no parameter found for incomplete deduction result");
9003     S.Diag(Templated->getLocation(),
9004            diag::note_ovl_candidate_incomplete_deduction)
9005         << ParamD->getDeclName();
9006     MaybeEmitInheritedConstructorNote(S, Templated);
9007     return;
9008   }
9009 
9010   case Sema::TDK_Underqualified: {
9011     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9012     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9013 
9014     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9015 
9016     // Param will have been canonicalized, but it should just be a
9017     // qualified version of ParamD, so move the qualifiers to that.
9018     QualifierCollector Qs;
9019     Qs.strip(Param);
9020     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9021     assert(S.Context.hasSameType(Param, NonCanonParam));
9022 
9023     // Arg has also been canonicalized, but there's nothing we can do
9024     // about that.  It also doesn't matter as much, because it won't
9025     // have any template parameters in it (because deduction isn't
9026     // done on dependent types).
9027     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9028 
9029     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9030         << ParamD->getDeclName() << Arg << NonCanonParam;
9031     MaybeEmitInheritedConstructorNote(S, Templated);
9032     return;
9033   }
9034 
9035   case Sema::TDK_Inconsistent: {
9036     assert(ParamD && "no parameter found for inconsistent deduction result");
9037     int which = 0;
9038     if (isa<TemplateTypeParmDecl>(ParamD))
9039       which = 0;
9040     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9041       which = 1;
9042     else {
9043       which = 2;
9044     }
9045 
9046     S.Diag(Templated->getLocation(),
9047            diag::note_ovl_candidate_inconsistent_deduction)
9048         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9049         << *DeductionFailure.getSecondArg();
9050     MaybeEmitInheritedConstructorNote(S, Templated);
9051     return;
9052   }
9053 
9054   case Sema::TDK_InvalidExplicitArguments:
9055     assert(ParamD && "no parameter found for invalid explicit arguments");
9056     if (ParamD->getDeclName())
9057       S.Diag(Templated->getLocation(),
9058              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9059           << ParamD->getDeclName();
9060     else {
9061       int index = 0;
9062       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9063         index = TTP->getIndex();
9064       else if (NonTypeTemplateParmDecl *NTTP
9065                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9066         index = NTTP->getIndex();
9067       else
9068         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9069       S.Diag(Templated->getLocation(),
9070              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9071           << (index + 1);
9072     }
9073     MaybeEmitInheritedConstructorNote(S, Templated);
9074     return;
9075 
9076   case Sema::TDK_TooManyArguments:
9077   case Sema::TDK_TooFewArguments:
9078     DiagnoseArityMismatch(S, Templated, NumArgs);
9079     return;
9080 
9081   case Sema::TDK_InstantiationDepth:
9082     S.Diag(Templated->getLocation(),
9083            diag::note_ovl_candidate_instantiation_depth);
9084     MaybeEmitInheritedConstructorNote(S, Templated);
9085     return;
9086 
9087   case Sema::TDK_SubstitutionFailure: {
9088     // Format the template argument list into the argument string.
9089     SmallString<128> TemplateArgString;
9090     if (TemplateArgumentList *Args =
9091             DeductionFailure.getTemplateArgumentList()) {
9092       TemplateArgString = " ";
9093       TemplateArgString += S.getTemplateArgumentBindingsText(
9094           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9095     }
9096 
9097     // If this candidate was disabled by enable_if, say so.
9098     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9099     if (PDiag && PDiag->second.getDiagID() ==
9100           diag::err_typename_nested_not_found_enable_if) {
9101       // FIXME: Use the source range of the condition, and the fully-qualified
9102       //        name of the enable_if template. These are both present in PDiag.
9103       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9104         << "'enable_if'" << TemplateArgString;
9105       return;
9106     }
9107 
9108     // Format the SFINAE diagnostic into the argument string.
9109     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9110     //        formatted message in another diagnostic.
9111     SmallString<128> SFINAEArgString;
9112     SourceRange R;
9113     if (PDiag) {
9114       SFINAEArgString = ": ";
9115       R = SourceRange(PDiag->first, PDiag->first);
9116       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9117     }
9118 
9119     S.Diag(Templated->getLocation(),
9120            diag::note_ovl_candidate_substitution_failure)
9121         << TemplateArgString << SFINAEArgString << R;
9122     MaybeEmitInheritedConstructorNote(S, Templated);
9123     return;
9124   }
9125 
9126   case Sema::TDK_FailedOverloadResolution: {
9127     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9128     S.Diag(Templated->getLocation(),
9129            diag::note_ovl_candidate_failed_overload_resolution)
9130         << R.Expression->getName();
9131     return;
9132   }
9133 
9134   case Sema::TDK_NonDeducedMismatch: {
9135     // FIXME: Provide a source location to indicate what we couldn't match.
9136     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9137     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9138     if (FirstTA.getKind() == TemplateArgument::Template &&
9139         SecondTA.getKind() == TemplateArgument::Template) {
9140       TemplateName FirstTN = FirstTA.getAsTemplate();
9141       TemplateName SecondTN = SecondTA.getAsTemplate();
9142       if (FirstTN.getKind() == TemplateName::Template &&
9143           SecondTN.getKind() == TemplateName::Template) {
9144         if (FirstTN.getAsTemplateDecl()->getName() ==
9145             SecondTN.getAsTemplateDecl()->getName()) {
9146           // FIXME: This fixes a bad diagnostic where both templates are named
9147           // the same.  This particular case is a bit difficult since:
9148           // 1) It is passed as a string to the diagnostic printer.
9149           // 2) The diagnostic printer only attempts to find a better
9150           //    name for types, not decls.
9151           // Ideally, this should folded into the diagnostic printer.
9152           S.Diag(Templated->getLocation(),
9153                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9154               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9155           return;
9156         }
9157       }
9158     }
9159     // FIXME: For generic lambda parameters, check if the function is a lambda
9160     // call operator, and if so, emit a prettier and more informative
9161     // diagnostic that mentions 'auto' and lambda in addition to
9162     // (or instead of?) the canonical template type parameters.
9163     S.Diag(Templated->getLocation(),
9164            diag::note_ovl_candidate_non_deduced_mismatch)
9165         << FirstTA << SecondTA;
9166     return;
9167   }
9168   // TODO: diagnose these individually, then kill off
9169   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9170   case Sema::TDK_MiscellaneousDeductionFailure:
9171     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9172     MaybeEmitInheritedConstructorNote(S, Templated);
9173     return;
9174   }
9175 }
9176 
9177 /// Diagnose a failed template-argument deduction, for function calls.
9178 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9179                                  unsigned NumArgs) {
9180   unsigned TDK = Cand->DeductionFailure.Result;
9181   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9182     if (CheckArityMismatch(S, Cand, NumArgs))
9183       return;
9184   }
9185   DiagnoseBadDeduction(S, Cand->Function, // pattern
9186                        Cand->DeductionFailure, NumArgs);
9187 }
9188 
9189 /// CUDA: diagnose an invalid call across targets.
9190 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9191   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9192   FunctionDecl *Callee = Cand->Function;
9193 
9194   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9195                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9196 
9197   std::string FnDesc;
9198   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9199 
9200   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9201       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9202 
9203   // This could be an implicit constructor for which we could not infer the
9204   // target due to a collsion. Diagnose that case.
9205   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9206   if (Meth != nullptr && Meth->isImplicit()) {
9207     CXXRecordDecl *ParentClass = Meth->getParent();
9208     Sema::CXXSpecialMember CSM;
9209 
9210     switch (FnKind) {
9211     default:
9212       return;
9213     case oc_implicit_default_constructor:
9214       CSM = Sema::CXXDefaultConstructor;
9215       break;
9216     case oc_implicit_copy_constructor:
9217       CSM = Sema::CXXCopyConstructor;
9218       break;
9219     case oc_implicit_move_constructor:
9220       CSM = Sema::CXXMoveConstructor;
9221       break;
9222     case oc_implicit_copy_assignment:
9223       CSM = Sema::CXXCopyAssignment;
9224       break;
9225     case oc_implicit_move_assignment:
9226       CSM = Sema::CXXMoveAssignment;
9227       break;
9228     };
9229 
9230     bool ConstRHS = false;
9231     if (Meth->getNumParams()) {
9232       if (const ReferenceType *RT =
9233               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9234         ConstRHS = RT->getPointeeType().isConstQualified();
9235       }
9236     }
9237 
9238     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9239                                               /* ConstRHS */ ConstRHS,
9240                                               /* Diagnose */ true);
9241   }
9242 }
9243 
9244 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9245   FunctionDecl *Callee = Cand->Function;
9246   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9247 
9248   S.Diag(Callee->getLocation(),
9249          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9250       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9251 }
9252 
9253 /// Generates a 'note' diagnostic for an overload candidate.  We've
9254 /// already generated a primary error at the call site.
9255 ///
9256 /// It really does need to be a single diagnostic with its caret
9257 /// pointed at the candidate declaration.  Yes, this creates some
9258 /// major challenges of technical writing.  Yes, this makes pointing
9259 /// out problems with specific arguments quite awkward.  It's still
9260 /// better than generating twenty screens of text for every failed
9261 /// overload.
9262 ///
9263 /// It would be great to be able to express per-candidate problems
9264 /// more richly for those diagnostic clients that cared, but we'd
9265 /// still have to be just as careful with the default diagnostics.
9266 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9267                                   unsigned NumArgs) {
9268   FunctionDecl *Fn = Cand->Function;
9269 
9270   // Note deleted candidates, but only if they're viable.
9271   if (Cand->Viable && (Fn->isDeleted() ||
9272       S.isFunctionConsideredUnavailable(Fn))) {
9273     std::string FnDesc;
9274     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9275 
9276     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9277       << FnKind << FnDesc
9278       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9279     MaybeEmitInheritedConstructorNote(S, Fn);
9280     return;
9281   }
9282 
9283   // We don't really have anything else to say about viable candidates.
9284   if (Cand->Viable) {
9285     S.NoteOverloadCandidate(Fn);
9286     return;
9287   }
9288 
9289   switch (Cand->FailureKind) {
9290   case ovl_fail_too_many_arguments:
9291   case ovl_fail_too_few_arguments:
9292     return DiagnoseArityMismatch(S, Cand, NumArgs);
9293 
9294   case ovl_fail_bad_deduction:
9295     return DiagnoseBadDeduction(S, Cand, NumArgs);
9296 
9297   case ovl_fail_illegal_constructor: {
9298     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9299       << (Fn->getPrimaryTemplate() ? 1 : 0);
9300     MaybeEmitInheritedConstructorNote(S, Fn);
9301     return;
9302   }
9303 
9304   case ovl_fail_trivial_conversion:
9305   case ovl_fail_bad_final_conversion:
9306   case ovl_fail_final_conversion_not_exact:
9307     return S.NoteOverloadCandidate(Fn);
9308 
9309   case ovl_fail_bad_conversion: {
9310     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9311     for (unsigned N = Cand->NumConversions; I != N; ++I)
9312       if (Cand->Conversions[I].isBad())
9313         return DiagnoseBadConversion(S, Cand, I);
9314 
9315     // FIXME: this currently happens when we're called from SemaInit
9316     // when user-conversion overload fails.  Figure out how to handle
9317     // those conditions and diagnose them well.
9318     return S.NoteOverloadCandidate(Fn);
9319   }
9320 
9321   case ovl_fail_bad_target:
9322     return DiagnoseBadTarget(S, Cand);
9323 
9324   case ovl_fail_enable_if:
9325     return DiagnoseFailedEnableIfAttr(S, Cand);
9326   }
9327 }
9328 
9329 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9330   // Desugar the type of the surrogate down to a function type,
9331   // retaining as many typedefs as possible while still showing
9332   // the function type (and, therefore, its parameter types).
9333   QualType FnType = Cand->Surrogate->getConversionType();
9334   bool isLValueReference = false;
9335   bool isRValueReference = false;
9336   bool isPointer = false;
9337   if (const LValueReferenceType *FnTypeRef =
9338         FnType->getAs<LValueReferenceType>()) {
9339     FnType = FnTypeRef->getPointeeType();
9340     isLValueReference = true;
9341   } else if (const RValueReferenceType *FnTypeRef =
9342                FnType->getAs<RValueReferenceType>()) {
9343     FnType = FnTypeRef->getPointeeType();
9344     isRValueReference = true;
9345   }
9346   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9347     FnType = FnTypePtr->getPointeeType();
9348     isPointer = true;
9349   }
9350   // Desugar down to a function type.
9351   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9352   // Reconstruct the pointer/reference as appropriate.
9353   if (isPointer) FnType = S.Context.getPointerType(FnType);
9354   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9355   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9356 
9357   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9358     << FnType;
9359   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9360 }
9361 
9362 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9363                                          SourceLocation OpLoc,
9364                                          OverloadCandidate *Cand) {
9365   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9366   std::string TypeStr("operator");
9367   TypeStr += Opc;
9368   TypeStr += "(";
9369   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9370   if (Cand->NumConversions == 1) {
9371     TypeStr += ")";
9372     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9373   } else {
9374     TypeStr += ", ";
9375     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9376     TypeStr += ")";
9377     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9378   }
9379 }
9380 
9381 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9382                                          OverloadCandidate *Cand) {
9383   unsigned NoOperands = Cand->NumConversions;
9384   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9385     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9386     if (ICS.isBad()) break; // all meaningless after first invalid
9387     if (!ICS.isAmbiguous()) continue;
9388 
9389     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9390                               S.PDiag(diag::note_ambiguous_type_conversion));
9391   }
9392 }
9393 
9394 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9395   if (Cand->Function)
9396     return Cand->Function->getLocation();
9397   if (Cand->IsSurrogate)
9398     return Cand->Surrogate->getLocation();
9399   return SourceLocation();
9400 }
9401 
9402 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9403   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9404   case Sema::TDK_Success:
9405     llvm_unreachable("TDK_success while diagnosing bad deduction");
9406 
9407   case Sema::TDK_Invalid:
9408   case Sema::TDK_Incomplete:
9409     return 1;
9410 
9411   case Sema::TDK_Underqualified:
9412   case Sema::TDK_Inconsistent:
9413     return 2;
9414 
9415   case Sema::TDK_SubstitutionFailure:
9416   case Sema::TDK_NonDeducedMismatch:
9417   case Sema::TDK_MiscellaneousDeductionFailure:
9418     return 3;
9419 
9420   case Sema::TDK_InstantiationDepth:
9421   case Sema::TDK_FailedOverloadResolution:
9422     return 4;
9423 
9424   case Sema::TDK_InvalidExplicitArguments:
9425     return 5;
9426 
9427   case Sema::TDK_TooManyArguments:
9428   case Sema::TDK_TooFewArguments:
9429     return 6;
9430   }
9431   llvm_unreachable("Unhandled deduction result");
9432 }
9433 
9434 namespace {
9435 struct CompareOverloadCandidatesForDisplay {
9436   Sema &S;
9437   size_t NumArgs;
9438 
9439   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9440       : S(S), NumArgs(nArgs) {}
9441 
9442   bool operator()(const OverloadCandidate *L,
9443                   const OverloadCandidate *R) {
9444     // Fast-path this check.
9445     if (L == R) return false;
9446 
9447     // Order first by viability.
9448     if (L->Viable) {
9449       if (!R->Viable) return true;
9450 
9451       // TODO: introduce a tri-valued comparison for overload
9452       // candidates.  Would be more worthwhile if we had a sort
9453       // that could exploit it.
9454       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9455       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9456     } else if (R->Viable)
9457       return false;
9458 
9459     assert(L->Viable == R->Viable);
9460 
9461     // Criteria by which we can sort non-viable candidates:
9462     if (!L->Viable) {
9463       // 1. Arity mismatches come after other candidates.
9464       if (L->FailureKind == ovl_fail_too_many_arguments ||
9465           L->FailureKind == ovl_fail_too_few_arguments) {
9466         if (R->FailureKind == ovl_fail_too_many_arguments ||
9467             R->FailureKind == ovl_fail_too_few_arguments) {
9468           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9469           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9470           if (LDist == RDist) {
9471             if (L->FailureKind == R->FailureKind)
9472               // Sort non-surrogates before surrogates.
9473               return !L->IsSurrogate && R->IsSurrogate;
9474             // Sort candidates requiring fewer parameters than there were
9475             // arguments given after candidates requiring more parameters
9476             // than there were arguments given.
9477             return L->FailureKind == ovl_fail_too_many_arguments;
9478           }
9479           return LDist < RDist;
9480         }
9481         return false;
9482       }
9483       if (R->FailureKind == ovl_fail_too_many_arguments ||
9484           R->FailureKind == ovl_fail_too_few_arguments)
9485         return true;
9486 
9487       // 2. Bad conversions come first and are ordered by the number
9488       // of bad conversions and quality of good conversions.
9489       if (L->FailureKind == ovl_fail_bad_conversion) {
9490         if (R->FailureKind != ovl_fail_bad_conversion)
9491           return true;
9492 
9493         // The conversion that can be fixed with a smaller number of changes,
9494         // comes first.
9495         unsigned numLFixes = L->Fix.NumConversionsFixed;
9496         unsigned numRFixes = R->Fix.NumConversionsFixed;
9497         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9498         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9499         if (numLFixes != numRFixes) {
9500           if (numLFixes < numRFixes)
9501             return true;
9502           else
9503             return false;
9504         }
9505 
9506         // If there's any ordering between the defined conversions...
9507         // FIXME: this might not be transitive.
9508         assert(L->NumConversions == R->NumConversions);
9509 
9510         int leftBetter = 0;
9511         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9512         for (unsigned E = L->NumConversions; I != E; ++I) {
9513           switch (CompareImplicitConversionSequences(S,
9514                                                      L->Conversions[I],
9515                                                      R->Conversions[I])) {
9516           case ImplicitConversionSequence::Better:
9517             leftBetter++;
9518             break;
9519 
9520           case ImplicitConversionSequence::Worse:
9521             leftBetter--;
9522             break;
9523 
9524           case ImplicitConversionSequence::Indistinguishable:
9525             break;
9526           }
9527         }
9528         if (leftBetter > 0) return true;
9529         if (leftBetter < 0) return false;
9530 
9531       } else if (R->FailureKind == ovl_fail_bad_conversion)
9532         return false;
9533 
9534       if (L->FailureKind == ovl_fail_bad_deduction) {
9535         if (R->FailureKind != ovl_fail_bad_deduction)
9536           return true;
9537 
9538         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9539           return RankDeductionFailure(L->DeductionFailure)
9540                < RankDeductionFailure(R->DeductionFailure);
9541       } else if (R->FailureKind == ovl_fail_bad_deduction)
9542         return false;
9543 
9544       // TODO: others?
9545     }
9546 
9547     // Sort everything else by location.
9548     SourceLocation LLoc = GetLocationForCandidate(L);
9549     SourceLocation RLoc = GetLocationForCandidate(R);
9550 
9551     // Put candidates without locations (e.g. builtins) at the end.
9552     if (LLoc.isInvalid()) return false;
9553     if (RLoc.isInvalid()) return true;
9554 
9555     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9556   }
9557 };
9558 }
9559 
9560 /// CompleteNonViableCandidate - Normally, overload resolution only
9561 /// computes up to the first. Produces the FixIt set if possible.
9562 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9563                                        ArrayRef<Expr *> Args) {
9564   assert(!Cand->Viable);
9565 
9566   // Don't do anything on failures other than bad conversion.
9567   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9568 
9569   // We only want the FixIts if all the arguments can be corrected.
9570   bool Unfixable = false;
9571   // Use a implicit copy initialization to check conversion fixes.
9572   Cand->Fix.setConversionChecker(TryCopyInitialization);
9573 
9574   // Skip forward to the first bad conversion.
9575   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9576   unsigned ConvCount = Cand->NumConversions;
9577   while (true) {
9578     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9579     ConvIdx++;
9580     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9581       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9582       break;
9583     }
9584   }
9585 
9586   if (ConvIdx == ConvCount)
9587     return;
9588 
9589   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9590          "remaining conversion is initialized?");
9591 
9592   // FIXME: this should probably be preserved from the overload
9593   // operation somehow.
9594   bool SuppressUserConversions = false;
9595 
9596   const FunctionProtoType* Proto;
9597   unsigned ArgIdx = ConvIdx;
9598 
9599   if (Cand->IsSurrogate) {
9600     QualType ConvType
9601       = Cand->Surrogate->getConversionType().getNonReferenceType();
9602     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9603       ConvType = ConvPtrType->getPointeeType();
9604     Proto = ConvType->getAs<FunctionProtoType>();
9605     ArgIdx--;
9606   } else if (Cand->Function) {
9607     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9608     if (isa<CXXMethodDecl>(Cand->Function) &&
9609         !isa<CXXConstructorDecl>(Cand->Function))
9610       ArgIdx--;
9611   } else {
9612     // Builtin binary operator with a bad first conversion.
9613     assert(ConvCount <= 3);
9614     for (; ConvIdx != ConvCount; ++ConvIdx)
9615       Cand->Conversions[ConvIdx]
9616         = TryCopyInitialization(S, Args[ConvIdx],
9617                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9618                                 SuppressUserConversions,
9619                                 /*InOverloadResolution*/ true,
9620                                 /*AllowObjCWritebackConversion=*/
9621                                   S.getLangOpts().ObjCAutoRefCount);
9622     return;
9623   }
9624 
9625   // Fill in the rest of the conversions.
9626   unsigned NumParams = Proto->getNumParams();
9627   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9628     if (ArgIdx < NumParams) {
9629       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9630           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9631           /*InOverloadResolution=*/true,
9632           /*AllowObjCWritebackConversion=*/
9633           S.getLangOpts().ObjCAutoRefCount);
9634       // Store the FixIt in the candidate if it exists.
9635       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9636         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9637     }
9638     else
9639       Cand->Conversions[ConvIdx].setEllipsis();
9640   }
9641 }
9642 
9643 /// PrintOverloadCandidates - When overload resolution fails, prints
9644 /// diagnostic messages containing the candidates in the candidate
9645 /// set.
9646 void OverloadCandidateSet::NoteCandidates(Sema &S,
9647                                           OverloadCandidateDisplayKind OCD,
9648                                           ArrayRef<Expr *> Args,
9649                                           StringRef Opc,
9650                                           SourceLocation OpLoc) {
9651   // Sort the candidates by viability and position.  Sorting directly would
9652   // be prohibitive, so we make a set of pointers and sort those.
9653   SmallVector<OverloadCandidate*, 32> Cands;
9654   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9655   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9656     if (Cand->Viable)
9657       Cands.push_back(Cand);
9658     else if (OCD == OCD_AllCandidates) {
9659       CompleteNonViableCandidate(S, Cand, Args);
9660       if (Cand->Function || Cand->IsSurrogate)
9661         Cands.push_back(Cand);
9662       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9663       // want to list every possible builtin candidate.
9664     }
9665   }
9666 
9667   std::sort(Cands.begin(), Cands.end(),
9668             CompareOverloadCandidatesForDisplay(S, Args.size()));
9669 
9670   bool ReportedAmbiguousConversions = false;
9671 
9672   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9673   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9674   unsigned CandsShown = 0;
9675   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9676     OverloadCandidate *Cand = *I;
9677 
9678     // Set an arbitrary limit on the number of candidate functions we'll spam
9679     // the user with.  FIXME: This limit should depend on details of the
9680     // candidate list.
9681     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9682       break;
9683     }
9684     ++CandsShown;
9685 
9686     if (Cand->Function)
9687       NoteFunctionCandidate(S, Cand, Args.size());
9688     else if (Cand->IsSurrogate)
9689       NoteSurrogateCandidate(S, Cand);
9690     else {
9691       assert(Cand->Viable &&
9692              "Non-viable built-in candidates are not added to Cands.");
9693       // Generally we only see ambiguities including viable builtin
9694       // operators if overload resolution got screwed up by an
9695       // ambiguous user-defined conversion.
9696       //
9697       // FIXME: It's quite possible for different conversions to see
9698       // different ambiguities, though.
9699       if (!ReportedAmbiguousConversions) {
9700         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9701         ReportedAmbiguousConversions = true;
9702       }
9703 
9704       // If this is a viable builtin, print it.
9705       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9706     }
9707   }
9708 
9709   if (I != E)
9710     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9711 }
9712 
9713 static SourceLocation
9714 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9715   return Cand->Specialization ? Cand->Specialization->getLocation()
9716                               : SourceLocation();
9717 }
9718 
9719 namespace {
9720 struct CompareTemplateSpecCandidatesForDisplay {
9721   Sema &S;
9722   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9723 
9724   bool operator()(const TemplateSpecCandidate *L,
9725                   const TemplateSpecCandidate *R) {
9726     // Fast-path this check.
9727     if (L == R)
9728       return false;
9729 
9730     // Assuming that both candidates are not matches...
9731 
9732     // Sort by the ranking of deduction failures.
9733     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9734       return RankDeductionFailure(L->DeductionFailure) <
9735              RankDeductionFailure(R->DeductionFailure);
9736 
9737     // Sort everything else by location.
9738     SourceLocation LLoc = GetLocationForCandidate(L);
9739     SourceLocation RLoc = GetLocationForCandidate(R);
9740 
9741     // Put candidates without locations (e.g. builtins) at the end.
9742     if (LLoc.isInvalid())
9743       return false;
9744     if (RLoc.isInvalid())
9745       return true;
9746 
9747     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9748   }
9749 };
9750 }
9751 
9752 /// Diagnose a template argument deduction failure.
9753 /// We are treating these failures as overload failures due to bad
9754 /// deductions.
9755 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9756   DiagnoseBadDeduction(S, Specialization, // pattern
9757                        DeductionFailure, /*NumArgs=*/0);
9758 }
9759 
9760 void TemplateSpecCandidateSet::destroyCandidates() {
9761   for (iterator i = begin(), e = end(); i != e; ++i) {
9762     i->DeductionFailure.Destroy();
9763   }
9764 }
9765 
9766 void TemplateSpecCandidateSet::clear() {
9767   destroyCandidates();
9768   Candidates.clear();
9769 }
9770 
9771 /// NoteCandidates - When no template specialization match is found, prints
9772 /// diagnostic messages containing the non-matching specializations that form
9773 /// the candidate set.
9774 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9775 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9776 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9777   // Sort the candidates by position (assuming no candidate is a match).
9778   // Sorting directly would be prohibitive, so we make a set of pointers
9779   // and sort those.
9780   SmallVector<TemplateSpecCandidate *, 32> Cands;
9781   Cands.reserve(size());
9782   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9783     if (Cand->Specialization)
9784       Cands.push_back(Cand);
9785     // Otherwise, this is a non-matching builtin candidate.  We do not,
9786     // in general, want to list every possible builtin candidate.
9787   }
9788 
9789   std::sort(Cands.begin(), Cands.end(),
9790             CompareTemplateSpecCandidatesForDisplay(S));
9791 
9792   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9793   // for generalization purposes (?).
9794   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9795 
9796   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9797   unsigned CandsShown = 0;
9798   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9799     TemplateSpecCandidate *Cand = *I;
9800 
9801     // Set an arbitrary limit on the number of candidates we'll spam
9802     // the user with.  FIXME: This limit should depend on details of the
9803     // candidate list.
9804     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9805       break;
9806     ++CandsShown;
9807 
9808     assert(Cand->Specialization &&
9809            "Non-matching built-in candidates are not added to Cands.");
9810     Cand->NoteDeductionFailure(S);
9811   }
9812 
9813   if (I != E)
9814     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9815 }
9816 
9817 // [PossiblyAFunctionType]  -->   [Return]
9818 // NonFunctionType --> NonFunctionType
9819 // R (A) --> R(A)
9820 // R (*)(A) --> R (A)
9821 // R (&)(A) --> R (A)
9822 // R (S::*)(A) --> R (A)
9823 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9824   QualType Ret = PossiblyAFunctionType;
9825   if (const PointerType *ToTypePtr =
9826     PossiblyAFunctionType->getAs<PointerType>())
9827     Ret = ToTypePtr->getPointeeType();
9828   else if (const ReferenceType *ToTypeRef =
9829     PossiblyAFunctionType->getAs<ReferenceType>())
9830     Ret = ToTypeRef->getPointeeType();
9831   else if (const MemberPointerType *MemTypePtr =
9832     PossiblyAFunctionType->getAs<MemberPointerType>())
9833     Ret = MemTypePtr->getPointeeType();
9834   Ret =
9835     Context.getCanonicalType(Ret).getUnqualifiedType();
9836   return Ret;
9837 }
9838 
9839 namespace {
9840 // A helper class to help with address of function resolution
9841 // - allows us to avoid passing around all those ugly parameters
9842 class AddressOfFunctionResolver {
9843   Sema& S;
9844   Expr* SourceExpr;
9845   const QualType& TargetType;
9846   QualType TargetFunctionType; // Extracted function type from target type
9847 
9848   bool Complain;
9849   //DeclAccessPair& ResultFunctionAccessPair;
9850   ASTContext& Context;
9851 
9852   bool TargetTypeIsNonStaticMemberFunction;
9853   bool FoundNonTemplateFunction;
9854   bool StaticMemberFunctionFromBoundPointer;
9855 
9856   OverloadExpr::FindResult OvlExprInfo;
9857   OverloadExpr *OvlExpr;
9858   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9859   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9860   TemplateSpecCandidateSet FailedCandidates;
9861 
9862 public:
9863   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9864                             const QualType &TargetType, bool Complain)
9865       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9866         Complain(Complain), Context(S.getASTContext()),
9867         TargetTypeIsNonStaticMemberFunction(
9868             !!TargetType->getAs<MemberPointerType>()),
9869         FoundNonTemplateFunction(false),
9870         StaticMemberFunctionFromBoundPointer(false),
9871         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9872         OvlExpr(OvlExprInfo.Expression),
9873         FailedCandidates(OvlExpr->getNameLoc()) {
9874     ExtractUnqualifiedFunctionTypeFromTargetType();
9875 
9876     if (TargetFunctionType->isFunctionType()) {
9877       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9878         if (!UME->isImplicitAccess() &&
9879             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9880           StaticMemberFunctionFromBoundPointer = true;
9881     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9882       DeclAccessPair dap;
9883       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9884               OvlExpr, false, &dap)) {
9885         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9886           if (!Method->isStatic()) {
9887             // If the target type is a non-function type and the function found
9888             // is a non-static member function, pretend as if that was the
9889             // target, it's the only possible type to end up with.
9890             TargetTypeIsNonStaticMemberFunction = true;
9891 
9892             // And skip adding the function if its not in the proper form.
9893             // We'll diagnose this due to an empty set of functions.
9894             if (!OvlExprInfo.HasFormOfMemberPointer)
9895               return;
9896           }
9897 
9898         Matches.push_back(std::make_pair(dap, Fn));
9899       }
9900       return;
9901     }
9902 
9903     if (OvlExpr->hasExplicitTemplateArgs())
9904       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9905 
9906     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9907       // C++ [over.over]p4:
9908       //   If more than one function is selected, [...]
9909       if (Matches.size() > 1) {
9910         if (FoundNonTemplateFunction)
9911           EliminateAllTemplateMatches();
9912         else
9913           EliminateAllExceptMostSpecializedTemplate();
9914       }
9915     }
9916   }
9917 
9918 private:
9919   bool isTargetTypeAFunction() const {
9920     return TargetFunctionType->isFunctionType();
9921   }
9922 
9923   // [ToType]     [Return]
9924 
9925   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9926   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9927   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9928   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9929     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9930   }
9931 
9932   // return true if any matching specializations were found
9933   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9934                                    const DeclAccessPair& CurAccessFunPair) {
9935     if (CXXMethodDecl *Method
9936               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9937       // Skip non-static function templates when converting to pointer, and
9938       // static when converting to member pointer.
9939       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9940         return false;
9941     }
9942     else if (TargetTypeIsNonStaticMemberFunction)
9943       return false;
9944 
9945     // C++ [over.over]p2:
9946     //   If the name is a function template, template argument deduction is
9947     //   done (14.8.2.2), and if the argument deduction succeeds, the
9948     //   resulting template argument list is used to generate a single
9949     //   function template specialization, which is added to the set of
9950     //   overloaded functions considered.
9951     FunctionDecl *Specialization = nullptr;
9952     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9953     if (Sema::TemplateDeductionResult Result
9954           = S.DeduceTemplateArguments(FunctionTemplate,
9955                                       &OvlExplicitTemplateArgs,
9956                                       TargetFunctionType, Specialization,
9957                                       Info, /*InOverloadResolution=*/true)) {
9958       // Make a note of the failed deduction for diagnostics.
9959       FailedCandidates.addCandidate()
9960           .set(FunctionTemplate->getTemplatedDecl(),
9961                MakeDeductionFailureInfo(Context, Result, Info));
9962       return false;
9963     }
9964 
9965     // Template argument deduction ensures that we have an exact match or
9966     // compatible pointer-to-function arguments that would be adjusted by ICS.
9967     // This function template specicalization works.
9968     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9969     assert(S.isSameOrCompatibleFunctionType(
9970               Context.getCanonicalType(Specialization->getType()),
9971               Context.getCanonicalType(TargetFunctionType)));
9972     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9973     return true;
9974   }
9975 
9976   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9977                                       const DeclAccessPair& CurAccessFunPair) {
9978     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9979       // Skip non-static functions when converting to pointer, and static
9980       // when converting to member pointer.
9981       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9982         return false;
9983     }
9984     else if (TargetTypeIsNonStaticMemberFunction)
9985       return false;
9986 
9987     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9988       if (S.getLangOpts().CUDA)
9989         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9990           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
9991             return false;
9992 
9993       // If any candidate has a placeholder return type, trigger its deduction
9994       // now.
9995       if (S.getLangOpts().CPlusPlus14 &&
9996           FunDecl->getReturnType()->isUndeducedType() &&
9997           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9998         return false;
9999 
10000       QualType ResultTy;
10001       if (Context.hasSameUnqualifiedType(TargetFunctionType,
10002                                          FunDecl->getType()) ||
10003           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10004                                  ResultTy)) {
10005         Matches.push_back(std::make_pair(CurAccessFunPair,
10006           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10007         FoundNonTemplateFunction = true;
10008         return true;
10009       }
10010     }
10011 
10012     return false;
10013   }
10014 
10015   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10016     bool Ret = false;
10017 
10018     // If the overload expression doesn't have the form of a pointer to
10019     // member, don't try to convert it to a pointer-to-member type.
10020     if (IsInvalidFormOfPointerToMemberFunction())
10021       return false;
10022 
10023     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10024                                E = OvlExpr->decls_end();
10025          I != E; ++I) {
10026       // Look through any using declarations to find the underlying function.
10027       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10028 
10029       // C++ [over.over]p3:
10030       //   Non-member functions and static member functions match
10031       //   targets of type "pointer-to-function" or "reference-to-function."
10032       //   Nonstatic member functions match targets of
10033       //   type "pointer-to-member-function."
10034       // Note that according to DR 247, the containing class does not matter.
10035       if (FunctionTemplateDecl *FunctionTemplate
10036                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10037         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10038           Ret = true;
10039       }
10040       // If we have explicit template arguments supplied, skip non-templates.
10041       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10042                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10043         Ret = true;
10044     }
10045     assert(Ret || Matches.empty());
10046     return Ret;
10047   }
10048 
10049   void EliminateAllExceptMostSpecializedTemplate() {
10050     //   [...] and any given function template specialization F1 is
10051     //   eliminated if the set contains a second function template
10052     //   specialization whose function template is more specialized
10053     //   than the function template of F1 according to the partial
10054     //   ordering rules of 14.5.5.2.
10055 
10056     // The algorithm specified above is quadratic. We instead use a
10057     // two-pass algorithm (similar to the one used to identify the
10058     // best viable function in an overload set) that identifies the
10059     // best function template (if it exists).
10060 
10061     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10062     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10063       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10064 
10065     // TODO: It looks like FailedCandidates does not serve much purpose
10066     // here, since the no_viable diagnostic has index 0.
10067     UnresolvedSetIterator Result = S.getMostSpecialized(
10068         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10069         SourceExpr->getLocStart(), S.PDiag(),
10070         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10071                                                      .second->getDeclName(),
10072         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10073         Complain, TargetFunctionType);
10074 
10075     if (Result != MatchesCopy.end()) {
10076       // Make it the first and only element
10077       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10078       Matches[0].second = cast<FunctionDecl>(*Result);
10079       Matches.resize(1);
10080     }
10081   }
10082 
10083   void EliminateAllTemplateMatches() {
10084     //   [...] any function template specializations in the set are
10085     //   eliminated if the set also contains a non-template function, [...]
10086     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10087       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10088         ++I;
10089       else {
10090         Matches[I] = Matches[--N];
10091         Matches.set_size(N);
10092       }
10093     }
10094   }
10095 
10096 public:
10097   void ComplainNoMatchesFound() const {
10098     assert(Matches.empty());
10099     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10100         << OvlExpr->getName() << TargetFunctionType
10101         << OvlExpr->getSourceRange();
10102     if (FailedCandidates.empty())
10103       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10104     else {
10105       // We have some deduction failure messages. Use them to diagnose
10106       // the function templates, and diagnose the non-template candidates
10107       // normally.
10108       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10109                                  IEnd = OvlExpr->decls_end();
10110            I != IEnd; ++I)
10111         if (FunctionDecl *Fun =
10112                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10113           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10114       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10115     }
10116   }
10117 
10118   bool IsInvalidFormOfPointerToMemberFunction() const {
10119     return TargetTypeIsNonStaticMemberFunction &&
10120       !OvlExprInfo.HasFormOfMemberPointer;
10121   }
10122 
10123   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10124       // TODO: Should we condition this on whether any functions might
10125       // have matched, or is it more appropriate to do that in callers?
10126       // TODO: a fixit wouldn't hurt.
10127       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10128         << TargetType << OvlExpr->getSourceRange();
10129   }
10130 
10131   bool IsStaticMemberFunctionFromBoundPointer() const {
10132     return StaticMemberFunctionFromBoundPointer;
10133   }
10134 
10135   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10136     S.Diag(OvlExpr->getLocStart(),
10137            diag::err_invalid_form_pointer_member_function)
10138       << OvlExpr->getSourceRange();
10139   }
10140 
10141   void ComplainOfInvalidConversion() const {
10142     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10143       << OvlExpr->getName() << TargetType;
10144   }
10145 
10146   void ComplainMultipleMatchesFound() const {
10147     assert(Matches.size() > 1);
10148     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10149       << OvlExpr->getName()
10150       << OvlExpr->getSourceRange();
10151     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10152   }
10153 
10154   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10155 
10156   int getNumMatches() const { return Matches.size(); }
10157 
10158   FunctionDecl* getMatchingFunctionDecl() const {
10159     if (Matches.size() != 1) return nullptr;
10160     return Matches[0].second;
10161   }
10162 
10163   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10164     if (Matches.size() != 1) return nullptr;
10165     return &Matches[0].first;
10166   }
10167 };
10168 }
10169 
10170 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10171 /// an overloaded function (C++ [over.over]), where @p From is an
10172 /// expression with overloaded function type and @p ToType is the type
10173 /// we're trying to resolve to. For example:
10174 ///
10175 /// @code
10176 /// int f(double);
10177 /// int f(int);
10178 ///
10179 /// int (*pfd)(double) = f; // selects f(double)
10180 /// @endcode
10181 ///
10182 /// This routine returns the resulting FunctionDecl if it could be
10183 /// resolved, and NULL otherwise. When @p Complain is true, this
10184 /// routine will emit diagnostics if there is an error.
10185 FunctionDecl *
10186 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10187                                          QualType TargetType,
10188                                          bool Complain,
10189                                          DeclAccessPair &FoundResult,
10190                                          bool *pHadMultipleCandidates) {
10191   assert(AddressOfExpr->getType() == Context.OverloadTy);
10192 
10193   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10194                                      Complain);
10195   int NumMatches = Resolver.getNumMatches();
10196   FunctionDecl *Fn = nullptr;
10197   if (NumMatches == 0 && Complain) {
10198     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10199       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10200     else
10201       Resolver.ComplainNoMatchesFound();
10202   }
10203   else if (NumMatches > 1 && Complain)
10204     Resolver.ComplainMultipleMatchesFound();
10205   else if (NumMatches == 1) {
10206     Fn = Resolver.getMatchingFunctionDecl();
10207     assert(Fn);
10208     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10209     if (Complain) {
10210       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10211         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10212       else
10213         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10214     }
10215   }
10216 
10217   if (pHadMultipleCandidates)
10218     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10219   return Fn;
10220 }
10221 
10222 /// \brief Given an expression that refers to an overloaded function, try to
10223 /// resolve that overloaded function expression down to a single function.
10224 ///
10225 /// This routine can only resolve template-ids that refer to a single function
10226 /// template, where that template-id refers to a single template whose template
10227 /// arguments are either provided by the template-id or have defaults,
10228 /// as described in C++0x [temp.arg.explicit]p3.
10229 ///
10230 /// If no template-ids are found, no diagnostics are emitted and NULL is
10231 /// returned.
10232 FunctionDecl *
10233 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10234                                                   bool Complain,
10235                                                   DeclAccessPair *FoundResult) {
10236   // C++ [over.over]p1:
10237   //   [...] [Note: any redundant set of parentheses surrounding the
10238   //   overloaded function name is ignored (5.1). ]
10239   // C++ [over.over]p1:
10240   //   [...] The overloaded function name can be preceded by the &
10241   //   operator.
10242 
10243   // If we didn't actually find any template-ids, we're done.
10244   if (!ovl->hasExplicitTemplateArgs())
10245     return nullptr;
10246 
10247   TemplateArgumentListInfo ExplicitTemplateArgs;
10248   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10249   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10250 
10251   // Look through all of the overloaded functions, searching for one
10252   // whose type matches exactly.
10253   FunctionDecl *Matched = nullptr;
10254   for (UnresolvedSetIterator I = ovl->decls_begin(),
10255          E = ovl->decls_end(); I != E; ++I) {
10256     // C++0x [temp.arg.explicit]p3:
10257     //   [...] In contexts where deduction is done and fails, or in contexts
10258     //   where deduction is not done, if a template argument list is
10259     //   specified and it, along with any default template arguments,
10260     //   identifies a single function template specialization, then the
10261     //   template-id is an lvalue for the function template specialization.
10262     FunctionTemplateDecl *FunctionTemplate
10263       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10264 
10265     // C++ [over.over]p2:
10266     //   If the name is a function template, template argument deduction is
10267     //   done (14.8.2.2), and if the argument deduction succeeds, the
10268     //   resulting template argument list is used to generate a single
10269     //   function template specialization, which is added to the set of
10270     //   overloaded functions considered.
10271     FunctionDecl *Specialization = nullptr;
10272     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10273     if (TemplateDeductionResult Result
10274           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10275                                     Specialization, Info,
10276                                     /*InOverloadResolution=*/true)) {
10277       // Make a note of the failed deduction for diagnostics.
10278       // TODO: Actually use the failed-deduction info?
10279       FailedCandidates.addCandidate()
10280           .set(FunctionTemplate->getTemplatedDecl(),
10281                MakeDeductionFailureInfo(Context, Result, Info));
10282       continue;
10283     }
10284 
10285     assert(Specialization && "no specialization and no error?");
10286 
10287     // Multiple matches; we can't resolve to a single declaration.
10288     if (Matched) {
10289       if (Complain) {
10290         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10291           << ovl->getName();
10292         NoteAllOverloadCandidates(ovl);
10293       }
10294       return nullptr;
10295     }
10296 
10297     Matched = Specialization;
10298     if (FoundResult) *FoundResult = I.getPair();
10299   }
10300 
10301   if (Matched && getLangOpts().CPlusPlus14 &&
10302       Matched->getReturnType()->isUndeducedType() &&
10303       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10304     return nullptr;
10305 
10306   return Matched;
10307 }
10308 
10309 
10310 
10311 
10312 // Resolve and fix an overloaded expression that can be resolved
10313 // because it identifies a single function template specialization.
10314 //
10315 // Last three arguments should only be supplied if Complain = true
10316 //
10317 // Return true if it was logically possible to so resolve the
10318 // expression, regardless of whether or not it succeeded.  Always
10319 // returns true if 'complain' is set.
10320 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10321                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10322                    bool complain, const SourceRange& OpRangeForComplaining,
10323                                            QualType DestTypeForComplaining,
10324                                             unsigned DiagIDForComplaining) {
10325   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10326 
10327   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10328 
10329   DeclAccessPair found;
10330   ExprResult SingleFunctionExpression;
10331   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10332                            ovl.Expression, /*complain*/ false, &found)) {
10333     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10334       SrcExpr = ExprError();
10335       return true;
10336     }
10337 
10338     // It is only correct to resolve to an instance method if we're
10339     // resolving a form that's permitted to be a pointer to member.
10340     // Otherwise we'll end up making a bound member expression, which
10341     // is illegal in all the contexts we resolve like this.
10342     if (!ovl.HasFormOfMemberPointer &&
10343         isa<CXXMethodDecl>(fn) &&
10344         cast<CXXMethodDecl>(fn)->isInstance()) {
10345       if (!complain) return false;
10346 
10347       Diag(ovl.Expression->getExprLoc(),
10348            diag::err_bound_member_function)
10349         << 0 << ovl.Expression->getSourceRange();
10350 
10351       // TODO: I believe we only end up here if there's a mix of
10352       // static and non-static candidates (otherwise the expression
10353       // would have 'bound member' type, not 'overload' type).
10354       // Ideally we would note which candidate was chosen and why
10355       // the static candidates were rejected.
10356       SrcExpr = ExprError();
10357       return true;
10358     }
10359 
10360     // Fix the expression to refer to 'fn'.
10361     SingleFunctionExpression =
10362         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10363 
10364     // If desired, do function-to-pointer decay.
10365     if (doFunctionPointerConverion) {
10366       SingleFunctionExpression =
10367         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10368       if (SingleFunctionExpression.isInvalid()) {
10369         SrcExpr = ExprError();
10370         return true;
10371       }
10372     }
10373   }
10374 
10375   if (!SingleFunctionExpression.isUsable()) {
10376     if (complain) {
10377       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10378         << ovl.Expression->getName()
10379         << DestTypeForComplaining
10380         << OpRangeForComplaining
10381         << ovl.Expression->getQualifierLoc().getSourceRange();
10382       NoteAllOverloadCandidates(SrcExpr.get());
10383 
10384       SrcExpr = ExprError();
10385       return true;
10386     }
10387 
10388     return false;
10389   }
10390 
10391   SrcExpr = SingleFunctionExpression;
10392   return true;
10393 }
10394 
10395 /// \brief Add a single candidate to the overload set.
10396 static void AddOverloadedCallCandidate(Sema &S,
10397                                        DeclAccessPair FoundDecl,
10398                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10399                                        ArrayRef<Expr *> Args,
10400                                        OverloadCandidateSet &CandidateSet,
10401                                        bool PartialOverloading,
10402                                        bool KnownValid) {
10403   NamedDecl *Callee = FoundDecl.getDecl();
10404   if (isa<UsingShadowDecl>(Callee))
10405     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10406 
10407   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10408     if (ExplicitTemplateArgs) {
10409       assert(!KnownValid && "Explicit template arguments?");
10410       return;
10411     }
10412     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10413                            /*SuppressUsedConversions=*/false,
10414                            PartialOverloading);
10415     return;
10416   }
10417 
10418   if (FunctionTemplateDecl *FuncTemplate
10419       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10420     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10421                                    ExplicitTemplateArgs, Args, CandidateSet,
10422                                    /*SuppressUsedConversions=*/false,
10423                                    PartialOverloading);
10424     return;
10425   }
10426 
10427   assert(!KnownValid && "unhandled case in overloaded call candidate");
10428 }
10429 
10430 /// \brief Add the overload candidates named by callee and/or found by argument
10431 /// dependent lookup to the given overload set.
10432 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10433                                        ArrayRef<Expr *> Args,
10434                                        OverloadCandidateSet &CandidateSet,
10435                                        bool PartialOverloading) {
10436 
10437 #ifndef NDEBUG
10438   // Verify that ArgumentDependentLookup is consistent with the rules
10439   // in C++0x [basic.lookup.argdep]p3:
10440   //
10441   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10442   //   and let Y be the lookup set produced by argument dependent
10443   //   lookup (defined as follows). If X contains
10444   //
10445   //     -- a declaration of a class member, or
10446   //
10447   //     -- a block-scope function declaration that is not a
10448   //        using-declaration, or
10449   //
10450   //     -- a declaration that is neither a function or a function
10451   //        template
10452   //
10453   //   then Y is empty.
10454 
10455   if (ULE->requiresADL()) {
10456     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10457            E = ULE->decls_end(); I != E; ++I) {
10458       assert(!(*I)->getDeclContext()->isRecord());
10459       assert(isa<UsingShadowDecl>(*I) ||
10460              !(*I)->getDeclContext()->isFunctionOrMethod());
10461       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10462     }
10463   }
10464 #endif
10465 
10466   // It would be nice to avoid this copy.
10467   TemplateArgumentListInfo TABuffer;
10468   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10469   if (ULE->hasExplicitTemplateArgs()) {
10470     ULE->copyTemplateArgumentsInto(TABuffer);
10471     ExplicitTemplateArgs = &TABuffer;
10472   }
10473 
10474   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10475          E = ULE->decls_end(); I != E; ++I)
10476     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10477                                CandidateSet, PartialOverloading,
10478                                /*KnownValid*/ true);
10479 
10480   if (ULE->requiresADL())
10481     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10482                                          Args, ExplicitTemplateArgs,
10483                                          CandidateSet, PartialOverloading);
10484 }
10485 
10486 /// Determine whether a declaration with the specified name could be moved into
10487 /// a different namespace.
10488 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10489   switch (Name.getCXXOverloadedOperator()) {
10490   case OO_New: case OO_Array_New:
10491   case OO_Delete: case OO_Array_Delete:
10492     return false;
10493 
10494   default:
10495     return true;
10496   }
10497 }
10498 
10499 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10500 /// template, where the non-dependent name was declared after the template
10501 /// was defined. This is common in code written for a compilers which do not
10502 /// correctly implement two-stage name lookup.
10503 ///
10504 /// Returns true if a viable candidate was found and a diagnostic was issued.
10505 static bool
10506 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10507                        const CXXScopeSpec &SS, LookupResult &R,
10508                        OverloadCandidateSet::CandidateSetKind CSK,
10509                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10510                        ArrayRef<Expr *> Args) {
10511   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10512     return false;
10513 
10514   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10515     if (DC->isTransparentContext())
10516       continue;
10517 
10518     SemaRef.LookupQualifiedName(R, DC);
10519 
10520     if (!R.empty()) {
10521       R.suppressDiagnostics();
10522 
10523       if (isa<CXXRecordDecl>(DC)) {
10524         // Don't diagnose names we find in classes; we get much better
10525         // diagnostics for these from DiagnoseEmptyLookup.
10526         R.clear();
10527         return false;
10528       }
10529 
10530       OverloadCandidateSet Candidates(FnLoc, CSK);
10531       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10532         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10533                                    ExplicitTemplateArgs, Args,
10534                                    Candidates, false, /*KnownValid*/ false);
10535 
10536       OverloadCandidateSet::iterator Best;
10537       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10538         // No viable functions. Don't bother the user with notes for functions
10539         // which don't work and shouldn't be found anyway.
10540         R.clear();
10541         return false;
10542       }
10543 
10544       // Find the namespaces where ADL would have looked, and suggest
10545       // declaring the function there instead.
10546       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10547       Sema::AssociatedClassSet AssociatedClasses;
10548       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10549                                                  AssociatedNamespaces,
10550                                                  AssociatedClasses);
10551       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10552       if (canBeDeclaredInNamespace(R.getLookupName())) {
10553         DeclContext *Std = SemaRef.getStdNamespace();
10554         for (Sema::AssociatedNamespaceSet::iterator
10555                it = AssociatedNamespaces.begin(),
10556                end = AssociatedNamespaces.end(); it != end; ++it) {
10557           // Never suggest declaring a function within namespace 'std'.
10558           if (Std && Std->Encloses(*it))
10559             continue;
10560 
10561           // Never suggest declaring a function within a namespace with a
10562           // reserved name, like __gnu_cxx.
10563           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10564           if (NS &&
10565               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10566             continue;
10567 
10568           SuggestedNamespaces.insert(*it);
10569         }
10570       }
10571 
10572       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10573         << R.getLookupName();
10574       if (SuggestedNamespaces.empty()) {
10575         SemaRef.Diag(Best->Function->getLocation(),
10576                      diag::note_not_found_by_two_phase_lookup)
10577           << R.getLookupName() << 0;
10578       } else if (SuggestedNamespaces.size() == 1) {
10579         SemaRef.Diag(Best->Function->getLocation(),
10580                      diag::note_not_found_by_two_phase_lookup)
10581           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10582       } else {
10583         // FIXME: It would be useful to list the associated namespaces here,
10584         // but the diagnostics infrastructure doesn't provide a way to produce
10585         // a localized representation of a list of items.
10586         SemaRef.Diag(Best->Function->getLocation(),
10587                      diag::note_not_found_by_two_phase_lookup)
10588           << R.getLookupName() << 2;
10589       }
10590 
10591       // Try to recover by calling this function.
10592       return true;
10593     }
10594 
10595     R.clear();
10596   }
10597 
10598   return false;
10599 }
10600 
10601 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10602 /// template, where the non-dependent operator was declared after the template
10603 /// was defined.
10604 ///
10605 /// Returns true if a viable candidate was found and a diagnostic was issued.
10606 static bool
10607 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10608                                SourceLocation OpLoc,
10609                                ArrayRef<Expr *> Args) {
10610   DeclarationName OpName =
10611     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10612   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10613   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10614                                 OverloadCandidateSet::CSK_Operator,
10615                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10616 }
10617 
10618 namespace {
10619 class BuildRecoveryCallExprRAII {
10620   Sema &SemaRef;
10621 public:
10622   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10623     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10624     SemaRef.IsBuildingRecoveryCallExpr = true;
10625   }
10626 
10627   ~BuildRecoveryCallExprRAII() {
10628     SemaRef.IsBuildingRecoveryCallExpr = false;
10629   }
10630 };
10631 
10632 }
10633 
10634 static std::unique_ptr<CorrectionCandidateCallback>
10635 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10636               bool HasTemplateArgs, bool AllowTypoCorrection) {
10637   if (!AllowTypoCorrection)
10638     return llvm::make_unique<NoTypoCorrectionCCC>();
10639   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10640                                                   HasTemplateArgs, ME);
10641 }
10642 
10643 /// Attempts to recover from a call where no functions were found.
10644 ///
10645 /// Returns true if new candidates were found.
10646 static ExprResult
10647 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10648                       UnresolvedLookupExpr *ULE,
10649                       SourceLocation LParenLoc,
10650                       MutableArrayRef<Expr *> Args,
10651                       SourceLocation RParenLoc,
10652                       bool EmptyLookup, bool AllowTypoCorrection) {
10653   // Do not try to recover if it is already building a recovery call.
10654   // This stops infinite loops for template instantiations like
10655   //
10656   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10657   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10658   //
10659   if (SemaRef.IsBuildingRecoveryCallExpr)
10660     return ExprError();
10661   BuildRecoveryCallExprRAII RCE(SemaRef);
10662 
10663   CXXScopeSpec SS;
10664   SS.Adopt(ULE->getQualifierLoc());
10665   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10666 
10667   TemplateArgumentListInfo TABuffer;
10668   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10669   if (ULE->hasExplicitTemplateArgs()) {
10670     ULE->copyTemplateArgumentsInto(TABuffer);
10671     ExplicitTemplateArgs = &TABuffer;
10672   }
10673 
10674   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10675                  Sema::LookupOrdinaryName);
10676   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10677                               OverloadCandidateSet::CSK_Normal,
10678                               ExplicitTemplateArgs, Args) &&
10679       (!EmptyLookup ||
10680        SemaRef.DiagnoseEmptyLookup(
10681            S, SS, R,
10682            MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10683                          ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10684            ExplicitTemplateArgs, Args)))
10685     return ExprError();
10686 
10687   assert(!R.empty() && "lookup results empty despite recovery");
10688 
10689   // Build an implicit member call if appropriate.  Just drop the
10690   // casts and such from the call, we don't really care.
10691   ExprResult NewFn = ExprError();
10692   if ((*R.begin())->isCXXClassMember())
10693     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10694                                                     R, ExplicitTemplateArgs);
10695   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10696     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10697                                         ExplicitTemplateArgs);
10698   else
10699     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10700 
10701   if (NewFn.isInvalid())
10702     return ExprError();
10703 
10704   // This shouldn't cause an infinite loop because we're giving it
10705   // an expression with viable lookup results, which should never
10706   // end up here.
10707   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10708                                MultiExprArg(Args.data(), Args.size()),
10709                                RParenLoc);
10710 }
10711 
10712 /// \brief Constructs and populates an OverloadedCandidateSet from
10713 /// the given function.
10714 /// \returns true when an the ExprResult output parameter has been set.
10715 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10716                                   UnresolvedLookupExpr *ULE,
10717                                   MultiExprArg Args,
10718                                   SourceLocation RParenLoc,
10719                                   OverloadCandidateSet *CandidateSet,
10720                                   ExprResult *Result) {
10721 #ifndef NDEBUG
10722   if (ULE->requiresADL()) {
10723     // To do ADL, we must have found an unqualified name.
10724     assert(!ULE->getQualifier() && "qualified name with ADL");
10725 
10726     // We don't perform ADL for implicit declarations of builtins.
10727     // Verify that this was correctly set up.
10728     FunctionDecl *F;
10729     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10730         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10731         F->getBuiltinID() && F->isImplicit())
10732       llvm_unreachable("performing ADL for builtin");
10733 
10734     // We don't perform ADL in C.
10735     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10736   }
10737 #endif
10738 
10739   UnbridgedCastsSet UnbridgedCasts;
10740   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10741     *Result = ExprError();
10742     return true;
10743   }
10744 
10745   // Add the functions denoted by the callee to the set of candidate
10746   // functions, including those from argument-dependent lookup.
10747   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10748 
10749   // If we found nothing, try to recover.
10750   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10751   // out if it fails.
10752   if (CandidateSet->empty()) {
10753     // In Microsoft mode, if we are inside a template class member function then
10754     // create a type dependent CallExpr. The goal is to postpone name lookup
10755     // to instantiation time to be able to search into type dependent base
10756     // classes.
10757     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10758         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10759       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10760                                             Context.DependentTy, VK_RValue,
10761                                             RParenLoc);
10762       CE->setTypeDependent(true);
10763       *Result = CE;
10764       return true;
10765     }
10766     return false;
10767   }
10768 
10769   UnbridgedCasts.restore();
10770   return false;
10771 }
10772 
10773 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10774 /// the completed call expression. If overload resolution fails, emits
10775 /// diagnostics and returns ExprError()
10776 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10777                                            UnresolvedLookupExpr *ULE,
10778                                            SourceLocation LParenLoc,
10779                                            MultiExprArg Args,
10780                                            SourceLocation RParenLoc,
10781                                            Expr *ExecConfig,
10782                                            OverloadCandidateSet *CandidateSet,
10783                                            OverloadCandidateSet::iterator *Best,
10784                                            OverloadingResult OverloadResult,
10785                                            bool AllowTypoCorrection) {
10786   if (CandidateSet->empty())
10787     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10788                                  RParenLoc, /*EmptyLookup=*/true,
10789                                  AllowTypoCorrection);
10790 
10791   switch (OverloadResult) {
10792   case OR_Success: {
10793     FunctionDecl *FDecl = (*Best)->Function;
10794     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10795     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10796       return ExprError();
10797     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10798     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10799                                          ExecConfig);
10800   }
10801 
10802   case OR_No_Viable_Function: {
10803     // Try to recover by looking for viable functions which the user might
10804     // have meant to call.
10805     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10806                                                 Args, RParenLoc,
10807                                                 /*EmptyLookup=*/false,
10808                                                 AllowTypoCorrection);
10809     if (!Recovery.isInvalid())
10810       return Recovery;
10811 
10812     SemaRef.Diag(Fn->getLocStart(),
10813          diag::err_ovl_no_viable_function_in_call)
10814       << ULE->getName() << Fn->getSourceRange();
10815     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10816     break;
10817   }
10818 
10819   case OR_Ambiguous:
10820     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10821       << ULE->getName() << Fn->getSourceRange();
10822     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10823     break;
10824 
10825   case OR_Deleted: {
10826     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10827       << (*Best)->Function->isDeleted()
10828       << ULE->getName()
10829       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10830       << Fn->getSourceRange();
10831     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10832 
10833     // We emitted an error for the unvailable/deleted function call but keep
10834     // the call in the AST.
10835     FunctionDecl *FDecl = (*Best)->Function;
10836     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10837     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10838                                          ExecConfig);
10839   }
10840   }
10841 
10842   // Overload resolution failed.
10843   return ExprError();
10844 }
10845 
10846 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10847 /// (which eventually refers to the declaration Func) and the call
10848 /// arguments Args/NumArgs, attempt to resolve the function call down
10849 /// to a specific function. If overload resolution succeeds, returns
10850 /// the call expression produced by overload resolution.
10851 /// Otherwise, emits diagnostics and returns ExprError.
10852 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10853                                          UnresolvedLookupExpr *ULE,
10854                                          SourceLocation LParenLoc,
10855                                          MultiExprArg Args,
10856                                          SourceLocation RParenLoc,
10857                                          Expr *ExecConfig,
10858                                          bool AllowTypoCorrection) {
10859   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10860                                     OverloadCandidateSet::CSK_Normal);
10861   ExprResult result;
10862 
10863   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10864                              &result))
10865     return result;
10866 
10867   OverloadCandidateSet::iterator Best;
10868   OverloadingResult OverloadResult =
10869       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10870 
10871   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10872                                   RParenLoc, ExecConfig, &CandidateSet,
10873                                   &Best, OverloadResult,
10874                                   AllowTypoCorrection);
10875 }
10876 
10877 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10878   return Functions.size() > 1 ||
10879     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10880 }
10881 
10882 /// \brief Create a unary operation that may resolve to an overloaded
10883 /// operator.
10884 ///
10885 /// \param OpLoc The location of the operator itself (e.g., '*').
10886 ///
10887 /// \param OpcIn The UnaryOperator::Opcode that describes this
10888 /// operator.
10889 ///
10890 /// \param Fns The set of non-member functions that will be
10891 /// considered by overload resolution. The caller needs to build this
10892 /// set based on the context using, e.g.,
10893 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10894 /// set should not contain any member functions; those will be added
10895 /// by CreateOverloadedUnaryOp().
10896 ///
10897 /// \param Input The input argument.
10898 ExprResult
10899 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10900                               const UnresolvedSetImpl &Fns,
10901                               Expr *Input) {
10902   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10903 
10904   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10905   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10906   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10907   // TODO: provide better source location info.
10908   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10909 
10910   if (checkPlaceholderForOverload(*this, Input))
10911     return ExprError();
10912 
10913   Expr *Args[2] = { Input, nullptr };
10914   unsigned NumArgs = 1;
10915 
10916   // For post-increment and post-decrement, add the implicit '0' as
10917   // the second argument, so that we know this is a post-increment or
10918   // post-decrement.
10919   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10920     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10921     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10922                                      SourceLocation());
10923     NumArgs = 2;
10924   }
10925 
10926   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10927 
10928   if (Input->isTypeDependent()) {
10929     if (Fns.empty())
10930       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10931                                          VK_RValue, OK_Ordinary, OpLoc);
10932 
10933     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10934     UnresolvedLookupExpr *Fn
10935       = UnresolvedLookupExpr::Create(Context, NamingClass,
10936                                      NestedNameSpecifierLoc(), OpNameInfo,
10937                                      /*ADL*/ true, IsOverloaded(Fns),
10938                                      Fns.begin(), Fns.end());
10939     return new (Context)
10940         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10941                             VK_RValue, OpLoc, false);
10942   }
10943 
10944   // Build an empty overload set.
10945   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10946 
10947   // Add the candidates from the given function set.
10948   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
10949 
10950   // Add operator candidates that are member functions.
10951   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10952 
10953   // Add candidates from ADL.
10954   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10955                                        /*ExplicitTemplateArgs*/nullptr,
10956                                        CandidateSet);
10957 
10958   // Add builtin operator candidates.
10959   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10960 
10961   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10962 
10963   // Perform overload resolution.
10964   OverloadCandidateSet::iterator Best;
10965   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10966   case OR_Success: {
10967     // We found a built-in operator or an overloaded operator.
10968     FunctionDecl *FnDecl = Best->Function;
10969 
10970     if (FnDecl) {
10971       // We matched an overloaded operator. Build a call to that
10972       // operator.
10973 
10974       // Convert the arguments.
10975       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10976         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10977 
10978         ExprResult InputRes =
10979           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10980                                               Best->FoundDecl, Method);
10981         if (InputRes.isInvalid())
10982           return ExprError();
10983         Input = InputRes.get();
10984       } else {
10985         // Convert the arguments.
10986         ExprResult InputInit
10987           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10988                                                       Context,
10989                                                       FnDecl->getParamDecl(0)),
10990                                       SourceLocation(),
10991                                       Input);
10992         if (InputInit.isInvalid())
10993           return ExprError();
10994         Input = InputInit.get();
10995       }
10996 
10997       // Build the actual expression node.
10998       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10999                                                 HadMultipleCandidates, OpLoc);
11000       if (FnExpr.isInvalid())
11001         return ExprError();
11002 
11003       // Determine the result type.
11004       QualType ResultTy = FnDecl->getReturnType();
11005       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11006       ResultTy = ResultTy.getNonLValueExprType(Context);
11007 
11008       Args[0] = Input;
11009       CallExpr *TheCall =
11010         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11011                                           ResultTy, VK, OpLoc, false);
11012 
11013       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11014         return ExprError();
11015 
11016       return MaybeBindToTemporary(TheCall);
11017     } else {
11018       // We matched a built-in operator. Convert the arguments, then
11019       // break out so that we will build the appropriate built-in
11020       // operator node.
11021       ExprResult InputRes =
11022         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11023                                   Best->Conversions[0], AA_Passing);
11024       if (InputRes.isInvalid())
11025         return ExprError();
11026       Input = InputRes.get();
11027       break;
11028     }
11029   }
11030 
11031   case OR_No_Viable_Function:
11032     // This is an erroneous use of an operator which can be overloaded by
11033     // a non-member function. Check for non-member operators which were
11034     // defined too late to be candidates.
11035     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11036       // FIXME: Recover by calling the found function.
11037       return ExprError();
11038 
11039     // No viable function; fall through to handling this as a
11040     // built-in operator, which will produce an error message for us.
11041     break;
11042 
11043   case OR_Ambiguous:
11044     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11045         << UnaryOperator::getOpcodeStr(Opc)
11046         << Input->getType()
11047         << Input->getSourceRange();
11048     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11049                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11050     return ExprError();
11051 
11052   case OR_Deleted:
11053     Diag(OpLoc, diag::err_ovl_deleted_oper)
11054       << Best->Function->isDeleted()
11055       << UnaryOperator::getOpcodeStr(Opc)
11056       << getDeletedOrUnavailableSuffix(Best->Function)
11057       << Input->getSourceRange();
11058     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11059                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11060     return ExprError();
11061   }
11062 
11063   // Either we found no viable overloaded operator or we matched a
11064   // built-in operator. In either case, fall through to trying to
11065   // build a built-in operation.
11066   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11067 }
11068 
11069 /// \brief Create a binary operation that may resolve to an overloaded
11070 /// operator.
11071 ///
11072 /// \param OpLoc The location of the operator itself (e.g., '+').
11073 ///
11074 /// \param OpcIn The BinaryOperator::Opcode that describes this
11075 /// operator.
11076 ///
11077 /// \param Fns The set of non-member functions that will be
11078 /// considered by overload resolution. The caller needs to build this
11079 /// set based on the context using, e.g.,
11080 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11081 /// set should not contain any member functions; those will be added
11082 /// by CreateOverloadedBinOp().
11083 ///
11084 /// \param LHS Left-hand argument.
11085 /// \param RHS Right-hand argument.
11086 ExprResult
11087 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11088                             unsigned OpcIn,
11089                             const UnresolvedSetImpl &Fns,
11090                             Expr *LHS, Expr *RHS) {
11091   Expr *Args[2] = { LHS, RHS };
11092   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11093 
11094   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11095   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11096   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11097 
11098   // If either side is type-dependent, create an appropriate dependent
11099   // expression.
11100   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11101     if (Fns.empty()) {
11102       // If there are no functions to store, just build a dependent
11103       // BinaryOperator or CompoundAssignment.
11104       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11105         return new (Context) BinaryOperator(
11106             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11107             OpLoc, FPFeatures.fp_contract);
11108 
11109       return new (Context) CompoundAssignOperator(
11110           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11111           Context.DependentTy, Context.DependentTy, OpLoc,
11112           FPFeatures.fp_contract);
11113     }
11114 
11115     // FIXME: save results of ADL from here?
11116     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11117     // TODO: provide better source location info in DNLoc component.
11118     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11119     UnresolvedLookupExpr *Fn
11120       = UnresolvedLookupExpr::Create(Context, NamingClass,
11121                                      NestedNameSpecifierLoc(), OpNameInfo,
11122                                      /*ADL*/ true, IsOverloaded(Fns),
11123                                      Fns.begin(), Fns.end());
11124     return new (Context)
11125         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11126                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11127   }
11128 
11129   // Always do placeholder-like conversions on the RHS.
11130   if (checkPlaceholderForOverload(*this, Args[1]))
11131     return ExprError();
11132 
11133   // Do placeholder-like conversion on the LHS; note that we should
11134   // not get here with a PseudoObject LHS.
11135   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11136   if (checkPlaceholderForOverload(*this, Args[0]))
11137     return ExprError();
11138 
11139   // If this is the assignment operator, we only perform overload resolution
11140   // if the left-hand side is a class or enumeration type. This is actually
11141   // a hack. The standard requires that we do overload resolution between the
11142   // various built-in candidates, but as DR507 points out, this can lead to
11143   // problems. So we do it this way, which pretty much follows what GCC does.
11144   // Note that we go the traditional code path for compound assignment forms.
11145   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11146     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11147 
11148   // If this is the .* operator, which is not overloadable, just
11149   // create a built-in binary operator.
11150   if (Opc == BO_PtrMemD)
11151     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11152 
11153   // Build an empty overload set.
11154   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11155 
11156   // Add the candidates from the given function set.
11157   AddFunctionCandidates(Fns, Args, CandidateSet);
11158 
11159   // Add operator candidates that are member functions.
11160   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11161 
11162   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11163   // performed for an assignment operator (nor for operator[] nor operator->,
11164   // which don't get here).
11165   if (Opc != BO_Assign)
11166     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11167                                          /*ExplicitTemplateArgs*/ nullptr,
11168                                          CandidateSet);
11169 
11170   // Add builtin operator candidates.
11171   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11172 
11173   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11174 
11175   // Perform overload resolution.
11176   OverloadCandidateSet::iterator Best;
11177   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11178     case OR_Success: {
11179       // We found a built-in operator or an overloaded operator.
11180       FunctionDecl *FnDecl = Best->Function;
11181 
11182       if (FnDecl) {
11183         // We matched an overloaded operator. Build a call to that
11184         // operator.
11185 
11186         // Convert the arguments.
11187         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11188           // Best->Access is only meaningful for class members.
11189           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11190 
11191           ExprResult Arg1 =
11192             PerformCopyInitialization(
11193               InitializedEntity::InitializeParameter(Context,
11194                                                      FnDecl->getParamDecl(0)),
11195               SourceLocation(), Args[1]);
11196           if (Arg1.isInvalid())
11197             return ExprError();
11198 
11199           ExprResult Arg0 =
11200             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11201                                                 Best->FoundDecl, Method);
11202           if (Arg0.isInvalid())
11203             return ExprError();
11204           Args[0] = Arg0.getAs<Expr>();
11205           Args[1] = RHS = Arg1.getAs<Expr>();
11206         } else {
11207           // Convert the arguments.
11208           ExprResult Arg0 = PerformCopyInitialization(
11209             InitializedEntity::InitializeParameter(Context,
11210                                                    FnDecl->getParamDecl(0)),
11211             SourceLocation(), Args[0]);
11212           if (Arg0.isInvalid())
11213             return ExprError();
11214 
11215           ExprResult Arg1 =
11216             PerformCopyInitialization(
11217               InitializedEntity::InitializeParameter(Context,
11218                                                      FnDecl->getParamDecl(1)),
11219               SourceLocation(), Args[1]);
11220           if (Arg1.isInvalid())
11221             return ExprError();
11222           Args[0] = LHS = Arg0.getAs<Expr>();
11223           Args[1] = RHS = Arg1.getAs<Expr>();
11224         }
11225 
11226         // Build the actual expression node.
11227         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11228                                                   Best->FoundDecl,
11229                                                   HadMultipleCandidates, OpLoc);
11230         if (FnExpr.isInvalid())
11231           return ExprError();
11232 
11233         // Determine the result type.
11234         QualType ResultTy = FnDecl->getReturnType();
11235         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11236         ResultTy = ResultTy.getNonLValueExprType(Context);
11237 
11238         CXXOperatorCallExpr *TheCall =
11239           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11240                                             Args, ResultTy, VK, OpLoc,
11241                                             FPFeatures.fp_contract);
11242 
11243         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11244                                 FnDecl))
11245           return ExprError();
11246 
11247         ArrayRef<const Expr *> ArgsArray(Args, 2);
11248         // Cut off the implicit 'this'.
11249         if (isa<CXXMethodDecl>(FnDecl))
11250           ArgsArray = ArgsArray.slice(1);
11251 
11252         // Check for a self move.
11253         if (Op == OO_Equal)
11254           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11255 
11256         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11257                   TheCall->getSourceRange(), VariadicDoesNotApply);
11258 
11259         return MaybeBindToTemporary(TheCall);
11260       } else {
11261         // We matched a built-in operator. Convert the arguments, then
11262         // break out so that we will build the appropriate built-in
11263         // operator node.
11264         ExprResult ArgsRes0 =
11265           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11266                                     Best->Conversions[0], AA_Passing);
11267         if (ArgsRes0.isInvalid())
11268           return ExprError();
11269         Args[0] = ArgsRes0.get();
11270 
11271         ExprResult ArgsRes1 =
11272           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11273                                     Best->Conversions[1], AA_Passing);
11274         if (ArgsRes1.isInvalid())
11275           return ExprError();
11276         Args[1] = ArgsRes1.get();
11277         break;
11278       }
11279     }
11280 
11281     case OR_No_Viable_Function: {
11282       // C++ [over.match.oper]p9:
11283       //   If the operator is the operator , [...] and there are no
11284       //   viable functions, then the operator is assumed to be the
11285       //   built-in operator and interpreted according to clause 5.
11286       if (Opc == BO_Comma)
11287         break;
11288 
11289       // For class as left operand for assignment or compound assigment
11290       // operator do not fall through to handling in built-in, but report that
11291       // no overloaded assignment operator found
11292       ExprResult Result = ExprError();
11293       if (Args[0]->getType()->isRecordType() &&
11294           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11295         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11296              << BinaryOperator::getOpcodeStr(Opc)
11297              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11298         if (Args[0]->getType()->isIncompleteType()) {
11299           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11300             << Args[0]->getType()
11301             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11302         }
11303       } else {
11304         // This is an erroneous use of an operator which can be overloaded by
11305         // a non-member function. Check for non-member operators which were
11306         // defined too late to be candidates.
11307         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11308           // FIXME: Recover by calling the found function.
11309           return ExprError();
11310 
11311         // No viable function; try to create a built-in operation, which will
11312         // produce an error. Then, show the non-viable candidates.
11313         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11314       }
11315       assert(Result.isInvalid() &&
11316              "C++ binary operator overloading is missing candidates!");
11317       if (Result.isInvalid())
11318         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11319                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11320       return Result;
11321     }
11322 
11323     case OR_Ambiguous:
11324       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11325           << BinaryOperator::getOpcodeStr(Opc)
11326           << Args[0]->getType() << Args[1]->getType()
11327           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11328       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11329                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11330       return ExprError();
11331 
11332     case OR_Deleted:
11333       if (isImplicitlyDeleted(Best->Function)) {
11334         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11335         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11336           << Context.getRecordType(Method->getParent())
11337           << getSpecialMember(Method);
11338 
11339         // The user probably meant to call this special member. Just
11340         // explain why it's deleted.
11341         NoteDeletedFunction(Method);
11342         return ExprError();
11343       } else {
11344         Diag(OpLoc, diag::err_ovl_deleted_oper)
11345           << Best->Function->isDeleted()
11346           << BinaryOperator::getOpcodeStr(Opc)
11347           << getDeletedOrUnavailableSuffix(Best->Function)
11348           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11349       }
11350       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11351                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11352       return ExprError();
11353   }
11354 
11355   // We matched a built-in operator; build it.
11356   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11357 }
11358 
11359 ExprResult
11360 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11361                                          SourceLocation RLoc,
11362                                          Expr *Base, Expr *Idx) {
11363   Expr *Args[2] = { Base, Idx };
11364   DeclarationName OpName =
11365       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11366 
11367   // If either side is type-dependent, create an appropriate dependent
11368   // expression.
11369   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11370 
11371     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11372     // CHECKME: no 'operator' keyword?
11373     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11374     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11375     UnresolvedLookupExpr *Fn
11376       = UnresolvedLookupExpr::Create(Context, NamingClass,
11377                                      NestedNameSpecifierLoc(), OpNameInfo,
11378                                      /*ADL*/ true, /*Overloaded*/ false,
11379                                      UnresolvedSetIterator(),
11380                                      UnresolvedSetIterator());
11381     // Can't add any actual overloads yet
11382 
11383     return new (Context)
11384         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11385                             Context.DependentTy, VK_RValue, RLoc, false);
11386   }
11387 
11388   // Handle placeholders on both operands.
11389   if (checkPlaceholderForOverload(*this, Args[0]))
11390     return ExprError();
11391   if (checkPlaceholderForOverload(*this, Args[1]))
11392     return ExprError();
11393 
11394   // Build an empty overload set.
11395   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11396 
11397   // Subscript can only be overloaded as a member function.
11398 
11399   // Add operator candidates that are member functions.
11400   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11401 
11402   // Add builtin operator candidates.
11403   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11404 
11405   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11406 
11407   // Perform overload resolution.
11408   OverloadCandidateSet::iterator Best;
11409   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11410     case OR_Success: {
11411       // We found a built-in operator or an overloaded operator.
11412       FunctionDecl *FnDecl = Best->Function;
11413 
11414       if (FnDecl) {
11415         // We matched an overloaded operator. Build a call to that
11416         // operator.
11417 
11418         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11419 
11420         // Convert the arguments.
11421         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11422         ExprResult Arg0 =
11423           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11424                                               Best->FoundDecl, Method);
11425         if (Arg0.isInvalid())
11426           return ExprError();
11427         Args[0] = Arg0.get();
11428 
11429         // Convert the arguments.
11430         ExprResult InputInit
11431           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11432                                                       Context,
11433                                                       FnDecl->getParamDecl(0)),
11434                                       SourceLocation(),
11435                                       Args[1]);
11436         if (InputInit.isInvalid())
11437           return ExprError();
11438 
11439         Args[1] = InputInit.getAs<Expr>();
11440 
11441         // Build the actual expression node.
11442         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11443         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11444         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11445                                                   Best->FoundDecl,
11446                                                   HadMultipleCandidates,
11447                                                   OpLocInfo.getLoc(),
11448                                                   OpLocInfo.getInfo());
11449         if (FnExpr.isInvalid())
11450           return ExprError();
11451 
11452         // Determine the result type
11453         QualType ResultTy = FnDecl->getReturnType();
11454         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11455         ResultTy = ResultTy.getNonLValueExprType(Context);
11456 
11457         CXXOperatorCallExpr *TheCall =
11458           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11459                                             FnExpr.get(), Args,
11460                                             ResultTy, VK, RLoc,
11461                                             false);
11462 
11463         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11464           return ExprError();
11465 
11466         return MaybeBindToTemporary(TheCall);
11467       } else {
11468         // We matched a built-in operator. Convert the arguments, then
11469         // break out so that we will build the appropriate built-in
11470         // operator node.
11471         ExprResult ArgsRes0 =
11472           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11473                                     Best->Conversions[0], AA_Passing);
11474         if (ArgsRes0.isInvalid())
11475           return ExprError();
11476         Args[0] = ArgsRes0.get();
11477 
11478         ExprResult ArgsRes1 =
11479           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11480                                     Best->Conversions[1], AA_Passing);
11481         if (ArgsRes1.isInvalid())
11482           return ExprError();
11483         Args[1] = ArgsRes1.get();
11484 
11485         break;
11486       }
11487     }
11488 
11489     case OR_No_Viable_Function: {
11490       if (CandidateSet.empty())
11491         Diag(LLoc, diag::err_ovl_no_oper)
11492           << Args[0]->getType() << /*subscript*/ 0
11493           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11494       else
11495         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11496           << Args[0]->getType()
11497           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11498       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11499                                   "[]", LLoc);
11500       return ExprError();
11501     }
11502 
11503     case OR_Ambiguous:
11504       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11505           << "[]"
11506           << Args[0]->getType() << Args[1]->getType()
11507           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11508       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11509                                   "[]", LLoc);
11510       return ExprError();
11511 
11512     case OR_Deleted:
11513       Diag(LLoc, diag::err_ovl_deleted_oper)
11514         << Best->Function->isDeleted() << "[]"
11515         << getDeletedOrUnavailableSuffix(Best->Function)
11516         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11517       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11518                                   "[]", LLoc);
11519       return ExprError();
11520     }
11521 
11522   // We matched a built-in operator; build it.
11523   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11524 }
11525 
11526 /// BuildCallToMemberFunction - Build a call to a member
11527 /// function. MemExpr is the expression that refers to the member
11528 /// function (and includes the object parameter), Args/NumArgs are the
11529 /// arguments to the function call (not including the object
11530 /// parameter). The caller needs to validate that the member
11531 /// expression refers to a non-static member function or an overloaded
11532 /// member function.
11533 ExprResult
11534 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11535                                 SourceLocation LParenLoc,
11536                                 MultiExprArg Args,
11537                                 SourceLocation RParenLoc) {
11538   assert(MemExprE->getType() == Context.BoundMemberTy ||
11539          MemExprE->getType() == Context.OverloadTy);
11540 
11541   // Dig out the member expression. This holds both the object
11542   // argument and the member function we're referring to.
11543   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11544 
11545   // Determine whether this is a call to a pointer-to-member function.
11546   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11547     assert(op->getType() == Context.BoundMemberTy);
11548     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11549 
11550     QualType fnType =
11551       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11552 
11553     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11554     QualType resultType = proto->getCallResultType(Context);
11555     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11556 
11557     // Check that the object type isn't more qualified than the
11558     // member function we're calling.
11559     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11560 
11561     QualType objectType = op->getLHS()->getType();
11562     if (op->getOpcode() == BO_PtrMemI)
11563       objectType = objectType->castAs<PointerType>()->getPointeeType();
11564     Qualifiers objectQuals = objectType.getQualifiers();
11565 
11566     Qualifiers difference = objectQuals - funcQuals;
11567     difference.removeObjCGCAttr();
11568     difference.removeAddressSpace();
11569     if (difference) {
11570       std::string qualsString = difference.getAsString();
11571       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11572         << fnType.getUnqualifiedType()
11573         << qualsString
11574         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11575     }
11576 
11577     if (resultType->isMemberPointerType())
11578       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11579         RequireCompleteType(LParenLoc, resultType, 0);
11580 
11581     CXXMemberCallExpr *call
11582       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11583                                         resultType, valueKind, RParenLoc);
11584 
11585     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11586                             call, nullptr))
11587       return ExprError();
11588 
11589     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11590       return ExprError();
11591 
11592     if (CheckOtherCall(call, proto))
11593       return ExprError();
11594 
11595     return MaybeBindToTemporary(call);
11596   }
11597 
11598   UnbridgedCastsSet UnbridgedCasts;
11599   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11600     return ExprError();
11601 
11602   MemberExpr *MemExpr;
11603   CXXMethodDecl *Method = nullptr;
11604   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11605   NestedNameSpecifier *Qualifier = nullptr;
11606   if (isa<MemberExpr>(NakedMemExpr)) {
11607     MemExpr = cast<MemberExpr>(NakedMemExpr);
11608     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11609     FoundDecl = MemExpr->getFoundDecl();
11610     Qualifier = MemExpr->getQualifier();
11611     UnbridgedCasts.restore();
11612   } else {
11613     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11614     Qualifier = UnresExpr->getQualifier();
11615 
11616     QualType ObjectType = UnresExpr->getBaseType();
11617     Expr::Classification ObjectClassification
11618       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11619                             : UnresExpr->getBase()->Classify(Context);
11620 
11621     // Add overload candidates
11622     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11623                                       OverloadCandidateSet::CSK_Normal);
11624 
11625     // FIXME: avoid copy.
11626     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11627     if (UnresExpr->hasExplicitTemplateArgs()) {
11628       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11629       TemplateArgs = &TemplateArgsBuffer;
11630     }
11631 
11632     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11633            E = UnresExpr->decls_end(); I != E; ++I) {
11634 
11635       NamedDecl *Func = *I;
11636       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11637       if (isa<UsingShadowDecl>(Func))
11638         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11639 
11640 
11641       // Microsoft supports direct constructor calls.
11642       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11643         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11644                              Args, CandidateSet);
11645       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11646         // If explicit template arguments were provided, we can't call a
11647         // non-template member function.
11648         if (TemplateArgs)
11649           continue;
11650 
11651         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11652                            ObjectClassification, Args, CandidateSet,
11653                            /*SuppressUserConversions=*/false);
11654       } else {
11655         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11656                                    I.getPair(), ActingDC, TemplateArgs,
11657                                    ObjectType,  ObjectClassification,
11658                                    Args, CandidateSet,
11659                                    /*SuppressUsedConversions=*/false);
11660       }
11661     }
11662 
11663     DeclarationName DeclName = UnresExpr->getMemberName();
11664 
11665     UnbridgedCasts.restore();
11666 
11667     OverloadCandidateSet::iterator Best;
11668     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11669                                             Best)) {
11670     case OR_Success:
11671       Method = cast<CXXMethodDecl>(Best->Function);
11672       FoundDecl = Best->FoundDecl;
11673       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11674       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11675         return ExprError();
11676       // If FoundDecl is different from Method (such as if one is a template
11677       // and the other a specialization), make sure DiagnoseUseOfDecl is
11678       // called on both.
11679       // FIXME: This would be more comprehensively addressed by modifying
11680       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11681       // being used.
11682       if (Method != FoundDecl.getDecl() &&
11683                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11684         return ExprError();
11685       break;
11686 
11687     case OR_No_Viable_Function:
11688       Diag(UnresExpr->getMemberLoc(),
11689            diag::err_ovl_no_viable_member_function_in_call)
11690         << DeclName << MemExprE->getSourceRange();
11691       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11692       // FIXME: Leaking incoming expressions!
11693       return ExprError();
11694 
11695     case OR_Ambiguous:
11696       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11697         << DeclName << MemExprE->getSourceRange();
11698       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11699       // FIXME: Leaking incoming expressions!
11700       return ExprError();
11701 
11702     case OR_Deleted:
11703       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11704         << Best->Function->isDeleted()
11705         << DeclName
11706         << getDeletedOrUnavailableSuffix(Best->Function)
11707         << MemExprE->getSourceRange();
11708       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11709       // FIXME: Leaking incoming expressions!
11710       return ExprError();
11711     }
11712 
11713     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11714 
11715     // If overload resolution picked a static member, build a
11716     // non-member call based on that function.
11717     if (Method->isStatic()) {
11718       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11719                                    RParenLoc);
11720     }
11721 
11722     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11723   }
11724 
11725   QualType ResultType = Method->getReturnType();
11726   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11727   ResultType = ResultType.getNonLValueExprType(Context);
11728 
11729   assert(Method && "Member call to something that isn't a method?");
11730   CXXMemberCallExpr *TheCall =
11731     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11732                                     ResultType, VK, RParenLoc);
11733 
11734   // (CUDA B.1): Check for invalid calls between targets.
11735   if (getLangOpts().CUDA) {
11736     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11737       if (CheckCUDATarget(Caller, Method)) {
11738         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11739             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11740             << IdentifyCUDATarget(Caller);
11741         return ExprError();
11742       }
11743     }
11744   }
11745 
11746   // Check for a valid return type.
11747   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11748                           TheCall, Method))
11749     return ExprError();
11750 
11751   // Convert the object argument (for a non-static member function call).
11752   // We only need to do this if there was actually an overload; otherwise
11753   // it was done at lookup.
11754   if (!Method->isStatic()) {
11755     ExprResult ObjectArg =
11756       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11757                                           FoundDecl, Method);
11758     if (ObjectArg.isInvalid())
11759       return ExprError();
11760     MemExpr->setBase(ObjectArg.get());
11761   }
11762 
11763   // Convert the rest of the arguments
11764   const FunctionProtoType *Proto =
11765     Method->getType()->getAs<FunctionProtoType>();
11766   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11767                               RParenLoc))
11768     return ExprError();
11769 
11770   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11771 
11772   if (CheckFunctionCall(Method, TheCall, Proto))
11773     return ExprError();
11774 
11775   if ((isa<CXXConstructorDecl>(CurContext) ||
11776        isa<CXXDestructorDecl>(CurContext)) &&
11777       TheCall->getMethodDecl()->isPure()) {
11778     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11779 
11780     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11781       Diag(MemExpr->getLocStart(),
11782            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11783         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11784         << MD->getParent()->getDeclName();
11785 
11786       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11787     }
11788   }
11789   return MaybeBindToTemporary(TheCall);
11790 }
11791 
11792 /// BuildCallToObjectOfClassType - Build a call to an object of class
11793 /// type (C++ [over.call.object]), which can end up invoking an
11794 /// overloaded function call operator (@c operator()) or performing a
11795 /// user-defined conversion on the object argument.
11796 ExprResult
11797 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11798                                    SourceLocation LParenLoc,
11799                                    MultiExprArg Args,
11800                                    SourceLocation RParenLoc) {
11801   if (checkPlaceholderForOverload(*this, Obj))
11802     return ExprError();
11803   ExprResult Object = Obj;
11804 
11805   UnbridgedCastsSet UnbridgedCasts;
11806   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11807     return ExprError();
11808 
11809   assert(Object.get()->getType()->isRecordType() &&
11810          "Requires object type argument");
11811   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11812 
11813   // C++ [over.call.object]p1:
11814   //  If the primary-expression E in the function call syntax
11815   //  evaluates to a class object of type "cv T", then the set of
11816   //  candidate functions includes at least the function call
11817   //  operators of T. The function call operators of T are obtained by
11818   //  ordinary lookup of the name operator() in the context of
11819   //  (E).operator().
11820   OverloadCandidateSet CandidateSet(LParenLoc,
11821                                     OverloadCandidateSet::CSK_Operator);
11822   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11823 
11824   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11825                           diag::err_incomplete_object_call, Object.get()))
11826     return true;
11827 
11828   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11829   LookupQualifiedName(R, Record->getDecl());
11830   R.suppressDiagnostics();
11831 
11832   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11833        Oper != OperEnd; ++Oper) {
11834     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11835                        Object.get()->Classify(Context),
11836                        Args, CandidateSet,
11837                        /*SuppressUserConversions=*/ false);
11838   }
11839 
11840   // C++ [over.call.object]p2:
11841   //   In addition, for each (non-explicit in C++0x) conversion function
11842   //   declared in T of the form
11843   //
11844   //        operator conversion-type-id () cv-qualifier;
11845   //
11846   //   where cv-qualifier is the same cv-qualification as, or a
11847   //   greater cv-qualification than, cv, and where conversion-type-id
11848   //   denotes the type "pointer to function of (P1,...,Pn) returning
11849   //   R", or the type "reference to pointer to function of
11850   //   (P1,...,Pn) returning R", or the type "reference to function
11851   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11852   //   is also considered as a candidate function. Similarly,
11853   //   surrogate call functions are added to the set of candidate
11854   //   functions for each conversion function declared in an
11855   //   accessible base class provided the function is not hidden
11856   //   within T by another intervening declaration.
11857   const auto &Conversions =
11858       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11859   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11860     NamedDecl *D = *I;
11861     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11862     if (isa<UsingShadowDecl>(D))
11863       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11864 
11865     // Skip over templated conversion functions; they aren't
11866     // surrogates.
11867     if (isa<FunctionTemplateDecl>(D))
11868       continue;
11869 
11870     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11871     if (!Conv->isExplicit()) {
11872       // Strip the reference type (if any) and then the pointer type (if
11873       // any) to get down to what might be a function type.
11874       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11875       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11876         ConvType = ConvPtrType->getPointeeType();
11877 
11878       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11879       {
11880         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11881                               Object.get(), Args, CandidateSet);
11882       }
11883     }
11884   }
11885 
11886   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11887 
11888   // Perform overload resolution.
11889   OverloadCandidateSet::iterator Best;
11890   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11891                              Best)) {
11892   case OR_Success:
11893     // Overload resolution succeeded; we'll build the appropriate call
11894     // below.
11895     break;
11896 
11897   case OR_No_Viable_Function:
11898     if (CandidateSet.empty())
11899       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11900         << Object.get()->getType() << /*call*/ 1
11901         << Object.get()->getSourceRange();
11902     else
11903       Diag(Object.get()->getLocStart(),
11904            diag::err_ovl_no_viable_object_call)
11905         << Object.get()->getType() << Object.get()->getSourceRange();
11906     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11907     break;
11908 
11909   case OR_Ambiguous:
11910     Diag(Object.get()->getLocStart(),
11911          diag::err_ovl_ambiguous_object_call)
11912       << Object.get()->getType() << Object.get()->getSourceRange();
11913     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11914     break;
11915 
11916   case OR_Deleted:
11917     Diag(Object.get()->getLocStart(),
11918          diag::err_ovl_deleted_object_call)
11919       << Best->Function->isDeleted()
11920       << Object.get()->getType()
11921       << getDeletedOrUnavailableSuffix(Best->Function)
11922       << Object.get()->getSourceRange();
11923     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11924     break;
11925   }
11926 
11927   if (Best == CandidateSet.end())
11928     return true;
11929 
11930   UnbridgedCasts.restore();
11931 
11932   if (Best->Function == nullptr) {
11933     // Since there is no function declaration, this is one of the
11934     // surrogate candidates. Dig out the conversion function.
11935     CXXConversionDecl *Conv
11936       = cast<CXXConversionDecl>(
11937                          Best->Conversions[0].UserDefined.ConversionFunction);
11938 
11939     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11940                               Best->FoundDecl);
11941     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11942       return ExprError();
11943     assert(Conv == Best->FoundDecl.getDecl() &&
11944              "Found Decl & conversion-to-functionptr should be same, right?!");
11945     // We selected one of the surrogate functions that converts the
11946     // object parameter to a function pointer. Perform the conversion
11947     // on the object argument, then let ActOnCallExpr finish the job.
11948 
11949     // Create an implicit member expr to refer to the conversion operator.
11950     // and then call it.
11951     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11952                                              Conv, HadMultipleCandidates);
11953     if (Call.isInvalid())
11954       return ExprError();
11955     // Record usage of conversion in an implicit cast.
11956     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11957                                     CK_UserDefinedConversion, Call.get(),
11958                                     nullptr, VK_RValue);
11959 
11960     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11961   }
11962 
11963   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11964 
11965   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11966   // that calls this method, using Object for the implicit object
11967   // parameter and passing along the remaining arguments.
11968   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11969 
11970   // An error diagnostic has already been printed when parsing the declaration.
11971   if (Method->isInvalidDecl())
11972     return ExprError();
11973 
11974   const FunctionProtoType *Proto =
11975     Method->getType()->getAs<FunctionProtoType>();
11976 
11977   unsigned NumParams = Proto->getNumParams();
11978 
11979   DeclarationNameInfo OpLocInfo(
11980                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11981   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11982   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11983                                            HadMultipleCandidates,
11984                                            OpLocInfo.getLoc(),
11985                                            OpLocInfo.getInfo());
11986   if (NewFn.isInvalid())
11987     return true;
11988 
11989   // Build the full argument list for the method call (the implicit object
11990   // parameter is placed at the beginning of the list).
11991   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11992   MethodArgs[0] = Object.get();
11993   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11994 
11995   // Once we've built TheCall, all of the expressions are properly
11996   // owned.
11997   QualType ResultTy = Method->getReturnType();
11998   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11999   ResultTy = ResultTy.getNonLValueExprType(Context);
12000 
12001   CXXOperatorCallExpr *TheCall = new (Context)
12002       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12003                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12004                           ResultTy, VK, RParenLoc, false);
12005   MethodArgs.reset();
12006 
12007   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12008     return true;
12009 
12010   // We may have default arguments. If so, we need to allocate more
12011   // slots in the call for them.
12012   if (Args.size() < NumParams)
12013     TheCall->setNumArgs(Context, NumParams + 1);
12014 
12015   bool IsError = false;
12016 
12017   // Initialize the implicit object parameter.
12018   ExprResult ObjRes =
12019     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12020                                         Best->FoundDecl, Method);
12021   if (ObjRes.isInvalid())
12022     IsError = true;
12023   else
12024     Object = ObjRes;
12025   TheCall->setArg(0, Object.get());
12026 
12027   // Check the argument types.
12028   for (unsigned i = 0; i != NumParams; i++) {
12029     Expr *Arg;
12030     if (i < Args.size()) {
12031       Arg = Args[i];
12032 
12033       // Pass the argument.
12034 
12035       ExprResult InputInit
12036         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12037                                                     Context,
12038                                                     Method->getParamDecl(i)),
12039                                     SourceLocation(), Arg);
12040 
12041       IsError |= InputInit.isInvalid();
12042       Arg = InputInit.getAs<Expr>();
12043     } else {
12044       ExprResult DefArg
12045         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12046       if (DefArg.isInvalid()) {
12047         IsError = true;
12048         break;
12049       }
12050 
12051       Arg = DefArg.getAs<Expr>();
12052     }
12053 
12054     TheCall->setArg(i + 1, Arg);
12055   }
12056 
12057   // If this is a variadic call, handle args passed through "...".
12058   if (Proto->isVariadic()) {
12059     // Promote the arguments (C99 6.5.2.2p7).
12060     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12061       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12062                                                         nullptr);
12063       IsError |= Arg.isInvalid();
12064       TheCall->setArg(i + 1, Arg.get());
12065     }
12066   }
12067 
12068   if (IsError) return true;
12069 
12070   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12071 
12072   if (CheckFunctionCall(Method, TheCall, Proto))
12073     return true;
12074 
12075   return MaybeBindToTemporary(TheCall);
12076 }
12077 
12078 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12079 ///  (if one exists), where @c Base is an expression of class type and
12080 /// @c Member is the name of the member we're trying to find.
12081 ExprResult
12082 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12083                                bool *NoArrowOperatorFound) {
12084   assert(Base->getType()->isRecordType() &&
12085          "left-hand side must have class type");
12086 
12087   if (checkPlaceholderForOverload(*this, Base))
12088     return ExprError();
12089 
12090   SourceLocation Loc = Base->getExprLoc();
12091 
12092   // C++ [over.ref]p1:
12093   //
12094   //   [...] An expression x->m is interpreted as (x.operator->())->m
12095   //   for a class object x of type T if T::operator->() exists and if
12096   //   the operator is selected as the best match function by the
12097   //   overload resolution mechanism (13.3).
12098   DeclarationName OpName =
12099     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12100   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12101   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12102 
12103   if (RequireCompleteType(Loc, Base->getType(),
12104                           diag::err_typecheck_incomplete_tag, Base))
12105     return ExprError();
12106 
12107   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12108   LookupQualifiedName(R, BaseRecord->getDecl());
12109   R.suppressDiagnostics();
12110 
12111   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12112        Oper != OperEnd; ++Oper) {
12113     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12114                        None, CandidateSet, /*SuppressUserConversions=*/false);
12115   }
12116 
12117   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12118 
12119   // Perform overload resolution.
12120   OverloadCandidateSet::iterator Best;
12121   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12122   case OR_Success:
12123     // Overload resolution succeeded; we'll build the call below.
12124     break;
12125 
12126   case OR_No_Viable_Function:
12127     if (CandidateSet.empty()) {
12128       QualType BaseType = Base->getType();
12129       if (NoArrowOperatorFound) {
12130         // Report this specific error to the caller instead of emitting a
12131         // diagnostic, as requested.
12132         *NoArrowOperatorFound = true;
12133         return ExprError();
12134       }
12135       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12136         << BaseType << Base->getSourceRange();
12137       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12138         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12139           << FixItHint::CreateReplacement(OpLoc, ".");
12140       }
12141     } else
12142       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12143         << "operator->" << Base->getSourceRange();
12144     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12145     return ExprError();
12146 
12147   case OR_Ambiguous:
12148     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12149       << "->" << Base->getType() << Base->getSourceRange();
12150     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12151     return ExprError();
12152 
12153   case OR_Deleted:
12154     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12155       << Best->Function->isDeleted()
12156       << "->"
12157       << getDeletedOrUnavailableSuffix(Best->Function)
12158       << Base->getSourceRange();
12159     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12160     return ExprError();
12161   }
12162 
12163   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12164 
12165   // Convert the object parameter.
12166   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12167   ExprResult BaseResult =
12168     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12169                                         Best->FoundDecl, Method);
12170   if (BaseResult.isInvalid())
12171     return ExprError();
12172   Base = BaseResult.get();
12173 
12174   // Build the operator call.
12175   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12176                                             HadMultipleCandidates, OpLoc);
12177   if (FnExpr.isInvalid())
12178     return ExprError();
12179 
12180   QualType ResultTy = Method->getReturnType();
12181   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12182   ResultTy = ResultTy.getNonLValueExprType(Context);
12183   CXXOperatorCallExpr *TheCall =
12184     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12185                                       Base, ResultTy, VK, OpLoc, false);
12186 
12187   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12188           return ExprError();
12189 
12190   return MaybeBindToTemporary(TheCall);
12191 }
12192 
12193 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12194 /// a literal operator described by the provided lookup results.
12195 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12196                                           DeclarationNameInfo &SuffixInfo,
12197                                           ArrayRef<Expr*> Args,
12198                                           SourceLocation LitEndLoc,
12199                                        TemplateArgumentListInfo *TemplateArgs) {
12200   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12201 
12202   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12203                                     OverloadCandidateSet::CSK_Normal);
12204   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12205                         /*SuppressUserConversions=*/true);
12206 
12207   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12208 
12209   // Perform overload resolution. This will usually be trivial, but might need
12210   // to perform substitutions for a literal operator template.
12211   OverloadCandidateSet::iterator Best;
12212   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12213   case OR_Success:
12214   case OR_Deleted:
12215     break;
12216 
12217   case OR_No_Viable_Function:
12218     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12219       << R.getLookupName();
12220     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12221     return ExprError();
12222 
12223   case OR_Ambiguous:
12224     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12225     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12226     return ExprError();
12227   }
12228 
12229   FunctionDecl *FD = Best->Function;
12230   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12231                                         HadMultipleCandidates,
12232                                         SuffixInfo.getLoc(),
12233                                         SuffixInfo.getInfo());
12234   if (Fn.isInvalid())
12235     return true;
12236 
12237   // Check the argument types. This should almost always be a no-op, except
12238   // that array-to-pointer decay is applied to string literals.
12239   Expr *ConvArgs[2];
12240   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12241     ExprResult InputInit = PerformCopyInitialization(
12242       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12243       SourceLocation(), Args[ArgIdx]);
12244     if (InputInit.isInvalid())
12245       return true;
12246     ConvArgs[ArgIdx] = InputInit.get();
12247   }
12248 
12249   QualType ResultTy = FD->getReturnType();
12250   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12251   ResultTy = ResultTy.getNonLValueExprType(Context);
12252 
12253   UserDefinedLiteral *UDL =
12254     new (Context) UserDefinedLiteral(Context, Fn.get(),
12255                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12256                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12257 
12258   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12259     return ExprError();
12260 
12261   if (CheckFunctionCall(FD, UDL, nullptr))
12262     return ExprError();
12263 
12264   return MaybeBindToTemporary(UDL);
12265 }
12266 
12267 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12268 /// given LookupResult is non-empty, it is assumed to describe a member which
12269 /// will be invoked. Otherwise, the function will be found via argument
12270 /// dependent lookup.
12271 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12272 /// otherwise CallExpr is set to ExprError() and some non-success value
12273 /// is returned.
12274 Sema::ForRangeStatus
12275 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12276                                 SourceLocation RangeLoc, VarDecl *Decl,
12277                                 BeginEndFunction BEF,
12278                                 const DeclarationNameInfo &NameInfo,
12279                                 LookupResult &MemberLookup,
12280                                 OverloadCandidateSet *CandidateSet,
12281                                 Expr *Range, ExprResult *CallExpr) {
12282   CandidateSet->clear();
12283   if (!MemberLookup.empty()) {
12284     ExprResult MemberRef =
12285         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12286                                  /*IsPtr=*/false, CXXScopeSpec(),
12287                                  /*TemplateKWLoc=*/SourceLocation(),
12288                                  /*FirstQualifierInScope=*/nullptr,
12289                                  MemberLookup,
12290                                  /*TemplateArgs=*/nullptr);
12291     if (MemberRef.isInvalid()) {
12292       *CallExpr = ExprError();
12293       Diag(Range->getLocStart(), diag::note_in_for_range)
12294           << RangeLoc << BEF << Range->getType();
12295       return FRS_DiagnosticIssued;
12296     }
12297     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12298     if (CallExpr->isInvalid()) {
12299       *CallExpr = ExprError();
12300       Diag(Range->getLocStart(), diag::note_in_for_range)
12301           << RangeLoc << BEF << Range->getType();
12302       return FRS_DiagnosticIssued;
12303     }
12304   } else {
12305     UnresolvedSet<0> FoundNames;
12306     UnresolvedLookupExpr *Fn =
12307       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12308                                    NestedNameSpecifierLoc(), NameInfo,
12309                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12310                                    FoundNames.begin(), FoundNames.end());
12311 
12312     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12313                                                     CandidateSet, CallExpr);
12314     if (CandidateSet->empty() || CandidateSetError) {
12315       *CallExpr = ExprError();
12316       return FRS_NoViableFunction;
12317     }
12318     OverloadCandidateSet::iterator Best;
12319     OverloadingResult OverloadResult =
12320         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12321 
12322     if (OverloadResult == OR_No_Viable_Function) {
12323       *CallExpr = ExprError();
12324       return FRS_NoViableFunction;
12325     }
12326     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12327                                          Loc, nullptr, CandidateSet, &Best,
12328                                          OverloadResult,
12329                                          /*AllowTypoCorrection=*/false);
12330     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12331       *CallExpr = ExprError();
12332       Diag(Range->getLocStart(), diag::note_in_for_range)
12333           << RangeLoc << BEF << Range->getType();
12334       return FRS_DiagnosticIssued;
12335     }
12336   }
12337   return FRS_Success;
12338 }
12339 
12340 
12341 /// FixOverloadedFunctionReference - E is an expression that refers to
12342 /// a C++ overloaded function (possibly with some parentheses and
12343 /// perhaps a '&' around it). We have resolved the overloaded function
12344 /// to the function declaration Fn, so patch up the expression E to
12345 /// refer (possibly indirectly) to Fn. Returns the new expr.
12346 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12347                                            FunctionDecl *Fn) {
12348   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12349     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12350                                                    Found, Fn);
12351     if (SubExpr == PE->getSubExpr())
12352       return PE;
12353 
12354     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12355   }
12356 
12357   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12358     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12359                                                    Found, Fn);
12360     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12361                                SubExpr->getType()) &&
12362            "Implicit cast type cannot be determined from overload");
12363     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12364     if (SubExpr == ICE->getSubExpr())
12365       return ICE;
12366 
12367     return ImplicitCastExpr::Create(Context, ICE->getType(),
12368                                     ICE->getCastKind(),
12369                                     SubExpr, nullptr,
12370                                     ICE->getValueKind());
12371   }
12372 
12373   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12374     assert(UnOp->getOpcode() == UO_AddrOf &&
12375            "Can only take the address of an overloaded function");
12376     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12377       if (Method->isStatic()) {
12378         // Do nothing: static member functions aren't any different
12379         // from non-member functions.
12380       } else {
12381         // Fix the subexpression, which really has to be an
12382         // UnresolvedLookupExpr holding an overloaded member function
12383         // or template.
12384         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12385                                                        Found, Fn);
12386         if (SubExpr == UnOp->getSubExpr())
12387           return UnOp;
12388 
12389         assert(isa<DeclRefExpr>(SubExpr)
12390                && "fixed to something other than a decl ref");
12391         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12392                && "fixed to a member ref with no nested name qualifier");
12393 
12394         // We have taken the address of a pointer to member
12395         // function. Perform the computation here so that we get the
12396         // appropriate pointer to member type.
12397         QualType ClassType
12398           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12399         QualType MemPtrType
12400           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12401 
12402         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12403                                            VK_RValue, OK_Ordinary,
12404                                            UnOp->getOperatorLoc());
12405       }
12406     }
12407     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12408                                                    Found, Fn);
12409     if (SubExpr == UnOp->getSubExpr())
12410       return UnOp;
12411 
12412     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12413                                      Context.getPointerType(SubExpr->getType()),
12414                                        VK_RValue, OK_Ordinary,
12415                                        UnOp->getOperatorLoc());
12416   }
12417 
12418   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12419     // FIXME: avoid copy.
12420     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12421     if (ULE->hasExplicitTemplateArgs()) {
12422       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12423       TemplateArgs = &TemplateArgsBuffer;
12424     }
12425 
12426     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12427                                            ULE->getQualifierLoc(),
12428                                            ULE->getTemplateKeywordLoc(),
12429                                            Fn,
12430                                            /*enclosing*/ false, // FIXME?
12431                                            ULE->getNameLoc(),
12432                                            Fn->getType(),
12433                                            VK_LValue,
12434                                            Found.getDecl(),
12435                                            TemplateArgs);
12436     MarkDeclRefReferenced(DRE);
12437     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12438     return DRE;
12439   }
12440 
12441   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12442     // FIXME: avoid copy.
12443     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12444     if (MemExpr->hasExplicitTemplateArgs()) {
12445       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12446       TemplateArgs = &TemplateArgsBuffer;
12447     }
12448 
12449     Expr *Base;
12450 
12451     // If we're filling in a static method where we used to have an
12452     // implicit member access, rewrite to a simple decl ref.
12453     if (MemExpr->isImplicitAccess()) {
12454       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12455         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12456                                                MemExpr->getQualifierLoc(),
12457                                                MemExpr->getTemplateKeywordLoc(),
12458                                                Fn,
12459                                                /*enclosing*/ false,
12460                                                MemExpr->getMemberLoc(),
12461                                                Fn->getType(),
12462                                                VK_LValue,
12463                                                Found.getDecl(),
12464                                                TemplateArgs);
12465         MarkDeclRefReferenced(DRE);
12466         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12467         return DRE;
12468       } else {
12469         SourceLocation Loc = MemExpr->getMemberLoc();
12470         if (MemExpr->getQualifier())
12471           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12472         CheckCXXThisCapture(Loc);
12473         Base = new (Context) CXXThisExpr(Loc,
12474                                          MemExpr->getBaseType(),
12475                                          /*isImplicit=*/true);
12476       }
12477     } else
12478       Base = MemExpr->getBase();
12479 
12480     ExprValueKind valueKind;
12481     QualType type;
12482     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12483       valueKind = VK_LValue;
12484       type = Fn->getType();
12485     } else {
12486       valueKind = VK_RValue;
12487       type = Context.BoundMemberTy;
12488     }
12489 
12490     MemberExpr *ME = MemberExpr::Create(Context, Base,
12491                                         MemExpr->isArrow(),
12492                                         MemExpr->getQualifierLoc(),
12493                                         MemExpr->getTemplateKeywordLoc(),
12494                                         Fn,
12495                                         Found,
12496                                         MemExpr->getMemberNameInfo(),
12497                                         TemplateArgs,
12498                                         type, valueKind, OK_Ordinary);
12499     ME->setHadMultipleCandidates(true);
12500     MarkMemberReferenced(ME);
12501     return ME;
12502   }
12503 
12504   llvm_unreachable("Invalid reference to overloaded function");
12505 }
12506 
12507 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12508                                                 DeclAccessPair Found,
12509                                                 FunctionDecl *Fn) {
12510   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12511 }
12512