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   // -- from a floating-point type to an integer type, or
290   //
291   // -- from an integer type or unscoped enumeration type to a floating-point
292   //    type, except where the source is a constant expression and the actual
293   //    value after conversion will fit into the target type and will produce
294   //    the original value when converted back to the original type, or
295   case ICK_Floating_Integral:
296     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
297       return NK_Type_Narrowing;
298     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
299       llvm::APSInt IntConstantValue;
300       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
301       if (Initializer &&
302           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
303         // Convert the integer to the floating type.
304         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
305         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
306                                 llvm::APFloat::rmNearestTiesToEven);
307         // And back.
308         llvm::APSInt ConvertedValue = IntConstantValue;
309         bool ignored;
310         Result.convertToInteger(ConvertedValue,
311                                 llvm::APFloat::rmTowardZero, &ignored);
312         // If the resulting value is different, this was a narrowing conversion.
313         if (IntConstantValue != ConvertedValue) {
314           ConstantValue = APValue(IntConstantValue);
315           ConstantType = Initializer->getType();
316           return NK_Constant_Narrowing;
317         }
318       } else {
319         // Variables are always narrowings.
320         return NK_Variable_Narrowing;
321       }
322     }
323     return NK_Not_Narrowing;
324 
325   // -- from long double to double or float, or from double to float, except
326   //    where the source is a constant expression and the actual value after
327   //    conversion is within the range of values that can be represented (even
328   //    if it cannot be represented exactly), or
329   case ICK_Floating_Conversion:
330     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
331         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
332       // FromType is larger than ToType.
333       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
335         // Constant!
336         assert(ConstantValue.isFloat());
337         llvm::APFloat FloatVal = ConstantValue.getFloat();
338         // Convert the source value into the target type.
339         bool ignored;
340         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
341           Ctx.getFloatTypeSemantics(ToType),
342           llvm::APFloat::rmNearestTiesToEven, &ignored);
343         // If there was no overflow, the source value is within the range of
344         // values that can be represented.
345         if (ConvertStatus & llvm::APFloat::opOverflow) {
346           ConstantType = Initializer->getType();
347           return NK_Constant_Narrowing;
348         }
349       } else {
350         return NK_Variable_Narrowing;
351       }
352     }
353     return NK_Not_Narrowing;
354 
355   // -- from an integer type or unscoped enumeration type to an integer type
356   //    that cannot represent all the values of the original type, except where
357   //    the source is a constant expression and the actual value after
358   //    conversion will fit into the target type and will produce the original
359   //    value when converted back to the original type.
360   case ICK_Boolean_Conversion:  // Bools are integers too.
361     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
362       // Boolean conversions can be from pointers and pointers to members
363       // [conv.bool], and those aren't considered narrowing conversions.
364       return NK_Not_Narrowing;
365     }  // Otherwise, fall through to the integral case.
366   case ICK_Integral_Conversion: {
367     assert(FromType->isIntegralOrUnscopedEnumerationType());
368     assert(ToType->isIntegralOrUnscopedEnumerationType());
369     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
370     const unsigned FromWidth = Ctx.getIntWidth(FromType);
371     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
372     const unsigned ToWidth = Ctx.getIntWidth(ToType);
373 
374     if (FromWidth > ToWidth ||
375         (FromWidth == ToWidth && FromSigned != ToSigned) ||
376         (FromSigned && !ToSigned)) {
377       // Not all values of FromType can be represented in ToType.
378       llvm::APSInt InitializerValue;
379       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
380       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
381         // Such conversions on variables are always narrowing.
382         return NK_Variable_Narrowing;
383       }
384       bool Narrowing = false;
385       if (FromWidth < ToWidth) {
386         // Negative -> unsigned is narrowing. Otherwise, more bits is never
387         // narrowing.
388         if (InitializerValue.isSigned() && InitializerValue.isNegative())
389           Narrowing = true;
390       } else {
391         // Add a bit to the InitializerValue so we don't have to worry about
392         // signed vs. unsigned comparisons.
393         InitializerValue = InitializerValue.extend(
394           InitializerValue.getBitWidth() + 1);
395         // Convert the initializer to and from the target width and signed-ness.
396         llvm::APSInt ConvertedValue = InitializerValue;
397         ConvertedValue = ConvertedValue.trunc(ToWidth);
398         ConvertedValue.setIsSigned(ToSigned);
399         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400         ConvertedValue.setIsSigned(InitializerValue.isSigned());
401         // If the result is different, this was a narrowing conversion.
402         if (ConvertedValue != InitializerValue)
403           Narrowing = true;
404       }
405       if (Narrowing) {
406         ConstantType = Initializer->getType();
407         ConstantValue = APValue(InitializerValue);
408         return NK_Constant_Narrowing;
409       }
410     }
411     return NK_Not_Narrowing;
412   }
413 
414   default:
415     // Other kinds of conversions are not narrowings.
416     return NK_Not_Narrowing;
417   }
418 }
419 
420 /// dump - Print this standard conversion sequence to standard
421 /// error. Useful for debugging overloading issues.
422 void StandardConversionSequence::dump() const {
423   raw_ostream &OS = llvm::errs();
424   bool PrintedSomething = false;
425   if (First != ICK_Identity) {
426     OS << GetImplicitConversionName(First);
427     PrintedSomething = true;
428   }
429 
430   if (Second != ICK_Identity) {
431     if (PrintedSomething) {
432       OS << " -> ";
433     }
434     OS << GetImplicitConversionName(Second);
435 
436     if (CopyConstructor) {
437       OS << " (by copy constructor)";
438     } else if (DirectBinding) {
439       OS << " (direct reference binding)";
440     } else if (ReferenceBinding) {
441       OS << " (reference binding)";
442     }
443     PrintedSomething = true;
444   }
445 
446   if (Third != ICK_Identity) {
447     if (PrintedSomething) {
448       OS << " -> ";
449     }
450     OS << GetImplicitConversionName(Third);
451     PrintedSomething = true;
452   }
453 
454   if (!PrintedSomething) {
455     OS << "No conversions required";
456   }
457 }
458 
459 /// dump - Print this user-defined conversion sequence to standard
460 /// error. Useful for debugging overloading issues.
461 void UserDefinedConversionSequence::dump() const {
462   raw_ostream &OS = llvm::errs();
463   if (Before.First || Before.Second || Before.Third) {
464     Before.dump();
465     OS << " -> ";
466   }
467   if (ConversionFunction)
468     OS << '\'' << *ConversionFunction << '\'';
469   else
470     OS << "aggregate initialization";
471   if (After.First || After.Second || After.Third) {
472     OS << " -> ";
473     After.dump();
474   }
475 }
476 
477 /// dump - Print this implicit conversion sequence to standard
478 /// error. Useful for debugging overloading issues.
479 void ImplicitConversionSequence::dump() const {
480   raw_ostream &OS = llvm::errs();
481   if (isStdInitializerListElement())
482     OS << "Worst std::initializer_list element conversion: ";
483   switch (ConversionKind) {
484   case StandardConversion:
485     OS << "Standard conversion: ";
486     Standard.dump();
487     break;
488   case UserDefinedConversion:
489     OS << "User-defined conversion: ";
490     UserDefined.dump();
491     break;
492   case EllipsisConversion:
493     OS << "Ellipsis conversion";
494     break;
495   case AmbiguousConversion:
496     OS << "Ambiguous conversion";
497     break;
498   case BadConversion:
499     OS << "Bad conversion";
500     break;
501   }
502 
503   OS << "\n";
504 }
505 
506 void AmbiguousConversionSequence::construct() {
507   new (&conversions()) ConversionSet();
508 }
509 
510 void AmbiguousConversionSequence::destruct() {
511   conversions().~ConversionSet();
512 }
513 
514 void
515 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
516   FromTypePtr = O.FromTypePtr;
517   ToTypePtr = O.ToTypePtr;
518   new (&conversions()) ConversionSet(O.conversions());
519 }
520 
521 namespace {
522   // Structure used by DeductionFailureInfo to store
523   // template argument information.
524   struct DFIArguments {
525     TemplateArgument FirstArg;
526     TemplateArgument SecondArg;
527   };
528   // Structure used by DeductionFailureInfo to store
529   // template parameter and template argument information.
530   struct DFIParamWithArguments : DFIArguments {
531     TemplateParameter Param;
532   };
533 }
534 
535 /// \brief Convert from Sema's representation of template deduction information
536 /// to the form used in overload-candidate information.
537 DeductionFailureInfo
538 clang::MakeDeductionFailureInfo(ASTContext &Context,
539                                 Sema::TemplateDeductionResult TDK,
540                                 TemplateDeductionInfo &Info) {
541   DeductionFailureInfo Result;
542   Result.Result = static_cast<unsigned>(TDK);
543   Result.HasDiagnostic = false;
544   Result.Data = nullptr;
545   switch (TDK) {
546   case Sema::TDK_Success:
547   case Sema::TDK_Invalid:
548   case Sema::TDK_InstantiationDepth:
549   case Sema::TDK_TooManyArguments:
550   case Sema::TDK_TooFewArguments:
551     break;
552 
553   case Sema::TDK_Incomplete:
554   case Sema::TDK_InvalidExplicitArguments:
555     Result.Data = Info.Param.getOpaqueValue();
556     break;
557 
558   case Sema::TDK_NonDeducedMismatch: {
559     // FIXME: Should allocate from normal heap so that we can free this later.
560     DFIArguments *Saved = new (Context) DFIArguments;
561     Saved->FirstArg = Info.FirstArg;
562     Saved->SecondArg = Info.SecondArg;
563     Result.Data = Saved;
564     break;
565   }
566 
567   case Sema::TDK_Inconsistent:
568   case Sema::TDK_Underqualified: {
569     // FIXME: Should allocate from normal heap so that we can free this later.
570     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
571     Saved->Param = Info.Param;
572     Saved->FirstArg = Info.FirstArg;
573     Saved->SecondArg = Info.SecondArg;
574     Result.Data = Saved;
575     break;
576   }
577 
578   case Sema::TDK_SubstitutionFailure:
579     Result.Data = Info.take();
580     if (Info.hasSFINAEDiagnostic()) {
581       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
582           SourceLocation(), PartialDiagnostic::NullDiagnostic());
583       Info.takeSFINAEDiagnostic(*Diag);
584       Result.HasDiagnostic = true;
585     }
586     break;
587 
588   case Sema::TDK_FailedOverloadResolution:
589     Result.Data = Info.Expression;
590     break;
591 
592   case Sema::TDK_MiscellaneousDeductionFailure:
593     break;
594   }
595 
596   return Result;
597 }
598 
599 void DeductionFailureInfo::Destroy() {
600   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601   case Sema::TDK_Success:
602   case Sema::TDK_Invalid:
603   case Sema::TDK_InstantiationDepth:
604   case Sema::TDK_Incomplete:
605   case Sema::TDK_TooManyArguments:
606   case Sema::TDK_TooFewArguments:
607   case Sema::TDK_InvalidExplicitArguments:
608   case Sema::TDK_FailedOverloadResolution:
609     break;
610 
611   case Sema::TDK_Inconsistent:
612   case Sema::TDK_Underqualified:
613   case Sema::TDK_NonDeducedMismatch:
614     // FIXME: Destroy the data?
615     Data = nullptr;
616     break;
617 
618   case Sema::TDK_SubstitutionFailure:
619     // FIXME: Destroy the template argument list?
620     Data = nullptr;
621     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
622       Diag->~PartialDiagnosticAt();
623       HasDiagnostic = false;
624     }
625     break;
626 
627   // Unhandled
628   case Sema::TDK_MiscellaneousDeductionFailure:
629     break;
630   }
631 }
632 
633 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
634   if (HasDiagnostic)
635     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636   return nullptr;
637 }
638 
639 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
640   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641   case Sema::TDK_Success:
642   case Sema::TDK_Invalid:
643   case Sema::TDK_InstantiationDepth:
644   case Sema::TDK_TooManyArguments:
645   case Sema::TDK_TooFewArguments:
646   case Sema::TDK_SubstitutionFailure:
647   case Sema::TDK_NonDeducedMismatch:
648   case Sema::TDK_FailedOverloadResolution:
649     return TemplateParameter();
650 
651   case Sema::TDK_Incomplete:
652   case Sema::TDK_InvalidExplicitArguments:
653     return TemplateParameter::getFromOpaqueValue(Data);
654 
655   case Sema::TDK_Inconsistent:
656   case Sema::TDK_Underqualified:
657     return static_cast<DFIParamWithArguments*>(Data)->Param;
658 
659   // Unhandled
660   case Sema::TDK_MiscellaneousDeductionFailure:
661     break;
662   }
663 
664   return TemplateParameter();
665 }
666 
667 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
668   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669   case Sema::TDK_Success:
670   case Sema::TDK_Invalid:
671   case Sema::TDK_InstantiationDepth:
672   case Sema::TDK_TooManyArguments:
673   case Sema::TDK_TooFewArguments:
674   case Sema::TDK_Incomplete:
675   case Sema::TDK_InvalidExplicitArguments:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_NonDeducedMismatch:
679   case Sema::TDK_FailedOverloadResolution:
680     return nullptr;
681 
682   case Sema::TDK_SubstitutionFailure:
683     return static_cast<TemplateArgumentList*>(Data);
684 
685   // Unhandled
686   case Sema::TDK_MiscellaneousDeductionFailure:
687     break;
688   }
689 
690   return nullptr;
691 }
692 
693 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
694   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695   case Sema::TDK_Success:
696   case Sema::TDK_Invalid:
697   case Sema::TDK_InstantiationDepth:
698   case Sema::TDK_Incomplete:
699   case Sema::TDK_TooManyArguments:
700   case Sema::TDK_TooFewArguments:
701   case Sema::TDK_InvalidExplicitArguments:
702   case Sema::TDK_SubstitutionFailure:
703   case Sema::TDK_FailedOverloadResolution:
704     return nullptr;
705 
706   case Sema::TDK_Inconsistent:
707   case Sema::TDK_Underqualified:
708   case Sema::TDK_NonDeducedMismatch:
709     return &static_cast<DFIArguments*>(Data)->FirstArg;
710 
711   // Unhandled
712   case Sema::TDK_MiscellaneousDeductionFailure:
713     break;
714   }
715 
716   return nullptr;
717 }
718 
719 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
720   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721   case Sema::TDK_Success:
722   case Sema::TDK_Invalid:
723   case Sema::TDK_InstantiationDepth:
724   case Sema::TDK_Incomplete:
725   case Sema::TDK_TooManyArguments:
726   case Sema::TDK_TooFewArguments:
727   case Sema::TDK_InvalidExplicitArguments:
728   case Sema::TDK_SubstitutionFailure:
729   case Sema::TDK_FailedOverloadResolution:
730     return nullptr;
731 
732   case Sema::TDK_Inconsistent:
733   case Sema::TDK_Underqualified:
734   case Sema::TDK_NonDeducedMismatch:
735     return &static_cast<DFIArguments*>(Data)->SecondArg;
736 
737   // Unhandled
738   case Sema::TDK_MiscellaneousDeductionFailure:
739     break;
740   }
741 
742   return nullptr;
743 }
744 
745 Expr *DeductionFailureInfo::getExpr() {
746   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
747         Sema::TDK_FailedOverloadResolution)
748     return static_cast<Expr*>(Data);
749 
750   return nullptr;
751 }
752 
753 void OverloadCandidateSet::destroyCandidates() {
754   for (iterator i = begin(), e = end(); i != e; ++i) {
755     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
756       i->Conversions[ii].~ImplicitConversionSequence();
757     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
758       i->DeductionFailure.Destroy();
759   }
760 }
761 
762 void OverloadCandidateSet::clear() {
763   destroyCandidates();
764   NumInlineSequences = 0;
765   Candidates.clear();
766   Functions.clear();
767 }
768 
769 namespace {
770   class UnbridgedCastsSet {
771     struct Entry {
772       Expr **Addr;
773       Expr *Saved;
774     };
775     SmallVector<Entry, 2> Entries;
776 
777   public:
778     void save(Sema &S, Expr *&E) {
779       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
780       Entry entry = { &E, E };
781       Entries.push_back(entry);
782       E = S.stripARCUnbridgedCast(E);
783     }
784 
785     void restore() {
786       for (SmallVectorImpl<Entry>::iterator
787              i = Entries.begin(), e = Entries.end(); i != e; ++i)
788         *i->Addr = i->Saved;
789     }
790   };
791 }
792 
793 /// checkPlaceholderForOverload - Do any interesting placeholder-like
794 /// preprocessing on the given expression.
795 ///
796 /// \param unbridgedCasts a collection to which to add unbridged casts;
797 ///   without this, they will be immediately diagnosed as errors
798 ///
799 /// Return true on unrecoverable error.
800 static bool
801 checkPlaceholderForOverload(Sema &S, Expr *&E,
802                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
803   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
804     // We can't handle overloaded expressions here because overload
805     // resolution might reasonably tweak them.
806     if (placeholder->getKind() == BuiltinType::Overload) return false;
807 
808     // If the context potentially accepts unbridged ARC casts, strip
809     // the unbridged cast and add it to the collection for later restoration.
810     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
811         unbridgedCasts) {
812       unbridgedCasts->save(S, E);
813       return false;
814     }
815 
816     // Go ahead and check everything else.
817     ExprResult result = S.CheckPlaceholderExpr(E);
818     if (result.isInvalid())
819       return true;
820 
821     E = result.get();
822     return false;
823   }
824 
825   // Nothing to do.
826   return false;
827 }
828 
829 /// checkArgPlaceholdersForOverload - Check a set of call operands for
830 /// placeholders.
831 static bool checkArgPlaceholdersForOverload(Sema &S,
832                                             MultiExprArg Args,
833                                             UnbridgedCastsSet &unbridged) {
834   for (unsigned i = 0, e = Args.size(); i != e; ++i)
835     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
836       return true;
837 
838   return false;
839 }
840 
841 // IsOverload - Determine whether the given New declaration is an
842 // overload of the declarations in Old. This routine returns false if
843 // New and Old cannot be overloaded, e.g., if New has the same
844 // signature as some function in Old (C++ 1.3.10) or if the Old
845 // declarations aren't functions (or function templates) at all. When
846 // it does return false, MatchedDecl will point to the decl that New
847 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
848 // top of the underlying declaration.
849 //
850 // Example: Given the following input:
851 //
852 //   void f(int, float); // #1
853 //   void f(int, int); // #2
854 //   int f(int, int); // #3
855 //
856 // When we process #1, there is no previous declaration of "f",
857 // so IsOverload will not be used.
858 //
859 // When we process #2, Old contains only the FunctionDecl for #1.  By
860 // comparing the parameter types, we see that #1 and #2 are overloaded
861 // (since they have different signatures), so this routine returns
862 // false; MatchedDecl is unchanged.
863 //
864 // When we process #3, Old is an overload set containing #1 and #2. We
865 // compare the signatures of #3 to #1 (they're overloaded, so we do
866 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
867 // identical (return types of functions are not part of the
868 // signature), IsOverload returns false and MatchedDecl will be set to
869 // point to the FunctionDecl for #2.
870 //
871 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
872 // into a class by a using declaration.  The rules for whether to hide
873 // shadow declarations ignore some properties which otherwise figure
874 // into a function template's signature.
875 Sema::OverloadKind
876 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
877                     NamedDecl *&Match, bool NewIsUsingDecl) {
878   for (LookupResult::iterator I = Old.begin(), E = Old.end();
879          I != E; ++I) {
880     NamedDecl *OldD = *I;
881 
882     bool OldIsUsingDecl = false;
883     if (isa<UsingShadowDecl>(OldD)) {
884       OldIsUsingDecl = true;
885 
886       // We can always introduce two using declarations into the same
887       // context, even if they have identical signatures.
888       if (NewIsUsingDecl) continue;
889 
890       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
891     }
892 
893     // If either declaration was introduced by a using declaration,
894     // we'll need to use slightly different rules for matching.
895     // Essentially, these rules are the normal rules, except that
896     // function templates hide function templates with different
897     // return types or template parameter lists.
898     bool UseMemberUsingDeclRules =
899       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
900       !New->getFriendObjectKind();
901 
902     if (FunctionDecl *OldF = OldD->getAsFunction()) {
903       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
904         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
905           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
906           continue;
907         }
908 
909         if (!isa<FunctionTemplateDecl>(OldD) &&
910             !shouldLinkPossiblyHiddenDecl(*I, New))
911           continue;
912 
913         Match = *I;
914         return Ovl_Match;
915       }
916     } else if (isa<UsingDecl>(OldD)) {
917       // We can overload with these, which can show up when doing
918       // redeclaration checks for UsingDecls.
919       assert(Old.getLookupKind() == LookupUsingDeclName);
920     } else if (isa<TagDecl>(OldD)) {
921       // We can always overload with tags by hiding them.
922     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
923       // Optimistically assume that an unresolved using decl will
924       // overload; if it doesn't, we'll have to diagnose during
925       // template instantiation.
926     } else {
927       // (C++ 13p1):
928       //   Only function declarations can be overloaded; object and type
929       //   declarations cannot be overloaded.
930       Match = *I;
931       return Ovl_NonFunction;
932     }
933   }
934 
935   return Ovl_Overload;
936 }
937 
938 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
939                       bool UseUsingDeclRules) {
940   // C++ [basic.start.main]p2: This function shall not be overloaded.
941   if (New->isMain())
942     return false;
943 
944   // MSVCRT user defined entry points cannot be overloaded.
945   if (New->isMSVCRTEntryPoint())
946     return false;
947 
948   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950 
951   // C++ [temp.fct]p2:
952   //   A function template can be overloaded with other function templates
953   //   and with normal (non-template) functions.
954   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
955     return true;
956 
957   // Is the function New an overload of the function Old?
958   QualType OldQType = Context.getCanonicalType(Old->getType());
959   QualType NewQType = Context.getCanonicalType(New->getType());
960 
961   // Compare the signatures (C++ 1.3.10) of the two functions to
962   // determine whether they are overloads. If we find any mismatch
963   // in the signature, they are overloads.
964 
965   // If either of these functions is a K&R-style function (no
966   // prototype), then we consider them to have matching signatures.
967   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969     return false;
970 
971   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
972   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
973 
974   // The signature of a function includes the types of its
975   // parameters (C++ 1.3.10), which includes the presence or absence
976   // of the ellipsis; see C++ DR 357).
977   if (OldQType != NewQType &&
978       (OldType->getNumParams() != NewType->getNumParams() ||
979        OldType->isVariadic() != NewType->isVariadic() ||
980        !FunctionParamTypesAreEqual(OldType, NewType)))
981     return true;
982 
983   // C++ [temp.over.link]p4:
984   //   The signature of a function template consists of its function
985   //   signature, its return type and its template parameter list. The names
986   //   of the template parameters are significant only for establishing the
987   //   relationship between the template parameters and the rest of the
988   //   signature.
989   //
990   // We check the return type and template parameter lists for function
991   // templates first; the remaining checks follow.
992   //
993   // However, we don't consider either of these when deciding whether
994   // a member introduced by a shadow declaration is hidden.
995   if (!UseUsingDeclRules && NewTemplate &&
996       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997                                        OldTemplate->getTemplateParameters(),
998                                        false, TPL_TemplateMatch) ||
999        OldType->getReturnType() != NewType->getReturnType()))
1000     return true;
1001 
1002   // If the function is a class member, its signature includes the
1003   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1004   //
1005   // As part of this, also check whether one of the member functions
1006   // is static, in which case they are not overloads (C++
1007   // 13.1p2). While not part of the definition of the signature,
1008   // this check is important to determine whether these functions
1009   // can be overloaded.
1010   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1012   if (OldMethod && NewMethod &&
1013       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1014     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1015       if (!UseUsingDeclRules &&
1016           (OldMethod->getRefQualifier() == RQ_None ||
1017            NewMethod->getRefQualifier() == RQ_None)) {
1018         // C++0x [over.load]p2:
1019         //   - Member function declarations with the same name and the same
1020         //     parameter-type-list as well as member function template
1021         //     declarations with the same name, the same parameter-type-list, and
1022         //     the same template parameter lists cannot be overloaded if any of
1023         //     them, but not all, have a ref-qualifier (8.3.5).
1024         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1025           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1026         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1027       }
1028       return true;
1029     }
1030 
1031     // We may not have applied the implicit const for a constexpr member
1032     // function yet (because we haven't yet resolved whether this is a static
1033     // or non-static member function). Add it now, on the assumption that this
1034     // is a redeclaration of OldMethod.
1035     unsigned OldQuals = OldMethod->getTypeQualifiers();
1036     unsigned NewQuals = NewMethod->getTypeQualifiers();
1037     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1038         !isa<CXXConstructorDecl>(NewMethod))
1039       NewQuals |= Qualifiers::Const;
1040 
1041     // We do not allow overloading based off of '__restrict'.
1042     OldQuals &= ~Qualifiers::Restrict;
1043     NewQuals &= ~Qualifiers::Restrict;
1044     if (OldQuals != NewQuals)
1045       return true;
1046   }
1047 
1048   // enable_if attributes are an order-sensitive part of the signature.
1049   for (specific_attr_iterator<EnableIfAttr>
1050          NewI = New->specific_attr_begin<EnableIfAttr>(),
1051          NewE = New->specific_attr_end<EnableIfAttr>(),
1052          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1053          OldE = Old->specific_attr_end<EnableIfAttr>();
1054        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1055     if (NewI == NewE || OldI == OldE)
1056       return true;
1057     llvm::FoldingSetNodeID NewID, OldID;
1058     NewI->getCond()->Profile(NewID, Context, true);
1059     OldI->getCond()->Profile(OldID, Context, true);
1060     if (NewID != OldID)
1061       return true;
1062   }
1063 
1064   // The signatures match; this is not an overload.
1065   return false;
1066 }
1067 
1068 /// \brief Checks availability of the function depending on the current
1069 /// function context. Inside an unavailable function, unavailability is ignored.
1070 ///
1071 /// \returns true if \arg FD is unavailable and current context is inside
1072 /// an available function, false otherwise.
1073 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1074   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1075 }
1076 
1077 /// \brief Tries a user-defined conversion from From to ToType.
1078 ///
1079 /// Produces an implicit conversion sequence for when a standard conversion
1080 /// is not an option. See TryImplicitConversion for more information.
1081 static ImplicitConversionSequence
1082 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1083                          bool SuppressUserConversions,
1084                          bool AllowExplicit,
1085                          bool InOverloadResolution,
1086                          bool CStyle,
1087                          bool AllowObjCWritebackConversion,
1088                          bool AllowObjCConversionOnExplicit) {
1089   ImplicitConversionSequence ICS;
1090 
1091   if (SuppressUserConversions) {
1092     // We're not in the case above, so there is no conversion that
1093     // we can perform.
1094     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1095     return ICS;
1096   }
1097 
1098   // Attempt user-defined conversion.
1099   OverloadCandidateSet Conversions(From->getExprLoc(),
1100                                    OverloadCandidateSet::CSK_Normal);
1101   OverloadingResult UserDefResult
1102     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1103                               AllowExplicit, AllowObjCConversionOnExplicit);
1104 
1105   if (UserDefResult == OR_Success) {
1106     ICS.setUserDefined();
1107     ICS.UserDefined.Before.setAsIdentityConversion();
1108     // C++ [over.ics.user]p4:
1109     //   A conversion of an expression of class type to the same class
1110     //   type is given Exact Match rank, and a conversion of an
1111     //   expression of class type to a base class of that type is
1112     //   given Conversion rank, in spite of the fact that a copy
1113     //   constructor (i.e., a user-defined conversion function) is
1114     //   called for those cases.
1115     if (CXXConstructorDecl *Constructor
1116           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1117       QualType FromCanon
1118         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1119       QualType ToCanon
1120         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1121       if (Constructor->isCopyConstructor() &&
1122           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1123         // Turn this into a "standard" conversion sequence, so that it
1124         // gets ranked with standard conversion sequences.
1125         ICS.setStandard();
1126         ICS.Standard.setAsIdentityConversion();
1127         ICS.Standard.setFromType(From->getType());
1128         ICS.Standard.setAllToTypes(ToType);
1129         ICS.Standard.CopyConstructor = Constructor;
1130         if (ToCanon != FromCanon)
1131           ICS.Standard.Second = ICK_Derived_To_Base;
1132       }
1133     }
1134   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1135     ICS.setAmbiguous();
1136     ICS.Ambiguous.setFromType(From->getType());
1137     ICS.Ambiguous.setToType(ToType);
1138     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1139          Cand != Conversions.end(); ++Cand)
1140       if (Cand->Viable)
1141         ICS.Ambiguous.addConversion(Cand->Function);
1142   } else {
1143     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1144   }
1145 
1146   return ICS;
1147 }
1148 
1149 /// TryImplicitConversion - Attempt to perform an implicit conversion
1150 /// from the given expression (Expr) to the given type (ToType). This
1151 /// function returns an implicit conversion sequence that can be used
1152 /// to perform the initialization. Given
1153 ///
1154 ///   void f(float f);
1155 ///   void g(int i) { f(i); }
1156 ///
1157 /// this routine would produce an implicit conversion sequence to
1158 /// describe the initialization of f from i, which will be a standard
1159 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1160 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1161 //
1162 /// Note that this routine only determines how the conversion can be
1163 /// performed; it does not actually perform the conversion. As such,
1164 /// it will not produce any diagnostics if no conversion is available,
1165 /// but will instead return an implicit conversion sequence of kind
1166 /// "BadConversion".
1167 ///
1168 /// If @p SuppressUserConversions, then user-defined conversions are
1169 /// not permitted.
1170 /// If @p AllowExplicit, then explicit user-defined conversions are
1171 /// permitted.
1172 ///
1173 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1174 /// writeback conversion, which allows __autoreleasing id* parameters to
1175 /// be initialized with __strong id* or __weak id* arguments.
1176 static ImplicitConversionSequence
1177 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1178                       bool SuppressUserConversions,
1179                       bool AllowExplicit,
1180                       bool InOverloadResolution,
1181                       bool CStyle,
1182                       bool AllowObjCWritebackConversion,
1183                       bool AllowObjCConversionOnExplicit) {
1184   ImplicitConversionSequence ICS;
1185   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1186                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1187     ICS.setStandard();
1188     return ICS;
1189   }
1190 
1191   if (!S.getLangOpts().CPlusPlus) {
1192     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193     return ICS;
1194   }
1195 
1196   // C++ [over.ics.user]p4:
1197   //   A conversion of an expression of class type to the same class
1198   //   type is given Exact Match rank, and a conversion of an
1199   //   expression of class type to a base class of that type is
1200   //   given Conversion rank, in spite of the fact that a copy/move
1201   //   constructor (i.e., a user-defined conversion function) is
1202   //   called for those cases.
1203   QualType FromType = From->getType();
1204   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1205       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1206        S.IsDerivedFrom(FromType, ToType))) {
1207     ICS.setStandard();
1208     ICS.Standard.setAsIdentityConversion();
1209     ICS.Standard.setFromType(FromType);
1210     ICS.Standard.setAllToTypes(ToType);
1211 
1212     // We don't actually check at this point whether there is a valid
1213     // copy/move constructor, since overloading just assumes that it
1214     // exists. When we actually perform initialization, we'll find the
1215     // appropriate constructor to copy the returned object, if needed.
1216     ICS.Standard.CopyConstructor = nullptr;
1217 
1218     // Determine whether this is considered a derived-to-base conversion.
1219     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1220       ICS.Standard.Second = ICK_Derived_To_Base;
1221 
1222     return ICS;
1223   }
1224 
1225   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1226                                   AllowExplicit, InOverloadResolution, CStyle,
1227                                   AllowObjCWritebackConversion,
1228                                   AllowObjCConversionOnExplicit);
1229 }
1230 
1231 ImplicitConversionSequence
1232 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1233                             bool SuppressUserConversions,
1234                             bool AllowExplicit,
1235                             bool InOverloadResolution,
1236                             bool CStyle,
1237                             bool AllowObjCWritebackConversion) {
1238   return ::TryImplicitConversion(*this, From, ToType,
1239                                  SuppressUserConversions, AllowExplicit,
1240                                  InOverloadResolution, CStyle,
1241                                  AllowObjCWritebackConversion,
1242                                  /*AllowObjCConversionOnExplicit=*/false);
1243 }
1244 
1245 /// PerformImplicitConversion - Perform an implicit conversion of the
1246 /// expression From to the type ToType. Returns the
1247 /// converted expression. Flavor is the kind of conversion we're
1248 /// performing, used in the error message. If @p AllowExplicit,
1249 /// explicit user-defined conversions are permitted.
1250 ExprResult
1251 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1252                                 AssignmentAction Action, bool AllowExplicit) {
1253   ImplicitConversionSequence ICS;
1254   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1255 }
1256 
1257 ExprResult
1258 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1259                                 AssignmentAction Action, bool AllowExplicit,
1260                                 ImplicitConversionSequence& ICS) {
1261   if (checkPlaceholderForOverload(*this, From))
1262     return ExprError();
1263 
1264   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1265   bool AllowObjCWritebackConversion
1266     = getLangOpts().ObjCAutoRefCount &&
1267       (Action == AA_Passing || Action == AA_Sending);
1268   if (getLangOpts().ObjC1)
1269     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1270                                       ToType, From->getType(), From);
1271   ICS = ::TryImplicitConversion(*this, From, ToType,
1272                                 /*SuppressUserConversions=*/false,
1273                                 AllowExplicit,
1274                                 /*InOverloadResolution=*/false,
1275                                 /*CStyle=*/false,
1276                                 AllowObjCWritebackConversion,
1277                                 /*AllowObjCConversionOnExplicit=*/false);
1278   return PerformImplicitConversion(From, ToType, ICS, Action);
1279 }
1280 
1281 /// \brief Determine whether the conversion from FromType to ToType is a valid
1282 /// conversion that strips "noreturn" off the nested function type.
1283 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1284                                 QualType &ResultTy) {
1285   if (Context.hasSameUnqualifiedType(FromType, ToType))
1286     return false;
1287 
1288   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1289   // where F adds one of the following at most once:
1290   //   - a pointer
1291   //   - a member pointer
1292   //   - a block pointer
1293   CanQualType CanTo = Context.getCanonicalType(ToType);
1294   CanQualType CanFrom = Context.getCanonicalType(FromType);
1295   Type::TypeClass TyClass = CanTo->getTypeClass();
1296   if (TyClass != CanFrom->getTypeClass()) return false;
1297   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1298     if (TyClass == Type::Pointer) {
1299       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1300       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1301     } else if (TyClass == Type::BlockPointer) {
1302       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1303       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1304     } else if (TyClass == Type::MemberPointer) {
1305       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1306       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1307     } else {
1308       return false;
1309     }
1310 
1311     TyClass = CanTo->getTypeClass();
1312     if (TyClass != CanFrom->getTypeClass()) return false;
1313     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1314       return false;
1315   }
1316 
1317   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1318   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1319   if (!EInfo.getNoReturn()) return false;
1320 
1321   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1322   assert(QualType(FromFn, 0).isCanonical());
1323   if (QualType(FromFn, 0) != CanTo) return false;
1324 
1325   ResultTy = ToType;
1326   return true;
1327 }
1328 
1329 /// \brief Determine whether the conversion from FromType to ToType is a valid
1330 /// vector conversion.
1331 ///
1332 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1333 /// conversion.
1334 static bool IsVectorConversion(Sema &S, QualType FromType,
1335                                QualType ToType, ImplicitConversionKind &ICK) {
1336   // We need at least one of these types to be a vector type to have a vector
1337   // conversion.
1338   if (!ToType->isVectorType() && !FromType->isVectorType())
1339     return false;
1340 
1341   // Identical types require no conversions.
1342   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1343     return false;
1344 
1345   // There are no conversions between extended vector types, only identity.
1346   if (ToType->isExtVectorType()) {
1347     // There are no conversions between extended vector types other than the
1348     // identity conversion.
1349     if (FromType->isExtVectorType())
1350       return false;
1351 
1352     // Vector splat from any arithmetic type to a vector.
1353     if (FromType->isArithmeticType()) {
1354       ICK = ICK_Vector_Splat;
1355       return true;
1356     }
1357   }
1358 
1359   // We can perform the conversion between vector types in the following cases:
1360   // 1)vector types are equivalent AltiVec and GCC vector types
1361   // 2)lax vector conversions are permitted and the vector types are of the
1362   //   same size
1363   if (ToType->isVectorType() && FromType->isVectorType()) {
1364     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1365         S.isLaxVectorConversion(FromType, ToType)) {
1366       ICK = ICK_Vector_Conversion;
1367       return true;
1368     }
1369   }
1370 
1371   return false;
1372 }
1373 
1374 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1375                                 bool InOverloadResolution,
1376                                 StandardConversionSequence &SCS,
1377                                 bool CStyle);
1378 
1379 /// IsStandardConversion - Determines whether there is a standard
1380 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1381 /// expression From to the type ToType. Standard conversion sequences
1382 /// only consider non-class types; for conversions that involve class
1383 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1384 /// contain the standard conversion sequence required to perform this
1385 /// conversion and this routine will return true. Otherwise, this
1386 /// routine will return false and the value of SCS is unspecified.
1387 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1388                                  bool InOverloadResolution,
1389                                  StandardConversionSequence &SCS,
1390                                  bool CStyle,
1391                                  bool AllowObjCWritebackConversion) {
1392   QualType FromType = From->getType();
1393 
1394   // Standard conversions (C++ [conv])
1395   SCS.setAsIdentityConversion();
1396   SCS.IncompatibleObjC = false;
1397   SCS.setFromType(FromType);
1398   SCS.CopyConstructor = nullptr;
1399 
1400   // There are no standard conversions for class types in C++, so
1401   // abort early. When overloading in C, however, we do permit
1402   if (FromType->isRecordType() || ToType->isRecordType()) {
1403     if (S.getLangOpts().CPlusPlus)
1404       return false;
1405 
1406     // When we're overloading in C, we allow, as standard conversions,
1407   }
1408 
1409   // The first conversion can be an lvalue-to-rvalue conversion,
1410   // array-to-pointer conversion, or function-to-pointer conversion
1411   // (C++ 4p1).
1412 
1413   if (FromType == S.Context.OverloadTy) {
1414     DeclAccessPair AccessPair;
1415     if (FunctionDecl *Fn
1416           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1417                                                  AccessPair)) {
1418       // We were able to resolve the address of the overloaded function,
1419       // so we can convert to the type of that function.
1420       FromType = Fn->getType();
1421       SCS.setFromType(FromType);
1422 
1423       // we can sometimes resolve &foo<int> regardless of ToType, so check
1424       // if the type matches (identity) or we are converting to bool
1425       if (!S.Context.hasSameUnqualifiedType(
1426                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1427         QualType resultTy;
1428         // if the function type matches except for [[noreturn]], it's ok
1429         if (!S.IsNoReturnConversion(FromType,
1430               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1431           // otherwise, only a boolean conversion is standard
1432           if (!ToType->isBooleanType())
1433             return false;
1434       }
1435 
1436       // Check if the "from" expression is taking the address of an overloaded
1437       // function and recompute the FromType accordingly. Take advantage of the
1438       // fact that non-static member functions *must* have such an address-of
1439       // expression.
1440       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1441       if (Method && !Method->isStatic()) {
1442         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1443                "Non-unary operator on non-static member address");
1444         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1445                == UO_AddrOf &&
1446                "Non-address-of operator on non-static member address");
1447         const Type *ClassType
1448           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1449         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1450       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1451         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1452                UO_AddrOf &&
1453                "Non-address-of operator for overloaded function expression");
1454         FromType = S.Context.getPointerType(FromType);
1455       }
1456 
1457       // Check that we've computed the proper type after overload resolution.
1458       assert(S.Context.hasSameType(
1459         FromType,
1460         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1461     } else {
1462       return false;
1463     }
1464   }
1465   // Lvalue-to-rvalue conversion (C++11 4.1):
1466   //   A glvalue (3.10) of a non-function, non-array type T can
1467   //   be converted to a prvalue.
1468   bool argIsLValue = From->isGLValue();
1469   if (argIsLValue &&
1470       !FromType->isFunctionType() && !FromType->isArrayType() &&
1471       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1472     SCS.First = ICK_Lvalue_To_Rvalue;
1473 
1474     // C11 6.3.2.1p2:
1475     //   ... if the lvalue has atomic type, the value has the non-atomic version
1476     //   of the type of the lvalue ...
1477     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1478       FromType = Atomic->getValueType();
1479 
1480     // If T is a non-class type, the type of the rvalue is the
1481     // cv-unqualified version of T. Otherwise, the type of the rvalue
1482     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1483     // just strip the qualifiers because they don't matter.
1484     FromType = FromType.getUnqualifiedType();
1485   } else if (FromType->isArrayType()) {
1486     // Array-to-pointer conversion (C++ 4.2)
1487     SCS.First = ICK_Array_To_Pointer;
1488 
1489     // An lvalue or rvalue of type "array of N T" or "array of unknown
1490     // bound of T" can be converted to an rvalue of type "pointer to
1491     // T" (C++ 4.2p1).
1492     FromType = S.Context.getArrayDecayedType(FromType);
1493 
1494     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1495       // This conversion is deprecated in C++03 (D.4)
1496       SCS.DeprecatedStringLiteralToCharPtr = true;
1497 
1498       // For the purpose of ranking in overload resolution
1499       // (13.3.3.1.1), this conversion is considered an
1500       // array-to-pointer conversion followed by a qualification
1501       // conversion (4.4). (C++ 4.2p2)
1502       SCS.Second = ICK_Identity;
1503       SCS.Third = ICK_Qualification;
1504       SCS.QualificationIncludesObjCLifetime = false;
1505       SCS.setAllToTypes(FromType);
1506       return true;
1507     }
1508   } else if (FromType->isFunctionType() && argIsLValue) {
1509     // Function-to-pointer conversion (C++ 4.3).
1510     SCS.First = ICK_Function_To_Pointer;
1511 
1512     // An lvalue of function type T can be converted to an rvalue of
1513     // type "pointer to T." The result is a pointer to the
1514     // function. (C++ 4.3p1).
1515     FromType = S.Context.getPointerType(FromType);
1516   } else {
1517     // We don't require any conversions for the first step.
1518     SCS.First = ICK_Identity;
1519   }
1520   SCS.setToType(0, FromType);
1521 
1522   // The second conversion can be an integral promotion, floating
1523   // point promotion, integral conversion, floating point conversion,
1524   // floating-integral conversion, pointer conversion,
1525   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1526   // For overloading in C, this can also be a "compatible-type"
1527   // conversion.
1528   bool IncompatibleObjC = false;
1529   ImplicitConversionKind SecondICK = ICK_Identity;
1530   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1531     // The unqualified versions of the types are the same: there's no
1532     // conversion to do.
1533     SCS.Second = ICK_Identity;
1534   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1535     // Integral promotion (C++ 4.5).
1536     SCS.Second = ICK_Integral_Promotion;
1537     FromType = ToType.getUnqualifiedType();
1538   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1539     // Floating point promotion (C++ 4.6).
1540     SCS.Second = ICK_Floating_Promotion;
1541     FromType = ToType.getUnqualifiedType();
1542   } else if (S.IsComplexPromotion(FromType, ToType)) {
1543     // Complex promotion (Clang extension)
1544     SCS.Second = ICK_Complex_Promotion;
1545     FromType = ToType.getUnqualifiedType();
1546   } else if (ToType->isBooleanType() &&
1547              (FromType->isArithmeticType() ||
1548               FromType->isAnyPointerType() ||
1549               FromType->isBlockPointerType() ||
1550               FromType->isMemberPointerType() ||
1551               FromType->isNullPtrType())) {
1552     // Boolean conversions (C++ 4.12).
1553     SCS.Second = ICK_Boolean_Conversion;
1554     FromType = S.Context.BoolTy;
1555   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1556              ToType->isIntegralType(S.Context)) {
1557     // Integral conversions (C++ 4.7).
1558     SCS.Second = ICK_Integral_Conversion;
1559     FromType = ToType.getUnqualifiedType();
1560   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1561     // Complex conversions (C99 6.3.1.6)
1562     SCS.Second = ICK_Complex_Conversion;
1563     FromType = ToType.getUnqualifiedType();
1564   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1565              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1566     // Complex-real conversions (C99 6.3.1.7)
1567     SCS.Second = ICK_Complex_Real;
1568     FromType = ToType.getUnqualifiedType();
1569   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1570     // Floating point conversions (C++ 4.8).
1571     SCS.Second = ICK_Floating_Conversion;
1572     FromType = ToType.getUnqualifiedType();
1573   } else if ((FromType->isRealFloatingType() &&
1574               ToType->isIntegralType(S.Context)) ||
1575              (FromType->isIntegralOrUnscopedEnumerationType() &&
1576               ToType->isRealFloatingType())) {
1577     // Floating-integral conversions (C++ 4.9).
1578     SCS.Second = ICK_Floating_Integral;
1579     FromType = ToType.getUnqualifiedType();
1580   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1581     SCS.Second = ICK_Block_Pointer_Conversion;
1582   } else if (AllowObjCWritebackConversion &&
1583              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1584     SCS.Second = ICK_Writeback_Conversion;
1585   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1586                                    FromType, IncompatibleObjC)) {
1587     // Pointer conversions (C++ 4.10).
1588     SCS.Second = ICK_Pointer_Conversion;
1589     SCS.IncompatibleObjC = IncompatibleObjC;
1590     FromType = FromType.getUnqualifiedType();
1591   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1592                                          InOverloadResolution, FromType)) {
1593     // Pointer to member conversions (4.11).
1594     SCS.Second = ICK_Pointer_Member;
1595   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1596     SCS.Second = SecondICK;
1597     FromType = ToType.getUnqualifiedType();
1598   } else if (!S.getLangOpts().CPlusPlus &&
1599              S.Context.typesAreCompatible(ToType, FromType)) {
1600     // Compatible conversions (Clang extension for C function overloading)
1601     SCS.Second = ICK_Compatible_Conversion;
1602     FromType = ToType.getUnqualifiedType();
1603   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1604     // Treat a conversion that strips "noreturn" as an identity conversion.
1605     SCS.Second = ICK_NoReturn_Adjustment;
1606   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1607                                              InOverloadResolution,
1608                                              SCS, CStyle)) {
1609     SCS.Second = ICK_TransparentUnionConversion;
1610     FromType = ToType;
1611   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1612                                  CStyle)) {
1613     // tryAtomicConversion has updated the standard conversion sequence
1614     // appropriately.
1615     return true;
1616   } else if (ToType->isEventT() &&
1617              From->isIntegerConstantExpr(S.getASTContext()) &&
1618              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1619     SCS.Second = ICK_Zero_Event_Conversion;
1620     FromType = ToType;
1621   } else {
1622     // No second conversion required.
1623     SCS.Second = ICK_Identity;
1624   }
1625   SCS.setToType(1, FromType);
1626 
1627   QualType CanonFrom;
1628   QualType CanonTo;
1629   // The third conversion can be a qualification conversion (C++ 4p1).
1630   bool ObjCLifetimeConversion;
1631   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1632                                   ObjCLifetimeConversion)) {
1633     SCS.Third = ICK_Qualification;
1634     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1635     FromType = ToType;
1636     CanonFrom = S.Context.getCanonicalType(FromType);
1637     CanonTo = S.Context.getCanonicalType(ToType);
1638   } else {
1639     // No conversion required
1640     SCS.Third = ICK_Identity;
1641 
1642     // C++ [over.best.ics]p6:
1643     //   [...] Any difference in top-level cv-qualification is
1644     //   subsumed by the initialization itself and does not constitute
1645     //   a conversion. [...]
1646     CanonFrom = S.Context.getCanonicalType(FromType);
1647     CanonTo = S.Context.getCanonicalType(ToType);
1648     if (CanonFrom.getLocalUnqualifiedType()
1649                                        == CanonTo.getLocalUnqualifiedType() &&
1650         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1651       FromType = ToType;
1652       CanonFrom = CanonTo;
1653     }
1654   }
1655   SCS.setToType(2, FromType);
1656 
1657   // If we have not converted the argument type to the parameter type,
1658   // this is a bad conversion sequence.
1659   if (CanonFrom != CanonTo)
1660     return false;
1661 
1662   return true;
1663 }
1664 
1665 static bool
1666 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1667                                      QualType &ToType,
1668                                      bool InOverloadResolution,
1669                                      StandardConversionSequence &SCS,
1670                                      bool CStyle) {
1671 
1672   const RecordType *UT = ToType->getAsUnionType();
1673   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1674     return false;
1675   // The field to initialize within the transparent union.
1676   RecordDecl *UD = UT->getDecl();
1677   // It's compatible if the expression matches any of the fields.
1678   for (const auto *it : UD->fields()) {
1679     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1680                              CStyle, /*ObjCWritebackConversion=*/false)) {
1681       ToType = it->getType();
1682       return true;
1683     }
1684   }
1685   return false;
1686 }
1687 
1688 /// IsIntegralPromotion - Determines whether the conversion from the
1689 /// expression From (whose potentially-adjusted type is FromType) to
1690 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1691 /// sets PromotedType to the promoted type.
1692 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1693   const BuiltinType *To = ToType->getAs<BuiltinType>();
1694   // All integers are built-in.
1695   if (!To) {
1696     return false;
1697   }
1698 
1699   // An rvalue of type char, signed char, unsigned char, short int, or
1700   // unsigned short int can be converted to an rvalue of type int if
1701   // int can represent all the values of the source type; otherwise,
1702   // the source rvalue can be converted to an rvalue of type unsigned
1703   // int (C++ 4.5p1).
1704   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1705       !FromType->isEnumeralType()) {
1706     if (// We can promote any signed, promotable integer type to an int
1707         (FromType->isSignedIntegerType() ||
1708          // We can promote any unsigned integer type whose size is
1709          // less than int to an int.
1710          (!FromType->isSignedIntegerType() &&
1711           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1712       return To->getKind() == BuiltinType::Int;
1713     }
1714 
1715     return To->getKind() == BuiltinType::UInt;
1716   }
1717 
1718   // C++11 [conv.prom]p3:
1719   //   A prvalue of an unscoped enumeration type whose underlying type is not
1720   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1721   //   following types that can represent all the values of the enumeration
1722   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1723   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1724   //   long long int. If none of the types in that list can represent all the
1725   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1726   //   type can be converted to an rvalue a prvalue of the extended integer type
1727   //   with lowest integer conversion rank (4.13) greater than the rank of long
1728   //   long in which all the values of the enumeration can be represented. If
1729   //   there are two such extended types, the signed one is chosen.
1730   // C++11 [conv.prom]p4:
1731   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1732   //   can be converted to a prvalue of its underlying type. Moreover, if
1733   //   integral promotion can be applied to its underlying type, a prvalue of an
1734   //   unscoped enumeration type whose underlying type is fixed can also be
1735   //   converted to a prvalue of the promoted underlying type.
1736   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1737     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1738     // provided for a scoped enumeration.
1739     if (FromEnumType->getDecl()->isScoped())
1740       return false;
1741 
1742     // We can perform an integral promotion to the underlying type of the enum,
1743     // even if that's not the promoted type.
1744     if (FromEnumType->getDecl()->isFixed()) {
1745       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1746       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1747              IsIntegralPromotion(From, Underlying, ToType);
1748     }
1749 
1750     // We have already pre-calculated the promotion type, so this is trivial.
1751     if (ToType->isIntegerType() &&
1752         !RequireCompleteType(From->getLocStart(), FromType, 0))
1753       return Context.hasSameUnqualifiedType(ToType,
1754                                 FromEnumType->getDecl()->getPromotionType());
1755   }
1756 
1757   // C++0x [conv.prom]p2:
1758   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1759   //   to an rvalue a prvalue of the first of the following types that can
1760   //   represent all the values of its underlying type: int, unsigned int,
1761   //   long int, unsigned long int, long long int, or unsigned long long int.
1762   //   If none of the types in that list can represent all the values of its
1763   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1764   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1765   //   type.
1766   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1767       ToType->isIntegerType()) {
1768     // Determine whether the type we're converting from is signed or
1769     // unsigned.
1770     bool FromIsSigned = FromType->isSignedIntegerType();
1771     uint64_t FromSize = Context.getTypeSize(FromType);
1772 
1773     // The types we'll try to promote to, in the appropriate
1774     // order. Try each of these types.
1775     QualType PromoteTypes[6] = {
1776       Context.IntTy, Context.UnsignedIntTy,
1777       Context.LongTy, Context.UnsignedLongTy ,
1778       Context.LongLongTy, Context.UnsignedLongLongTy
1779     };
1780     for (int Idx = 0; Idx < 6; ++Idx) {
1781       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1782       if (FromSize < ToSize ||
1783           (FromSize == ToSize &&
1784            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1785         // We found the type that we can promote to. If this is the
1786         // type we wanted, we have a promotion. Otherwise, no
1787         // promotion.
1788         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1789       }
1790     }
1791   }
1792 
1793   // An rvalue for an integral bit-field (9.6) can be converted to an
1794   // rvalue of type int if int can represent all the values of the
1795   // bit-field; otherwise, it can be converted to unsigned int if
1796   // unsigned int can represent all the values of the bit-field. If
1797   // the bit-field is larger yet, no integral promotion applies to
1798   // it. If the bit-field has an enumerated type, it is treated as any
1799   // other value of that type for promotion purposes (C++ 4.5p3).
1800   // FIXME: We should delay checking of bit-fields until we actually perform the
1801   // conversion.
1802   using llvm::APSInt;
1803   if (From)
1804     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1805       APSInt BitWidth;
1806       if (FromType->isIntegralType(Context) &&
1807           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1808         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1809         ToSize = Context.getTypeSize(ToType);
1810 
1811         // Are we promoting to an int from a bitfield that fits in an int?
1812         if (BitWidth < ToSize ||
1813             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1814           return To->getKind() == BuiltinType::Int;
1815         }
1816 
1817         // Are we promoting to an unsigned int from an unsigned bitfield
1818         // that fits into an unsigned int?
1819         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1820           return To->getKind() == BuiltinType::UInt;
1821         }
1822 
1823         return false;
1824       }
1825     }
1826 
1827   // An rvalue of type bool can be converted to an rvalue of type int,
1828   // with false becoming zero and true becoming one (C++ 4.5p4).
1829   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1830     return true;
1831   }
1832 
1833   return false;
1834 }
1835 
1836 /// IsFloatingPointPromotion - Determines whether the conversion from
1837 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1838 /// returns true and sets PromotedType to the promoted type.
1839 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1840   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1841     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1842       /// An rvalue of type float can be converted to an rvalue of type
1843       /// double. (C++ 4.6p1).
1844       if (FromBuiltin->getKind() == BuiltinType::Float &&
1845           ToBuiltin->getKind() == BuiltinType::Double)
1846         return true;
1847 
1848       // C99 6.3.1.5p1:
1849       //   When a float is promoted to double or long double, or a
1850       //   double is promoted to long double [...].
1851       if (!getLangOpts().CPlusPlus &&
1852           (FromBuiltin->getKind() == BuiltinType::Float ||
1853            FromBuiltin->getKind() == BuiltinType::Double) &&
1854           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1855         return true;
1856 
1857       // Half can be promoted to float.
1858       if (!getLangOpts().NativeHalfType &&
1859            FromBuiltin->getKind() == BuiltinType::Half &&
1860           ToBuiltin->getKind() == BuiltinType::Float)
1861         return true;
1862     }
1863 
1864   return false;
1865 }
1866 
1867 /// \brief Determine if a conversion is a complex promotion.
1868 ///
1869 /// A complex promotion is defined as a complex -> complex conversion
1870 /// where the conversion between the underlying real types is a
1871 /// floating-point or integral promotion.
1872 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1873   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1874   if (!FromComplex)
1875     return false;
1876 
1877   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1878   if (!ToComplex)
1879     return false;
1880 
1881   return IsFloatingPointPromotion(FromComplex->getElementType(),
1882                                   ToComplex->getElementType()) ||
1883     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1884                         ToComplex->getElementType());
1885 }
1886 
1887 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1888 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1889 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1890 /// if non-empty, will be a pointer to ToType that may or may not have
1891 /// the right set of qualifiers on its pointee.
1892 ///
1893 static QualType
1894 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1895                                    QualType ToPointee, QualType ToType,
1896                                    ASTContext &Context,
1897                                    bool StripObjCLifetime = false) {
1898   assert((FromPtr->getTypeClass() == Type::Pointer ||
1899           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1900          "Invalid similarly-qualified pointer type");
1901 
1902   /// Conversions to 'id' subsume cv-qualifier conversions.
1903   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1904     return ToType.getUnqualifiedType();
1905 
1906   QualType CanonFromPointee
1907     = Context.getCanonicalType(FromPtr->getPointeeType());
1908   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1909   Qualifiers Quals = CanonFromPointee.getQualifiers();
1910 
1911   if (StripObjCLifetime)
1912     Quals.removeObjCLifetime();
1913 
1914   // Exact qualifier match -> return the pointer type we're converting to.
1915   if (CanonToPointee.getLocalQualifiers() == Quals) {
1916     // ToType is exactly what we need. Return it.
1917     if (!ToType.isNull())
1918       return ToType.getUnqualifiedType();
1919 
1920     // Build a pointer to ToPointee. It has the right qualifiers
1921     // already.
1922     if (isa<ObjCObjectPointerType>(ToType))
1923       return Context.getObjCObjectPointerType(ToPointee);
1924     return Context.getPointerType(ToPointee);
1925   }
1926 
1927   // Just build a canonical type that has the right qualifiers.
1928   QualType QualifiedCanonToPointee
1929     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1930 
1931   if (isa<ObjCObjectPointerType>(ToType))
1932     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1933   return Context.getPointerType(QualifiedCanonToPointee);
1934 }
1935 
1936 static bool isNullPointerConstantForConversion(Expr *Expr,
1937                                                bool InOverloadResolution,
1938                                                ASTContext &Context) {
1939   // Handle value-dependent integral null pointer constants correctly.
1940   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1941   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1942       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1943     return !InOverloadResolution;
1944 
1945   return Expr->isNullPointerConstant(Context,
1946                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1947                                         : Expr::NPC_ValueDependentIsNull);
1948 }
1949 
1950 /// IsPointerConversion - Determines whether the conversion of the
1951 /// expression From, which has the (possibly adjusted) type FromType,
1952 /// can be converted to the type ToType via a pointer conversion (C++
1953 /// 4.10). If so, returns true and places the converted type (that
1954 /// might differ from ToType in its cv-qualifiers at some level) into
1955 /// ConvertedType.
1956 ///
1957 /// This routine also supports conversions to and from block pointers
1958 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1959 /// pointers to interfaces. FIXME: Once we've determined the
1960 /// appropriate overloading rules for Objective-C, we may want to
1961 /// split the Objective-C checks into a different routine; however,
1962 /// GCC seems to consider all of these conversions to be pointer
1963 /// conversions, so for now they live here. IncompatibleObjC will be
1964 /// set if the conversion is an allowed Objective-C conversion that
1965 /// should result in a warning.
1966 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1967                                bool InOverloadResolution,
1968                                QualType& ConvertedType,
1969                                bool &IncompatibleObjC) {
1970   IncompatibleObjC = false;
1971   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1972                               IncompatibleObjC))
1973     return true;
1974 
1975   // Conversion from a null pointer constant to any Objective-C pointer type.
1976   if (ToType->isObjCObjectPointerType() &&
1977       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1978     ConvertedType = ToType;
1979     return true;
1980   }
1981 
1982   // Blocks: Block pointers can be converted to void*.
1983   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1984       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1985     ConvertedType = ToType;
1986     return true;
1987   }
1988   // Blocks: A null pointer constant can be converted to a block
1989   // pointer type.
1990   if (ToType->isBlockPointerType() &&
1991       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1992     ConvertedType = ToType;
1993     return true;
1994   }
1995 
1996   // If the left-hand-side is nullptr_t, the right side can be a null
1997   // pointer constant.
1998   if (ToType->isNullPtrType() &&
1999       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2000     ConvertedType = ToType;
2001     return true;
2002   }
2003 
2004   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2005   if (!ToTypePtr)
2006     return false;
2007 
2008   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2009   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2010     ConvertedType = ToType;
2011     return true;
2012   }
2013 
2014   // Beyond this point, both types need to be pointers
2015   // , including objective-c pointers.
2016   QualType ToPointeeType = ToTypePtr->getPointeeType();
2017   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2018       !getLangOpts().ObjCAutoRefCount) {
2019     ConvertedType = BuildSimilarlyQualifiedPointerType(
2020                                       FromType->getAs<ObjCObjectPointerType>(),
2021                                                        ToPointeeType,
2022                                                        ToType, Context);
2023     return true;
2024   }
2025   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2026   if (!FromTypePtr)
2027     return false;
2028 
2029   QualType FromPointeeType = FromTypePtr->getPointeeType();
2030 
2031   // If the unqualified pointee types are the same, this can't be a
2032   // pointer conversion, so don't do all of the work below.
2033   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2034     return false;
2035 
2036   // An rvalue of type "pointer to cv T," where T is an object type,
2037   // can be converted to an rvalue of type "pointer to cv void" (C++
2038   // 4.10p2).
2039   if (FromPointeeType->isIncompleteOrObjectType() &&
2040       ToPointeeType->isVoidType()) {
2041     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2042                                                        ToPointeeType,
2043                                                        ToType, Context,
2044                                                    /*StripObjCLifetime=*/true);
2045     return true;
2046   }
2047 
2048   // MSVC allows implicit function to void* type conversion.
2049   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2050       ToPointeeType->isVoidType()) {
2051     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052                                                        ToPointeeType,
2053                                                        ToType, Context);
2054     return true;
2055   }
2056 
2057   // When we're overloading in C, we allow a special kind of pointer
2058   // conversion for compatible-but-not-identical pointee types.
2059   if (!getLangOpts().CPlusPlus &&
2060       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2061     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2062                                                        ToPointeeType,
2063                                                        ToType, Context);
2064     return true;
2065   }
2066 
2067   // C++ [conv.ptr]p3:
2068   //
2069   //   An rvalue of type "pointer to cv D," where D is a class type,
2070   //   can be converted to an rvalue of type "pointer to cv B," where
2071   //   B is a base class (clause 10) of D. If B is an inaccessible
2072   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2073   //   necessitates this conversion is ill-formed. The result of the
2074   //   conversion is a pointer to the base class sub-object of the
2075   //   derived class object. The null pointer value is converted to
2076   //   the null pointer value of the destination type.
2077   //
2078   // Note that we do not check for ambiguity or inaccessibility
2079   // here. That is handled by CheckPointerConversion.
2080   if (getLangOpts().CPlusPlus &&
2081       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2082       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2083       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2084       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2085     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2086                                                        ToPointeeType,
2087                                                        ToType, Context);
2088     return true;
2089   }
2090 
2091   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2092       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2093     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2094                                                        ToPointeeType,
2095                                                        ToType, Context);
2096     return true;
2097   }
2098 
2099   return false;
2100 }
2101 
2102 /// \brief Adopt the given qualifiers for the given type.
2103 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2104   Qualifiers TQs = T.getQualifiers();
2105 
2106   // Check whether qualifiers already match.
2107   if (TQs == Qs)
2108     return T;
2109 
2110   if (Qs.compatiblyIncludes(TQs))
2111     return Context.getQualifiedType(T, Qs);
2112 
2113   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2114 }
2115 
2116 /// isObjCPointerConversion - Determines whether this is an
2117 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2118 /// with the same arguments and return values.
2119 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2120                                    QualType& ConvertedType,
2121                                    bool &IncompatibleObjC) {
2122   if (!getLangOpts().ObjC1)
2123     return false;
2124 
2125   // The set of qualifiers on the type we're converting from.
2126   Qualifiers FromQualifiers = FromType.getQualifiers();
2127 
2128   // First, we handle all conversions on ObjC object pointer types.
2129   const ObjCObjectPointerType* ToObjCPtr =
2130     ToType->getAs<ObjCObjectPointerType>();
2131   const ObjCObjectPointerType *FromObjCPtr =
2132     FromType->getAs<ObjCObjectPointerType>();
2133 
2134   if (ToObjCPtr && FromObjCPtr) {
2135     // If the pointee types are the same (ignoring qualifications),
2136     // then this is not a pointer conversion.
2137     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2138                                        FromObjCPtr->getPointeeType()))
2139       return false;
2140 
2141     // Check for compatible
2142     // Objective C++: We're able to convert between "id" or "Class" and a
2143     // pointer to any interface (in both directions).
2144     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2145       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2146       return true;
2147     }
2148     // Conversions with Objective-C's id<...>.
2149     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2150          ToObjCPtr->isObjCQualifiedIdType()) &&
2151         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2152                                                   /*compare=*/false)) {
2153       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2154       return true;
2155     }
2156     // Objective C++: We're able to convert from a pointer to an
2157     // interface to a pointer to a different interface.
2158     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2159       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2160       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2161       if (getLangOpts().CPlusPlus && LHS && RHS &&
2162           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2163                                                 FromObjCPtr->getPointeeType()))
2164         return false;
2165       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2166                                                    ToObjCPtr->getPointeeType(),
2167                                                          ToType, Context);
2168       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2169       return true;
2170     }
2171 
2172     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2173       // Okay: this is some kind of implicit downcast of Objective-C
2174       // interfaces, which is permitted. However, we're going to
2175       // complain about it.
2176       IncompatibleObjC = true;
2177       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2178                                                    ToObjCPtr->getPointeeType(),
2179                                                          ToType, Context);
2180       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2181       return true;
2182     }
2183   }
2184   // Beyond this point, both types need to be C pointers or block pointers.
2185   QualType ToPointeeType;
2186   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2187     ToPointeeType = ToCPtr->getPointeeType();
2188   else if (const BlockPointerType *ToBlockPtr =
2189             ToType->getAs<BlockPointerType>()) {
2190     // Objective C++: We're able to convert from a pointer to any object
2191     // to a block pointer type.
2192     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2193       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2194       return true;
2195     }
2196     ToPointeeType = ToBlockPtr->getPointeeType();
2197   }
2198   else if (FromType->getAs<BlockPointerType>() &&
2199            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2200     // Objective C++: We're able to convert from a block pointer type to a
2201     // pointer to any object.
2202     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2203     return true;
2204   }
2205   else
2206     return false;
2207 
2208   QualType FromPointeeType;
2209   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2210     FromPointeeType = FromCPtr->getPointeeType();
2211   else if (const BlockPointerType *FromBlockPtr =
2212            FromType->getAs<BlockPointerType>())
2213     FromPointeeType = FromBlockPtr->getPointeeType();
2214   else
2215     return false;
2216 
2217   // If we have pointers to pointers, recursively check whether this
2218   // is an Objective-C conversion.
2219   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2220       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2221                               IncompatibleObjC)) {
2222     // We always complain about this conversion.
2223     IncompatibleObjC = true;
2224     ConvertedType = Context.getPointerType(ConvertedType);
2225     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2226     return true;
2227   }
2228   // Allow conversion of pointee being objective-c pointer to another one;
2229   // as in I* to id.
2230   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2231       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2232       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2233                               IncompatibleObjC)) {
2234 
2235     ConvertedType = Context.getPointerType(ConvertedType);
2236     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2237     return true;
2238   }
2239 
2240   // If we have pointers to functions or blocks, check whether the only
2241   // differences in the argument and result types are in Objective-C
2242   // pointer conversions. If so, we permit the conversion (but
2243   // complain about it).
2244   const FunctionProtoType *FromFunctionType
2245     = FromPointeeType->getAs<FunctionProtoType>();
2246   const FunctionProtoType *ToFunctionType
2247     = ToPointeeType->getAs<FunctionProtoType>();
2248   if (FromFunctionType && ToFunctionType) {
2249     // If the function types are exactly the same, this isn't an
2250     // Objective-C pointer conversion.
2251     if (Context.getCanonicalType(FromPointeeType)
2252           == Context.getCanonicalType(ToPointeeType))
2253       return false;
2254 
2255     // Perform the quick checks that will tell us whether these
2256     // function types are obviously different.
2257     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2258         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2259         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2260       return false;
2261 
2262     bool HasObjCConversion = false;
2263     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2264         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2265       // Okay, the types match exactly. Nothing to do.
2266     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2267                                        ToFunctionType->getReturnType(),
2268                                        ConvertedType, IncompatibleObjC)) {
2269       // Okay, we have an Objective-C pointer conversion.
2270       HasObjCConversion = true;
2271     } else {
2272       // Function types are too different. Abort.
2273       return false;
2274     }
2275 
2276     // Check argument types.
2277     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2278          ArgIdx != NumArgs; ++ArgIdx) {
2279       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2280       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2281       if (Context.getCanonicalType(FromArgType)
2282             == Context.getCanonicalType(ToArgType)) {
2283         // Okay, the types match exactly. Nothing to do.
2284       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2285                                          ConvertedType, IncompatibleObjC)) {
2286         // Okay, we have an Objective-C pointer conversion.
2287         HasObjCConversion = true;
2288       } else {
2289         // Argument types are too different. Abort.
2290         return false;
2291       }
2292     }
2293 
2294     if (HasObjCConversion) {
2295       // We had an Objective-C conversion. Allow this pointer
2296       // conversion, but complain about it.
2297       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2298       IncompatibleObjC = true;
2299       return true;
2300     }
2301   }
2302 
2303   return false;
2304 }
2305 
2306 /// \brief Determine whether this is an Objective-C writeback conversion,
2307 /// used for parameter passing when performing automatic reference counting.
2308 ///
2309 /// \param FromType The type we're converting form.
2310 ///
2311 /// \param ToType The type we're converting to.
2312 ///
2313 /// \param ConvertedType The type that will be produced after applying
2314 /// this conversion.
2315 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2316                                      QualType &ConvertedType) {
2317   if (!getLangOpts().ObjCAutoRefCount ||
2318       Context.hasSameUnqualifiedType(FromType, ToType))
2319     return false;
2320 
2321   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2322   QualType ToPointee;
2323   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2324     ToPointee = ToPointer->getPointeeType();
2325   else
2326     return false;
2327 
2328   Qualifiers ToQuals = ToPointee.getQualifiers();
2329   if (!ToPointee->isObjCLifetimeType() ||
2330       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2331       !ToQuals.withoutObjCLifetime().empty())
2332     return false;
2333 
2334   // Argument must be a pointer to __strong to __weak.
2335   QualType FromPointee;
2336   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2337     FromPointee = FromPointer->getPointeeType();
2338   else
2339     return false;
2340 
2341   Qualifiers FromQuals = FromPointee.getQualifiers();
2342   if (!FromPointee->isObjCLifetimeType() ||
2343       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2344        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2345     return false;
2346 
2347   // Make sure that we have compatible qualifiers.
2348   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2349   if (!ToQuals.compatiblyIncludes(FromQuals))
2350     return false;
2351 
2352   // Remove qualifiers from the pointee type we're converting from; they
2353   // aren't used in the compatibility check belong, and we'll be adding back
2354   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2355   FromPointee = FromPointee.getUnqualifiedType();
2356 
2357   // The unqualified form of the pointee types must be compatible.
2358   ToPointee = ToPointee.getUnqualifiedType();
2359   bool IncompatibleObjC;
2360   if (Context.typesAreCompatible(FromPointee, ToPointee))
2361     FromPointee = ToPointee;
2362   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2363                                     IncompatibleObjC))
2364     return false;
2365 
2366   /// \brief Construct the type we're converting to, which is a pointer to
2367   /// __autoreleasing pointee.
2368   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2369   ConvertedType = Context.getPointerType(FromPointee);
2370   return true;
2371 }
2372 
2373 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2374                                     QualType& ConvertedType) {
2375   QualType ToPointeeType;
2376   if (const BlockPointerType *ToBlockPtr =
2377         ToType->getAs<BlockPointerType>())
2378     ToPointeeType = ToBlockPtr->getPointeeType();
2379   else
2380     return false;
2381 
2382   QualType FromPointeeType;
2383   if (const BlockPointerType *FromBlockPtr =
2384       FromType->getAs<BlockPointerType>())
2385     FromPointeeType = FromBlockPtr->getPointeeType();
2386   else
2387     return false;
2388   // We have pointer to blocks, check whether the only
2389   // differences in the argument and result types are in Objective-C
2390   // pointer conversions. If so, we permit the conversion.
2391 
2392   const FunctionProtoType *FromFunctionType
2393     = FromPointeeType->getAs<FunctionProtoType>();
2394   const FunctionProtoType *ToFunctionType
2395     = ToPointeeType->getAs<FunctionProtoType>();
2396 
2397   if (!FromFunctionType || !ToFunctionType)
2398     return false;
2399 
2400   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2401     return true;
2402 
2403   // Perform the quick checks that will tell us whether these
2404   // function types are obviously different.
2405   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2406       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2407     return false;
2408 
2409   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2410   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2411   if (FromEInfo != ToEInfo)
2412     return false;
2413 
2414   bool IncompatibleObjC = false;
2415   if (Context.hasSameType(FromFunctionType->getReturnType(),
2416                           ToFunctionType->getReturnType())) {
2417     // Okay, the types match exactly. Nothing to do.
2418   } else {
2419     QualType RHS = FromFunctionType->getReturnType();
2420     QualType LHS = ToFunctionType->getReturnType();
2421     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2422         !RHS.hasQualifiers() && LHS.hasQualifiers())
2423        LHS = LHS.getUnqualifiedType();
2424 
2425      if (Context.hasSameType(RHS,LHS)) {
2426        // OK exact match.
2427      } else if (isObjCPointerConversion(RHS, LHS,
2428                                         ConvertedType, IncompatibleObjC)) {
2429      if (IncompatibleObjC)
2430        return false;
2431      // Okay, we have an Objective-C pointer conversion.
2432      }
2433      else
2434        return false;
2435    }
2436 
2437    // Check argument types.
2438    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2439         ArgIdx != NumArgs; ++ArgIdx) {
2440      IncompatibleObjC = false;
2441      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2442      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2443      if (Context.hasSameType(FromArgType, ToArgType)) {
2444        // Okay, the types match exactly. Nothing to do.
2445      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2446                                         ConvertedType, IncompatibleObjC)) {
2447        if (IncompatibleObjC)
2448          return false;
2449        // Okay, we have an Objective-C pointer conversion.
2450      } else
2451        // Argument types are too different. Abort.
2452        return false;
2453    }
2454    if (LangOpts.ObjCAutoRefCount &&
2455        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2456                                                     ToFunctionType))
2457      return false;
2458 
2459    ConvertedType = ToType;
2460    return true;
2461 }
2462 
2463 enum {
2464   ft_default,
2465   ft_different_class,
2466   ft_parameter_arity,
2467   ft_parameter_mismatch,
2468   ft_return_type,
2469   ft_qualifer_mismatch
2470 };
2471 
2472 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2473 /// function types.  Catches different number of parameter, mismatch in
2474 /// parameter types, and different return types.
2475 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2476                                       QualType FromType, QualType ToType) {
2477   // If either type is not valid, include no extra info.
2478   if (FromType.isNull() || ToType.isNull()) {
2479     PDiag << ft_default;
2480     return;
2481   }
2482 
2483   // Get the function type from the pointers.
2484   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2485     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2486                             *ToMember = ToType->getAs<MemberPointerType>();
2487     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2488       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2489             << QualType(FromMember->getClass(), 0);
2490       return;
2491     }
2492     FromType = FromMember->getPointeeType();
2493     ToType = ToMember->getPointeeType();
2494   }
2495 
2496   if (FromType->isPointerType())
2497     FromType = FromType->getPointeeType();
2498   if (ToType->isPointerType())
2499     ToType = ToType->getPointeeType();
2500 
2501   // Remove references.
2502   FromType = FromType.getNonReferenceType();
2503   ToType = ToType.getNonReferenceType();
2504 
2505   // Don't print extra info for non-specialized template functions.
2506   if (FromType->isInstantiationDependentType() &&
2507       !FromType->getAs<TemplateSpecializationType>()) {
2508     PDiag << ft_default;
2509     return;
2510   }
2511 
2512   // No extra info for same types.
2513   if (Context.hasSameType(FromType, ToType)) {
2514     PDiag << ft_default;
2515     return;
2516   }
2517 
2518   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2519                           *ToFunction = ToType->getAs<FunctionProtoType>();
2520 
2521   // Both types need to be function types.
2522   if (!FromFunction || !ToFunction) {
2523     PDiag << ft_default;
2524     return;
2525   }
2526 
2527   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2528     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2529           << FromFunction->getNumParams();
2530     return;
2531   }
2532 
2533   // Handle different parameter types.
2534   unsigned ArgPos;
2535   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2536     PDiag << ft_parameter_mismatch << ArgPos + 1
2537           << ToFunction->getParamType(ArgPos)
2538           << FromFunction->getParamType(ArgPos);
2539     return;
2540   }
2541 
2542   // Handle different return type.
2543   if (!Context.hasSameType(FromFunction->getReturnType(),
2544                            ToFunction->getReturnType())) {
2545     PDiag << ft_return_type << ToFunction->getReturnType()
2546           << FromFunction->getReturnType();
2547     return;
2548   }
2549 
2550   unsigned FromQuals = FromFunction->getTypeQuals(),
2551            ToQuals = ToFunction->getTypeQuals();
2552   if (FromQuals != ToQuals) {
2553     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2554     return;
2555   }
2556 
2557   // Unable to find a difference, so add no extra info.
2558   PDiag << ft_default;
2559 }
2560 
2561 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2562 /// for equality of their argument types. Caller has already checked that
2563 /// they have same number of arguments.  If the parameters are different,
2564 /// ArgPos will have the parameter index of the first different parameter.
2565 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2566                                       const FunctionProtoType *NewType,
2567                                       unsigned *ArgPos) {
2568   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2569                                               N = NewType->param_type_begin(),
2570                                               E = OldType->param_type_end();
2571        O && (O != E); ++O, ++N) {
2572     if (!Context.hasSameType(O->getUnqualifiedType(),
2573                              N->getUnqualifiedType())) {
2574       if (ArgPos)
2575         *ArgPos = O - OldType->param_type_begin();
2576       return false;
2577     }
2578   }
2579   return true;
2580 }
2581 
2582 /// CheckPointerConversion - Check the pointer conversion from the
2583 /// expression From to the type ToType. This routine checks for
2584 /// ambiguous or inaccessible derived-to-base pointer
2585 /// conversions for which IsPointerConversion has already returned
2586 /// true. It returns true and produces a diagnostic if there was an
2587 /// error, or returns false otherwise.
2588 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2589                                   CastKind &Kind,
2590                                   CXXCastPath& BasePath,
2591                                   bool IgnoreBaseAccess) {
2592   QualType FromType = From->getType();
2593   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2594 
2595   Kind = CK_BitCast;
2596 
2597   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2598       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2599       Expr::NPCK_ZeroExpression) {
2600     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2601       DiagRuntimeBehavior(From->getExprLoc(), From,
2602                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2603                             << ToType << From->getSourceRange());
2604     else if (!isUnevaluatedContext())
2605       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2606         << ToType << From->getSourceRange();
2607   }
2608   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2609     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2610       QualType FromPointeeType = FromPtrType->getPointeeType(),
2611                ToPointeeType   = ToPtrType->getPointeeType();
2612 
2613       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2614           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2615         // We must have a derived-to-base conversion. Check an
2616         // ambiguous or inaccessible conversion.
2617         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2618                                          From->getExprLoc(),
2619                                          From->getSourceRange(), &BasePath,
2620                                          IgnoreBaseAccess))
2621           return true;
2622 
2623         // The conversion was successful.
2624         Kind = CK_DerivedToBase;
2625       }
2626     }
2627   } else if (const ObjCObjectPointerType *ToPtrType =
2628                ToType->getAs<ObjCObjectPointerType>()) {
2629     if (const ObjCObjectPointerType *FromPtrType =
2630           FromType->getAs<ObjCObjectPointerType>()) {
2631       // Objective-C++ conversions are always okay.
2632       // FIXME: We should have a different class of conversions for the
2633       // Objective-C++ implicit conversions.
2634       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2635         return false;
2636     } else if (FromType->isBlockPointerType()) {
2637       Kind = CK_BlockPointerToObjCPointerCast;
2638     } else {
2639       Kind = CK_CPointerToObjCPointerCast;
2640     }
2641   } else if (ToType->isBlockPointerType()) {
2642     if (!FromType->isBlockPointerType())
2643       Kind = CK_AnyPointerToBlockPointerCast;
2644   }
2645 
2646   // We shouldn't fall into this case unless it's valid for other
2647   // reasons.
2648   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2649     Kind = CK_NullToPointer;
2650 
2651   return false;
2652 }
2653 
2654 /// IsMemberPointerConversion - Determines whether the conversion of the
2655 /// expression From, which has the (possibly adjusted) type FromType, can be
2656 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2657 /// If so, returns true and places the converted type (that might differ from
2658 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2659 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2660                                      QualType ToType,
2661                                      bool InOverloadResolution,
2662                                      QualType &ConvertedType) {
2663   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2664   if (!ToTypePtr)
2665     return false;
2666 
2667   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2668   if (From->isNullPointerConstant(Context,
2669                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2670                                         : Expr::NPC_ValueDependentIsNull)) {
2671     ConvertedType = ToType;
2672     return true;
2673   }
2674 
2675   // Otherwise, both types have to be member pointers.
2676   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2677   if (!FromTypePtr)
2678     return false;
2679 
2680   // A pointer to member of B can be converted to a pointer to member of D,
2681   // where D is derived from B (C++ 4.11p2).
2682   QualType FromClass(FromTypePtr->getClass(), 0);
2683   QualType ToClass(ToTypePtr->getClass(), 0);
2684 
2685   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2686       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2687       IsDerivedFrom(ToClass, FromClass)) {
2688     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2689                                                  ToClass.getTypePtr());
2690     return true;
2691   }
2692 
2693   return false;
2694 }
2695 
2696 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2697 /// expression From to the type ToType. This routine checks for ambiguous or
2698 /// virtual or inaccessible base-to-derived member pointer conversions
2699 /// for which IsMemberPointerConversion has already returned true. It returns
2700 /// true and produces a diagnostic if there was an error, or returns false
2701 /// otherwise.
2702 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2703                                         CastKind &Kind,
2704                                         CXXCastPath &BasePath,
2705                                         bool IgnoreBaseAccess) {
2706   QualType FromType = From->getType();
2707   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2708   if (!FromPtrType) {
2709     // This must be a null pointer to member pointer conversion
2710     assert(From->isNullPointerConstant(Context,
2711                                        Expr::NPC_ValueDependentIsNull) &&
2712            "Expr must be null pointer constant!");
2713     Kind = CK_NullToMemberPointer;
2714     return false;
2715   }
2716 
2717   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2718   assert(ToPtrType && "No member pointer cast has a target type "
2719                       "that is not a member pointer.");
2720 
2721   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2722   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2723 
2724   // FIXME: What about dependent types?
2725   assert(FromClass->isRecordType() && "Pointer into non-class.");
2726   assert(ToClass->isRecordType() && "Pointer into non-class.");
2727 
2728   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2729                      /*DetectVirtual=*/true);
2730   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2731   assert(DerivationOkay &&
2732          "Should not have been called if derivation isn't OK.");
2733   (void)DerivationOkay;
2734 
2735   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2736                                   getUnqualifiedType())) {
2737     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2738     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2739       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2740     return true;
2741   }
2742 
2743   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2744     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2745       << FromClass << ToClass << QualType(VBase, 0)
2746       << From->getSourceRange();
2747     return true;
2748   }
2749 
2750   if (!IgnoreBaseAccess)
2751     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2752                          Paths.front(),
2753                          diag::err_downcast_from_inaccessible_base);
2754 
2755   // Must be a base to derived member conversion.
2756   BuildBasePathArray(Paths, BasePath);
2757   Kind = CK_BaseToDerivedMemberPointer;
2758   return false;
2759 }
2760 
2761 /// Determine whether the lifetime conversion between the two given
2762 /// qualifiers sets is nontrivial.
2763 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2764                                                Qualifiers ToQuals) {
2765   // Converting anything to const __unsafe_unretained is trivial.
2766   if (ToQuals.hasConst() &&
2767       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2768     return false;
2769 
2770   return true;
2771 }
2772 
2773 /// IsQualificationConversion - Determines whether the conversion from
2774 /// an rvalue of type FromType to ToType is a qualification conversion
2775 /// (C++ 4.4).
2776 ///
2777 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2778 /// when the qualification conversion involves a change in the Objective-C
2779 /// object lifetime.
2780 bool
2781 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2782                                 bool CStyle, bool &ObjCLifetimeConversion) {
2783   FromType = Context.getCanonicalType(FromType);
2784   ToType = Context.getCanonicalType(ToType);
2785   ObjCLifetimeConversion = false;
2786 
2787   // If FromType and ToType are the same type, this is not a
2788   // qualification conversion.
2789   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2790     return false;
2791 
2792   // (C++ 4.4p4):
2793   //   A conversion can add cv-qualifiers at levels other than the first
2794   //   in multi-level pointers, subject to the following rules: [...]
2795   bool PreviousToQualsIncludeConst = true;
2796   bool UnwrappedAnyPointer = false;
2797   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2798     // Within each iteration of the loop, we check the qualifiers to
2799     // determine if this still looks like a qualification
2800     // conversion. Then, if all is well, we unwrap one more level of
2801     // pointers or pointers-to-members and do it all again
2802     // until there are no more pointers or pointers-to-members left to
2803     // unwrap.
2804     UnwrappedAnyPointer = true;
2805 
2806     Qualifiers FromQuals = FromType.getQualifiers();
2807     Qualifiers ToQuals = ToType.getQualifiers();
2808 
2809     // Objective-C ARC:
2810     //   Check Objective-C lifetime conversions.
2811     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2812         UnwrappedAnyPointer) {
2813       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2814         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2815           ObjCLifetimeConversion = true;
2816         FromQuals.removeObjCLifetime();
2817         ToQuals.removeObjCLifetime();
2818       } else {
2819         // Qualification conversions cannot cast between different
2820         // Objective-C lifetime qualifiers.
2821         return false;
2822       }
2823     }
2824 
2825     // Allow addition/removal of GC attributes but not changing GC attributes.
2826     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2827         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2828       FromQuals.removeObjCGCAttr();
2829       ToQuals.removeObjCGCAttr();
2830     }
2831 
2832     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2833     //      2,j, and similarly for volatile.
2834     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2835       return false;
2836 
2837     //   -- if the cv 1,j and cv 2,j are different, then const is in
2838     //      every cv for 0 < k < j.
2839     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2840         && !PreviousToQualsIncludeConst)
2841       return false;
2842 
2843     // Keep track of whether all prior cv-qualifiers in the "to" type
2844     // include const.
2845     PreviousToQualsIncludeConst
2846       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2847   }
2848 
2849   // We are left with FromType and ToType being the pointee types
2850   // after unwrapping the original FromType and ToType the same number
2851   // of types. If we unwrapped any pointers, and if FromType and
2852   // ToType have the same unqualified type (since we checked
2853   // qualifiers above), then this is a qualification conversion.
2854   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2855 }
2856 
2857 /// \brief - Determine whether this is a conversion from a scalar type to an
2858 /// atomic type.
2859 ///
2860 /// If successful, updates \c SCS's second and third steps in the conversion
2861 /// sequence to finish the conversion.
2862 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2863                                 bool InOverloadResolution,
2864                                 StandardConversionSequence &SCS,
2865                                 bool CStyle) {
2866   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2867   if (!ToAtomic)
2868     return false;
2869 
2870   StandardConversionSequence InnerSCS;
2871   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2872                             InOverloadResolution, InnerSCS,
2873                             CStyle, /*AllowObjCWritebackConversion=*/false))
2874     return false;
2875 
2876   SCS.Second = InnerSCS.Second;
2877   SCS.setToType(1, InnerSCS.getToType(1));
2878   SCS.Third = InnerSCS.Third;
2879   SCS.QualificationIncludesObjCLifetime
2880     = InnerSCS.QualificationIncludesObjCLifetime;
2881   SCS.setToType(2, InnerSCS.getToType(2));
2882   return true;
2883 }
2884 
2885 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2886                                               CXXConstructorDecl *Constructor,
2887                                               QualType Type) {
2888   const FunctionProtoType *CtorType =
2889       Constructor->getType()->getAs<FunctionProtoType>();
2890   if (CtorType->getNumParams() > 0) {
2891     QualType FirstArg = CtorType->getParamType(0);
2892     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2893       return true;
2894   }
2895   return false;
2896 }
2897 
2898 static OverloadingResult
2899 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2900                                        CXXRecordDecl *To,
2901                                        UserDefinedConversionSequence &User,
2902                                        OverloadCandidateSet &CandidateSet,
2903                                        bool AllowExplicit) {
2904   DeclContext::lookup_result R = S.LookupConstructors(To);
2905   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2906        Con != ConEnd; ++Con) {
2907     NamedDecl *D = *Con;
2908     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2909 
2910     // Find the constructor (which may be a template).
2911     CXXConstructorDecl *Constructor = nullptr;
2912     FunctionTemplateDecl *ConstructorTmpl
2913       = dyn_cast<FunctionTemplateDecl>(D);
2914     if (ConstructorTmpl)
2915       Constructor
2916         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2917     else
2918       Constructor = cast<CXXConstructorDecl>(D);
2919 
2920     bool Usable = !Constructor->isInvalidDecl() &&
2921                   S.isInitListConstructor(Constructor) &&
2922                   (AllowExplicit || !Constructor->isExplicit());
2923     if (Usable) {
2924       // If the first argument is (a reference to) the target type,
2925       // suppress conversions.
2926       bool SuppressUserConversions =
2927           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2928       if (ConstructorTmpl)
2929         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2930                                        /*ExplicitArgs*/ nullptr,
2931                                        From, CandidateSet,
2932                                        SuppressUserConversions);
2933       else
2934         S.AddOverloadCandidate(Constructor, FoundDecl,
2935                                From, CandidateSet,
2936                                SuppressUserConversions);
2937     }
2938   }
2939 
2940   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2941 
2942   OverloadCandidateSet::iterator Best;
2943   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2944   case OR_Success: {
2945     // Record the standard conversion we used and the conversion function.
2946     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2947     QualType ThisType = Constructor->getThisType(S.Context);
2948     // Initializer lists don't have conversions as such.
2949     User.Before.setAsIdentityConversion();
2950     User.HadMultipleCandidates = HadMultipleCandidates;
2951     User.ConversionFunction = Constructor;
2952     User.FoundConversionFunction = Best->FoundDecl;
2953     User.After.setAsIdentityConversion();
2954     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2955     User.After.setAllToTypes(ToType);
2956     return OR_Success;
2957   }
2958 
2959   case OR_No_Viable_Function:
2960     return OR_No_Viable_Function;
2961   case OR_Deleted:
2962     return OR_Deleted;
2963   case OR_Ambiguous:
2964     return OR_Ambiguous;
2965   }
2966 
2967   llvm_unreachable("Invalid OverloadResult!");
2968 }
2969 
2970 /// Determines whether there is a user-defined conversion sequence
2971 /// (C++ [over.ics.user]) that converts expression From to the type
2972 /// ToType. If such a conversion exists, User will contain the
2973 /// user-defined conversion sequence that performs such a conversion
2974 /// and this routine will return true. Otherwise, this routine returns
2975 /// false and User is unspecified.
2976 ///
2977 /// \param AllowExplicit  true if the conversion should consider C++0x
2978 /// "explicit" conversion functions as well as non-explicit conversion
2979 /// functions (C++0x [class.conv.fct]p2).
2980 ///
2981 /// \param AllowObjCConversionOnExplicit true if the conversion should
2982 /// allow an extra Objective-C pointer conversion on uses of explicit
2983 /// constructors. Requires \c AllowExplicit to also be set.
2984 static OverloadingResult
2985 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2986                         UserDefinedConversionSequence &User,
2987                         OverloadCandidateSet &CandidateSet,
2988                         bool AllowExplicit,
2989                         bool AllowObjCConversionOnExplicit) {
2990   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
2991 
2992   // Whether we will only visit constructors.
2993   bool ConstructorsOnly = false;
2994 
2995   // If the type we are conversion to is a class type, enumerate its
2996   // constructors.
2997   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2998     // C++ [over.match.ctor]p1:
2999     //   When objects of class type are direct-initialized (8.5), or
3000     //   copy-initialized from an expression of the same or a
3001     //   derived class type (8.5), overload resolution selects the
3002     //   constructor. [...] For copy-initialization, the candidate
3003     //   functions are all the converting constructors (12.3.1) of
3004     //   that class. The argument list is the expression-list within
3005     //   the parentheses of the initializer.
3006     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3007         (From->getType()->getAs<RecordType>() &&
3008          S.IsDerivedFrom(From->getType(), ToType)))
3009       ConstructorsOnly = true;
3010 
3011     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3012     // RequireCompleteType may have returned true due to some invalid decl
3013     // during template instantiation, but ToType may be complete enough now
3014     // to try to recover.
3015     if (ToType->isIncompleteType()) {
3016       // We're not going to find any constructors.
3017     } else if (CXXRecordDecl *ToRecordDecl
3018                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3019 
3020       Expr **Args = &From;
3021       unsigned NumArgs = 1;
3022       bool ListInitializing = false;
3023       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3024         // But first, see if there is an init-list-constructor that will work.
3025         OverloadingResult Result = IsInitializerListConstructorConversion(
3026             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3027         if (Result != OR_No_Viable_Function)
3028           return Result;
3029         // Never mind.
3030         CandidateSet.clear();
3031 
3032         // If we're list-initializing, we pass the individual elements as
3033         // arguments, not the entire list.
3034         Args = InitList->getInits();
3035         NumArgs = InitList->getNumInits();
3036         ListInitializing = true;
3037       }
3038 
3039       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3040       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3041            Con != ConEnd; ++Con) {
3042         NamedDecl *D = *Con;
3043         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3044 
3045         // Find the constructor (which may be a template).
3046         CXXConstructorDecl *Constructor = nullptr;
3047         FunctionTemplateDecl *ConstructorTmpl
3048           = dyn_cast<FunctionTemplateDecl>(D);
3049         if (ConstructorTmpl)
3050           Constructor
3051             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3052         else
3053           Constructor = cast<CXXConstructorDecl>(D);
3054 
3055         bool Usable = !Constructor->isInvalidDecl();
3056         if (ListInitializing)
3057           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3058         else
3059           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3060         if (Usable) {
3061           bool SuppressUserConversions = !ConstructorsOnly;
3062           if (SuppressUserConversions && ListInitializing) {
3063             SuppressUserConversions = false;
3064             if (NumArgs == 1) {
3065               // If the first argument is (a reference to) the target type,
3066               // suppress conversions.
3067               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3068                                                 S.Context, Constructor, ToType);
3069             }
3070           }
3071           if (ConstructorTmpl)
3072             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3073                                            /*ExplicitArgs*/ nullptr,
3074                                            llvm::makeArrayRef(Args, NumArgs),
3075                                            CandidateSet, SuppressUserConversions);
3076           else
3077             // Allow one user-defined conversion when user specifies a
3078             // From->ToType conversion via an static cast (c-style, etc).
3079             S.AddOverloadCandidate(Constructor, FoundDecl,
3080                                    llvm::makeArrayRef(Args, NumArgs),
3081                                    CandidateSet, SuppressUserConversions);
3082         }
3083       }
3084     }
3085   }
3086 
3087   // Enumerate conversion functions, if we're allowed to.
3088   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3089   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3090     // No conversion functions from incomplete types.
3091   } else if (const RecordType *FromRecordType
3092                                    = From->getType()->getAs<RecordType>()) {
3093     if (CXXRecordDecl *FromRecordDecl
3094          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3095       // Add all of the conversion functions as candidates.
3096       std::pair<CXXRecordDecl::conversion_iterator,
3097                 CXXRecordDecl::conversion_iterator>
3098         Conversions = FromRecordDecl->getVisibleConversionFunctions();
3099       for (CXXRecordDecl::conversion_iterator
3100              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3101         DeclAccessPair FoundDecl = I.getPair();
3102         NamedDecl *D = FoundDecl.getDecl();
3103         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3104         if (isa<UsingShadowDecl>(D))
3105           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3106 
3107         CXXConversionDecl *Conv;
3108         FunctionTemplateDecl *ConvTemplate;
3109         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3110           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3111         else
3112           Conv = cast<CXXConversionDecl>(D);
3113 
3114         if (AllowExplicit || !Conv->isExplicit()) {
3115           if (ConvTemplate)
3116             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3117                                              ActingContext, From, ToType,
3118                                              CandidateSet,
3119                                              AllowObjCConversionOnExplicit);
3120           else
3121             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3122                                      From, ToType, CandidateSet,
3123                                      AllowObjCConversionOnExplicit);
3124         }
3125       }
3126     }
3127   }
3128 
3129   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3130 
3131   OverloadCandidateSet::iterator Best;
3132   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3133   case OR_Success:
3134     // Record the standard conversion we used and the conversion function.
3135     if (CXXConstructorDecl *Constructor
3136           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3137       // C++ [over.ics.user]p1:
3138       //   If the user-defined conversion is specified by a
3139       //   constructor (12.3.1), the initial standard conversion
3140       //   sequence converts the source type to the type required by
3141       //   the argument of the constructor.
3142       //
3143       QualType ThisType = Constructor->getThisType(S.Context);
3144       if (isa<InitListExpr>(From)) {
3145         // Initializer lists don't have conversions as such.
3146         User.Before.setAsIdentityConversion();
3147       } else {
3148         if (Best->Conversions[0].isEllipsis())
3149           User.EllipsisConversion = true;
3150         else {
3151           User.Before = Best->Conversions[0].Standard;
3152           User.EllipsisConversion = false;
3153         }
3154       }
3155       User.HadMultipleCandidates = HadMultipleCandidates;
3156       User.ConversionFunction = Constructor;
3157       User.FoundConversionFunction = Best->FoundDecl;
3158       User.After.setAsIdentityConversion();
3159       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3160       User.After.setAllToTypes(ToType);
3161       return OR_Success;
3162     }
3163     if (CXXConversionDecl *Conversion
3164                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3165       // C++ [over.ics.user]p1:
3166       //
3167       //   [...] If the user-defined conversion is specified by a
3168       //   conversion function (12.3.2), the initial standard
3169       //   conversion sequence converts the source type to the
3170       //   implicit object parameter of the conversion function.
3171       User.Before = Best->Conversions[0].Standard;
3172       User.HadMultipleCandidates = HadMultipleCandidates;
3173       User.ConversionFunction = Conversion;
3174       User.FoundConversionFunction = Best->FoundDecl;
3175       User.EllipsisConversion = false;
3176 
3177       // C++ [over.ics.user]p2:
3178       //   The second standard conversion sequence converts the
3179       //   result of the user-defined conversion to the target type
3180       //   for the sequence. Since an implicit conversion sequence
3181       //   is an initialization, the special rules for
3182       //   initialization by user-defined conversion apply when
3183       //   selecting the best user-defined conversion for a
3184       //   user-defined conversion sequence (see 13.3.3 and
3185       //   13.3.3.1).
3186       User.After = Best->FinalConversion;
3187       return OR_Success;
3188     }
3189     llvm_unreachable("Not a constructor or conversion function?");
3190 
3191   case OR_No_Viable_Function:
3192     return OR_No_Viable_Function;
3193   case OR_Deleted:
3194     // No conversion here! We're done.
3195     return OR_Deleted;
3196 
3197   case OR_Ambiguous:
3198     return OR_Ambiguous;
3199   }
3200 
3201   llvm_unreachable("Invalid OverloadResult!");
3202 }
3203 
3204 bool
3205 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3206   ImplicitConversionSequence ICS;
3207   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3208                                     OverloadCandidateSet::CSK_Normal);
3209   OverloadingResult OvResult =
3210     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3211                             CandidateSet, false, false);
3212   if (OvResult == OR_Ambiguous)
3213     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3214         << From->getType() << ToType << From->getSourceRange();
3215   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3216     if (!RequireCompleteType(From->getLocStart(), ToType,
3217                              diag::err_typecheck_nonviable_condition_incomplete,
3218                              From->getType(), From->getSourceRange()))
3219       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3220           << From->getType() << From->getSourceRange() << ToType;
3221   } else
3222     return false;
3223   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3224   return true;
3225 }
3226 
3227 /// \brief Compare the user-defined conversion functions or constructors
3228 /// of two user-defined conversion sequences to determine whether any ordering
3229 /// is possible.
3230 static ImplicitConversionSequence::CompareKind
3231 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3232                            FunctionDecl *Function2) {
3233   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3234     return ImplicitConversionSequence::Indistinguishable;
3235 
3236   // Objective-C++:
3237   //   If both conversion functions are implicitly-declared conversions from
3238   //   a lambda closure type to a function pointer and a block pointer,
3239   //   respectively, always prefer the conversion to a function pointer,
3240   //   because the function pointer is more lightweight and is more likely
3241   //   to keep code working.
3242   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3243   if (!Conv1)
3244     return ImplicitConversionSequence::Indistinguishable;
3245 
3246   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247   if (!Conv2)
3248     return ImplicitConversionSequence::Indistinguishable;
3249 
3250   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253     if (Block1 != Block2)
3254       return Block1 ? ImplicitConversionSequence::Worse
3255                     : ImplicitConversionSequence::Better;
3256   }
3257 
3258   return ImplicitConversionSequence::Indistinguishable;
3259 }
3260 
3261 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3262     const ImplicitConversionSequence &ICS) {
3263   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3264          (ICS.isUserDefined() &&
3265           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3266 }
3267 
3268 /// CompareImplicitConversionSequences - Compare two implicit
3269 /// conversion sequences to determine whether one is better than the
3270 /// other or if they are indistinguishable (C++ 13.3.3.2).
3271 static ImplicitConversionSequence::CompareKind
3272 CompareImplicitConversionSequences(Sema &S,
3273                                    const ImplicitConversionSequence& ICS1,
3274                                    const ImplicitConversionSequence& ICS2)
3275 {
3276   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3277   // conversion sequences (as defined in 13.3.3.1)
3278   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3279   //      conversion sequence than a user-defined conversion sequence or
3280   //      an ellipsis conversion sequence, and
3281   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3282   //      conversion sequence than an ellipsis conversion sequence
3283   //      (13.3.3.1.3).
3284   //
3285   // C++0x [over.best.ics]p10:
3286   //   For the purpose of ranking implicit conversion sequences as
3287   //   described in 13.3.3.2, the ambiguous conversion sequence is
3288   //   treated as a user-defined sequence that is indistinguishable
3289   //   from any other user-defined conversion sequence.
3290 
3291   // String literal to 'char *' conversion has been deprecated in C++03. It has
3292   // been removed from C++11. We still accept this conversion, if it happens at
3293   // the best viable function. Otherwise, this conversion is considered worse
3294   // than ellipsis conversion. Consider this as an extension; this is not in the
3295   // standard. For example:
3296   //
3297   // int &f(...);    // #1
3298   // void f(char*);  // #2
3299   // void g() { int &r = f("foo"); }
3300   //
3301   // In C++03, we pick #2 as the best viable function.
3302   // In C++11, we pick #1 as the best viable function, because ellipsis
3303   // conversion is better than string-literal to char* conversion (since there
3304   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3305   // convert arguments, #2 would be the best viable function in C++11.
3306   // If the best viable function has this conversion, a warning will be issued
3307   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3308 
3309   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3310       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3311       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3312     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3313                ? ImplicitConversionSequence::Worse
3314                : ImplicitConversionSequence::Better;
3315 
3316   if (ICS1.getKindRank() < ICS2.getKindRank())
3317     return ImplicitConversionSequence::Better;
3318   if (ICS2.getKindRank() < ICS1.getKindRank())
3319     return ImplicitConversionSequence::Worse;
3320 
3321   // The following checks require both conversion sequences to be of
3322   // the same kind.
3323   if (ICS1.getKind() != ICS2.getKind())
3324     return ImplicitConversionSequence::Indistinguishable;
3325 
3326   ImplicitConversionSequence::CompareKind Result =
3327       ImplicitConversionSequence::Indistinguishable;
3328 
3329   // Two implicit conversion sequences of the same form are
3330   // indistinguishable conversion sequences unless one of the
3331   // following rules apply: (C++ 13.3.3.2p3):
3332   if (ICS1.isStandard())
3333     Result = CompareStandardConversionSequences(S,
3334                                                 ICS1.Standard, ICS2.Standard);
3335   else if (ICS1.isUserDefined()) {
3336     // User-defined conversion sequence U1 is a better conversion
3337     // sequence than another user-defined conversion sequence U2 if
3338     // they contain the same user-defined conversion function or
3339     // constructor and if the second standard conversion sequence of
3340     // U1 is better than the second standard conversion sequence of
3341     // U2 (C++ 13.3.3.2p3).
3342     if (ICS1.UserDefined.ConversionFunction ==
3343           ICS2.UserDefined.ConversionFunction)
3344       Result = CompareStandardConversionSequences(S,
3345                                                   ICS1.UserDefined.After,
3346                                                   ICS2.UserDefined.After);
3347     else
3348       Result = compareConversionFunctions(S,
3349                                           ICS1.UserDefined.ConversionFunction,
3350                                           ICS2.UserDefined.ConversionFunction);
3351   }
3352 
3353   // List-initialization sequence L1 is a better conversion sequence than
3354   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3355   // for some X and L2 does not.
3356   if (Result == ImplicitConversionSequence::Indistinguishable &&
3357       !ICS1.isBad()) {
3358     if (ICS1.isStdInitializerListElement() &&
3359         !ICS2.isStdInitializerListElement())
3360       return ImplicitConversionSequence::Better;
3361     if (!ICS1.isStdInitializerListElement() &&
3362         ICS2.isStdInitializerListElement())
3363       return ImplicitConversionSequence::Worse;
3364   }
3365 
3366   return Result;
3367 }
3368 
3369 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3370   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3371     Qualifiers Quals;
3372     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3373     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3374   }
3375 
3376   return Context.hasSameUnqualifiedType(T1, T2);
3377 }
3378 
3379 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3380 // determine if one is a proper subset of the other.
3381 static ImplicitConversionSequence::CompareKind
3382 compareStandardConversionSubsets(ASTContext &Context,
3383                                  const StandardConversionSequence& SCS1,
3384                                  const StandardConversionSequence& SCS2) {
3385   ImplicitConversionSequence::CompareKind Result
3386     = ImplicitConversionSequence::Indistinguishable;
3387 
3388   // the identity conversion sequence is considered to be a subsequence of
3389   // any non-identity conversion sequence
3390   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3391     return ImplicitConversionSequence::Better;
3392   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3393     return ImplicitConversionSequence::Worse;
3394 
3395   if (SCS1.Second != SCS2.Second) {
3396     if (SCS1.Second == ICK_Identity)
3397       Result = ImplicitConversionSequence::Better;
3398     else if (SCS2.Second == ICK_Identity)
3399       Result = ImplicitConversionSequence::Worse;
3400     else
3401       return ImplicitConversionSequence::Indistinguishable;
3402   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3403     return ImplicitConversionSequence::Indistinguishable;
3404 
3405   if (SCS1.Third == SCS2.Third) {
3406     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3407                              : ImplicitConversionSequence::Indistinguishable;
3408   }
3409 
3410   if (SCS1.Third == ICK_Identity)
3411     return Result == ImplicitConversionSequence::Worse
3412              ? ImplicitConversionSequence::Indistinguishable
3413              : ImplicitConversionSequence::Better;
3414 
3415   if (SCS2.Third == ICK_Identity)
3416     return Result == ImplicitConversionSequence::Better
3417              ? ImplicitConversionSequence::Indistinguishable
3418              : ImplicitConversionSequence::Worse;
3419 
3420   return ImplicitConversionSequence::Indistinguishable;
3421 }
3422 
3423 /// \brief Determine whether one of the given reference bindings is better
3424 /// than the other based on what kind of bindings they are.
3425 static bool
3426 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3427                              const StandardConversionSequence &SCS2) {
3428   // C++0x [over.ics.rank]p3b4:
3429   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3430   //      implicit object parameter of a non-static member function declared
3431   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3432   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3433   //      lvalue reference to a function lvalue and S2 binds an rvalue
3434   //      reference*.
3435   //
3436   // FIXME: Rvalue references. We're going rogue with the above edits,
3437   // because the semantics in the current C++0x working paper (N3225 at the
3438   // time of this writing) break the standard definition of std::forward
3439   // and std::reference_wrapper when dealing with references to functions.
3440   // Proposed wording changes submitted to CWG for consideration.
3441   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3442       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3443     return false;
3444 
3445   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3446           SCS2.IsLvalueReference) ||
3447          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3448           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3449 }
3450 
3451 /// CompareStandardConversionSequences - Compare two standard
3452 /// conversion sequences to determine whether one is better than the
3453 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3454 static ImplicitConversionSequence::CompareKind
3455 CompareStandardConversionSequences(Sema &S,
3456                                    const StandardConversionSequence& SCS1,
3457                                    const StandardConversionSequence& SCS2)
3458 {
3459   // Standard conversion sequence S1 is a better conversion sequence
3460   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3461 
3462   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3463   //     sequences in the canonical form defined by 13.3.3.1.1,
3464   //     excluding any Lvalue Transformation; the identity conversion
3465   //     sequence is considered to be a subsequence of any
3466   //     non-identity conversion sequence) or, if not that,
3467   if (ImplicitConversionSequence::CompareKind CK
3468         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3469     return CK;
3470 
3471   //  -- the rank of S1 is better than the rank of S2 (by the rules
3472   //     defined below), or, if not that,
3473   ImplicitConversionRank Rank1 = SCS1.getRank();
3474   ImplicitConversionRank Rank2 = SCS2.getRank();
3475   if (Rank1 < Rank2)
3476     return ImplicitConversionSequence::Better;
3477   else if (Rank2 < Rank1)
3478     return ImplicitConversionSequence::Worse;
3479 
3480   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3481   // are indistinguishable unless one of the following rules
3482   // applies:
3483 
3484   //   A conversion that is not a conversion of a pointer, or
3485   //   pointer to member, to bool is better than another conversion
3486   //   that is such a conversion.
3487   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3488     return SCS2.isPointerConversionToBool()
3489              ? ImplicitConversionSequence::Better
3490              : ImplicitConversionSequence::Worse;
3491 
3492   // C++ [over.ics.rank]p4b2:
3493   //
3494   //   If class B is derived directly or indirectly from class A,
3495   //   conversion of B* to A* is better than conversion of B* to
3496   //   void*, and conversion of A* to void* is better than conversion
3497   //   of B* to void*.
3498   bool SCS1ConvertsToVoid
3499     = SCS1.isPointerConversionToVoidPointer(S.Context);
3500   bool SCS2ConvertsToVoid
3501     = SCS2.isPointerConversionToVoidPointer(S.Context);
3502   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3503     // Exactly one of the conversion sequences is a conversion to
3504     // a void pointer; it's the worse conversion.
3505     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3506                               : ImplicitConversionSequence::Worse;
3507   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3508     // Neither conversion sequence converts to a void pointer; compare
3509     // their derived-to-base conversions.
3510     if (ImplicitConversionSequence::CompareKind DerivedCK
3511           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3512       return DerivedCK;
3513   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3514              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3515     // Both conversion sequences are conversions to void
3516     // pointers. Compare the source types to determine if there's an
3517     // inheritance relationship in their sources.
3518     QualType FromType1 = SCS1.getFromType();
3519     QualType FromType2 = SCS2.getFromType();
3520 
3521     // Adjust the types we're converting from via the array-to-pointer
3522     // conversion, if we need to.
3523     if (SCS1.First == ICK_Array_To_Pointer)
3524       FromType1 = S.Context.getArrayDecayedType(FromType1);
3525     if (SCS2.First == ICK_Array_To_Pointer)
3526       FromType2 = S.Context.getArrayDecayedType(FromType2);
3527 
3528     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3529     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3530 
3531     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3532       return ImplicitConversionSequence::Better;
3533     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3534       return ImplicitConversionSequence::Worse;
3535 
3536     // Objective-C++: If one interface is more specific than the
3537     // other, it is the better one.
3538     const ObjCObjectPointerType* FromObjCPtr1
3539       = FromType1->getAs<ObjCObjectPointerType>();
3540     const ObjCObjectPointerType* FromObjCPtr2
3541       = FromType2->getAs<ObjCObjectPointerType>();
3542     if (FromObjCPtr1 && FromObjCPtr2) {
3543       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3544                                                           FromObjCPtr2);
3545       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3546                                                            FromObjCPtr1);
3547       if (AssignLeft != AssignRight) {
3548         return AssignLeft? ImplicitConversionSequence::Better
3549                          : ImplicitConversionSequence::Worse;
3550       }
3551     }
3552   }
3553 
3554   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3555   // bullet 3).
3556   if (ImplicitConversionSequence::CompareKind QualCK
3557         = CompareQualificationConversions(S, SCS1, SCS2))
3558     return QualCK;
3559 
3560   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3561     // Check for a better reference binding based on the kind of bindings.
3562     if (isBetterReferenceBindingKind(SCS1, SCS2))
3563       return ImplicitConversionSequence::Better;
3564     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3565       return ImplicitConversionSequence::Worse;
3566 
3567     // C++ [over.ics.rank]p3b4:
3568     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3569     //      which the references refer are the same type except for
3570     //      top-level cv-qualifiers, and the type to which the reference
3571     //      initialized by S2 refers is more cv-qualified than the type
3572     //      to which the reference initialized by S1 refers.
3573     QualType T1 = SCS1.getToType(2);
3574     QualType T2 = SCS2.getToType(2);
3575     T1 = S.Context.getCanonicalType(T1);
3576     T2 = S.Context.getCanonicalType(T2);
3577     Qualifiers T1Quals, T2Quals;
3578     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3579     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3580     if (UnqualT1 == UnqualT2) {
3581       // Objective-C++ ARC: If the references refer to objects with different
3582       // lifetimes, prefer bindings that don't change lifetime.
3583       if (SCS1.ObjCLifetimeConversionBinding !=
3584                                           SCS2.ObjCLifetimeConversionBinding) {
3585         return SCS1.ObjCLifetimeConversionBinding
3586                                            ? ImplicitConversionSequence::Worse
3587                                            : ImplicitConversionSequence::Better;
3588       }
3589 
3590       // If the type is an array type, promote the element qualifiers to the
3591       // type for comparison.
3592       if (isa<ArrayType>(T1) && T1Quals)
3593         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3594       if (isa<ArrayType>(T2) && T2Quals)
3595         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3596       if (T2.isMoreQualifiedThan(T1))
3597         return ImplicitConversionSequence::Better;
3598       else if (T1.isMoreQualifiedThan(T2))
3599         return ImplicitConversionSequence::Worse;
3600     }
3601   }
3602 
3603   // In Microsoft mode, prefer an integral conversion to a
3604   // floating-to-integral conversion if the integral conversion
3605   // is between types of the same size.
3606   // For example:
3607   // void f(float);
3608   // void f(int);
3609   // int main {
3610   //    long a;
3611   //    f(a);
3612   // }
3613   // Here, MSVC will call f(int) instead of generating a compile error
3614   // as clang will do in standard mode.
3615   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3616       SCS2.Second == ICK_Floating_Integral &&
3617       S.Context.getTypeSize(SCS1.getFromType()) ==
3618           S.Context.getTypeSize(SCS1.getToType(2)))
3619     return ImplicitConversionSequence::Better;
3620 
3621   return ImplicitConversionSequence::Indistinguishable;
3622 }
3623 
3624 /// CompareQualificationConversions - Compares two standard conversion
3625 /// sequences to determine whether they can be ranked based on their
3626 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3627 static ImplicitConversionSequence::CompareKind
3628 CompareQualificationConversions(Sema &S,
3629                                 const StandardConversionSequence& SCS1,
3630                                 const StandardConversionSequence& SCS2) {
3631   // C++ 13.3.3.2p3:
3632   //  -- S1 and S2 differ only in their qualification conversion and
3633   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3634   //     cv-qualification signature of type T1 is a proper subset of
3635   //     the cv-qualification signature of type T2, and S1 is not the
3636   //     deprecated string literal array-to-pointer conversion (4.2).
3637   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3638       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3639     return ImplicitConversionSequence::Indistinguishable;
3640 
3641   // FIXME: the example in the standard doesn't use a qualification
3642   // conversion (!)
3643   QualType T1 = SCS1.getToType(2);
3644   QualType T2 = SCS2.getToType(2);
3645   T1 = S.Context.getCanonicalType(T1);
3646   T2 = S.Context.getCanonicalType(T2);
3647   Qualifiers T1Quals, T2Quals;
3648   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3649   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3650 
3651   // If the types are the same, we won't learn anything by unwrapped
3652   // them.
3653   if (UnqualT1 == UnqualT2)
3654     return ImplicitConversionSequence::Indistinguishable;
3655 
3656   // If the type is an array type, promote the element qualifiers to the type
3657   // for comparison.
3658   if (isa<ArrayType>(T1) && T1Quals)
3659     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3660   if (isa<ArrayType>(T2) && T2Quals)
3661     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3662 
3663   ImplicitConversionSequence::CompareKind Result
3664     = ImplicitConversionSequence::Indistinguishable;
3665 
3666   // Objective-C++ ARC:
3667   //   Prefer qualification conversions not involving a change in lifetime
3668   //   to qualification conversions that do not change lifetime.
3669   if (SCS1.QualificationIncludesObjCLifetime !=
3670                                       SCS2.QualificationIncludesObjCLifetime) {
3671     Result = SCS1.QualificationIncludesObjCLifetime
3672                ? ImplicitConversionSequence::Worse
3673                : ImplicitConversionSequence::Better;
3674   }
3675 
3676   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3677     // Within each iteration of the loop, we check the qualifiers to
3678     // determine if this still looks like a qualification
3679     // conversion. Then, if all is well, we unwrap one more level of
3680     // pointers or pointers-to-members and do it all again
3681     // until there are no more pointers or pointers-to-members left
3682     // to unwrap. This essentially mimics what
3683     // IsQualificationConversion does, but here we're checking for a
3684     // strict subset of qualifiers.
3685     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3686       // The qualifiers are the same, so this doesn't tell us anything
3687       // about how the sequences rank.
3688       ;
3689     else if (T2.isMoreQualifiedThan(T1)) {
3690       // T1 has fewer qualifiers, so it could be the better sequence.
3691       if (Result == ImplicitConversionSequence::Worse)
3692         // Neither has qualifiers that are a subset of the other's
3693         // qualifiers.
3694         return ImplicitConversionSequence::Indistinguishable;
3695 
3696       Result = ImplicitConversionSequence::Better;
3697     } else if (T1.isMoreQualifiedThan(T2)) {
3698       // T2 has fewer qualifiers, so it could be the better sequence.
3699       if (Result == ImplicitConversionSequence::Better)
3700         // Neither has qualifiers that are a subset of the other's
3701         // qualifiers.
3702         return ImplicitConversionSequence::Indistinguishable;
3703 
3704       Result = ImplicitConversionSequence::Worse;
3705     } else {
3706       // Qualifiers are disjoint.
3707       return ImplicitConversionSequence::Indistinguishable;
3708     }
3709 
3710     // If the types after this point are equivalent, we're done.
3711     if (S.Context.hasSameUnqualifiedType(T1, T2))
3712       break;
3713   }
3714 
3715   // Check that the winning standard conversion sequence isn't using
3716   // the deprecated string literal array to pointer conversion.
3717   switch (Result) {
3718   case ImplicitConversionSequence::Better:
3719     if (SCS1.DeprecatedStringLiteralToCharPtr)
3720       Result = ImplicitConversionSequence::Indistinguishable;
3721     break;
3722 
3723   case ImplicitConversionSequence::Indistinguishable:
3724     break;
3725 
3726   case ImplicitConversionSequence::Worse:
3727     if (SCS2.DeprecatedStringLiteralToCharPtr)
3728       Result = ImplicitConversionSequence::Indistinguishable;
3729     break;
3730   }
3731 
3732   return Result;
3733 }
3734 
3735 /// CompareDerivedToBaseConversions - Compares two standard conversion
3736 /// sequences to determine whether they can be ranked based on their
3737 /// various kinds of derived-to-base conversions (C++
3738 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3739 /// conversions between Objective-C interface types.
3740 static ImplicitConversionSequence::CompareKind
3741 CompareDerivedToBaseConversions(Sema &S,
3742                                 const StandardConversionSequence& SCS1,
3743                                 const StandardConversionSequence& SCS2) {
3744   QualType FromType1 = SCS1.getFromType();
3745   QualType ToType1 = SCS1.getToType(1);
3746   QualType FromType2 = SCS2.getFromType();
3747   QualType ToType2 = SCS2.getToType(1);
3748 
3749   // Adjust the types we're converting from via the array-to-pointer
3750   // conversion, if we need to.
3751   if (SCS1.First == ICK_Array_To_Pointer)
3752     FromType1 = S.Context.getArrayDecayedType(FromType1);
3753   if (SCS2.First == ICK_Array_To_Pointer)
3754     FromType2 = S.Context.getArrayDecayedType(FromType2);
3755 
3756   // Canonicalize all of the types.
3757   FromType1 = S.Context.getCanonicalType(FromType1);
3758   ToType1 = S.Context.getCanonicalType(ToType1);
3759   FromType2 = S.Context.getCanonicalType(FromType2);
3760   ToType2 = S.Context.getCanonicalType(ToType2);
3761 
3762   // C++ [over.ics.rank]p4b3:
3763   //
3764   //   If class B is derived directly or indirectly from class A and
3765   //   class C is derived directly or indirectly from B,
3766   //
3767   // Compare based on pointer conversions.
3768   if (SCS1.Second == ICK_Pointer_Conversion &&
3769       SCS2.Second == ICK_Pointer_Conversion &&
3770       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3771       FromType1->isPointerType() && FromType2->isPointerType() &&
3772       ToType1->isPointerType() && ToType2->isPointerType()) {
3773     QualType FromPointee1
3774       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3775     QualType ToPointee1
3776       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3777     QualType FromPointee2
3778       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3779     QualType ToPointee2
3780       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781 
3782     //   -- conversion of C* to B* is better than conversion of C* to A*,
3783     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3784       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3785         return ImplicitConversionSequence::Better;
3786       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3787         return ImplicitConversionSequence::Worse;
3788     }
3789 
3790     //   -- conversion of B* to A* is better than conversion of C* to A*,
3791     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3792       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3793         return ImplicitConversionSequence::Better;
3794       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3795         return ImplicitConversionSequence::Worse;
3796     }
3797   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3798              SCS2.Second == ICK_Pointer_Conversion) {
3799     const ObjCObjectPointerType *FromPtr1
3800       = FromType1->getAs<ObjCObjectPointerType>();
3801     const ObjCObjectPointerType *FromPtr2
3802       = FromType2->getAs<ObjCObjectPointerType>();
3803     const ObjCObjectPointerType *ToPtr1
3804       = ToType1->getAs<ObjCObjectPointerType>();
3805     const ObjCObjectPointerType *ToPtr2
3806       = ToType2->getAs<ObjCObjectPointerType>();
3807 
3808     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3809       // Apply the same conversion ranking rules for Objective-C pointer types
3810       // that we do for C++ pointers to class types. However, we employ the
3811       // Objective-C pseudo-subtyping relationship used for assignment of
3812       // Objective-C pointer types.
3813       bool FromAssignLeft
3814         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3815       bool FromAssignRight
3816         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3817       bool ToAssignLeft
3818         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3819       bool ToAssignRight
3820         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3821 
3822       // A conversion to an a non-id object pointer type or qualified 'id'
3823       // type is better than a conversion to 'id'.
3824       if (ToPtr1->isObjCIdType() &&
3825           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3826         return ImplicitConversionSequence::Worse;
3827       if (ToPtr2->isObjCIdType() &&
3828           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3829         return ImplicitConversionSequence::Better;
3830 
3831       // A conversion to a non-id object pointer type is better than a
3832       // conversion to a qualified 'id' type
3833       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3834         return ImplicitConversionSequence::Worse;
3835       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3836         return ImplicitConversionSequence::Better;
3837 
3838       // A conversion to an a non-Class object pointer type or qualified 'Class'
3839       // type is better than a conversion to 'Class'.
3840       if (ToPtr1->isObjCClassType() &&
3841           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3842         return ImplicitConversionSequence::Worse;
3843       if (ToPtr2->isObjCClassType() &&
3844           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3845         return ImplicitConversionSequence::Better;
3846 
3847       // A conversion to a non-Class object pointer type is better than a
3848       // conversion to a qualified 'Class' type.
3849       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3850         return ImplicitConversionSequence::Worse;
3851       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3852         return ImplicitConversionSequence::Better;
3853 
3854       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3855       if (S.Context.hasSameType(FromType1, FromType2) &&
3856           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3857           (ToAssignLeft != ToAssignRight))
3858         return ToAssignLeft? ImplicitConversionSequence::Worse
3859                            : ImplicitConversionSequence::Better;
3860 
3861       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3862       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3863           (FromAssignLeft != FromAssignRight))
3864         return FromAssignLeft? ImplicitConversionSequence::Better
3865         : ImplicitConversionSequence::Worse;
3866     }
3867   }
3868 
3869   // Ranking of member-pointer types.
3870   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3871       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3872       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3873     const MemberPointerType * FromMemPointer1 =
3874                                         FromType1->getAs<MemberPointerType>();
3875     const MemberPointerType * ToMemPointer1 =
3876                                           ToType1->getAs<MemberPointerType>();
3877     const MemberPointerType * FromMemPointer2 =
3878                                           FromType2->getAs<MemberPointerType>();
3879     const MemberPointerType * ToMemPointer2 =
3880                                           ToType2->getAs<MemberPointerType>();
3881     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3882     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3883     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3884     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3885     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3886     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3887     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3888     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3889     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3890     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3891       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3892         return ImplicitConversionSequence::Worse;
3893       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3894         return ImplicitConversionSequence::Better;
3895     }
3896     // conversion of B::* to C::* is better than conversion of A::* to C::*
3897     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3898       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3899         return ImplicitConversionSequence::Better;
3900       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3901         return ImplicitConversionSequence::Worse;
3902     }
3903   }
3904 
3905   if (SCS1.Second == ICK_Derived_To_Base) {
3906     //   -- conversion of C to B is better than conversion of C to A,
3907     //   -- binding of an expression of type C to a reference of type
3908     //      B& is better than binding an expression of type C to a
3909     //      reference of type A&,
3910     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3911         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3912       if (S.IsDerivedFrom(ToType1, ToType2))
3913         return ImplicitConversionSequence::Better;
3914       else if (S.IsDerivedFrom(ToType2, ToType1))
3915         return ImplicitConversionSequence::Worse;
3916     }
3917 
3918     //   -- conversion of B to A is better than conversion of C to A.
3919     //   -- binding of an expression of type B to a reference of type
3920     //      A& is better than binding an expression of type C to a
3921     //      reference of type A&,
3922     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924       if (S.IsDerivedFrom(FromType2, FromType1))
3925         return ImplicitConversionSequence::Better;
3926       else if (S.IsDerivedFrom(FromType1, FromType2))
3927         return ImplicitConversionSequence::Worse;
3928     }
3929   }
3930 
3931   return ImplicitConversionSequence::Indistinguishable;
3932 }
3933 
3934 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3935 /// C++ class.
3936 static bool isTypeValid(QualType T) {
3937   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3938     return !Record->isInvalidDecl();
3939 
3940   return true;
3941 }
3942 
3943 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3944 /// determine whether they are reference-related,
3945 /// reference-compatible, reference-compatible with added
3946 /// qualification, or incompatible, for use in C++ initialization by
3947 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3948 /// type, and the first type (T1) is the pointee type of the reference
3949 /// type being initialized.
3950 Sema::ReferenceCompareResult
3951 Sema::CompareReferenceRelationship(SourceLocation Loc,
3952                                    QualType OrigT1, QualType OrigT2,
3953                                    bool &DerivedToBase,
3954                                    bool &ObjCConversion,
3955                                    bool &ObjCLifetimeConversion) {
3956   assert(!OrigT1->isReferenceType() &&
3957     "T1 must be the pointee type of the reference type");
3958   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3959 
3960   QualType T1 = Context.getCanonicalType(OrigT1);
3961   QualType T2 = Context.getCanonicalType(OrigT2);
3962   Qualifiers T1Quals, T2Quals;
3963   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3964   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3965 
3966   // C++ [dcl.init.ref]p4:
3967   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3968   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3969   //   T1 is a base class of T2.
3970   DerivedToBase = false;
3971   ObjCConversion = false;
3972   ObjCLifetimeConversion = false;
3973   if (UnqualT1 == UnqualT2) {
3974     // Nothing to do.
3975   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3976              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3977              IsDerivedFrom(UnqualT2, UnqualT1))
3978     DerivedToBase = true;
3979   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3980            UnqualT2->isObjCObjectOrInterfaceType() &&
3981            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3982     ObjCConversion = true;
3983   else
3984     return Ref_Incompatible;
3985 
3986   // At this point, we know that T1 and T2 are reference-related (at
3987   // least).
3988 
3989   // If the type is an array type, promote the element qualifiers to the type
3990   // for comparison.
3991   if (isa<ArrayType>(T1) && T1Quals)
3992     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3993   if (isa<ArrayType>(T2) && T2Quals)
3994     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3995 
3996   // C++ [dcl.init.ref]p4:
3997   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3998   //   reference-related to T2 and cv1 is the same cv-qualification
3999   //   as, or greater cv-qualification than, cv2. For purposes of
4000   //   overload resolution, cases for which cv1 is greater
4001   //   cv-qualification than cv2 are identified as
4002   //   reference-compatible with added qualification (see 13.3.3.2).
4003   //
4004   // Note that we also require equivalence of Objective-C GC and address-space
4005   // qualifiers when performing these computations, so that e.g., an int in
4006   // address space 1 is not reference-compatible with an int in address
4007   // space 2.
4008   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4009       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4010     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4011       ObjCLifetimeConversion = true;
4012 
4013     T1Quals.removeObjCLifetime();
4014     T2Quals.removeObjCLifetime();
4015   }
4016 
4017   if (T1Quals == T2Quals)
4018     return Ref_Compatible;
4019   else if (T1Quals.compatiblyIncludes(T2Quals))
4020     return Ref_Compatible_With_Added_Qualification;
4021   else
4022     return Ref_Related;
4023 }
4024 
4025 /// \brief Look for a user-defined conversion to an value reference-compatible
4026 ///        with DeclType. Return true if something definite is found.
4027 static bool
4028 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4029                          QualType DeclType, SourceLocation DeclLoc,
4030                          Expr *Init, QualType T2, bool AllowRvalues,
4031                          bool AllowExplicit) {
4032   assert(T2->isRecordType() && "Can only find conversions of record types.");
4033   CXXRecordDecl *T2RecordDecl
4034     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4035 
4036   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4037   std::pair<CXXRecordDecl::conversion_iterator,
4038             CXXRecordDecl::conversion_iterator>
4039     Conversions = T2RecordDecl->getVisibleConversionFunctions();
4040   for (CXXRecordDecl::conversion_iterator
4041          I = Conversions.first, E = Conversions.second; I != E; ++I) {
4042     NamedDecl *D = *I;
4043     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4044     if (isa<UsingShadowDecl>(D))
4045       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4046 
4047     FunctionTemplateDecl *ConvTemplate
4048       = dyn_cast<FunctionTemplateDecl>(D);
4049     CXXConversionDecl *Conv;
4050     if (ConvTemplate)
4051       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4052     else
4053       Conv = cast<CXXConversionDecl>(D);
4054 
4055     // If this is an explicit conversion, and we're not allowed to consider
4056     // explicit conversions, skip it.
4057     if (!AllowExplicit && Conv->isExplicit())
4058       continue;
4059 
4060     if (AllowRvalues) {
4061       bool DerivedToBase = false;
4062       bool ObjCConversion = false;
4063       bool ObjCLifetimeConversion = false;
4064 
4065       // If we are initializing an rvalue reference, don't permit conversion
4066       // functions that return lvalues.
4067       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4068         const ReferenceType *RefType
4069           = Conv->getConversionType()->getAs<LValueReferenceType>();
4070         if (RefType && !RefType->getPointeeType()->isFunctionType())
4071           continue;
4072       }
4073 
4074       if (!ConvTemplate &&
4075           S.CompareReferenceRelationship(
4076             DeclLoc,
4077             Conv->getConversionType().getNonReferenceType()
4078               .getUnqualifiedType(),
4079             DeclType.getNonReferenceType().getUnqualifiedType(),
4080             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4081           Sema::Ref_Incompatible)
4082         continue;
4083     } else {
4084       // If the conversion function doesn't return a reference type,
4085       // it can't be considered for this conversion. An rvalue reference
4086       // is only acceptable if its referencee is a function type.
4087 
4088       const ReferenceType *RefType =
4089         Conv->getConversionType()->getAs<ReferenceType>();
4090       if (!RefType ||
4091           (!RefType->isLValueReferenceType() &&
4092            !RefType->getPointeeType()->isFunctionType()))
4093         continue;
4094     }
4095 
4096     if (ConvTemplate)
4097       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4098                                        Init, DeclType, CandidateSet,
4099                                        /*AllowObjCConversionOnExplicit=*/false);
4100     else
4101       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4102                                DeclType, CandidateSet,
4103                                /*AllowObjCConversionOnExplicit=*/false);
4104   }
4105 
4106   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4107 
4108   OverloadCandidateSet::iterator Best;
4109   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4110   case OR_Success:
4111     // C++ [over.ics.ref]p1:
4112     //
4113     //   [...] If the parameter binds directly to the result of
4114     //   applying a conversion function to the argument
4115     //   expression, the implicit conversion sequence is a
4116     //   user-defined conversion sequence (13.3.3.1.2), with the
4117     //   second standard conversion sequence either an identity
4118     //   conversion or, if the conversion function returns an
4119     //   entity of a type that is a derived class of the parameter
4120     //   type, a derived-to-base Conversion.
4121     if (!Best->FinalConversion.DirectBinding)
4122       return false;
4123 
4124     ICS.setUserDefined();
4125     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4126     ICS.UserDefined.After = Best->FinalConversion;
4127     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4128     ICS.UserDefined.ConversionFunction = Best->Function;
4129     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4130     ICS.UserDefined.EllipsisConversion = false;
4131     assert(ICS.UserDefined.After.ReferenceBinding &&
4132            ICS.UserDefined.After.DirectBinding &&
4133            "Expected a direct reference binding!");
4134     return true;
4135 
4136   case OR_Ambiguous:
4137     ICS.setAmbiguous();
4138     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4139          Cand != CandidateSet.end(); ++Cand)
4140       if (Cand->Viable)
4141         ICS.Ambiguous.addConversion(Cand->Function);
4142     return true;
4143 
4144   case OR_No_Viable_Function:
4145   case OR_Deleted:
4146     // There was no suitable conversion, or we found a deleted
4147     // conversion; continue with other checks.
4148     return false;
4149   }
4150 
4151   llvm_unreachable("Invalid OverloadResult!");
4152 }
4153 
4154 /// \brief Compute an implicit conversion sequence for reference
4155 /// initialization.
4156 static ImplicitConversionSequence
4157 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4158                  SourceLocation DeclLoc,
4159                  bool SuppressUserConversions,
4160                  bool AllowExplicit) {
4161   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4162 
4163   // Most paths end in a failed conversion.
4164   ImplicitConversionSequence ICS;
4165   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4166 
4167   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4168   QualType T2 = Init->getType();
4169 
4170   // If the initializer is the address of an overloaded function, try
4171   // to resolve the overloaded function. If all goes well, T2 is the
4172   // type of the resulting function.
4173   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4174     DeclAccessPair Found;
4175     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4176                                                                 false, Found))
4177       T2 = Fn->getType();
4178   }
4179 
4180   // Compute some basic properties of the types and the initializer.
4181   bool isRValRef = DeclType->isRValueReferenceType();
4182   bool DerivedToBase = false;
4183   bool ObjCConversion = false;
4184   bool ObjCLifetimeConversion = false;
4185   Expr::Classification InitCategory = Init->Classify(S.Context);
4186   Sema::ReferenceCompareResult RefRelationship
4187     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4188                                      ObjCConversion, ObjCLifetimeConversion);
4189 
4190 
4191   // C++0x [dcl.init.ref]p5:
4192   //   A reference to type "cv1 T1" is initialized by an expression
4193   //   of type "cv2 T2" as follows:
4194 
4195   //     -- If reference is an lvalue reference and the initializer expression
4196   if (!isRValRef) {
4197     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4198     //        reference-compatible with "cv2 T2," or
4199     //
4200     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4201     if (InitCategory.isLValue() &&
4202         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4203       // C++ [over.ics.ref]p1:
4204       //   When a parameter of reference type binds directly (8.5.3)
4205       //   to an argument expression, the implicit conversion sequence
4206       //   is the identity conversion, unless the argument expression
4207       //   has a type that is a derived class of the parameter type,
4208       //   in which case the implicit conversion sequence is a
4209       //   derived-to-base Conversion (13.3.3.1).
4210       ICS.setStandard();
4211       ICS.Standard.First = ICK_Identity;
4212       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4213                          : ObjCConversion? ICK_Compatible_Conversion
4214                          : ICK_Identity;
4215       ICS.Standard.Third = ICK_Identity;
4216       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4217       ICS.Standard.setToType(0, T2);
4218       ICS.Standard.setToType(1, T1);
4219       ICS.Standard.setToType(2, T1);
4220       ICS.Standard.ReferenceBinding = true;
4221       ICS.Standard.DirectBinding = true;
4222       ICS.Standard.IsLvalueReference = !isRValRef;
4223       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4224       ICS.Standard.BindsToRvalue = false;
4225       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4226       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4227       ICS.Standard.CopyConstructor = nullptr;
4228       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4229 
4230       // Nothing more to do: the inaccessibility/ambiguity check for
4231       // derived-to-base conversions is suppressed when we're
4232       // computing the implicit conversion sequence (C++
4233       // [over.best.ics]p2).
4234       return ICS;
4235     }
4236 
4237     //       -- has a class type (i.e., T2 is a class type), where T1 is
4238     //          not reference-related to T2, and can be implicitly
4239     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4240     //          is reference-compatible with "cv3 T3" 92) (this
4241     //          conversion is selected by enumerating the applicable
4242     //          conversion functions (13.3.1.6) and choosing the best
4243     //          one through overload resolution (13.3)),
4244     if (!SuppressUserConversions && T2->isRecordType() &&
4245         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4246         RefRelationship == Sema::Ref_Incompatible) {
4247       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4248                                    Init, T2, /*AllowRvalues=*/false,
4249                                    AllowExplicit))
4250         return ICS;
4251     }
4252   }
4253 
4254   //     -- Otherwise, the reference shall be an lvalue reference to a
4255   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4256   //        shall be an rvalue reference.
4257   //
4258   // We actually handle one oddity of C++ [over.ics.ref] at this
4259   // point, which is that, due to p2 (which short-circuits reference
4260   // binding by only attempting a simple conversion for non-direct
4261   // bindings) and p3's strange wording, we allow a const volatile
4262   // reference to bind to an rvalue. Hence the check for the presence
4263   // of "const" rather than checking for "const" being the only
4264   // qualifier.
4265   // This is also the point where rvalue references and lvalue inits no longer
4266   // go together.
4267   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4268     return ICS;
4269 
4270   //       -- If the initializer expression
4271   //
4272   //            -- is an xvalue, class prvalue, array prvalue or function
4273   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4274   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4275       (InitCategory.isXValue() ||
4276       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4277       (InitCategory.isLValue() && T2->isFunctionType()))) {
4278     ICS.setStandard();
4279     ICS.Standard.First = ICK_Identity;
4280     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4281                       : ObjCConversion? ICK_Compatible_Conversion
4282                       : ICK_Identity;
4283     ICS.Standard.Third = ICK_Identity;
4284     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4285     ICS.Standard.setToType(0, T2);
4286     ICS.Standard.setToType(1, T1);
4287     ICS.Standard.setToType(2, T1);
4288     ICS.Standard.ReferenceBinding = true;
4289     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4290     // binding unless we're binding to a class prvalue.
4291     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4292     // allow the use of rvalue references in C++98/03 for the benefit of
4293     // standard library implementors; therefore, we need the xvalue check here.
4294     ICS.Standard.DirectBinding =
4295       S.getLangOpts().CPlusPlus11 ||
4296       !(InitCategory.isPRValue() || T2->isRecordType());
4297     ICS.Standard.IsLvalueReference = !isRValRef;
4298     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4299     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4300     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4301     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4302     ICS.Standard.CopyConstructor = nullptr;
4303     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4304     return ICS;
4305   }
4306 
4307   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4308   //               reference-related to T2, and can be implicitly converted to
4309   //               an xvalue, class prvalue, or function lvalue of type
4310   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4311   //               "cv3 T3",
4312   //
4313   //          then the reference is bound to the value of the initializer
4314   //          expression in the first case and to the result of the conversion
4315   //          in the second case (or, in either case, to an appropriate base
4316   //          class subobject).
4317   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4318       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4319       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320                                Init, T2, /*AllowRvalues=*/true,
4321                                AllowExplicit)) {
4322     // In the second case, if the reference is an rvalue reference
4323     // and the second standard conversion sequence of the
4324     // user-defined conversion sequence includes an lvalue-to-rvalue
4325     // conversion, the program is ill-formed.
4326     if (ICS.isUserDefined() && isRValRef &&
4327         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329 
4330     return ICS;
4331   }
4332 
4333   // A temporary of function type cannot be created; don't even try.
4334   if (T1->isFunctionType())
4335     return ICS;
4336 
4337   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4338   //          initialized from the initializer expression using the
4339   //          rules for a non-reference copy initialization (8.5). The
4340   //          reference is then bound to the temporary. If T1 is
4341   //          reference-related to T2, cv1 must be the same
4342   //          cv-qualification as, or greater cv-qualification than,
4343   //          cv2; otherwise, the program is ill-formed.
4344   if (RefRelationship == Sema::Ref_Related) {
4345     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4346     // we would be reference-compatible or reference-compatible with
4347     // added qualification. But that wasn't the case, so the reference
4348     // initialization fails.
4349     //
4350     // Note that we only want to check address spaces and cvr-qualifiers here.
4351     // ObjC GC and lifetime qualifiers aren't important.
4352     Qualifiers T1Quals = T1.getQualifiers();
4353     Qualifiers T2Quals = T2.getQualifiers();
4354     T1Quals.removeObjCGCAttr();
4355     T1Quals.removeObjCLifetime();
4356     T2Quals.removeObjCGCAttr();
4357     T2Quals.removeObjCLifetime();
4358     if (!T1Quals.compatiblyIncludes(T2Quals))
4359       return ICS;
4360   }
4361 
4362   // If at least one of the types is a class type, the types are not
4363   // related, and we aren't allowed any user conversions, the
4364   // reference binding fails. This case is important for breaking
4365   // recursion, since TryImplicitConversion below will attempt to
4366   // create a temporary through the use of a copy constructor.
4367   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4368       (T1->isRecordType() || T2->isRecordType()))
4369     return ICS;
4370 
4371   // If T1 is reference-related to T2 and the reference is an rvalue
4372   // reference, the initializer expression shall not be an lvalue.
4373   if (RefRelationship >= Sema::Ref_Related &&
4374       isRValRef && Init->Classify(S.Context).isLValue())
4375     return ICS;
4376 
4377   // C++ [over.ics.ref]p2:
4378   //   When a parameter of reference type is not bound directly to
4379   //   an argument expression, the conversion sequence is the one
4380   //   required to convert the argument expression to the
4381   //   underlying type of the reference according to
4382   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4383   //   to copy-initializing a temporary of the underlying type with
4384   //   the argument expression. Any difference in top-level
4385   //   cv-qualification is subsumed by the initialization itself
4386   //   and does not constitute a conversion.
4387   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4388                               /*AllowExplicit=*/false,
4389                               /*InOverloadResolution=*/false,
4390                               /*CStyle=*/false,
4391                               /*AllowObjCWritebackConversion=*/false,
4392                               /*AllowObjCConversionOnExplicit=*/false);
4393 
4394   // Of course, that's still a reference binding.
4395   if (ICS.isStandard()) {
4396     ICS.Standard.ReferenceBinding = true;
4397     ICS.Standard.IsLvalueReference = !isRValRef;
4398     ICS.Standard.BindsToFunctionLvalue = false;
4399     ICS.Standard.BindsToRvalue = true;
4400     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4401     ICS.Standard.ObjCLifetimeConversionBinding = false;
4402   } else if (ICS.isUserDefined()) {
4403     const ReferenceType *LValRefType =
4404         ICS.UserDefined.ConversionFunction->getReturnType()
4405             ->getAs<LValueReferenceType>();
4406 
4407     // C++ [over.ics.ref]p3:
4408     //   Except for an implicit object parameter, for which see 13.3.1, a
4409     //   standard conversion sequence cannot be formed if it requires [...]
4410     //   binding an rvalue reference to an lvalue other than a function
4411     //   lvalue.
4412     // Note that the function case is not possible here.
4413     if (DeclType->isRValueReferenceType() && LValRefType) {
4414       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4415       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4416       // reference to an rvalue!
4417       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4418       return ICS;
4419     }
4420 
4421     ICS.UserDefined.Before.setAsIdentityConversion();
4422     ICS.UserDefined.After.ReferenceBinding = true;
4423     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4424     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4425     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4426     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4427     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4428   }
4429 
4430   return ICS;
4431 }
4432 
4433 static ImplicitConversionSequence
4434 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4435                       bool SuppressUserConversions,
4436                       bool InOverloadResolution,
4437                       bool AllowObjCWritebackConversion,
4438                       bool AllowExplicit = false);
4439 
4440 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4441 /// initializer list From.
4442 static ImplicitConversionSequence
4443 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4444                   bool SuppressUserConversions,
4445                   bool InOverloadResolution,
4446                   bool AllowObjCWritebackConversion) {
4447   // C++11 [over.ics.list]p1:
4448   //   When an argument is an initializer list, it is not an expression and
4449   //   special rules apply for converting it to a parameter type.
4450 
4451   ImplicitConversionSequence Result;
4452   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4453 
4454   // We need a complete type for what follows. Incomplete types can never be
4455   // initialized from init lists.
4456   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4457     return Result;
4458 
4459   // C++11 [over.ics.list]p2:
4460   //   If the parameter type is std::initializer_list<X> or "array of X" and
4461   //   all the elements can be implicitly converted to X, the implicit
4462   //   conversion sequence is the worst conversion necessary to convert an
4463   //   element of the list to X.
4464   bool toStdInitializerList = false;
4465   QualType X;
4466   if (ToType->isArrayType())
4467     X = S.Context.getAsArrayType(ToType)->getElementType();
4468   else
4469     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4470   if (!X.isNull()) {
4471     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4472       Expr *Init = From->getInit(i);
4473       ImplicitConversionSequence ICS =
4474           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4475                                 InOverloadResolution,
4476                                 AllowObjCWritebackConversion);
4477       // If a single element isn't convertible, fail.
4478       if (ICS.isBad()) {
4479         Result = ICS;
4480         break;
4481       }
4482       // Otherwise, look for the worst conversion.
4483       if (Result.isBad() ||
4484           CompareImplicitConversionSequences(S, ICS, Result) ==
4485               ImplicitConversionSequence::Worse)
4486         Result = ICS;
4487     }
4488 
4489     // For an empty list, we won't have computed any conversion sequence.
4490     // Introduce the identity conversion sequence.
4491     if (From->getNumInits() == 0) {
4492       Result.setStandard();
4493       Result.Standard.setAsIdentityConversion();
4494       Result.Standard.setFromType(ToType);
4495       Result.Standard.setAllToTypes(ToType);
4496     }
4497 
4498     Result.setStdInitializerListElement(toStdInitializerList);
4499     return Result;
4500   }
4501 
4502   // C++11 [over.ics.list]p3:
4503   //   Otherwise, if the parameter is a non-aggregate class X and overload
4504   //   resolution chooses a single best constructor [...] the implicit
4505   //   conversion sequence is a user-defined conversion sequence. If multiple
4506   //   constructors are viable but none is better than the others, the
4507   //   implicit conversion sequence is a user-defined conversion sequence.
4508   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4509     // This function can deal with initializer lists.
4510     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4511                                     /*AllowExplicit=*/false,
4512                                     InOverloadResolution, /*CStyle=*/false,
4513                                     AllowObjCWritebackConversion,
4514                                     /*AllowObjCConversionOnExplicit=*/false);
4515   }
4516 
4517   // C++11 [over.ics.list]p4:
4518   //   Otherwise, if the parameter has an aggregate type which can be
4519   //   initialized from the initializer list [...] the implicit conversion
4520   //   sequence is a user-defined conversion sequence.
4521   if (ToType->isAggregateType()) {
4522     // Type is an aggregate, argument is an init list. At this point it comes
4523     // down to checking whether the initialization works.
4524     // FIXME: Find out whether this parameter is consumed or not.
4525     InitializedEntity Entity =
4526         InitializedEntity::InitializeParameter(S.Context, ToType,
4527                                                /*Consumed=*/false);
4528     if (S.CanPerformCopyInitialization(Entity, From)) {
4529       Result.setUserDefined();
4530       Result.UserDefined.Before.setAsIdentityConversion();
4531       // Initializer lists don't have a type.
4532       Result.UserDefined.Before.setFromType(QualType());
4533       Result.UserDefined.Before.setAllToTypes(QualType());
4534 
4535       Result.UserDefined.After.setAsIdentityConversion();
4536       Result.UserDefined.After.setFromType(ToType);
4537       Result.UserDefined.After.setAllToTypes(ToType);
4538       Result.UserDefined.ConversionFunction = nullptr;
4539     }
4540     return Result;
4541   }
4542 
4543   // C++11 [over.ics.list]p5:
4544   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4545   if (ToType->isReferenceType()) {
4546     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4547     // mention initializer lists in any way. So we go by what list-
4548     // initialization would do and try to extrapolate from that.
4549 
4550     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4551 
4552     // If the initializer list has a single element that is reference-related
4553     // to the parameter type, we initialize the reference from that.
4554     if (From->getNumInits() == 1) {
4555       Expr *Init = From->getInit(0);
4556 
4557       QualType T2 = Init->getType();
4558 
4559       // If the initializer is the address of an overloaded function, try
4560       // to resolve the overloaded function. If all goes well, T2 is the
4561       // type of the resulting function.
4562       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4563         DeclAccessPair Found;
4564         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4565                                    Init, ToType, false, Found))
4566           T2 = Fn->getType();
4567       }
4568 
4569       // Compute some basic properties of the types and the initializer.
4570       bool dummy1 = false;
4571       bool dummy2 = false;
4572       bool dummy3 = false;
4573       Sema::ReferenceCompareResult RefRelationship
4574         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4575                                          dummy2, dummy3);
4576 
4577       if (RefRelationship >= Sema::Ref_Related) {
4578         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4579                                 SuppressUserConversions,
4580                                 /*AllowExplicit=*/false);
4581       }
4582     }
4583 
4584     // Otherwise, we bind the reference to a temporary created from the
4585     // initializer list.
4586     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4587                                InOverloadResolution,
4588                                AllowObjCWritebackConversion);
4589     if (Result.isFailure())
4590       return Result;
4591     assert(!Result.isEllipsis() &&
4592            "Sub-initialization cannot result in ellipsis conversion.");
4593 
4594     // Can we even bind to a temporary?
4595     if (ToType->isRValueReferenceType() ||
4596         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4597       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4598                                             Result.UserDefined.After;
4599       SCS.ReferenceBinding = true;
4600       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4601       SCS.BindsToRvalue = true;
4602       SCS.BindsToFunctionLvalue = false;
4603       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4604       SCS.ObjCLifetimeConversionBinding = false;
4605     } else
4606       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4607                     From, ToType);
4608     return Result;
4609   }
4610 
4611   // C++11 [over.ics.list]p6:
4612   //   Otherwise, if the parameter type is not a class:
4613   if (!ToType->isRecordType()) {
4614     //    - if the initializer list has one element, the implicit conversion
4615     //      sequence is the one required to convert the element to the
4616     //      parameter type.
4617     unsigned NumInits = From->getNumInits();
4618     if (NumInits == 1)
4619       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4620                                      SuppressUserConversions,
4621                                      InOverloadResolution,
4622                                      AllowObjCWritebackConversion);
4623     //    - if the initializer list has no elements, the implicit conversion
4624     //      sequence is the identity conversion.
4625     else if (NumInits == 0) {
4626       Result.setStandard();
4627       Result.Standard.setAsIdentityConversion();
4628       Result.Standard.setFromType(ToType);
4629       Result.Standard.setAllToTypes(ToType);
4630     }
4631     return Result;
4632   }
4633 
4634   // C++11 [over.ics.list]p7:
4635   //   In all cases other than those enumerated above, no conversion is possible
4636   return Result;
4637 }
4638 
4639 /// TryCopyInitialization - Try to copy-initialize a value of type
4640 /// ToType from the expression From. Return the implicit conversion
4641 /// sequence required to pass this argument, which may be a bad
4642 /// conversion sequence (meaning that the argument cannot be passed to
4643 /// a parameter of this type). If @p SuppressUserConversions, then we
4644 /// do not permit any user-defined conversion sequences.
4645 static ImplicitConversionSequence
4646 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4647                       bool SuppressUserConversions,
4648                       bool InOverloadResolution,
4649                       bool AllowObjCWritebackConversion,
4650                       bool AllowExplicit) {
4651   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4652     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4653                              InOverloadResolution,AllowObjCWritebackConversion);
4654 
4655   if (ToType->isReferenceType())
4656     return TryReferenceInit(S, From, ToType,
4657                             /*FIXME:*/From->getLocStart(),
4658                             SuppressUserConversions,
4659                             AllowExplicit);
4660 
4661   return TryImplicitConversion(S, From, ToType,
4662                                SuppressUserConversions,
4663                                /*AllowExplicit=*/false,
4664                                InOverloadResolution,
4665                                /*CStyle=*/false,
4666                                AllowObjCWritebackConversion,
4667                                /*AllowObjCConversionOnExplicit=*/false);
4668 }
4669 
4670 static bool TryCopyInitialization(const CanQualType FromQTy,
4671                                   const CanQualType ToQTy,
4672                                   Sema &S,
4673                                   SourceLocation Loc,
4674                                   ExprValueKind FromVK) {
4675   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4676   ImplicitConversionSequence ICS =
4677     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4678 
4679   return !ICS.isBad();
4680 }
4681 
4682 /// TryObjectArgumentInitialization - Try to initialize the object
4683 /// parameter of the given member function (@c Method) from the
4684 /// expression @p From.
4685 static ImplicitConversionSequence
4686 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4687                                 Expr::Classification FromClassification,
4688                                 CXXMethodDecl *Method,
4689                                 CXXRecordDecl *ActingContext) {
4690   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4691   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4692   //                 const volatile object.
4693   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4694     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4695   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4696 
4697   // Set up the conversion sequence as a "bad" conversion, to allow us
4698   // to exit early.
4699   ImplicitConversionSequence ICS;
4700 
4701   // We need to have an object of class type.
4702   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4703     FromType = PT->getPointeeType();
4704 
4705     // When we had a pointer, it's implicitly dereferenced, so we
4706     // better have an lvalue.
4707     assert(FromClassification.isLValue());
4708   }
4709 
4710   assert(FromType->isRecordType());
4711 
4712   // C++0x [over.match.funcs]p4:
4713   //   For non-static member functions, the type of the implicit object
4714   //   parameter is
4715   //
4716   //     - "lvalue reference to cv X" for functions declared without a
4717   //        ref-qualifier or with the & ref-qualifier
4718   //     - "rvalue reference to cv X" for functions declared with the &&
4719   //        ref-qualifier
4720   //
4721   // where X is the class of which the function is a member and cv is the
4722   // cv-qualification on the member function declaration.
4723   //
4724   // However, when finding an implicit conversion sequence for the argument, we
4725   // are not allowed to create temporaries or perform user-defined conversions
4726   // (C++ [over.match.funcs]p5). We perform a simplified version of
4727   // reference binding here, that allows class rvalues to bind to
4728   // non-constant references.
4729 
4730   // First check the qualifiers.
4731   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4732   if (ImplicitParamType.getCVRQualifiers()
4733                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4734       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4735     ICS.setBad(BadConversionSequence::bad_qualifiers,
4736                FromType, ImplicitParamType);
4737     return ICS;
4738   }
4739 
4740   // Check that we have either the same type or a derived type. It
4741   // affects the conversion rank.
4742   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4743   ImplicitConversionKind SecondKind;
4744   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4745     SecondKind = ICK_Identity;
4746   } else if (S.IsDerivedFrom(FromType, ClassType))
4747     SecondKind = ICK_Derived_To_Base;
4748   else {
4749     ICS.setBad(BadConversionSequence::unrelated_class,
4750                FromType, ImplicitParamType);
4751     return ICS;
4752   }
4753 
4754   // Check the ref-qualifier.
4755   switch (Method->getRefQualifier()) {
4756   case RQ_None:
4757     // Do nothing; we don't care about lvalueness or rvalueness.
4758     break;
4759 
4760   case RQ_LValue:
4761     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4762       // non-const lvalue reference cannot bind to an rvalue
4763       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4764                  ImplicitParamType);
4765       return ICS;
4766     }
4767     break;
4768 
4769   case RQ_RValue:
4770     if (!FromClassification.isRValue()) {
4771       // rvalue reference cannot bind to an lvalue
4772       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4773                  ImplicitParamType);
4774       return ICS;
4775     }
4776     break;
4777   }
4778 
4779   // Success. Mark this as a reference binding.
4780   ICS.setStandard();
4781   ICS.Standard.setAsIdentityConversion();
4782   ICS.Standard.Second = SecondKind;
4783   ICS.Standard.setFromType(FromType);
4784   ICS.Standard.setAllToTypes(ImplicitParamType);
4785   ICS.Standard.ReferenceBinding = true;
4786   ICS.Standard.DirectBinding = true;
4787   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4788   ICS.Standard.BindsToFunctionLvalue = false;
4789   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4790   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4791     = (Method->getRefQualifier() == RQ_None);
4792   return ICS;
4793 }
4794 
4795 /// PerformObjectArgumentInitialization - Perform initialization of
4796 /// the implicit object parameter for the given Method with the given
4797 /// expression.
4798 ExprResult
4799 Sema::PerformObjectArgumentInitialization(Expr *From,
4800                                           NestedNameSpecifier *Qualifier,
4801                                           NamedDecl *FoundDecl,
4802                                           CXXMethodDecl *Method) {
4803   QualType FromRecordType, DestType;
4804   QualType ImplicitParamRecordType  =
4805     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4806 
4807   Expr::Classification FromClassification;
4808   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4809     FromRecordType = PT->getPointeeType();
4810     DestType = Method->getThisType(Context);
4811     FromClassification = Expr::Classification::makeSimpleLValue();
4812   } else {
4813     FromRecordType = From->getType();
4814     DestType = ImplicitParamRecordType;
4815     FromClassification = From->Classify(Context);
4816   }
4817 
4818   // Note that we always use the true parent context when performing
4819   // the actual argument initialization.
4820   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4821       *this, From->getType(), FromClassification, Method, Method->getParent());
4822   if (ICS.isBad()) {
4823     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4824       Qualifiers FromQs = FromRecordType.getQualifiers();
4825       Qualifiers ToQs = DestType.getQualifiers();
4826       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4827       if (CVR) {
4828         Diag(From->getLocStart(),
4829              diag::err_member_function_call_bad_cvr)
4830           << Method->getDeclName() << FromRecordType << (CVR - 1)
4831           << From->getSourceRange();
4832         Diag(Method->getLocation(), diag::note_previous_decl)
4833           << Method->getDeclName();
4834         return ExprError();
4835       }
4836     }
4837 
4838     return Diag(From->getLocStart(),
4839                 diag::err_implicit_object_parameter_init)
4840        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4841   }
4842 
4843   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4844     ExprResult FromRes =
4845       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4846     if (FromRes.isInvalid())
4847       return ExprError();
4848     From = FromRes.get();
4849   }
4850 
4851   if (!Context.hasSameType(From->getType(), DestType))
4852     From = ImpCastExprToType(From, DestType, CK_NoOp,
4853                              From->getValueKind()).get();
4854   return From;
4855 }
4856 
4857 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4858 /// expression From to bool (C++0x [conv]p3).
4859 static ImplicitConversionSequence
4860 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4861   return TryImplicitConversion(S, From, S.Context.BoolTy,
4862                                /*SuppressUserConversions=*/false,
4863                                /*AllowExplicit=*/true,
4864                                /*InOverloadResolution=*/false,
4865                                /*CStyle=*/false,
4866                                /*AllowObjCWritebackConversion=*/false,
4867                                /*AllowObjCConversionOnExplicit=*/false);
4868 }
4869 
4870 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4871 /// of the expression From to bool (C++0x [conv]p3).
4872 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4873   if (checkPlaceholderForOverload(*this, From))
4874     return ExprError();
4875 
4876   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4877   if (!ICS.isBad())
4878     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4879 
4880   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4881     return Diag(From->getLocStart(),
4882                 diag::err_typecheck_bool_condition)
4883                   << From->getType() << From->getSourceRange();
4884   return ExprError();
4885 }
4886 
4887 /// Check that the specified conversion is permitted in a converted constant
4888 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4889 /// is acceptable.
4890 static bool CheckConvertedConstantConversions(Sema &S,
4891                                               StandardConversionSequence &SCS) {
4892   // Since we know that the target type is an integral or unscoped enumeration
4893   // type, most conversion kinds are impossible. All possible First and Third
4894   // conversions are fine.
4895   switch (SCS.Second) {
4896   case ICK_Identity:
4897   case ICK_Integral_Promotion:
4898   case ICK_Integral_Conversion:
4899   case ICK_Zero_Event_Conversion:
4900     return true;
4901 
4902   case ICK_Boolean_Conversion:
4903     // Conversion from an integral or unscoped enumeration type to bool is
4904     // classified as ICK_Boolean_Conversion, but it's also an integral
4905     // conversion, so it's permitted in a converted constant expression.
4906     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4907            SCS.getToType(2)->isBooleanType();
4908 
4909   case ICK_Floating_Integral:
4910   case ICK_Complex_Real:
4911     return false;
4912 
4913   case ICK_Lvalue_To_Rvalue:
4914   case ICK_Array_To_Pointer:
4915   case ICK_Function_To_Pointer:
4916   case ICK_NoReturn_Adjustment:
4917   case ICK_Qualification:
4918   case ICK_Compatible_Conversion:
4919   case ICK_Vector_Conversion:
4920   case ICK_Vector_Splat:
4921   case ICK_Derived_To_Base:
4922   case ICK_Pointer_Conversion:
4923   case ICK_Pointer_Member:
4924   case ICK_Block_Pointer_Conversion:
4925   case ICK_Writeback_Conversion:
4926   case ICK_Floating_Promotion:
4927   case ICK_Complex_Promotion:
4928   case ICK_Complex_Conversion:
4929   case ICK_Floating_Conversion:
4930   case ICK_TransparentUnionConversion:
4931     llvm_unreachable("unexpected second conversion kind");
4932 
4933   case ICK_Num_Conversion_Kinds:
4934     break;
4935   }
4936 
4937   llvm_unreachable("unknown conversion kind");
4938 }
4939 
4940 /// CheckConvertedConstantExpression - Check that the expression From is a
4941 /// converted constant expression of type T, perform the conversion and produce
4942 /// the converted expression, per C++11 [expr.const]p3.
4943 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4944                                                   llvm::APSInt &Value,
4945                                                   CCEKind CCE) {
4946   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4947   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4948 
4949   if (checkPlaceholderForOverload(*this, From))
4950     return ExprError();
4951 
4952   // C++11 [expr.const]p3 with proposed wording fixes:
4953   //  A converted constant expression of type T is a core constant expression,
4954   //  implicitly converted to a prvalue of type T, where the converted
4955   //  expression is a literal constant expression and the implicit conversion
4956   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4957   //  conversions, integral promotions, and integral conversions other than
4958   //  narrowing conversions.
4959   ImplicitConversionSequence ICS =
4960     TryImplicitConversion(From, T,
4961                           /*SuppressUserConversions=*/false,
4962                           /*AllowExplicit=*/false,
4963                           /*InOverloadResolution=*/false,
4964                           /*CStyle=*/false,
4965                           /*AllowObjcWritebackConversion=*/false);
4966   StandardConversionSequence *SCS = nullptr;
4967   switch (ICS.getKind()) {
4968   case ImplicitConversionSequence::StandardConversion:
4969     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4970       return Diag(From->getLocStart(),
4971                   diag::err_typecheck_converted_constant_expression_disallowed)
4972                << From->getType() << From->getSourceRange() << T;
4973     SCS = &ICS.Standard;
4974     break;
4975   case ImplicitConversionSequence::UserDefinedConversion:
4976     // We are converting from class type to an integral or enumeration type, so
4977     // the Before sequence must be trivial.
4978     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4979       return Diag(From->getLocStart(),
4980                   diag::err_typecheck_converted_constant_expression_disallowed)
4981                << From->getType() << From->getSourceRange() << T;
4982     SCS = &ICS.UserDefined.After;
4983     break;
4984   case ImplicitConversionSequence::AmbiguousConversion:
4985   case ImplicitConversionSequence::BadConversion:
4986     if (!DiagnoseMultipleUserDefinedConversion(From, T))
4987       return Diag(From->getLocStart(),
4988                   diag::err_typecheck_converted_constant_expression)
4989                     << From->getType() << From->getSourceRange() << T;
4990     return ExprError();
4991 
4992   case ImplicitConversionSequence::EllipsisConversion:
4993     llvm_unreachable("ellipsis conversion in converted constant expression");
4994   }
4995 
4996   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4997   if (Result.isInvalid())
4998     return Result;
4999 
5000   // Check for a narrowing implicit conversion.
5001   APValue PreNarrowingValue;
5002   QualType PreNarrowingType;
5003   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5004                                 PreNarrowingType)) {
5005   case NK_Variable_Narrowing:
5006     // Implicit conversion to a narrower type, and the value is not a constant
5007     // expression. We'll diagnose this in a moment.
5008   case NK_Not_Narrowing:
5009     break;
5010 
5011   case NK_Constant_Narrowing:
5012     Diag(From->getLocStart(), diag::ext_cce_narrowing)
5013       << CCE << /*Constant*/1
5014       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5015     break;
5016 
5017   case NK_Type_Narrowing:
5018     Diag(From->getLocStart(), diag::ext_cce_narrowing)
5019       << CCE << /*Constant*/0 << From->getType() << T;
5020     break;
5021   }
5022 
5023   // Check the expression is a constant expression.
5024   SmallVector<PartialDiagnosticAt, 8> Notes;
5025   Expr::EvalResult Eval;
5026   Eval.Diag = &Notes;
5027 
5028   if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5029     // The expression can't be folded, so we can't keep it at this position in
5030     // the AST.
5031     Result = ExprError();
5032   } else {
5033     Value = Eval.Val.getInt();
5034 
5035     if (Notes.empty()) {
5036       // It's a constant expression.
5037       return Result;
5038     }
5039   }
5040 
5041   // It's not a constant expression. Produce an appropriate diagnostic.
5042   if (Notes.size() == 1 &&
5043       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5044     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5045   else {
5046     Diag(From->getLocStart(), diag::err_expr_not_cce)
5047       << CCE << From->getSourceRange();
5048     for (unsigned I = 0; I < Notes.size(); ++I)
5049       Diag(Notes[I].first, Notes[I].second);
5050   }
5051   return Result;
5052 }
5053 
5054 /// dropPointerConversions - If the given standard conversion sequence
5055 /// involves any pointer conversions, remove them.  This may change
5056 /// the result type of the conversion sequence.
5057 static void dropPointerConversion(StandardConversionSequence &SCS) {
5058   if (SCS.Second == ICK_Pointer_Conversion) {
5059     SCS.Second = ICK_Identity;
5060     SCS.Third = ICK_Identity;
5061     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5062   }
5063 }
5064 
5065 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5066 /// convert the expression From to an Objective-C pointer type.
5067 static ImplicitConversionSequence
5068 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5069   // Do an implicit conversion to 'id'.
5070   QualType Ty = S.Context.getObjCIdType();
5071   ImplicitConversionSequence ICS
5072     = TryImplicitConversion(S, From, Ty,
5073                             // FIXME: Are these flags correct?
5074                             /*SuppressUserConversions=*/false,
5075                             /*AllowExplicit=*/true,
5076                             /*InOverloadResolution=*/false,
5077                             /*CStyle=*/false,
5078                             /*AllowObjCWritebackConversion=*/false,
5079                             /*AllowObjCConversionOnExplicit=*/true);
5080 
5081   // Strip off any final conversions to 'id'.
5082   switch (ICS.getKind()) {
5083   case ImplicitConversionSequence::BadConversion:
5084   case ImplicitConversionSequence::AmbiguousConversion:
5085   case ImplicitConversionSequence::EllipsisConversion:
5086     break;
5087 
5088   case ImplicitConversionSequence::UserDefinedConversion:
5089     dropPointerConversion(ICS.UserDefined.After);
5090     break;
5091 
5092   case ImplicitConversionSequence::StandardConversion:
5093     dropPointerConversion(ICS.Standard);
5094     break;
5095   }
5096 
5097   return ICS;
5098 }
5099 
5100 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5101 /// conversion of the expression From to an Objective-C pointer type.
5102 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5103   if (checkPlaceholderForOverload(*this, From))
5104     return ExprError();
5105 
5106   QualType Ty = Context.getObjCIdType();
5107   ImplicitConversionSequence ICS =
5108     TryContextuallyConvertToObjCPointer(*this, From);
5109   if (!ICS.isBad())
5110     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5111   return ExprError();
5112 }
5113 
5114 /// Determine whether the provided type is an integral type, or an enumeration
5115 /// type of a permitted flavor.
5116 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5117   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5118                                  : T->isIntegralOrUnscopedEnumerationType();
5119 }
5120 
5121 static ExprResult
5122 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5123                             Sema::ContextualImplicitConverter &Converter,
5124                             QualType T, UnresolvedSetImpl &ViableConversions) {
5125 
5126   if (Converter.Suppress)
5127     return ExprError();
5128 
5129   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5130   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5131     CXXConversionDecl *Conv =
5132         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5133     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5134     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5135   }
5136   return From;
5137 }
5138 
5139 static bool
5140 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5141                            Sema::ContextualImplicitConverter &Converter,
5142                            QualType T, bool HadMultipleCandidates,
5143                            UnresolvedSetImpl &ExplicitConversions) {
5144   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5145     DeclAccessPair Found = ExplicitConversions[0];
5146     CXXConversionDecl *Conversion =
5147         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5148 
5149     // The user probably meant to invoke the given explicit
5150     // conversion; use it.
5151     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5152     std::string TypeStr;
5153     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5154 
5155     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5156         << FixItHint::CreateInsertion(From->getLocStart(),
5157                                       "static_cast<" + TypeStr + ">(")
5158         << FixItHint::CreateInsertion(
5159                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5160     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5161 
5162     // If we aren't in a SFINAE context, build a call to the
5163     // explicit conversion function.
5164     if (SemaRef.isSFINAEContext())
5165       return true;
5166 
5167     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5168     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5169                                                        HadMultipleCandidates);
5170     if (Result.isInvalid())
5171       return true;
5172     // Record usage of conversion in an implicit cast.
5173     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5174                                     CK_UserDefinedConversion, Result.get(),
5175                                     nullptr, Result.get()->getValueKind());
5176   }
5177   return false;
5178 }
5179 
5180 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5181                              Sema::ContextualImplicitConverter &Converter,
5182                              QualType T, bool HadMultipleCandidates,
5183                              DeclAccessPair &Found) {
5184   CXXConversionDecl *Conversion =
5185       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5186   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5187 
5188   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5189   if (!Converter.SuppressConversion) {
5190     if (SemaRef.isSFINAEContext())
5191       return true;
5192 
5193     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5194         << From->getSourceRange();
5195   }
5196 
5197   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5198                                                      HadMultipleCandidates);
5199   if (Result.isInvalid())
5200     return true;
5201   // Record usage of conversion in an implicit cast.
5202   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5203                                   CK_UserDefinedConversion, Result.get(),
5204                                   nullptr, Result.get()->getValueKind());
5205   return false;
5206 }
5207 
5208 static ExprResult finishContextualImplicitConversion(
5209     Sema &SemaRef, SourceLocation Loc, Expr *From,
5210     Sema::ContextualImplicitConverter &Converter) {
5211   if (!Converter.match(From->getType()) && !Converter.Suppress)
5212     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5213         << From->getSourceRange();
5214 
5215   return SemaRef.DefaultLvalueConversion(From);
5216 }
5217 
5218 static void
5219 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5220                                   UnresolvedSetImpl &ViableConversions,
5221                                   OverloadCandidateSet &CandidateSet) {
5222   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5223     DeclAccessPair FoundDecl = ViableConversions[I];
5224     NamedDecl *D = FoundDecl.getDecl();
5225     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5226     if (isa<UsingShadowDecl>(D))
5227       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5228 
5229     CXXConversionDecl *Conv;
5230     FunctionTemplateDecl *ConvTemplate;
5231     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5232       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5233     else
5234       Conv = cast<CXXConversionDecl>(D);
5235 
5236     if (ConvTemplate)
5237       SemaRef.AddTemplateConversionCandidate(
5238         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5239         /*AllowObjCConversionOnExplicit=*/false);
5240     else
5241       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5242                                      ToType, CandidateSet,
5243                                      /*AllowObjCConversionOnExplicit=*/false);
5244   }
5245 }
5246 
5247 /// \brief Attempt to convert the given expression to a type which is accepted
5248 /// by the given converter.
5249 ///
5250 /// This routine will attempt to convert an expression of class type to a
5251 /// type accepted by the specified converter. In C++11 and before, the class
5252 /// must have a single non-explicit conversion function converting to a matching
5253 /// type. In C++1y, there can be multiple such conversion functions, but only
5254 /// one target type.
5255 ///
5256 /// \param Loc The source location of the construct that requires the
5257 /// conversion.
5258 ///
5259 /// \param From The expression we're converting from.
5260 ///
5261 /// \param Converter Used to control and diagnose the conversion process.
5262 ///
5263 /// \returns The expression, converted to an integral or enumeration type if
5264 /// successful.
5265 ExprResult Sema::PerformContextualImplicitConversion(
5266     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5267   // We can't perform any more checking for type-dependent expressions.
5268   if (From->isTypeDependent())
5269     return From;
5270 
5271   // Process placeholders immediately.
5272   if (From->hasPlaceholderType()) {
5273     ExprResult result = CheckPlaceholderExpr(From);
5274     if (result.isInvalid())
5275       return result;
5276     From = result.get();
5277   }
5278 
5279   // If the expression already has a matching type, we're golden.
5280   QualType T = From->getType();
5281   if (Converter.match(T))
5282     return DefaultLvalueConversion(From);
5283 
5284   // FIXME: Check for missing '()' if T is a function type?
5285 
5286   // We can only perform contextual implicit conversions on objects of class
5287   // type.
5288   const RecordType *RecordTy = T->getAs<RecordType>();
5289   if (!RecordTy || !getLangOpts().CPlusPlus) {
5290     if (!Converter.Suppress)
5291       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5292     return From;
5293   }
5294 
5295   // We must have a complete class type.
5296   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5297     ContextualImplicitConverter &Converter;
5298     Expr *From;
5299 
5300     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5301         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5302 
5303     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5304       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5305     }
5306   } IncompleteDiagnoser(Converter, From);
5307 
5308   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5309     return From;
5310 
5311   // Look for a conversion to an integral or enumeration type.
5312   UnresolvedSet<4>
5313       ViableConversions; // These are *potentially* viable in C++1y.
5314   UnresolvedSet<4> ExplicitConversions;
5315   std::pair<CXXRecordDecl::conversion_iterator,
5316             CXXRecordDecl::conversion_iterator> Conversions =
5317       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5318 
5319   bool HadMultipleCandidates =
5320       (std::distance(Conversions.first, Conversions.second) > 1);
5321 
5322   // To check that there is only one target type, in C++1y:
5323   QualType ToType;
5324   bool HasUniqueTargetType = true;
5325 
5326   // Collect explicit or viable (potentially in C++1y) conversions.
5327   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5328                                           E = Conversions.second;
5329        I != E; ++I) {
5330     NamedDecl *D = (*I)->getUnderlyingDecl();
5331     CXXConversionDecl *Conversion;
5332     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5333     if (ConvTemplate) {
5334       if (getLangOpts().CPlusPlus14)
5335         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5336       else
5337         continue; // C++11 does not consider conversion operator templates(?).
5338     } else
5339       Conversion = cast<CXXConversionDecl>(D);
5340 
5341     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5342            "Conversion operator templates are considered potentially "
5343            "viable in C++1y");
5344 
5345     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5346     if (Converter.match(CurToType) || ConvTemplate) {
5347 
5348       if (Conversion->isExplicit()) {
5349         // FIXME: For C++1y, do we need this restriction?
5350         // cf. diagnoseNoViableConversion()
5351         if (!ConvTemplate)
5352           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5353       } else {
5354         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5355           if (ToType.isNull())
5356             ToType = CurToType.getUnqualifiedType();
5357           else if (HasUniqueTargetType &&
5358                    (CurToType.getUnqualifiedType() != ToType))
5359             HasUniqueTargetType = false;
5360         }
5361         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5362       }
5363     }
5364   }
5365 
5366   if (getLangOpts().CPlusPlus14) {
5367     // C++1y [conv]p6:
5368     // ... An expression e of class type E appearing in such a context
5369     // is said to be contextually implicitly converted to a specified
5370     // type T and is well-formed if and only if e can be implicitly
5371     // converted to a type T that is determined as follows: E is searched
5372     // for conversion functions whose return type is cv T or reference to
5373     // cv T such that T is allowed by the context. There shall be
5374     // exactly one such T.
5375 
5376     // If no unique T is found:
5377     if (ToType.isNull()) {
5378       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5379                                      HadMultipleCandidates,
5380                                      ExplicitConversions))
5381         return ExprError();
5382       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5383     }
5384 
5385     // If more than one unique Ts are found:
5386     if (!HasUniqueTargetType)
5387       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5388                                          ViableConversions);
5389 
5390     // If one unique T is found:
5391     // First, build a candidate set from the previously recorded
5392     // potentially viable conversions.
5393     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5394     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5395                                       CandidateSet);
5396 
5397     // Then, perform overload resolution over the candidate set.
5398     OverloadCandidateSet::iterator Best;
5399     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5400     case OR_Success: {
5401       // Apply this conversion.
5402       DeclAccessPair Found =
5403           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5404       if (recordConversion(*this, Loc, From, Converter, T,
5405                            HadMultipleCandidates, Found))
5406         return ExprError();
5407       break;
5408     }
5409     case OR_Ambiguous:
5410       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5411                                          ViableConversions);
5412     case OR_No_Viable_Function:
5413       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5414                                      HadMultipleCandidates,
5415                                      ExplicitConversions))
5416         return ExprError();
5417     // fall through 'OR_Deleted' case.
5418     case OR_Deleted:
5419       // We'll complain below about a non-integral condition type.
5420       break;
5421     }
5422   } else {
5423     switch (ViableConversions.size()) {
5424     case 0: {
5425       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5426                                      HadMultipleCandidates,
5427                                      ExplicitConversions))
5428         return ExprError();
5429 
5430       // We'll complain below about a non-integral condition type.
5431       break;
5432     }
5433     case 1: {
5434       // Apply this conversion.
5435       DeclAccessPair Found = ViableConversions[0];
5436       if (recordConversion(*this, Loc, From, Converter, T,
5437                            HadMultipleCandidates, Found))
5438         return ExprError();
5439       break;
5440     }
5441     default:
5442       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5443                                          ViableConversions);
5444     }
5445   }
5446 
5447   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5448 }
5449 
5450 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5451 /// an acceptable non-member overloaded operator for a call whose
5452 /// arguments have types T1 (and, if non-empty, T2). This routine
5453 /// implements the check in C++ [over.match.oper]p3b2 concerning
5454 /// enumeration types.
5455 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5456                                                    FunctionDecl *Fn,
5457                                                    ArrayRef<Expr *> Args) {
5458   QualType T1 = Args[0]->getType();
5459   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5460 
5461   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5462     return true;
5463 
5464   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5465     return true;
5466 
5467   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5468   if (Proto->getNumParams() < 1)
5469     return false;
5470 
5471   if (T1->isEnumeralType()) {
5472     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5473     if (Context.hasSameUnqualifiedType(T1, ArgType))
5474       return true;
5475   }
5476 
5477   if (Proto->getNumParams() < 2)
5478     return false;
5479 
5480   if (!T2.isNull() && T2->isEnumeralType()) {
5481     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5482     if (Context.hasSameUnqualifiedType(T2, ArgType))
5483       return true;
5484   }
5485 
5486   return false;
5487 }
5488 
5489 /// AddOverloadCandidate - Adds the given function to the set of
5490 /// candidate functions, using the given function call arguments.  If
5491 /// @p SuppressUserConversions, then don't allow user-defined
5492 /// conversions via constructors or conversion operators.
5493 ///
5494 /// \param PartialOverloading true if we are performing "partial" overloading
5495 /// based on an incomplete set of function arguments. This feature is used by
5496 /// code completion.
5497 void
5498 Sema::AddOverloadCandidate(FunctionDecl *Function,
5499                            DeclAccessPair FoundDecl,
5500                            ArrayRef<Expr *> Args,
5501                            OverloadCandidateSet &CandidateSet,
5502                            bool SuppressUserConversions,
5503                            bool PartialOverloading,
5504                            bool AllowExplicit) {
5505   const FunctionProtoType *Proto
5506     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5507   assert(Proto && "Functions without a prototype cannot be overloaded");
5508   assert(!Function->getDescribedFunctionTemplate() &&
5509          "Use AddTemplateOverloadCandidate for function templates");
5510 
5511   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5512     if (!isa<CXXConstructorDecl>(Method)) {
5513       // If we get here, it's because we're calling a member function
5514       // that is named without a member access expression (e.g.,
5515       // "this->f") that was either written explicitly or created
5516       // implicitly. This can happen with a qualified call to a member
5517       // function, e.g., X::f(). We use an empty type for the implied
5518       // object argument (C++ [over.call.func]p3), and the acting context
5519       // is irrelevant.
5520       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5521                          QualType(), Expr::Classification::makeSimpleLValue(),
5522                          Args, CandidateSet, SuppressUserConversions);
5523       return;
5524     }
5525     // We treat a constructor like a non-member function, since its object
5526     // argument doesn't participate in overload resolution.
5527   }
5528 
5529   if (!CandidateSet.isNewCandidate(Function))
5530     return;
5531 
5532   // C++ [over.match.oper]p3:
5533   //   if no operand has a class type, only those non-member functions in the
5534   //   lookup set that have a first parameter of type T1 or "reference to
5535   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5536   //   is a right operand) a second parameter of type T2 or "reference to
5537   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5538   //   candidate functions.
5539   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5540       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5541     return;
5542 
5543   // C++11 [class.copy]p11: [DR1402]
5544   //   A defaulted move constructor that is defined as deleted is ignored by
5545   //   overload resolution.
5546   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5547   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5548       Constructor->isMoveConstructor())
5549     return;
5550 
5551   // Overload resolution is always an unevaluated context.
5552   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5553 
5554   if (Constructor) {
5555     // C++ [class.copy]p3:
5556     //   A member function template is never instantiated to perform the copy
5557     //   of a class object to an object of its class type.
5558     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5559     if (Args.size() == 1 &&
5560         Constructor->isSpecializationCopyingObject() &&
5561         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5562          IsDerivedFrom(Args[0]->getType(), ClassType)))
5563       return;
5564   }
5565 
5566   // Add this candidate
5567   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5568   Candidate.FoundDecl = FoundDecl;
5569   Candidate.Function = Function;
5570   Candidate.Viable = true;
5571   Candidate.IsSurrogate = false;
5572   Candidate.IgnoreObjectArgument = false;
5573   Candidate.ExplicitCallArguments = Args.size();
5574 
5575   unsigned NumParams = Proto->getNumParams();
5576 
5577   // (C++ 13.3.2p2): A candidate function having fewer than m
5578   // parameters is viable only if it has an ellipsis in its parameter
5579   // list (8.3.5).
5580   if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
5581       !Proto->isVariadic()) {
5582     Candidate.Viable = false;
5583     Candidate.FailureKind = ovl_fail_too_many_arguments;
5584     return;
5585   }
5586 
5587   // (C++ 13.3.2p2): A candidate function having more than m parameters
5588   // is viable only if the (m+1)st parameter has a default argument
5589   // (8.3.6). For the purposes of overload resolution, the
5590   // parameter list is truncated on the right, so that there are
5591   // exactly m parameters.
5592   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5593   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5594     // Not enough arguments.
5595     Candidate.Viable = false;
5596     Candidate.FailureKind = ovl_fail_too_few_arguments;
5597     return;
5598   }
5599 
5600   // (CUDA B.1): Check for invalid calls between targets.
5601   if (getLangOpts().CUDA)
5602     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5603       // Skip the check for callers that are implicit members, because in this
5604       // case we may not yet know what the member's target is; the target is
5605       // inferred for the member automatically, based on the bases and fields of
5606       // the class.
5607       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5608         Candidate.Viable = false;
5609         Candidate.FailureKind = ovl_fail_bad_target;
5610         return;
5611       }
5612 
5613   // Determine the implicit conversion sequences for each of the
5614   // arguments.
5615   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5616     if (ArgIdx < NumParams) {
5617       // (C++ 13.3.2p3): for F to be a viable function, there shall
5618       // exist for each argument an implicit conversion sequence
5619       // (13.3.3.1) that converts that argument to the corresponding
5620       // parameter of F.
5621       QualType ParamType = Proto->getParamType(ArgIdx);
5622       Candidate.Conversions[ArgIdx]
5623         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5624                                 SuppressUserConversions,
5625                                 /*InOverloadResolution=*/true,
5626                                 /*AllowObjCWritebackConversion=*/
5627                                   getLangOpts().ObjCAutoRefCount,
5628                                 AllowExplicit);
5629       if (Candidate.Conversions[ArgIdx].isBad()) {
5630         Candidate.Viable = false;
5631         Candidate.FailureKind = ovl_fail_bad_conversion;
5632         return;
5633       }
5634     } else {
5635       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5636       // argument for which there is no corresponding parameter is
5637       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5638       Candidate.Conversions[ArgIdx].setEllipsis();
5639     }
5640   }
5641 
5642   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5643     Candidate.Viable = false;
5644     Candidate.FailureKind = ovl_fail_enable_if;
5645     Candidate.DeductionFailure.Data = FailedAttr;
5646     return;
5647   }
5648 }
5649 
5650 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5651                                        bool IsInstance) {
5652   SmallVector<ObjCMethodDecl*, 4> Methods;
5653   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5654     return nullptr;
5655 
5656   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5657     bool Match = true;
5658     ObjCMethodDecl *Method = Methods[b];
5659     unsigned NumNamedArgs = Sel.getNumArgs();
5660     // Method might have more arguments than selector indicates. This is due
5661     // to addition of c-style arguments in method.
5662     if (Method->param_size() > NumNamedArgs)
5663       NumNamedArgs = Method->param_size();
5664     if (Args.size() < NumNamedArgs)
5665       continue;
5666 
5667     for (unsigned i = 0; i < NumNamedArgs; i++) {
5668       // We can't do any type-checking on a type-dependent argument.
5669       if (Args[i]->isTypeDependent()) {
5670         Match = false;
5671         break;
5672       }
5673 
5674       ParmVarDecl *param = Method->parameters()[i];
5675       Expr *argExpr = Args[i];
5676       assert(argExpr && "SelectBestMethod(): missing expression");
5677 
5678       // Strip the unbridged-cast placeholder expression off unless it's
5679       // a consumed argument.
5680       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5681           !param->hasAttr<CFConsumedAttr>())
5682         argExpr = stripARCUnbridgedCast(argExpr);
5683 
5684       // If the parameter is __unknown_anytype, move on to the next method.
5685       if (param->getType() == Context.UnknownAnyTy) {
5686         Match = false;
5687         break;
5688       }
5689 
5690       ImplicitConversionSequence ConversionState
5691         = TryCopyInitialization(*this, argExpr, param->getType(),
5692                                 /*SuppressUserConversions*/false,
5693                                 /*InOverloadResolution=*/true,
5694                                 /*AllowObjCWritebackConversion=*/
5695                                 getLangOpts().ObjCAutoRefCount,
5696                                 /*AllowExplicit*/false);
5697         if (ConversionState.isBad()) {
5698           Match = false;
5699           break;
5700         }
5701     }
5702     // Promote additional arguments to variadic methods.
5703     if (Match && Method->isVariadic()) {
5704       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5705         if (Args[i]->isTypeDependent()) {
5706           Match = false;
5707           break;
5708         }
5709         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5710                                                           nullptr);
5711         if (Arg.isInvalid()) {
5712           Match = false;
5713           break;
5714         }
5715       }
5716     } else {
5717       // Check for extra arguments to non-variadic methods.
5718       if (Args.size() != NumNamedArgs)
5719         Match = false;
5720       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5721         // Special case when selectors have no argument. In this case, select
5722         // one with the most general result type of 'id'.
5723         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5724           QualType ReturnT = Methods[b]->getReturnType();
5725           if (ReturnT->isObjCIdType())
5726             return Methods[b];
5727         }
5728       }
5729     }
5730 
5731     if (Match)
5732       return Method;
5733   }
5734   return nullptr;
5735 }
5736 
5737 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5738 
5739 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5740                                   bool MissingImplicitThis) {
5741   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5742   // we need to find the first failing one.
5743   if (!Function->hasAttrs())
5744     return nullptr;
5745   AttrVec Attrs = Function->getAttrs();
5746   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5747                                        IsNotEnableIfAttr);
5748   if (Attrs.begin() == E)
5749     return nullptr;
5750   std::reverse(Attrs.begin(), E);
5751 
5752   SFINAETrap Trap(*this);
5753 
5754   // Convert the arguments.
5755   SmallVector<Expr *, 16> ConvertedArgs;
5756   bool InitializationFailed = false;
5757   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5758     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5759         !cast<CXXMethodDecl>(Function)->isStatic() &&
5760         !isa<CXXConstructorDecl>(Function)) {
5761       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5762       ExprResult R =
5763         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5764                                             Method, Method);
5765       if (R.isInvalid()) {
5766         InitializationFailed = true;
5767         break;
5768       }
5769       ConvertedArgs.push_back(R.get());
5770     } else {
5771       ExprResult R =
5772         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5773                                                 Context,
5774                                                 Function->getParamDecl(i)),
5775                                   SourceLocation(),
5776                                   Args[i]);
5777       if (R.isInvalid()) {
5778         InitializationFailed = true;
5779         break;
5780       }
5781       ConvertedArgs.push_back(R.get());
5782     }
5783   }
5784 
5785   if (InitializationFailed || Trap.hasErrorOccurred())
5786     return cast<EnableIfAttr>(Attrs[0]);
5787 
5788   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5789     APValue Result;
5790     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5791     if (!EIA->getCond()->EvaluateWithSubstitution(
5792             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) ||
5793         !Result.isInt() || !Result.getInt().getBoolValue()) {
5794       return EIA;
5795     }
5796   }
5797   return nullptr;
5798 }
5799 
5800 /// \brief Add all of the function declarations in the given function set to
5801 /// the overload candidate set.
5802 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5803                                  ArrayRef<Expr *> Args,
5804                                  OverloadCandidateSet& CandidateSet,
5805                                  bool SuppressUserConversions,
5806                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5807   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5808     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5809     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5810       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5811         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5812                            cast<CXXMethodDecl>(FD)->getParent(),
5813                            Args[0]->getType(), Args[0]->Classify(Context),
5814                            Args.slice(1), CandidateSet,
5815                            SuppressUserConversions);
5816       else
5817         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5818                              SuppressUserConversions);
5819     } else {
5820       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5821       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5822           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5823         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5824                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5825                                    ExplicitTemplateArgs,
5826                                    Args[0]->getType(),
5827                                    Args[0]->Classify(Context), Args.slice(1),
5828                                    CandidateSet, SuppressUserConversions);
5829       else
5830         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5831                                      ExplicitTemplateArgs, Args,
5832                                      CandidateSet, SuppressUserConversions);
5833     }
5834   }
5835 }
5836 
5837 /// AddMethodCandidate - Adds a named decl (which is some kind of
5838 /// method) as a method candidate to the given overload set.
5839 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5840                               QualType ObjectType,
5841                               Expr::Classification ObjectClassification,
5842                               ArrayRef<Expr *> Args,
5843                               OverloadCandidateSet& CandidateSet,
5844                               bool SuppressUserConversions) {
5845   NamedDecl *Decl = FoundDecl.getDecl();
5846   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5847 
5848   if (isa<UsingShadowDecl>(Decl))
5849     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5850 
5851   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5852     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5853            "Expected a member function template");
5854     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5855                                /*ExplicitArgs*/ nullptr,
5856                                ObjectType, ObjectClassification,
5857                                Args, CandidateSet,
5858                                SuppressUserConversions);
5859   } else {
5860     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5861                        ObjectType, ObjectClassification,
5862                        Args,
5863                        CandidateSet, SuppressUserConversions);
5864   }
5865 }
5866 
5867 /// AddMethodCandidate - Adds the given C++ member function to the set
5868 /// of candidate functions, using the given function call arguments
5869 /// and the object argument (@c Object). For example, in a call
5870 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5871 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5872 /// allow user-defined conversions via constructors or conversion
5873 /// operators.
5874 void
5875 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5876                          CXXRecordDecl *ActingContext, QualType ObjectType,
5877                          Expr::Classification ObjectClassification,
5878                          ArrayRef<Expr *> Args,
5879                          OverloadCandidateSet &CandidateSet,
5880                          bool SuppressUserConversions) {
5881   const FunctionProtoType *Proto
5882     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5883   assert(Proto && "Methods without a prototype cannot be overloaded");
5884   assert(!isa<CXXConstructorDecl>(Method) &&
5885          "Use AddOverloadCandidate for constructors");
5886 
5887   if (!CandidateSet.isNewCandidate(Method))
5888     return;
5889 
5890   // C++11 [class.copy]p23: [DR1402]
5891   //   A defaulted move assignment operator that is defined as deleted is
5892   //   ignored by overload resolution.
5893   if (Method->isDefaulted() && Method->isDeleted() &&
5894       Method->isMoveAssignmentOperator())
5895     return;
5896 
5897   // Overload resolution is always an unevaluated context.
5898   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5899 
5900   // Add this candidate
5901   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5902   Candidate.FoundDecl = FoundDecl;
5903   Candidate.Function = Method;
5904   Candidate.IsSurrogate = false;
5905   Candidate.IgnoreObjectArgument = false;
5906   Candidate.ExplicitCallArguments = Args.size();
5907 
5908   unsigned NumParams = Proto->getNumParams();
5909 
5910   // (C++ 13.3.2p2): A candidate function having fewer than m
5911   // parameters is viable only if it has an ellipsis in its parameter
5912   // list (8.3.5).
5913   if (Args.size() > NumParams && !Proto->isVariadic()) {
5914     Candidate.Viable = false;
5915     Candidate.FailureKind = ovl_fail_too_many_arguments;
5916     return;
5917   }
5918 
5919   // (C++ 13.3.2p2): A candidate function having more than m parameters
5920   // is viable only if the (m+1)st parameter has a default argument
5921   // (8.3.6). For the purposes of overload resolution, the
5922   // parameter list is truncated on the right, so that there are
5923   // exactly m parameters.
5924   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5925   if (Args.size() < MinRequiredArgs) {
5926     // Not enough arguments.
5927     Candidate.Viable = false;
5928     Candidate.FailureKind = ovl_fail_too_few_arguments;
5929     return;
5930   }
5931 
5932   Candidate.Viable = true;
5933 
5934   if (Method->isStatic() || ObjectType.isNull())
5935     // The implicit object argument is ignored.
5936     Candidate.IgnoreObjectArgument = true;
5937   else {
5938     // Determine the implicit conversion sequence for the object
5939     // parameter.
5940     Candidate.Conversions[0]
5941       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5942                                         Method, ActingContext);
5943     if (Candidate.Conversions[0].isBad()) {
5944       Candidate.Viable = false;
5945       Candidate.FailureKind = ovl_fail_bad_conversion;
5946       return;
5947     }
5948   }
5949 
5950   // (CUDA B.1): Check for invalid calls between targets.
5951   if (getLangOpts().CUDA)
5952     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5953       if (CheckCUDATarget(Caller, Method)) {
5954         Candidate.Viable = false;
5955         Candidate.FailureKind = ovl_fail_bad_target;
5956         return;
5957       }
5958 
5959   // Determine the implicit conversion sequences for each of the
5960   // arguments.
5961   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5962     if (ArgIdx < NumParams) {
5963       // (C++ 13.3.2p3): for F to be a viable function, there shall
5964       // exist for each argument an implicit conversion sequence
5965       // (13.3.3.1) that converts that argument to the corresponding
5966       // parameter of F.
5967       QualType ParamType = Proto->getParamType(ArgIdx);
5968       Candidate.Conversions[ArgIdx + 1]
5969         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5970                                 SuppressUserConversions,
5971                                 /*InOverloadResolution=*/true,
5972                                 /*AllowObjCWritebackConversion=*/
5973                                   getLangOpts().ObjCAutoRefCount);
5974       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5975         Candidate.Viable = false;
5976         Candidate.FailureKind = ovl_fail_bad_conversion;
5977         return;
5978       }
5979     } else {
5980       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5981       // argument for which there is no corresponding parameter is
5982       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
5983       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5984     }
5985   }
5986 
5987   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5988     Candidate.Viable = false;
5989     Candidate.FailureKind = ovl_fail_enable_if;
5990     Candidate.DeductionFailure.Data = FailedAttr;
5991     return;
5992   }
5993 }
5994 
5995 /// \brief Add a C++ member function template as a candidate to the candidate
5996 /// set, using template argument deduction to produce an appropriate member
5997 /// function template specialization.
5998 void
5999 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6000                                  DeclAccessPair FoundDecl,
6001                                  CXXRecordDecl *ActingContext,
6002                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6003                                  QualType ObjectType,
6004                                  Expr::Classification ObjectClassification,
6005                                  ArrayRef<Expr *> Args,
6006                                  OverloadCandidateSet& CandidateSet,
6007                                  bool SuppressUserConversions) {
6008   if (!CandidateSet.isNewCandidate(MethodTmpl))
6009     return;
6010 
6011   // C++ [over.match.funcs]p7:
6012   //   In each case where a candidate is a function template, candidate
6013   //   function template specializations are generated using template argument
6014   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6015   //   candidate functions in the usual way.113) A given name can refer to one
6016   //   or more function templates and also to a set of overloaded non-template
6017   //   functions. In such a case, the candidate functions generated from each
6018   //   function template are combined with the set of non-template candidate
6019   //   functions.
6020   TemplateDeductionInfo Info(CandidateSet.getLocation());
6021   FunctionDecl *Specialization = nullptr;
6022   if (TemplateDeductionResult Result
6023       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6024                                 Specialization, Info)) {
6025     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6026     Candidate.FoundDecl = FoundDecl;
6027     Candidate.Function = MethodTmpl->getTemplatedDecl();
6028     Candidate.Viable = false;
6029     Candidate.FailureKind = ovl_fail_bad_deduction;
6030     Candidate.IsSurrogate = false;
6031     Candidate.IgnoreObjectArgument = false;
6032     Candidate.ExplicitCallArguments = Args.size();
6033     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6034                                                           Info);
6035     return;
6036   }
6037 
6038   // Add the function template specialization produced by template argument
6039   // deduction as a candidate.
6040   assert(Specialization && "Missing member function template specialization?");
6041   assert(isa<CXXMethodDecl>(Specialization) &&
6042          "Specialization is not a member function?");
6043   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6044                      ActingContext, ObjectType, ObjectClassification, Args,
6045                      CandidateSet, SuppressUserConversions);
6046 }
6047 
6048 /// \brief Add a C++ function template specialization as a candidate
6049 /// in the candidate set, using template argument deduction to produce
6050 /// an appropriate function template specialization.
6051 void
6052 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6053                                    DeclAccessPair FoundDecl,
6054                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6055                                    ArrayRef<Expr *> Args,
6056                                    OverloadCandidateSet& CandidateSet,
6057                                    bool SuppressUserConversions) {
6058   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6059     return;
6060 
6061   // C++ [over.match.funcs]p7:
6062   //   In each case where a candidate is a function template, candidate
6063   //   function template specializations are generated using template argument
6064   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6065   //   candidate functions in the usual way.113) A given name can refer to one
6066   //   or more function templates and also to a set of overloaded non-template
6067   //   functions. In such a case, the candidate functions generated from each
6068   //   function template are combined with the set of non-template candidate
6069   //   functions.
6070   TemplateDeductionInfo Info(CandidateSet.getLocation());
6071   FunctionDecl *Specialization = nullptr;
6072   if (TemplateDeductionResult Result
6073         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6074                                   Specialization, Info)) {
6075     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6076     Candidate.FoundDecl = FoundDecl;
6077     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6078     Candidate.Viable = false;
6079     Candidate.FailureKind = ovl_fail_bad_deduction;
6080     Candidate.IsSurrogate = false;
6081     Candidate.IgnoreObjectArgument = false;
6082     Candidate.ExplicitCallArguments = Args.size();
6083     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6084                                                           Info);
6085     return;
6086   }
6087 
6088   // Add the function template specialization produced by template argument
6089   // deduction as a candidate.
6090   assert(Specialization && "Missing function template specialization?");
6091   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6092                        SuppressUserConversions);
6093 }
6094 
6095 /// Determine whether this is an allowable conversion from the result
6096 /// of an explicit conversion operator to the expected type, per C++
6097 /// [over.match.conv]p1 and [over.match.ref]p1.
6098 ///
6099 /// \param ConvType The return type of the conversion function.
6100 ///
6101 /// \param ToType The type we are converting to.
6102 ///
6103 /// \param AllowObjCPointerConversion Allow a conversion from one
6104 /// Objective-C pointer to another.
6105 ///
6106 /// \returns true if the conversion is allowable, false otherwise.
6107 static bool isAllowableExplicitConversion(Sema &S,
6108                                           QualType ConvType, QualType ToType,
6109                                           bool AllowObjCPointerConversion) {
6110   QualType ToNonRefType = ToType.getNonReferenceType();
6111 
6112   // Easy case: the types are the same.
6113   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6114     return true;
6115 
6116   // Allow qualification conversions.
6117   bool ObjCLifetimeConversion;
6118   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6119                                   ObjCLifetimeConversion))
6120     return true;
6121 
6122   // If we're not allowed to consider Objective-C pointer conversions,
6123   // we're done.
6124   if (!AllowObjCPointerConversion)
6125     return false;
6126 
6127   // Is this an Objective-C pointer conversion?
6128   bool IncompatibleObjC = false;
6129   QualType ConvertedType;
6130   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6131                                    IncompatibleObjC);
6132 }
6133 
6134 /// AddConversionCandidate - Add a C++ conversion function as a
6135 /// candidate in the candidate set (C++ [over.match.conv],
6136 /// C++ [over.match.copy]). From is the expression we're converting from,
6137 /// and ToType is the type that we're eventually trying to convert to
6138 /// (which may or may not be the same type as the type that the
6139 /// conversion function produces).
6140 void
6141 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6142                              DeclAccessPair FoundDecl,
6143                              CXXRecordDecl *ActingContext,
6144                              Expr *From, QualType ToType,
6145                              OverloadCandidateSet& CandidateSet,
6146                              bool AllowObjCConversionOnExplicit) {
6147   assert(!Conversion->getDescribedFunctionTemplate() &&
6148          "Conversion function templates use AddTemplateConversionCandidate");
6149   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6150   if (!CandidateSet.isNewCandidate(Conversion))
6151     return;
6152 
6153   // If the conversion function has an undeduced return type, trigger its
6154   // deduction now.
6155   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6156     if (DeduceReturnType(Conversion, From->getExprLoc()))
6157       return;
6158     ConvType = Conversion->getConversionType().getNonReferenceType();
6159   }
6160 
6161   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6162   // operator is only a candidate if its return type is the target type or
6163   // can be converted to the target type with a qualification conversion.
6164   if (Conversion->isExplicit() &&
6165       !isAllowableExplicitConversion(*this, ConvType, ToType,
6166                                      AllowObjCConversionOnExplicit))
6167     return;
6168 
6169   // Overload resolution is always an unevaluated context.
6170   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6171 
6172   // Add this candidate
6173   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6174   Candidate.FoundDecl = FoundDecl;
6175   Candidate.Function = Conversion;
6176   Candidate.IsSurrogate = false;
6177   Candidate.IgnoreObjectArgument = false;
6178   Candidate.FinalConversion.setAsIdentityConversion();
6179   Candidate.FinalConversion.setFromType(ConvType);
6180   Candidate.FinalConversion.setAllToTypes(ToType);
6181   Candidate.Viable = true;
6182   Candidate.ExplicitCallArguments = 1;
6183 
6184   // C++ [over.match.funcs]p4:
6185   //   For conversion functions, the function is considered to be a member of
6186   //   the class of the implicit implied object argument for the purpose of
6187   //   defining the type of the implicit object parameter.
6188   //
6189   // Determine the implicit conversion sequence for the implicit
6190   // object parameter.
6191   QualType ImplicitParamType = From->getType();
6192   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6193     ImplicitParamType = FromPtrType->getPointeeType();
6194   CXXRecordDecl *ConversionContext
6195     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6196 
6197   Candidate.Conversions[0]
6198     = TryObjectArgumentInitialization(*this, From->getType(),
6199                                       From->Classify(Context),
6200                                       Conversion, ConversionContext);
6201 
6202   if (Candidate.Conversions[0].isBad()) {
6203     Candidate.Viable = false;
6204     Candidate.FailureKind = ovl_fail_bad_conversion;
6205     return;
6206   }
6207 
6208   // We won't go through a user-defined type conversion function to convert a
6209   // derived to base as such conversions are given Conversion Rank. They only
6210   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6211   QualType FromCanon
6212     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6213   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6214   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6215     Candidate.Viable = false;
6216     Candidate.FailureKind = ovl_fail_trivial_conversion;
6217     return;
6218   }
6219 
6220   // To determine what the conversion from the result of calling the
6221   // conversion function to the type we're eventually trying to
6222   // convert to (ToType), we need to synthesize a call to the
6223   // conversion function and attempt copy initialization from it. This
6224   // makes sure that we get the right semantics with respect to
6225   // lvalues/rvalues and the type. Fortunately, we can allocate this
6226   // call on the stack and we don't need its arguments to be
6227   // well-formed.
6228   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6229                             VK_LValue, From->getLocStart());
6230   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6231                                 Context.getPointerType(Conversion->getType()),
6232                                 CK_FunctionToPointerDecay,
6233                                 &ConversionRef, VK_RValue);
6234 
6235   QualType ConversionType = Conversion->getConversionType();
6236   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6237     Candidate.Viable = false;
6238     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6239     return;
6240   }
6241 
6242   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6243 
6244   // Note that it is safe to allocate CallExpr on the stack here because
6245   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6246   // allocator).
6247   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6248   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6249                 From->getLocStart());
6250   ImplicitConversionSequence ICS =
6251     TryCopyInitialization(*this, &Call, ToType,
6252                           /*SuppressUserConversions=*/true,
6253                           /*InOverloadResolution=*/false,
6254                           /*AllowObjCWritebackConversion=*/false);
6255 
6256   switch (ICS.getKind()) {
6257   case ImplicitConversionSequence::StandardConversion:
6258     Candidate.FinalConversion = ICS.Standard;
6259 
6260     // C++ [over.ics.user]p3:
6261     //   If the user-defined conversion is specified by a specialization of a
6262     //   conversion function template, the second standard conversion sequence
6263     //   shall have exact match rank.
6264     if (Conversion->getPrimaryTemplate() &&
6265         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6266       Candidate.Viable = false;
6267       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6268       return;
6269     }
6270 
6271     // C++0x [dcl.init.ref]p5:
6272     //    In the second case, if the reference is an rvalue reference and
6273     //    the second standard conversion sequence of the user-defined
6274     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6275     //    program is ill-formed.
6276     if (ToType->isRValueReferenceType() &&
6277         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6278       Candidate.Viable = false;
6279       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6280       return;
6281     }
6282     break;
6283 
6284   case ImplicitConversionSequence::BadConversion:
6285     Candidate.Viable = false;
6286     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6287     return;
6288 
6289   default:
6290     llvm_unreachable(
6291            "Can only end up with a standard conversion sequence or failure");
6292   }
6293 
6294   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6295     Candidate.Viable = false;
6296     Candidate.FailureKind = ovl_fail_enable_if;
6297     Candidate.DeductionFailure.Data = FailedAttr;
6298     return;
6299   }
6300 }
6301 
6302 /// \brief Adds a conversion function template specialization
6303 /// candidate to the overload set, using template argument deduction
6304 /// to deduce the template arguments of the conversion function
6305 /// template from the type that we are converting to (C++
6306 /// [temp.deduct.conv]).
6307 void
6308 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6309                                      DeclAccessPair FoundDecl,
6310                                      CXXRecordDecl *ActingDC,
6311                                      Expr *From, QualType ToType,
6312                                      OverloadCandidateSet &CandidateSet,
6313                                      bool AllowObjCConversionOnExplicit) {
6314   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6315          "Only conversion function templates permitted here");
6316 
6317   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6318     return;
6319 
6320   TemplateDeductionInfo Info(CandidateSet.getLocation());
6321   CXXConversionDecl *Specialization = nullptr;
6322   if (TemplateDeductionResult Result
6323         = DeduceTemplateArguments(FunctionTemplate, ToType,
6324                                   Specialization, Info)) {
6325     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6326     Candidate.FoundDecl = FoundDecl;
6327     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6328     Candidate.Viable = false;
6329     Candidate.FailureKind = ovl_fail_bad_deduction;
6330     Candidate.IsSurrogate = false;
6331     Candidate.IgnoreObjectArgument = false;
6332     Candidate.ExplicitCallArguments = 1;
6333     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6334                                                           Info);
6335     return;
6336   }
6337 
6338   // Add the conversion function template specialization produced by
6339   // template argument deduction as a candidate.
6340   assert(Specialization && "Missing function template specialization?");
6341   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6342                          CandidateSet, AllowObjCConversionOnExplicit);
6343 }
6344 
6345 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6346 /// converts the given @c Object to a function pointer via the
6347 /// conversion function @c Conversion, and then attempts to call it
6348 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6349 /// the type of function that we'll eventually be calling.
6350 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6351                                  DeclAccessPair FoundDecl,
6352                                  CXXRecordDecl *ActingContext,
6353                                  const FunctionProtoType *Proto,
6354                                  Expr *Object,
6355                                  ArrayRef<Expr *> Args,
6356                                  OverloadCandidateSet& CandidateSet) {
6357   if (!CandidateSet.isNewCandidate(Conversion))
6358     return;
6359 
6360   // Overload resolution is always an unevaluated context.
6361   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6362 
6363   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6364   Candidate.FoundDecl = FoundDecl;
6365   Candidate.Function = nullptr;
6366   Candidate.Surrogate = Conversion;
6367   Candidate.Viable = true;
6368   Candidate.IsSurrogate = true;
6369   Candidate.IgnoreObjectArgument = false;
6370   Candidate.ExplicitCallArguments = Args.size();
6371 
6372   // Determine the implicit conversion sequence for the implicit
6373   // object parameter.
6374   ImplicitConversionSequence ObjectInit
6375     = TryObjectArgumentInitialization(*this, Object->getType(),
6376                                       Object->Classify(Context),
6377                                       Conversion, ActingContext);
6378   if (ObjectInit.isBad()) {
6379     Candidate.Viable = false;
6380     Candidate.FailureKind = ovl_fail_bad_conversion;
6381     Candidate.Conversions[0] = ObjectInit;
6382     return;
6383   }
6384 
6385   // The first conversion is actually a user-defined conversion whose
6386   // first conversion is ObjectInit's standard conversion (which is
6387   // effectively a reference binding). Record it as such.
6388   Candidate.Conversions[0].setUserDefined();
6389   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6390   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6391   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6392   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6393   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6394   Candidate.Conversions[0].UserDefined.After
6395     = Candidate.Conversions[0].UserDefined.Before;
6396   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6397 
6398   // Find the
6399   unsigned NumParams = Proto->getNumParams();
6400 
6401   // (C++ 13.3.2p2): A candidate function having fewer than m
6402   // parameters is viable only if it has an ellipsis in its parameter
6403   // list (8.3.5).
6404   if (Args.size() > NumParams && !Proto->isVariadic()) {
6405     Candidate.Viable = false;
6406     Candidate.FailureKind = ovl_fail_too_many_arguments;
6407     return;
6408   }
6409 
6410   // Function types don't have any default arguments, so just check if
6411   // we have enough arguments.
6412   if (Args.size() < NumParams) {
6413     // Not enough arguments.
6414     Candidate.Viable = false;
6415     Candidate.FailureKind = ovl_fail_too_few_arguments;
6416     return;
6417   }
6418 
6419   // Determine the implicit conversion sequences for each of the
6420   // arguments.
6421   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6422     if (ArgIdx < NumParams) {
6423       // (C++ 13.3.2p3): for F to be a viable function, there shall
6424       // exist for each argument an implicit conversion sequence
6425       // (13.3.3.1) that converts that argument to the corresponding
6426       // parameter of F.
6427       QualType ParamType = Proto->getParamType(ArgIdx);
6428       Candidate.Conversions[ArgIdx + 1]
6429         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6430                                 /*SuppressUserConversions=*/false,
6431                                 /*InOverloadResolution=*/false,
6432                                 /*AllowObjCWritebackConversion=*/
6433                                   getLangOpts().ObjCAutoRefCount);
6434       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6435         Candidate.Viable = false;
6436         Candidate.FailureKind = ovl_fail_bad_conversion;
6437         return;
6438       }
6439     } else {
6440       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6441       // argument for which there is no corresponding parameter is
6442       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6443       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6444     }
6445   }
6446 
6447   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6448     Candidate.Viable = false;
6449     Candidate.FailureKind = ovl_fail_enable_if;
6450     Candidate.DeductionFailure.Data = FailedAttr;
6451     return;
6452   }
6453 }
6454 
6455 /// \brief Add overload candidates for overloaded operators that are
6456 /// member functions.
6457 ///
6458 /// Add the overloaded operator candidates that are member functions
6459 /// for the operator Op that was used in an operator expression such
6460 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6461 /// CandidateSet will store the added overload candidates. (C++
6462 /// [over.match.oper]).
6463 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6464                                        SourceLocation OpLoc,
6465                                        ArrayRef<Expr *> Args,
6466                                        OverloadCandidateSet& CandidateSet,
6467                                        SourceRange OpRange) {
6468   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6469 
6470   // C++ [over.match.oper]p3:
6471   //   For a unary operator @ with an operand of a type whose
6472   //   cv-unqualified version is T1, and for a binary operator @ with
6473   //   a left operand of a type whose cv-unqualified version is T1 and
6474   //   a right operand of a type whose cv-unqualified version is T2,
6475   //   three sets of candidate functions, designated member
6476   //   candidates, non-member candidates and built-in candidates, are
6477   //   constructed as follows:
6478   QualType T1 = Args[0]->getType();
6479 
6480   //     -- If T1 is a complete class type or a class currently being
6481   //        defined, the set of member candidates is the result of the
6482   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6483   //        the set of member candidates is empty.
6484   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6485     // Complete the type if it can be completed.
6486     RequireCompleteType(OpLoc, T1, 0);
6487     // If the type is neither complete nor being defined, bail out now.
6488     if (!T1Rec->getDecl()->getDefinition())
6489       return;
6490 
6491     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6492     LookupQualifiedName(Operators, T1Rec->getDecl());
6493     Operators.suppressDiagnostics();
6494 
6495     for (LookupResult::iterator Oper = Operators.begin(),
6496                              OperEnd = Operators.end();
6497          Oper != OperEnd;
6498          ++Oper)
6499       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6500                          Args[0]->Classify(Context),
6501                          Args.slice(1),
6502                          CandidateSet,
6503                          /* SuppressUserConversions = */ false);
6504   }
6505 }
6506 
6507 /// AddBuiltinCandidate - Add a candidate for a built-in
6508 /// operator. ResultTy and ParamTys are the result and parameter types
6509 /// of the built-in candidate, respectively. Args and NumArgs are the
6510 /// arguments being passed to the candidate. IsAssignmentOperator
6511 /// should be true when this built-in candidate is an assignment
6512 /// operator. NumContextualBoolArguments is the number of arguments
6513 /// (at the beginning of the argument list) that will be contextually
6514 /// converted to bool.
6515 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6516                                ArrayRef<Expr *> Args,
6517                                OverloadCandidateSet& CandidateSet,
6518                                bool IsAssignmentOperator,
6519                                unsigned NumContextualBoolArguments) {
6520   // Overload resolution is always an unevaluated context.
6521   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6522 
6523   // Add this candidate
6524   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6525   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6526   Candidate.Function = nullptr;
6527   Candidate.IsSurrogate = false;
6528   Candidate.IgnoreObjectArgument = false;
6529   Candidate.BuiltinTypes.ResultTy = ResultTy;
6530   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6531     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6532 
6533   // Determine the implicit conversion sequences for each of the
6534   // arguments.
6535   Candidate.Viable = true;
6536   Candidate.ExplicitCallArguments = Args.size();
6537   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6538     // C++ [over.match.oper]p4:
6539     //   For the built-in assignment operators, conversions of the
6540     //   left operand are restricted as follows:
6541     //     -- no temporaries are introduced to hold the left operand, and
6542     //     -- no user-defined conversions are applied to the left
6543     //        operand to achieve a type match with the left-most
6544     //        parameter of a built-in candidate.
6545     //
6546     // We block these conversions by turning off user-defined
6547     // conversions, since that is the only way that initialization of
6548     // a reference to a non-class type can occur from something that
6549     // is not of the same type.
6550     if (ArgIdx < NumContextualBoolArguments) {
6551       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6552              "Contextual conversion to bool requires bool type");
6553       Candidate.Conversions[ArgIdx]
6554         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6555     } else {
6556       Candidate.Conversions[ArgIdx]
6557         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6558                                 ArgIdx == 0 && IsAssignmentOperator,
6559                                 /*InOverloadResolution=*/false,
6560                                 /*AllowObjCWritebackConversion=*/
6561                                   getLangOpts().ObjCAutoRefCount);
6562     }
6563     if (Candidate.Conversions[ArgIdx].isBad()) {
6564       Candidate.Viable = false;
6565       Candidate.FailureKind = ovl_fail_bad_conversion;
6566       break;
6567     }
6568   }
6569 }
6570 
6571 namespace {
6572 
6573 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6574 /// candidate operator functions for built-in operators (C++
6575 /// [over.built]). The types are separated into pointer types and
6576 /// enumeration types.
6577 class BuiltinCandidateTypeSet  {
6578   /// TypeSet - A set of types.
6579   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6580 
6581   /// PointerTypes - The set of pointer types that will be used in the
6582   /// built-in candidates.
6583   TypeSet PointerTypes;
6584 
6585   /// MemberPointerTypes - The set of member pointer types that will be
6586   /// used in the built-in candidates.
6587   TypeSet MemberPointerTypes;
6588 
6589   /// EnumerationTypes - The set of enumeration types that will be
6590   /// used in the built-in candidates.
6591   TypeSet EnumerationTypes;
6592 
6593   /// \brief The set of vector types that will be used in the built-in
6594   /// candidates.
6595   TypeSet VectorTypes;
6596 
6597   /// \brief A flag indicating non-record types are viable candidates
6598   bool HasNonRecordTypes;
6599 
6600   /// \brief A flag indicating whether either arithmetic or enumeration types
6601   /// were present in the candidate set.
6602   bool HasArithmeticOrEnumeralTypes;
6603 
6604   /// \brief A flag indicating whether the nullptr type was present in the
6605   /// candidate set.
6606   bool HasNullPtrType;
6607 
6608   /// Sema - The semantic analysis instance where we are building the
6609   /// candidate type set.
6610   Sema &SemaRef;
6611 
6612   /// Context - The AST context in which we will build the type sets.
6613   ASTContext &Context;
6614 
6615   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6616                                                const Qualifiers &VisibleQuals);
6617   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6618 
6619 public:
6620   /// iterator - Iterates through the types that are part of the set.
6621   typedef TypeSet::iterator iterator;
6622 
6623   BuiltinCandidateTypeSet(Sema &SemaRef)
6624     : HasNonRecordTypes(false),
6625       HasArithmeticOrEnumeralTypes(false),
6626       HasNullPtrType(false),
6627       SemaRef(SemaRef),
6628       Context(SemaRef.Context) { }
6629 
6630   void AddTypesConvertedFrom(QualType Ty,
6631                              SourceLocation Loc,
6632                              bool AllowUserConversions,
6633                              bool AllowExplicitConversions,
6634                              const Qualifiers &VisibleTypeConversionsQuals);
6635 
6636   /// pointer_begin - First pointer type found;
6637   iterator pointer_begin() { return PointerTypes.begin(); }
6638 
6639   /// pointer_end - Past the last pointer type found;
6640   iterator pointer_end() { return PointerTypes.end(); }
6641 
6642   /// member_pointer_begin - First member pointer type found;
6643   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6644 
6645   /// member_pointer_end - Past the last member pointer type found;
6646   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6647 
6648   /// enumeration_begin - First enumeration type found;
6649   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6650 
6651   /// enumeration_end - Past the last enumeration type found;
6652   iterator enumeration_end() { return EnumerationTypes.end(); }
6653 
6654   iterator vector_begin() { return VectorTypes.begin(); }
6655   iterator vector_end() { return VectorTypes.end(); }
6656 
6657   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6658   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6659   bool hasNullPtrType() const { return HasNullPtrType; }
6660 };
6661 
6662 } // end anonymous namespace
6663 
6664 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6665 /// the set of pointer types along with any more-qualified variants of
6666 /// that type. For example, if @p Ty is "int const *", this routine
6667 /// will add "int const *", "int const volatile *", "int const
6668 /// restrict *", and "int const volatile restrict *" to the set of
6669 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6670 /// false otherwise.
6671 ///
6672 /// FIXME: what to do about extended qualifiers?
6673 bool
6674 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6675                                              const Qualifiers &VisibleQuals) {
6676 
6677   // Insert this type.
6678   if (!PointerTypes.insert(Ty).second)
6679     return false;
6680 
6681   QualType PointeeTy;
6682   const PointerType *PointerTy = Ty->getAs<PointerType>();
6683   bool buildObjCPtr = false;
6684   if (!PointerTy) {
6685     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6686     PointeeTy = PTy->getPointeeType();
6687     buildObjCPtr = true;
6688   } else {
6689     PointeeTy = PointerTy->getPointeeType();
6690   }
6691 
6692   // Don't add qualified variants of arrays. For one, they're not allowed
6693   // (the qualifier would sink to the element type), and for another, the
6694   // only overload situation where it matters is subscript or pointer +- int,
6695   // and those shouldn't have qualifier variants anyway.
6696   if (PointeeTy->isArrayType())
6697     return true;
6698 
6699   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6700   bool hasVolatile = VisibleQuals.hasVolatile();
6701   bool hasRestrict = VisibleQuals.hasRestrict();
6702 
6703   // Iterate through all strict supersets of BaseCVR.
6704   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6705     if ((CVR | BaseCVR) != CVR) continue;
6706     // Skip over volatile if no volatile found anywhere in the types.
6707     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6708 
6709     // Skip over restrict if no restrict found anywhere in the types, or if
6710     // the type cannot be restrict-qualified.
6711     if ((CVR & Qualifiers::Restrict) &&
6712         (!hasRestrict ||
6713          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6714       continue;
6715 
6716     // Build qualified pointee type.
6717     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6718 
6719     // Build qualified pointer type.
6720     QualType QPointerTy;
6721     if (!buildObjCPtr)
6722       QPointerTy = Context.getPointerType(QPointeeTy);
6723     else
6724       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6725 
6726     // Insert qualified pointer type.
6727     PointerTypes.insert(QPointerTy);
6728   }
6729 
6730   return true;
6731 }
6732 
6733 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6734 /// to the set of pointer types along with any more-qualified variants of
6735 /// that type. For example, if @p Ty is "int const *", this routine
6736 /// will add "int const *", "int const volatile *", "int const
6737 /// restrict *", and "int const volatile restrict *" to the set of
6738 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6739 /// false otherwise.
6740 ///
6741 /// FIXME: what to do about extended qualifiers?
6742 bool
6743 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6744     QualType Ty) {
6745   // Insert this type.
6746   if (!MemberPointerTypes.insert(Ty).second)
6747     return false;
6748 
6749   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6750   assert(PointerTy && "type was not a member pointer type!");
6751 
6752   QualType PointeeTy = PointerTy->getPointeeType();
6753   // Don't add qualified variants of arrays. For one, they're not allowed
6754   // (the qualifier would sink to the element type), and for another, the
6755   // only overload situation where it matters is subscript or pointer +- int,
6756   // and those shouldn't have qualifier variants anyway.
6757   if (PointeeTy->isArrayType())
6758     return true;
6759   const Type *ClassTy = PointerTy->getClass();
6760 
6761   // Iterate through all strict supersets of the pointee type's CVR
6762   // qualifiers.
6763   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6764   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6765     if ((CVR | BaseCVR) != CVR) continue;
6766 
6767     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6768     MemberPointerTypes.insert(
6769       Context.getMemberPointerType(QPointeeTy, ClassTy));
6770   }
6771 
6772   return true;
6773 }
6774 
6775 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6776 /// Ty can be implicit converted to the given set of @p Types. We're
6777 /// primarily interested in pointer types and enumeration types. We also
6778 /// take member pointer types, for the conditional operator.
6779 /// AllowUserConversions is true if we should look at the conversion
6780 /// functions of a class type, and AllowExplicitConversions if we
6781 /// should also include the explicit conversion functions of a class
6782 /// type.
6783 void
6784 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6785                                                SourceLocation Loc,
6786                                                bool AllowUserConversions,
6787                                                bool AllowExplicitConversions,
6788                                                const Qualifiers &VisibleQuals) {
6789   // Only deal with canonical types.
6790   Ty = Context.getCanonicalType(Ty);
6791 
6792   // Look through reference types; they aren't part of the type of an
6793   // expression for the purposes of conversions.
6794   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6795     Ty = RefTy->getPointeeType();
6796 
6797   // If we're dealing with an array type, decay to the pointer.
6798   if (Ty->isArrayType())
6799     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6800 
6801   // Otherwise, we don't care about qualifiers on the type.
6802   Ty = Ty.getLocalUnqualifiedType();
6803 
6804   // Flag if we ever add a non-record type.
6805   const RecordType *TyRec = Ty->getAs<RecordType>();
6806   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6807 
6808   // Flag if we encounter an arithmetic type.
6809   HasArithmeticOrEnumeralTypes =
6810     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6811 
6812   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6813     PointerTypes.insert(Ty);
6814   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6815     // Insert our type, and its more-qualified variants, into the set
6816     // of types.
6817     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6818       return;
6819   } else if (Ty->isMemberPointerType()) {
6820     // Member pointers are far easier, since the pointee can't be converted.
6821     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6822       return;
6823   } else if (Ty->isEnumeralType()) {
6824     HasArithmeticOrEnumeralTypes = true;
6825     EnumerationTypes.insert(Ty);
6826   } else if (Ty->isVectorType()) {
6827     // We treat vector types as arithmetic types in many contexts as an
6828     // extension.
6829     HasArithmeticOrEnumeralTypes = true;
6830     VectorTypes.insert(Ty);
6831   } else if (Ty->isNullPtrType()) {
6832     HasNullPtrType = true;
6833   } else if (AllowUserConversions && TyRec) {
6834     // No conversion functions in incomplete types.
6835     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6836       return;
6837 
6838     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6839     std::pair<CXXRecordDecl::conversion_iterator,
6840               CXXRecordDecl::conversion_iterator>
6841       Conversions = ClassDecl->getVisibleConversionFunctions();
6842     for (CXXRecordDecl::conversion_iterator
6843            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6844       NamedDecl *D = I.getDecl();
6845       if (isa<UsingShadowDecl>(D))
6846         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6847 
6848       // Skip conversion function templates; they don't tell us anything
6849       // about which builtin types we can convert to.
6850       if (isa<FunctionTemplateDecl>(D))
6851         continue;
6852 
6853       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6854       if (AllowExplicitConversions || !Conv->isExplicit()) {
6855         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6856                               VisibleQuals);
6857       }
6858     }
6859   }
6860 }
6861 
6862 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6863 /// the volatile- and non-volatile-qualified assignment operators for the
6864 /// given type to the candidate set.
6865 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6866                                                    QualType T,
6867                                                    ArrayRef<Expr *> Args,
6868                                     OverloadCandidateSet &CandidateSet) {
6869   QualType ParamTypes[2];
6870 
6871   // T& operator=(T&, T)
6872   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6873   ParamTypes[1] = T;
6874   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6875                         /*IsAssignmentOperator=*/true);
6876 
6877   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6878     // volatile T& operator=(volatile T&, T)
6879     ParamTypes[0]
6880       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6881     ParamTypes[1] = T;
6882     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6883                           /*IsAssignmentOperator=*/true);
6884   }
6885 }
6886 
6887 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6888 /// if any, found in visible type conversion functions found in ArgExpr's type.
6889 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6890     Qualifiers VRQuals;
6891     const RecordType *TyRec;
6892     if (const MemberPointerType *RHSMPType =
6893         ArgExpr->getType()->getAs<MemberPointerType>())
6894       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6895     else
6896       TyRec = ArgExpr->getType()->getAs<RecordType>();
6897     if (!TyRec) {
6898       // Just to be safe, assume the worst case.
6899       VRQuals.addVolatile();
6900       VRQuals.addRestrict();
6901       return VRQuals;
6902     }
6903 
6904     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6905     if (!ClassDecl->hasDefinition())
6906       return VRQuals;
6907 
6908     std::pair<CXXRecordDecl::conversion_iterator,
6909               CXXRecordDecl::conversion_iterator>
6910       Conversions = ClassDecl->getVisibleConversionFunctions();
6911 
6912     for (CXXRecordDecl::conversion_iterator
6913            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6914       NamedDecl *D = I.getDecl();
6915       if (isa<UsingShadowDecl>(D))
6916         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6917       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6918         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6919         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6920           CanTy = ResTypeRef->getPointeeType();
6921         // Need to go down the pointer/mempointer chain and add qualifiers
6922         // as see them.
6923         bool done = false;
6924         while (!done) {
6925           if (CanTy.isRestrictQualified())
6926             VRQuals.addRestrict();
6927           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6928             CanTy = ResTypePtr->getPointeeType();
6929           else if (const MemberPointerType *ResTypeMPtr =
6930                 CanTy->getAs<MemberPointerType>())
6931             CanTy = ResTypeMPtr->getPointeeType();
6932           else
6933             done = true;
6934           if (CanTy.isVolatileQualified())
6935             VRQuals.addVolatile();
6936           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6937             return VRQuals;
6938         }
6939       }
6940     }
6941     return VRQuals;
6942 }
6943 
6944 namespace {
6945 
6946 /// \brief Helper class to manage the addition of builtin operator overload
6947 /// candidates. It provides shared state and utility methods used throughout
6948 /// the process, as well as a helper method to add each group of builtin
6949 /// operator overloads from the standard to a candidate set.
6950 class BuiltinOperatorOverloadBuilder {
6951   // Common instance state available to all overload candidate addition methods.
6952   Sema &S;
6953   ArrayRef<Expr *> Args;
6954   Qualifiers VisibleTypeConversionsQuals;
6955   bool HasArithmeticOrEnumeralCandidateType;
6956   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6957   OverloadCandidateSet &CandidateSet;
6958 
6959   // Define some constants used to index and iterate over the arithemetic types
6960   // provided via the getArithmeticType() method below.
6961   // The "promoted arithmetic types" are the arithmetic
6962   // types are that preserved by promotion (C++ [over.built]p2).
6963   static const unsigned FirstIntegralType = 3;
6964   static const unsigned LastIntegralType = 20;
6965   static const unsigned FirstPromotedIntegralType = 3,
6966                         LastPromotedIntegralType = 11;
6967   static const unsigned FirstPromotedArithmeticType = 0,
6968                         LastPromotedArithmeticType = 11;
6969   static const unsigned NumArithmeticTypes = 20;
6970 
6971   /// \brief Get the canonical type for a given arithmetic type index.
6972   CanQualType getArithmeticType(unsigned index) {
6973     assert(index < NumArithmeticTypes);
6974     static CanQualType ASTContext::* const
6975       ArithmeticTypes[NumArithmeticTypes] = {
6976       // Start of promoted types.
6977       &ASTContext::FloatTy,
6978       &ASTContext::DoubleTy,
6979       &ASTContext::LongDoubleTy,
6980 
6981       // Start of integral types.
6982       &ASTContext::IntTy,
6983       &ASTContext::LongTy,
6984       &ASTContext::LongLongTy,
6985       &ASTContext::Int128Ty,
6986       &ASTContext::UnsignedIntTy,
6987       &ASTContext::UnsignedLongTy,
6988       &ASTContext::UnsignedLongLongTy,
6989       &ASTContext::UnsignedInt128Ty,
6990       // End of promoted types.
6991 
6992       &ASTContext::BoolTy,
6993       &ASTContext::CharTy,
6994       &ASTContext::WCharTy,
6995       &ASTContext::Char16Ty,
6996       &ASTContext::Char32Ty,
6997       &ASTContext::SignedCharTy,
6998       &ASTContext::ShortTy,
6999       &ASTContext::UnsignedCharTy,
7000       &ASTContext::UnsignedShortTy,
7001       // End of integral types.
7002       // FIXME: What about complex? What about half?
7003     };
7004     return S.Context.*ArithmeticTypes[index];
7005   }
7006 
7007   /// \brief Gets the canonical type resulting from the usual arithemetic
7008   /// converions for the given arithmetic types.
7009   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7010     // Accelerator table for performing the usual arithmetic conversions.
7011     // The rules are basically:
7012     //   - if either is floating-point, use the wider floating-point
7013     //   - if same signedness, use the higher rank
7014     //   - if same size, use unsigned of the higher rank
7015     //   - use the larger type
7016     // These rules, together with the axiom that higher ranks are
7017     // never smaller, are sufficient to precompute all of these results
7018     // *except* when dealing with signed types of higher rank.
7019     // (we could precompute SLL x UI for all known platforms, but it's
7020     // better not to make any assumptions).
7021     // We assume that int128 has a higher rank than long long on all platforms.
7022     enum PromotedType {
7023             Dep=-1,
7024             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7025     };
7026     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7027                                         [LastPromotedArithmeticType] = {
7028 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7029 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7030 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7031 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7032 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7033 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7034 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7035 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7036 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7037 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7038 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7039     };
7040 
7041     assert(L < LastPromotedArithmeticType);
7042     assert(R < LastPromotedArithmeticType);
7043     int Idx = ConversionsTable[L][R];
7044 
7045     // Fast path: the table gives us a concrete answer.
7046     if (Idx != Dep) return getArithmeticType(Idx);
7047 
7048     // Slow path: we need to compare widths.
7049     // An invariant is that the signed type has higher rank.
7050     CanQualType LT = getArithmeticType(L),
7051                 RT = getArithmeticType(R);
7052     unsigned LW = S.Context.getIntWidth(LT),
7053              RW = S.Context.getIntWidth(RT);
7054 
7055     // If they're different widths, use the signed type.
7056     if (LW > RW) return LT;
7057     else if (LW < RW) return RT;
7058 
7059     // Otherwise, use the unsigned type of the signed type's rank.
7060     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7061     assert(L == SLL || R == SLL);
7062     return S.Context.UnsignedLongLongTy;
7063   }
7064 
7065   /// \brief Helper method to factor out the common pattern of adding overloads
7066   /// for '++' and '--' builtin operators.
7067   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7068                                            bool HasVolatile,
7069                                            bool HasRestrict) {
7070     QualType ParamTypes[2] = {
7071       S.Context.getLValueReferenceType(CandidateTy),
7072       S.Context.IntTy
7073     };
7074 
7075     // Non-volatile version.
7076     if (Args.size() == 1)
7077       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7078     else
7079       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7080 
7081     // Use a heuristic to reduce number of builtin candidates in the set:
7082     // add volatile version only if there are conversions to a volatile type.
7083     if (HasVolatile) {
7084       ParamTypes[0] =
7085         S.Context.getLValueReferenceType(
7086           S.Context.getVolatileType(CandidateTy));
7087       if (Args.size() == 1)
7088         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7089       else
7090         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7091     }
7092 
7093     // Add restrict version only if there are conversions to a restrict type
7094     // and our candidate type is a non-restrict-qualified pointer.
7095     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7096         !CandidateTy.isRestrictQualified()) {
7097       ParamTypes[0]
7098         = S.Context.getLValueReferenceType(
7099             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7100       if (Args.size() == 1)
7101         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7102       else
7103         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7104 
7105       if (HasVolatile) {
7106         ParamTypes[0]
7107           = S.Context.getLValueReferenceType(
7108               S.Context.getCVRQualifiedType(CandidateTy,
7109                                             (Qualifiers::Volatile |
7110                                              Qualifiers::Restrict)));
7111         if (Args.size() == 1)
7112           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7113         else
7114           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7115       }
7116     }
7117 
7118   }
7119 
7120 public:
7121   BuiltinOperatorOverloadBuilder(
7122     Sema &S, ArrayRef<Expr *> Args,
7123     Qualifiers VisibleTypeConversionsQuals,
7124     bool HasArithmeticOrEnumeralCandidateType,
7125     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7126     OverloadCandidateSet &CandidateSet)
7127     : S(S), Args(Args),
7128       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7129       HasArithmeticOrEnumeralCandidateType(
7130         HasArithmeticOrEnumeralCandidateType),
7131       CandidateTypes(CandidateTypes),
7132       CandidateSet(CandidateSet) {
7133     // Validate some of our static helper constants in debug builds.
7134     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7135            "Invalid first promoted integral type");
7136     assert(getArithmeticType(LastPromotedIntegralType - 1)
7137              == S.Context.UnsignedInt128Ty &&
7138            "Invalid last promoted integral type");
7139     assert(getArithmeticType(FirstPromotedArithmeticType)
7140              == S.Context.FloatTy &&
7141            "Invalid first promoted arithmetic type");
7142     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7143              == S.Context.UnsignedInt128Ty &&
7144            "Invalid last promoted arithmetic type");
7145   }
7146 
7147   // C++ [over.built]p3:
7148   //
7149   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7150   //   is either volatile or empty, there exist candidate operator
7151   //   functions of the form
7152   //
7153   //       VQ T&      operator++(VQ T&);
7154   //       T          operator++(VQ T&, int);
7155   //
7156   // C++ [over.built]p4:
7157   //
7158   //   For every pair (T, VQ), where T is an arithmetic type other
7159   //   than bool, and VQ is either volatile or empty, there exist
7160   //   candidate operator functions of the form
7161   //
7162   //       VQ T&      operator--(VQ T&);
7163   //       T          operator--(VQ T&, int);
7164   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7165     if (!HasArithmeticOrEnumeralCandidateType)
7166       return;
7167 
7168     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7169          Arith < NumArithmeticTypes; ++Arith) {
7170       addPlusPlusMinusMinusStyleOverloads(
7171         getArithmeticType(Arith),
7172         VisibleTypeConversionsQuals.hasVolatile(),
7173         VisibleTypeConversionsQuals.hasRestrict());
7174     }
7175   }
7176 
7177   // C++ [over.built]p5:
7178   //
7179   //   For every pair (T, VQ), where T is a cv-qualified or
7180   //   cv-unqualified object type, and VQ is either volatile or
7181   //   empty, there exist candidate operator functions of the form
7182   //
7183   //       T*VQ&      operator++(T*VQ&);
7184   //       T*VQ&      operator--(T*VQ&);
7185   //       T*         operator++(T*VQ&, int);
7186   //       T*         operator--(T*VQ&, int);
7187   void addPlusPlusMinusMinusPointerOverloads() {
7188     for (BuiltinCandidateTypeSet::iterator
7189               Ptr = CandidateTypes[0].pointer_begin(),
7190            PtrEnd = CandidateTypes[0].pointer_end();
7191          Ptr != PtrEnd; ++Ptr) {
7192       // Skip pointer types that aren't pointers to object types.
7193       if (!(*Ptr)->getPointeeType()->isObjectType())
7194         continue;
7195 
7196       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7197         (!(*Ptr).isVolatileQualified() &&
7198          VisibleTypeConversionsQuals.hasVolatile()),
7199         (!(*Ptr).isRestrictQualified() &&
7200          VisibleTypeConversionsQuals.hasRestrict()));
7201     }
7202   }
7203 
7204   // C++ [over.built]p6:
7205   //   For every cv-qualified or cv-unqualified object type T, there
7206   //   exist candidate operator functions of the form
7207   //
7208   //       T&         operator*(T*);
7209   //
7210   // C++ [over.built]p7:
7211   //   For every function type T that does not have cv-qualifiers or a
7212   //   ref-qualifier, there exist candidate operator functions of the form
7213   //       T&         operator*(T*);
7214   void addUnaryStarPointerOverloads() {
7215     for (BuiltinCandidateTypeSet::iterator
7216               Ptr = CandidateTypes[0].pointer_begin(),
7217            PtrEnd = CandidateTypes[0].pointer_end();
7218          Ptr != PtrEnd; ++Ptr) {
7219       QualType ParamTy = *Ptr;
7220       QualType PointeeTy = ParamTy->getPointeeType();
7221       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7222         continue;
7223 
7224       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7225         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7226           continue;
7227 
7228       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7229                             &ParamTy, Args, CandidateSet);
7230     }
7231   }
7232 
7233   // C++ [over.built]p9:
7234   //  For every promoted arithmetic type T, there exist candidate
7235   //  operator functions of the form
7236   //
7237   //       T         operator+(T);
7238   //       T         operator-(T);
7239   void addUnaryPlusOrMinusArithmeticOverloads() {
7240     if (!HasArithmeticOrEnumeralCandidateType)
7241       return;
7242 
7243     for (unsigned Arith = FirstPromotedArithmeticType;
7244          Arith < LastPromotedArithmeticType; ++Arith) {
7245       QualType ArithTy = getArithmeticType(Arith);
7246       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7247     }
7248 
7249     // Extension: We also add these operators for vector types.
7250     for (BuiltinCandidateTypeSet::iterator
7251               Vec = CandidateTypes[0].vector_begin(),
7252            VecEnd = CandidateTypes[0].vector_end();
7253          Vec != VecEnd; ++Vec) {
7254       QualType VecTy = *Vec;
7255       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7256     }
7257   }
7258 
7259   // C++ [over.built]p8:
7260   //   For every type T, there exist candidate operator functions of
7261   //   the form
7262   //
7263   //       T*         operator+(T*);
7264   void addUnaryPlusPointerOverloads() {
7265     for (BuiltinCandidateTypeSet::iterator
7266               Ptr = CandidateTypes[0].pointer_begin(),
7267            PtrEnd = CandidateTypes[0].pointer_end();
7268          Ptr != PtrEnd; ++Ptr) {
7269       QualType ParamTy = *Ptr;
7270       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7271     }
7272   }
7273 
7274   // C++ [over.built]p10:
7275   //   For every promoted integral type T, there exist candidate
7276   //   operator functions of the form
7277   //
7278   //        T         operator~(T);
7279   void addUnaryTildePromotedIntegralOverloads() {
7280     if (!HasArithmeticOrEnumeralCandidateType)
7281       return;
7282 
7283     for (unsigned Int = FirstPromotedIntegralType;
7284          Int < LastPromotedIntegralType; ++Int) {
7285       QualType IntTy = getArithmeticType(Int);
7286       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7287     }
7288 
7289     // Extension: We also add this operator for vector types.
7290     for (BuiltinCandidateTypeSet::iterator
7291               Vec = CandidateTypes[0].vector_begin(),
7292            VecEnd = CandidateTypes[0].vector_end();
7293          Vec != VecEnd; ++Vec) {
7294       QualType VecTy = *Vec;
7295       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7296     }
7297   }
7298 
7299   // C++ [over.match.oper]p16:
7300   //   For every pointer to member type T, there exist candidate operator
7301   //   functions of the form
7302   //
7303   //        bool operator==(T,T);
7304   //        bool operator!=(T,T);
7305   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7306     /// Set of (canonical) types that we've already handled.
7307     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7308 
7309     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7310       for (BuiltinCandidateTypeSet::iterator
7311                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7312              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7313            MemPtr != MemPtrEnd;
7314            ++MemPtr) {
7315         // Don't add the same builtin candidate twice.
7316         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7317           continue;
7318 
7319         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7320         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7321       }
7322     }
7323   }
7324 
7325   // C++ [over.built]p15:
7326   //
7327   //   For every T, where T is an enumeration type, a pointer type, or
7328   //   std::nullptr_t, there exist candidate operator functions of the form
7329   //
7330   //        bool       operator<(T, T);
7331   //        bool       operator>(T, T);
7332   //        bool       operator<=(T, T);
7333   //        bool       operator>=(T, T);
7334   //        bool       operator==(T, T);
7335   //        bool       operator!=(T, T);
7336   void addRelationalPointerOrEnumeralOverloads() {
7337     // C++ [over.match.oper]p3:
7338     //   [...]the built-in candidates include all of the candidate operator
7339     //   functions defined in 13.6 that, compared to the given operator, [...]
7340     //   do not have the same parameter-type-list as any non-template non-member
7341     //   candidate.
7342     //
7343     // Note that in practice, this only affects enumeration types because there
7344     // aren't any built-in candidates of record type, and a user-defined operator
7345     // must have an operand of record or enumeration type. Also, the only other
7346     // overloaded operator with enumeration arguments, operator=,
7347     // cannot be overloaded for enumeration types, so this is the only place
7348     // where we must suppress candidates like this.
7349     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7350       UserDefinedBinaryOperators;
7351 
7352     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7353       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7354           CandidateTypes[ArgIdx].enumeration_end()) {
7355         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7356                                          CEnd = CandidateSet.end();
7357              C != CEnd; ++C) {
7358           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7359             continue;
7360 
7361           if (C->Function->isFunctionTemplateSpecialization())
7362             continue;
7363 
7364           QualType FirstParamType =
7365             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7366           QualType SecondParamType =
7367             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7368 
7369           // Skip if either parameter isn't of enumeral type.
7370           if (!FirstParamType->isEnumeralType() ||
7371               !SecondParamType->isEnumeralType())
7372             continue;
7373 
7374           // Add this operator to the set of known user-defined operators.
7375           UserDefinedBinaryOperators.insert(
7376             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7377                            S.Context.getCanonicalType(SecondParamType)));
7378         }
7379       }
7380     }
7381 
7382     /// Set of (canonical) types that we've already handled.
7383     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7384 
7385     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7386       for (BuiltinCandidateTypeSet::iterator
7387                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7388              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7389            Ptr != PtrEnd; ++Ptr) {
7390         // Don't add the same builtin candidate twice.
7391         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7392           continue;
7393 
7394         QualType ParamTypes[2] = { *Ptr, *Ptr };
7395         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7396       }
7397       for (BuiltinCandidateTypeSet::iterator
7398                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7399              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7400            Enum != EnumEnd; ++Enum) {
7401         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7402 
7403         // Don't add the same builtin candidate twice, or if a user defined
7404         // candidate exists.
7405         if (!AddedTypes.insert(CanonType).second ||
7406             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7407                                                             CanonType)))
7408           continue;
7409 
7410         QualType ParamTypes[2] = { *Enum, *Enum };
7411         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7412       }
7413 
7414       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7415         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7416         if (AddedTypes.insert(NullPtrTy).second &&
7417             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7418                                                              NullPtrTy))) {
7419           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7420           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7421                                 CandidateSet);
7422         }
7423       }
7424     }
7425   }
7426 
7427   // C++ [over.built]p13:
7428   //
7429   //   For every cv-qualified or cv-unqualified object type T
7430   //   there exist candidate operator functions of the form
7431   //
7432   //      T*         operator+(T*, ptrdiff_t);
7433   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7434   //      T*         operator-(T*, ptrdiff_t);
7435   //      T*         operator+(ptrdiff_t, T*);
7436   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7437   //
7438   // C++ [over.built]p14:
7439   //
7440   //   For every T, where T is a pointer to object type, there
7441   //   exist candidate operator functions of the form
7442   //
7443   //      ptrdiff_t  operator-(T, T);
7444   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7445     /// Set of (canonical) types that we've already handled.
7446     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7447 
7448     for (int Arg = 0; Arg < 2; ++Arg) {
7449       QualType AsymetricParamTypes[2] = {
7450         S.Context.getPointerDiffType(),
7451         S.Context.getPointerDiffType(),
7452       };
7453       for (BuiltinCandidateTypeSet::iterator
7454                 Ptr = CandidateTypes[Arg].pointer_begin(),
7455              PtrEnd = CandidateTypes[Arg].pointer_end();
7456            Ptr != PtrEnd; ++Ptr) {
7457         QualType PointeeTy = (*Ptr)->getPointeeType();
7458         if (!PointeeTy->isObjectType())
7459           continue;
7460 
7461         AsymetricParamTypes[Arg] = *Ptr;
7462         if (Arg == 0 || Op == OO_Plus) {
7463           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7464           // T* operator+(ptrdiff_t, T*);
7465           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7466         }
7467         if (Op == OO_Minus) {
7468           // ptrdiff_t operator-(T, T);
7469           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7470             continue;
7471 
7472           QualType ParamTypes[2] = { *Ptr, *Ptr };
7473           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7474                                 Args, CandidateSet);
7475         }
7476       }
7477     }
7478   }
7479 
7480   // C++ [over.built]p12:
7481   //
7482   //   For every pair of promoted arithmetic types L and R, there
7483   //   exist candidate operator functions of the form
7484   //
7485   //        LR         operator*(L, R);
7486   //        LR         operator/(L, R);
7487   //        LR         operator+(L, R);
7488   //        LR         operator-(L, R);
7489   //        bool       operator<(L, R);
7490   //        bool       operator>(L, R);
7491   //        bool       operator<=(L, R);
7492   //        bool       operator>=(L, R);
7493   //        bool       operator==(L, R);
7494   //        bool       operator!=(L, R);
7495   //
7496   //   where LR is the result of the usual arithmetic conversions
7497   //   between types L and R.
7498   //
7499   // C++ [over.built]p24:
7500   //
7501   //   For every pair of promoted arithmetic types L and R, there exist
7502   //   candidate operator functions of the form
7503   //
7504   //        LR       operator?(bool, L, R);
7505   //
7506   //   where LR is the result of the usual arithmetic conversions
7507   //   between types L and R.
7508   // Our candidates ignore the first parameter.
7509   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7510     if (!HasArithmeticOrEnumeralCandidateType)
7511       return;
7512 
7513     for (unsigned Left = FirstPromotedArithmeticType;
7514          Left < LastPromotedArithmeticType; ++Left) {
7515       for (unsigned Right = FirstPromotedArithmeticType;
7516            Right < LastPromotedArithmeticType; ++Right) {
7517         QualType LandR[2] = { getArithmeticType(Left),
7518                               getArithmeticType(Right) };
7519         QualType Result =
7520           isComparison ? S.Context.BoolTy
7521                        : getUsualArithmeticConversions(Left, Right);
7522         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7523       }
7524     }
7525 
7526     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7527     // conditional operator for vector types.
7528     for (BuiltinCandidateTypeSet::iterator
7529               Vec1 = CandidateTypes[0].vector_begin(),
7530            Vec1End = CandidateTypes[0].vector_end();
7531          Vec1 != Vec1End; ++Vec1) {
7532       for (BuiltinCandidateTypeSet::iterator
7533                 Vec2 = CandidateTypes[1].vector_begin(),
7534              Vec2End = CandidateTypes[1].vector_end();
7535            Vec2 != Vec2End; ++Vec2) {
7536         QualType LandR[2] = { *Vec1, *Vec2 };
7537         QualType Result = S.Context.BoolTy;
7538         if (!isComparison) {
7539           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7540             Result = *Vec1;
7541           else
7542             Result = *Vec2;
7543         }
7544 
7545         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7546       }
7547     }
7548   }
7549 
7550   // C++ [over.built]p17:
7551   //
7552   //   For every pair of promoted integral types L and R, there
7553   //   exist candidate operator functions of the form
7554   //
7555   //      LR         operator%(L, R);
7556   //      LR         operator&(L, R);
7557   //      LR         operator^(L, R);
7558   //      LR         operator|(L, R);
7559   //      L          operator<<(L, R);
7560   //      L          operator>>(L, R);
7561   //
7562   //   where LR is the result of the usual arithmetic conversions
7563   //   between types L and R.
7564   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7565     if (!HasArithmeticOrEnumeralCandidateType)
7566       return;
7567 
7568     for (unsigned Left = FirstPromotedIntegralType;
7569          Left < LastPromotedIntegralType; ++Left) {
7570       for (unsigned Right = FirstPromotedIntegralType;
7571            Right < LastPromotedIntegralType; ++Right) {
7572         QualType LandR[2] = { getArithmeticType(Left),
7573                               getArithmeticType(Right) };
7574         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7575             ? LandR[0]
7576             : getUsualArithmeticConversions(Left, Right);
7577         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7578       }
7579     }
7580   }
7581 
7582   // C++ [over.built]p20:
7583   //
7584   //   For every pair (T, VQ), where T is an enumeration or
7585   //   pointer to member type and VQ is either volatile or
7586   //   empty, there exist candidate operator functions of the form
7587   //
7588   //        VQ T&      operator=(VQ T&, T);
7589   void addAssignmentMemberPointerOrEnumeralOverloads() {
7590     /// Set of (canonical) types that we've already handled.
7591     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7592 
7593     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7594       for (BuiltinCandidateTypeSet::iterator
7595                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7596              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7597            Enum != EnumEnd; ++Enum) {
7598         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7599           continue;
7600 
7601         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7602       }
7603 
7604       for (BuiltinCandidateTypeSet::iterator
7605                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7606              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7607            MemPtr != MemPtrEnd; ++MemPtr) {
7608         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7609           continue;
7610 
7611         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7612       }
7613     }
7614   }
7615 
7616   // C++ [over.built]p19:
7617   //
7618   //   For every pair (T, VQ), where T is any type and VQ is either
7619   //   volatile or empty, there exist candidate operator functions
7620   //   of the form
7621   //
7622   //        T*VQ&      operator=(T*VQ&, T*);
7623   //
7624   // C++ [over.built]p21:
7625   //
7626   //   For every pair (T, VQ), where T is a cv-qualified or
7627   //   cv-unqualified object type and VQ is either volatile or
7628   //   empty, there exist candidate operator functions of the form
7629   //
7630   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7631   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7632   void addAssignmentPointerOverloads(bool isEqualOp) {
7633     /// Set of (canonical) types that we've already handled.
7634     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7635 
7636     for (BuiltinCandidateTypeSet::iterator
7637               Ptr = CandidateTypes[0].pointer_begin(),
7638            PtrEnd = CandidateTypes[0].pointer_end();
7639          Ptr != PtrEnd; ++Ptr) {
7640       // If this is operator=, keep track of the builtin candidates we added.
7641       if (isEqualOp)
7642         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7643       else if (!(*Ptr)->getPointeeType()->isObjectType())
7644         continue;
7645 
7646       // non-volatile version
7647       QualType ParamTypes[2] = {
7648         S.Context.getLValueReferenceType(*Ptr),
7649         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7650       };
7651       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7652                             /*IsAssigmentOperator=*/ isEqualOp);
7653 
7654       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7655                           VisibleTypeConversionsQuals.hasVolatile();
7656       if (NeedVolatile) {
7657         // volatile version
7658         ParamTypes[0] =
7659           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7660         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7661                               /*IsAssigmentOperator=*/isEqualOp);
7662       }
7663 
7664       if (!(*Ptr).isRestrictQualified() &&
7665           VisibleTypeConversionsQuals.hasRestrict()) {
7666         // restrict version
7667         ParamTypes[0]
7668           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7669         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7670                               /*IsAssigmentOperator=*/isEqualOp);
7671 
7672         if (NeedVolatile) {
7673           // volatile restrict version
7674           ParamTypes[0]
7675             = S.Context.getLValueReferenceType(
7676                 S.Context.getCVRQualifiedType(*Ptr,
7677                                               (Qualifiers::Volatile |
7678                                                Qualifiers::Restrict)));
7679           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7680                                 /*IsAssigmentOperator=*/isEqualOp);
7681         }
7682       }
7683     }
7684 
7685     if (isEqualOp) {
7686       for (BuiltinCandidateTypeSet::iterator
7687                 Ptr = CandidateTypes[1].pointer_begin(),
7688              PtrEnd = CandidateTypes[1].pointer_end();
7689            Ptr != PtrEnd; ++Ptr) {
7690         // Make sure we don't add the same candidate twice.
7691         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7692           continue;
7693 
7694         QualType ParamTypes[2] = {
7695           S.Context.getLValueReferenceType(*Ptr),
7696           *Ptr,
7697         };
7698 
7699         // non-volatile version
7700         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7701                               /*IsAssigmentOperator=*/true);
7702 
7703         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7704                            VisibleTypeConversionsQuals.hasVolatile();
7705         if (NeedVolatile) {
7706           // volatile version
7707           ParamTypes[0] =
7708             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7709           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7710                                 /*IsAssigmentOperator=*/true);
7711         }
7712 
7713         if (!(*Ptr).isRestrictQualified() &&
7714             VisibleTypeConversionsQuals.hasRestrict()) {
7715           // restrict version
7716           ParamTypes[0]
7717             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7718           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7719                                 /*IsAssigmentOperator=*/true);
7720 
7721           if (NeedVolatile) {
7722             // volatile restrict version
7723             ParamTypes[0]
7724               = S.Context.getLValueReferenceType(
7725                   S.Context.getCVRQualifiedType(*Ptr,
7726                                                 (Qualifiers::Volatile |
7727                                                  Qualifiers::Restrict)));
7728             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7729                                   /*IsAssigmentOperator=*/true);
7730           }
7731         }
7732       }
7733     }
7734   }
7735 
7736   // C++ [over.built]p18:
7737   //
7738   //   For every triple (L, VQ, R), where L is an arithmetic type,
7739   //   VQ is either volatile or empty, and R is a promoted
7740   //   arithmetic type, there exist candidate operator functions of
7741   //   the form
7742   //
7743   //        VQ L&      operator=(VQ L&, R);
7744   //        VQ L&      operator*=(VQ L&, R);
7745   //        VQ L&      operator/=(VQ L&, R);
7746   //        VQ L&      operator+=(VQ L&, R);
7747   //        VQ L&      operator-=(VQ L&, R);
7748   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7749     if (!HasArithmeticOrEnumeralCandidateType)
7750       return;
7751 
7752     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7753       for (unsigned Right = FirstPromotedArithmeticType;
7754            Right < LastPromotedArithmeticType; ++Right) {
7755         QualType ParamTypes[2];
7756         ParamTypes[1] = getArithmeticType(Right);
7757 
7758         // Add this built-in operator as a candidate (VQ is empty).
7759         ParamTypes[0] =
7760           S.Context.getLValueReferenceType(getArithmeticType(Left));
7761         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7762                               /*IsAssigmentOperator=*/isEqualOp);
7763 
7764         // Add this built-in operator as a candidate (VQ is 'volatile').
7765         if (VisibleTypeConversionsQuals.hasVolatile()) {
7766           ParamTypes[0] =
7767             S.Context.getVolatileType(getArithmeticType(Left));
7768           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7769           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7770                                 /*IsAssigmentOperator=*/isEqualOp);
7771         }
7772       }
7773     }
7774 
7775     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7776     for (BuiltinCandidateTypeSet::iterator
7777               Vec1 = CandidateTypes[0].vector_begin(),
7778            Vec1End = CandidateTypes[0].vector_end();
7779          Vec1 != Vec1End; ++Vec1) {
7780       for (BuiltinCandidateTypeSet::iterator
7781                 Vec2 = CandidateTypes[1].vector_begin(),
7782              Vec2End = CandidateTypes[1].vector_end();
7783            Vec2 != Vec2End; ++Vec2) {
7784         QualType ParamTypes[2];
7785         ParamTypes[1] = *Vec2;
7786         // Add this built-in operator as a candidate (VQ is empty).
7787         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7788         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7789                               /*IsAssigmentOperator=*/isEqualOp);
7790 
7791         // Add this built-in operator as a candidate (VQ is 'volatile').
7792         if (VisibleTypeConversionsQuals.hasVolatile()) {
7793           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7794           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7795           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7796                                 /*IsAssigmentOperator=*/isEqualOp);
7797         }
7798       }
7799     }
7800   }
7801 
7802   // C++ [over.built]p22:
7803   //
7804   //   For every triple (L, VQ, R), where L is an integral type, VQ
7805   //   is either volatile or empty, and R is a promoted integral
7806   //   type, there exist candidate operator functions of the form
7807   //
7808   //        VQ L&       operator%=(VQ L&, R);
7809   //        VQ L&       operator<<=(VQ L&, R);
7810   //        VQ L&       operator>>=(VQ L&, R);
7811   //        VQ L&       operator&=(VQ L&, R);
7812   //        VQ L&       operator^=(VQ L&, R);
7813   //        VQ L&       operator|=(VQ L&, R);
7814   void addAssignmentIntegralOverloads() {
7815     if (!HasArithmeticOrEnumeralCandidateType)
7816       return;
7817 
7818     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7819       for (unsigned Right = FirstPromotedIntegralType;
7820            Right < LastPromotedIntegralType; ++Right) {
7821         QualType ParamTypes[2];
7822         ParamTypes[1] = getArithmeticType(Right);
7823 
7824         // Add this built-in operator as a candidate (VQ is empty).
7825         ParamTypes[0] =
7826           S.Context.getLValueReferenceType(getArithmeticType(Left));
7827         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7828         if (VisibleTypeConversionsQuals.hasVolatile()) {
7829           // Add this built-in operator as a candidate (VQ is 'volatile').
7830           ParamTypes[0] = getArithmeticType(Left);
7831           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7832           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7833           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7834         }
7835       }
7836     }
7837   }
7838 
7839   // C++ [over.operator]p23:
7840   //
7841   //   There also exist candidate operator functions of the form
7842   //
7843   //        bool        operator!(bool);
7844   //        bool        operator&&(bool, bool);
7845   //        bool        operator||(bool, bool);
7846   void addExclaimOverload() {
7847     QualType ParamTy = S.Context.BoolTy;
7848     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7849                           /*IsAssignmentOperator=*/false,
7850                           /*NumContextualBoolArguments=*/1);
7851   }
7852   void addAmpAmpOrPipePipeOverload() {
7853     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7854     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7855                           /*IsAssignmentOperator=*/false,
7856                           /*NumContextualBoolArguments=*/2);
7857   }
7858 
7859   // C++ [over.built]p13:
7860   //
7861   //   For every cv-qualified or cv-unqualified object type T there
7862   //   exist candidate operator functions of the form
7863   //
7864   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7865   //        T&         operator[](T*, ptrdiff_t);
7866   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7867   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7868   //        T&         operator[](ptrdiff_t, T*);
7869   void addSubscriptOverloads() {
7870     for (BuiltinCandidateTypeSet::iterator
7871               Ptr = CandidateTypes[0].pointer_begin(),
7872            PtrEnd = CandidateTypes[0].pointer_end();
7873          Ptr != PtrEnd; ++Ptr) {
7874       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7875       QualType PointeeType = (*Ptr)->getPointeeType();
7876       if (!PointeeType->isObjectType())
7877         continue;
7878 
7879       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7880 
7881       // T& operator[](T*, ptrdiff_t)
7882       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7883     }
7884 
7885     for (BuiltinCandidateTypeSet::iterator
7886               Ptr = CandidateTypes[1].pointer_begin(),
7887            PtrEnd = CandidateTypes[1].pointer_end();
7888          Ptr != PtrEnd; ++Ptr) {
7889       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7890       QualType PointeeType = (*Ptr)->getPointeeType();
7891       if (!PointeeType->isObjectType())
7892         continue;
7893 
7894       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7895 
7896       // T& operator[](ptrdiff_t, T*)
7897       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7898     }
7899   }
7900 
7901   // C++ [over.built]p11:
7902   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7903   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7904   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7905   //    there exist candidate operator functions of the form
7906   //
7907   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7908   //
7909   //    where CV12 is the union of CV1 and CV2.
7910   void addArrowStarOverloads() {
7911     for (BuiltinCandidateTypeSet::iterator
7912              Ptr = CandidateTypes[0].pointer_begin(),
7913            PtrEnd = CandidateTypes[0].pointer_end();
7914          Ptr != PtrEnd; ++Ptr) {
7915       QualType C1Ty = (*Ptr);
7916       QualType C1;
7917       QualifierCollector Q1;
7918       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7919       if (!isa<RecordType>(C1))
7920         continue;
7921       // heuristic to reduce number of builtin candidates in the set.
7922       // Add volatile/restrict version only if there are conversions to a
7923       // volatile/restrict type.
7924       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7925         continue;
7926       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7927         continue;
7928       for (BuiltinCandidateTypeSet::iterator
7929                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7930              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7931            MemPtr != MemPtrEnd; ++MemPtr) {
7932         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7933         QualType C2 = QualType(mptr->getClass(), 0);
7934         C2 = C2.getUnqualifiedType();
7935         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7936           break;
7937         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7938         // build CV12 T&
7939         QualType T = mptr->getPointeeType();
7940         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7941             T.isVolatileQualified())
7942           continue;
7943         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7944             T.isRestrictQualified())
7945           continue;
7946         T = Q1.apply(S.Context, T);
7947         QualType ResultTy = S.Context.getLValueReferenceType(T);
7948         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7949       }
7950     }
7951   }
7952 
7953   // Note that we don't consider the first argument, since it has been
7954   // contextually converted to bool long ago. The candidates below are
7955   // therefore added as binary.
7956   //
7957   // C++ [over.built]p25:
7958   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7959   //   enumeration type, there exist candidate operator functions of the form
7960   //
7961   //        T        operator?(bool, T, T);
7962   //
7963   void addConditionalOperatorOverloads() {
7964     /// Set of (canonical) types that we've already handled.
7965     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7966 
7967     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7968       for (BuiltinCandidateTypeSet::iterator
7969                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7970              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7971            Ptr != PtrEnd; ++Ptr) {
7972         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7973           continue;
7974 
7975         QualType ParamTypes[2] = { *Ptr, *Ptr };
7976         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7977       }
7978 
7979       for (BuiltinCandidateTypeSet::iterator
7980                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7981              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7982            MemPtr != MemPtrEnd; ++MemPtr) {
7983         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7984           continue;
7985 
7986         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7987         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7988       }
7989 
7990       if (S.getLangOpts().CPlusPlus11) {
7991         for (BuiltinCandidateTypeSet::iterator
7992                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7993                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7994              Enum != EnumEnd; ++Enum) {
7995           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7996             continue;
7997 
7998           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7999             continue;
8000 
8001           QualType ParamTypes[2] = { *Enum, *Enum };
8002           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8003         }
8004       }
8005     }
8006   }
8007 };
8008 
8009 } // end anonymous namespace
8010 
8011 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8012 /// operator overloads to the candidate set (C++ [over.built]), based
8013 /// on the operator @p Op and the arguments given. For example, if the
8014 /// operator is a binary '+', this routine might add "int
8015 /// operator+(int, int)" to cover integer addition.
8016 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8017                                         SourceLocation OpLoc,
8018                                         ArrayRef<Expr *> Args,
8019                                         OverloadCandidateSet &CandidateSet) {
8020   // Find all of the types that the arguments can convert to, but only
8021   // if the operator we're looking at has built-in operator candidates
8022   // that make use of these types. Also record whether we encounter non-record
8023   // candidate types or either arithmetic or enumeral candidate types.
8024   Qualifiers VisibleTypeConversionsQuals;
8025   VisibleTypeConversionsQuals.addConst();
8026   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8027     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8028 
8029   bool HasNonRecordCandidateType = false;
8030   bool HasArithmeticOrEnumeralCandidateType = false;
8031   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8032   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8033     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8034     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8035                                                  OpLoc,
8036                                                  true,
8037                                                  (Op == OO_Exclaim ||
8038                                                   Op == OO_AmpAmp ||
8039                                                   Op == OO_PipePipe),
8040                                                  VisibleTypeConversionsQuals);
8041     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8042         CandidateTypes[ArgIdx].hasNonRecordTypes();
8043     HasArithmeticOrEnumeralCandidateType =
8044         HasArithmeticOrEnumeralCandidateType ||
8045         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8046   }
8047 
8048   // Exit early when no non-record types have been added to the candidate set
8049   // for any of the arguments to the operator.
8050   //
8051   // We can't exit early for !, ||, or &&, since there we have always have
8052   // 'bool' overloads.
8053   if (!HasNonRecordCandidateType &&
8054       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8055     return;
8056 
8057   // Setup an object to manage the common state for building overloads.
8058   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8059                                            VisibleTypeConversionsQuals,
8060                                            HasArithmeticOrEnumeralCandidateType,
8061                                            CandidateTypes, CandidateSet);
8062 
8063   // Dispatch over the operation to add in only those overloads which apply.
8064   switch (Op) {
8065   case OO_None:
8066   case NUM_OVERLOADED_OPERATORS:
8067     llvm_unreachable("Expected an overloaded operator");
8068 
8069   case OO_New:
8070   case OO_Delete:
8071   case OO_Array_New:
8072   case OO_Array_Delete:
8073   case OO_Call:
8074     llvm_unreachable(
8075                     "Special operators don't use AddBuiltinOperatorCandidates");
8076 
8077   case OO_Comma:
8078   case OO_Arrow:
8079     // C++ [over.match.oper]p3:
8080     //   -- For the operator ',', the unary operator '&', or the
8081     //      operator '->', the built-in candidates set is empty.
8082     break;
8083 
8084   case OO_Plus: // '+' is either unary or binary
8085     if (Args.size() == 1)
8086       OpBuilder.addUnaryPlusPointerOverloads();
8087     // Fall through.
8088 
8089   case OO_Minus: // '-' is either unary or binary
8090     if (Args.size() == 1) {
8091       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8092     } else {
8093       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8094       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8095     }
8096     break;
8097 
8098   case OO_Star: // '*' is either unary or binary
8099     if (Args.size() == 1)
8100       OpBuilder.addUnaryStarPointerOverloads();
8101     else
8102       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8103     break;
8104 
8105   case OO_Slash:
8106     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8107     break;
8108 
8109   case OO_PlusPlus:
8110   case OO_MinusMinus:
8111     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8112     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8113     break;
8114 
8115   case OO_EqualEqual:
8116   case OO_ExclaimEqual:
8117     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8118     // Fall through.
8119 
8120   case OO_Less:
8121   case OO_Greater:
8122   case OO_LessEqual:
8123   case OO_GreaterEqual:
8124     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8125     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8126     break;
8127 
8128   case OO_Percent:
8129   case OO_Caret:
8130   case OO_Pipe:
8131   case OO_LessLess:
8132   case OO_GreaterGreater:
8133     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8134     break;
8135 
8136   case OO_Amp: // '&' is either unary or binary
8137     if (Args.size() == 1)
8138       // C++ [over.match.oper]p3:
8139       //   -- For the operator ',', the unary operator '&', or the
8140       //      operator '->', the built-in candidates set is empty.
8141       break;
8142 
8143     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8144     break;
8145 
8146   case OO_Tilde:
8147     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8148     break;
8149 
8150   case OO_Equal:
8151     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8152     // Fall through.
8153 
8154   case OO_PlusEqual:
8155   case OO_MinusEqual:
8156     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8157     // Fall through.
8158 
8159   case OO_StarEqual:
8160   case OO_SlashEqual:
8161     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8162     break;
8163 
8164   case OO_PercentEqual:
8165   case OO_LessLessEqual:
8166   case OO_GreaterGreaterEqual:
8167   case OO_AmpEqual:
8168   case OO_CaretEqual:
8169   case OO_PipeEqual:
8170     OpBuilder.addAssignmentIntegralOverloads();
8171     break;
8172 
8173   case OO_Exclaim:
8174     OpBuilder.addExclaimOverload();
8175     break;
8176 
8177   case OO_AmpAmp:
8178   case OO_PipePipe:
8179     OpBuilder.addAmpAmpOrPipePipeOverload();
8180     break;
8181 
8182   case OO_Subscript:
8183     OpBuilder.addSubscriptOverloads();
8184     break;
8185 
8186   case OO_ArrowStar:
8187     OpBuilder.addArrowStarOverloads();
8188     break;
8189 
8190   case OO_Conditional:
8191     OpBuilder.addConditionalOperatorOverloads();
8192     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8193     break;
8194   }
8195 }
8196 
8197 /// \brief Add function candidates found via argument-dependent lookup
8198 /// to the set of overloading candidates.
8199 ///
8200 /// This routine performs argument-dependent name lookup based on the
8201 /// given function name (which may also be an operator name) and adds
8202 /// all of the overload candidates found by ADL to the overload
8203 /// candidate set (C++ [basic.lookup.argdep]).
8204 void
8205 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8206                                            SourceLocation Loc,
8207                                            ArrayRef<Expr *> Args,
8208                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8209                                            OverloadCandidateSet& CandidateSet,
8210                                            bool PartialOverloading) {
8211   ADLResult Fns;
8212 
8213   // FIXME: This approach for uniquing ADL results (and removing
8214   // redundant candidates from the set) relies on pointer-equality,
8215   // which means we need to key off the canonical decl.  However,
8216   // always going back to the canonical decl might not get us the
8217   // right set of default arguments.  What default arguments are
8218   // we supposed to consider on ADL candidates, anyway?
8219 
8220   // FIXME: Pass in the explicit template arguments?
8221   ArgumentDependentLookup(Name, Loc, Args, Fns);
8222 
8223   // Erase all of the candidates we already knew about.
8224   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8225                                    CandEnd = CandidateSet.end();
8226        Cand != CandEnd; ++Cand)
8227     if (Cand->Function) {
8228       Fns.erase(Cand->Function);
8229       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8230         Fns.erase(FunTmpl);
8231     }
8232 
8233   // For each of the ADL candidates we found, add it to the overload
8234   // set.
8235   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8236     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8237     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8238       if (ExplicitTemplateArgs)
8239         continue;
8240 
8241       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8242                            PartialOverloading);
8243     } else
8244       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8245                                    FoundDecl, ExplicitTemplateArgs,
8246                                    Args, CandidateSet);
8247   }
8248 }
8249 
8250 /// isBetterOverloadCandidate - Determines whether the first overload
8251 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8252 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8253                                       const OverloadCandidate &Cand2,
8254                                       SourceLocation Loc,
8255                                       bool UserDefinedConversion) {
8256   // Define viable functions to be better candidates than non-viable
8257   // functions.
8258   if (!Cand2.Viable)
8259     return Cand1.Viable;
8260   else if (!Cand1.Viable)
8261     return false;
8262 
8263   // C++ [over.match.best]p1:
8264   //
8265   //   -- if F is a static member function, ICS1(F) is defined such
8266   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8267   //      any function G, and, symmetrically, ICS1(G) is neither
8268   //      better nor worse than ICS1(F).
8269   unsigned StartArg = 0;
8270   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8271     StartArg = 1;
8272 
8273   // C++ [over.match.best]p1:
8274   //   A viable function F1 is defined to be a better function than another
8275   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8276   //   conversion sequence than ICSi(F2), and then...
8277   unsigned NumArgs = Cand1.NumConversions;
8278   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8279   bool HasBetterConversion = false;
8280   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8281     switch (CompareImplicitConversionSequences(S,
8282                                                Cand1.Conversions[ArgIdx],
8283                                                Cand2.Conversions[ArgIdx])) {
8284     case ImplicitConversionSequence::Better:
8285       // Cand1 has a better conversion sequence.
8286       HasBetterConversion = true;
8287       break;
8288 
8289     case ImplicitConversionSequence::Worse:
8290       // Cand1 can't be better than Cand2.
8291       return false;
8292 
8293     case ImplicitConversionSequence::Indistinguishable:
8294       // Do nothing.
8295       break;
8296     }
8297   }
8298 
8299   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8300   //       ICSj(F2), or, if not that,
8301   if (HasBetterConversion)
8302     return true;
8303 
8304   //   -- the context is an initialization by user-defined conversion
8305   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8306   //      from the return type of F1 to the destination type (i.e.,
8307   //      the type of the entity being initialized) is a better
8308   //      conversion sequence than the standard conversion sequence
8309   //      from the return type of F2 to the destination type.
8310   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8311       isa<CXXConversionDecl>(Cand1.Function) &&
8312       isa<CXXConversionDecl>(Cand2.Function)) {
8313     // First check whether we prefer one of the conversion functions over the
8314     // other. This only distinguishes the results in non-standard, extension
8315     // cases such as the conversion from a lambda closure type to a function
8316     // pointer or block.
8317     ImplicitConversionSequence::CompareKind Result =
8318         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8319     if (Result == ImplicitConversionSequence::Indistinguishable)
8320       Result = CompareStandardConversionSequences(S,
8321                                                   Cand1.FinalConversion,
8322                                                   Cand2.FinalConversion);
8323 
8324     if (Result != ImplicitConversionSequence::Indistinguishable)
8325       return Result == ImplicitConversionSequence::Better;
8326 
8327     // FIXME: Compare kind of reference binding if conversion functions
8328     // convert to a reference type used in direct reference binding, per
8329     // C++14 [over.match.best]p1 section 2 bullet 3.
8330   }
8331 
8332   //    -- F1 is a non-template function and F2 is a function template
8333   //       specialization, or, if not that,
8334   bool Cand1IsSpecialization = Cand1.Function &&
8335                                Cand1.Function->getPrimaryTemplate();
8336   bool Cand2IsSpecialization = Cand2.Function &&
8337                                Cand2.Function->getPrimaryTemplate();
8338   if (Cand1IsSpecialization != Cand2IsSpecialization)
8339     return Cand2IsSpecialization;
8340 
8341   //   -- F1 and F2 are function template specializations, and the function
8342   //      template for F1 is more specialized than the template for F2
8343   //      according to the partial ordering rules described in 14.5.5.2, or,
8344   //      if not that,
8345   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8346     if (FunctionTemplateDecl *BetterTemplate
8347           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8348                                          Cand2.Function->getPrimaryTemplate(),
8349                                          Loc,
8350                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8351                                                              : TPOC_Call,
8352                                          Cand1.ExplicitCallArguments,
8353                                          Cand2.ExplicitCallArguments))
8354       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8355   }
8356 
8357   // Check for enable_if value-based overload resolution.
8358   if (Cand1.Function && Cand2.Function &&
8359       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8360        Cand2.Function->hasAttr<EnableIfAttr>())) {
8361     // FIXME: The next several lines are just
8362     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8363     // instead of reverse order which is how they're stored in the AST.
8364     AttrVec Cand1Attrs;
8365     if (Cand1.Function->hasAttrs()) {
8366       Cand1Attrs = Cand1.Function->getAttrs();
8367       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8368                                       IsNotEnableIfAttr),
8369                        Cand1Attrs.end());
8370       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8371     }
8372 
8373     AttrVec Cand2Attrs;
8374     if (Cand2.Function->hasAttrs()) {
8375       Cand2Attrs = Cand2.Function->getAttrs();
8376       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8377                                       IsNotEnableIfAttr),
8378                        Cand2Attrs.end());
8379       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8380     }
8381 
8382     // Candidate 1 is better if it has strictly more attributes and
8383     // the common sequence is identical.
8384     if (Cand1Attrs.size() <= Cand2Attrs.size())
8385       return false;
8386 
8387     auto Cand1I = Cand1Attrs.begin();
8388     for (auto &Cand2A : Cand2Attrs) {
8389       auto &Cand1A = *Cand1I++;
8390       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8391       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8392                                                      S.getASTContext(), true);
8393       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8394                                                      S.getASTContext(), true);
8395       if (Cand1ID != Cand2ID)
8396         return false;
8397     }
8398 
8399     return true;
8400   }
8401 
8402   return false;
8403 }
8404 
8405 /// \brief Computes the best viable function (C++ 13.3.3)
8406 /// within an overload candidate set.
8407 ///
8408 /// \param Loc The location of the function name (or operator symbol) for
8409 /// which overload resolution occurs.
8410 ///
8411 /// \param Best If overload resolution was successful or found a deleted
8412 /// function, \p Best points to the candidate function found.
8413 ///
8414 /// \returns The result of overload resolution.
8415 OverloadingResult
8416 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8417                                          iterator &Best,
8418                                          bool UserDefinedConversion) {
8419   // Find the best viable function.
8420   Best = end();
8421   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8422     if (Cand->Viable)
8423       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8424                                                      UserDefinedConversion))
8425         Best = Cand;
8426   }
8427 
8428   // If we didn't find any viable functions, abort.
8429   if (Best == end())
8430     return OR_No_Viable_Function;
8431 
8432   // Make sure that this function is better than every other viable
8433   // function. If not, we have an ambiguity.
8434   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8435     if (Cand->Viable &&
8436         Cand != Best &&
8437         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8438                                    UserDefinedConversion)) {
8439       Best = end();
8440       return OR_Ambiguous;
8441     }
8442   }
8443 
8444   // Best is the best viable function.
8445   if (Best->Function &&
8446       (Best->Function->isDeleted() ||
8447        S.isFunctionConsideredUnavailable(Best->Function)))
8448     return OR_Deleted;
8449 
8450   return OR_Success;
8451 }
8452 
8453 namespace {
8454 
8455 enum OverloadCandidateKind {
8456   oc_function,
8457   oc_method,
8458   oc_constructor,
8459   oc_function_template,
8460   oc_method_template,
8461   oc_constructor_template,
8462   oc_implicit_default_constructor,
8463   oc_implicit_copy_constructor,
8464   oc_implicit_move_constructor,
8465   oc_implicit_copy_assignment,
8466   oc_implicit_move_assignment,
8467   oc_implicit_inherited_constructor
8468 };
8469 
8470 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8471                                                 FunctionDecl *Fn,
8472                                                 std::string &Description) {
8473   bool isTemplate = false;
8474 
8475   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8476     isTemplate = true;
8477     Description = S.getTemplateArgumentBindingsText(
8478       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8479   }
8480 
8481   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8482     if (!Ctor->isImplicit())
8483       return isTemplate ? oc_constructor_template : oc_constructor;
8484 
8485     if (Ctor->getInheritedConstructor())
8486       return oc_implicit_inherited_constructor;
8487 
8488     if (Ctor->isDefaultConstructor())
8489       return oc_implicit_default_constructor;
8490 
8491     if (Ctor->isMoveConstructor())
8492       return oc_implicit_move_constructor;
8493 
8494     assert(Ctor->isCopyConstructor() &&
8495            "unexpected sort of implicit constructor");
8496     return oc_implicit_copy_constructor;
8497   }
8498 
8499   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8500     // This actually gets spelled 'candidate function' for now, but
8501     // it doesn't hurt to split it out.
8502     if (!Meth->isImplicit())
8503       return isTemplate ? oc_method_template : oc_method;
8504 
8505     if (Meth->isMoveAssignmentOperator())
8506       return oc_implicit_move_assignment;
8507 
8508     if (Meth->isCopyAssignmentOperator())
8509       return oc_implicit_copy_assignment;
8510 
8511     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8512     return oc_method;
8513   }
8514 
8515   return isTemplate ? oc_function_template : oc_function;
8516 }
8517 
8518 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8519   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8520   if (!Ctor) return;
8521 
8522   Ctor = Ctor->getInheritedConstructor();
8523   if (!Ctor) return;
8524 
8525   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8526 }
8527 
8528 } // end anonymous namespace
8529 
8530 // Notes the location of an overload candidate.
8531 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8532   std::string FnDesc;
8533   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8534   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8535                              << (unsigned) K << FnDesc;
8536   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8537   Diag(Fn->getLocation(), PD);
8538   MaybeEmitInheritedConstructorNote(*this, Fn);
8539 }
8540 
8541 // Notes the location of all overload candidates designated through
8542 // OverloadedExpr
8543 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8544   assert(OverloadedExpr->getType() == Context.OverloadTy);
8545 
8546   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8547   OverloadExpr *OvlExpr = Ovl.Expression;
8548 
8549   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8550                             IEnd = OvlExpr->decls_end();
8551        I != IEnd; ++I) {
8552     if (FunctionTemplateDecl *FunTmpl =
8553                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8554       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8555     } else if (FunctionDecl *Fun
8556                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8557       NoteOverloadCandidate(Fun, DestType);
8558     }
8559   }
8560 }
8561 
8562 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8563 /// "lead" diagnostic; it will be given two arguments, the source and
8564 /// target types of the conversion.
8565 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8566                                  Sema &S,
8567                                  SourceLocation CaretLoc,
8568                                  const PartialDiagnostic &PDiag) const {
8569   S.Diag(CaretLoc, PDiag)
8570     << Ambiguous.getFromType() << Ambiguous.getToType();
8571   // FIXME: The note limiting machinery is borrowed from
8572   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8573   // refactoring here.
8574   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8575   unsigned CandsShown = 0;
8576   AmbiguousConversionSequence::const_iterator I, E;
8577   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8578     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8579       break;
8580     ++CandsShown;
8581     S.NoteOverloadCandidate(*I);
8582   }
8583   if (I != E)
8584     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8585 }
8586 
8587 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8588                                   unsigned I) {
8589   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8590   assert(Conv.isBad());
8591   assert(Cand->Function && "for now, candidate must be a function");
8592   FunctionDecl *Fn = Cand->Function;
8593 
8594   // There's a conversion slot for the object argument if this is a
8595   // non-constructor method.  Note that 'I' corresponds the
8596   // conversion-slot index.
8597   bool isObjectArgument = false;
8598   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8599     if (I == 0)
8600       isObjectArgument = true;
8601     else
8602       I--;
8603   }
8604 
8605   std::string FnDesc;
8606   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8607 
8608   Expr *FromExpr = Conv.Bad.FromExpr;
8609   QualType FromTy = Conv.Bad.getFromType();
8610   QualType ToTy = Conv.Bad.getToType();
8611 
8612   if (FromTy == S.Context.OverloadTy) {
8613     assert(FromExpr && "overload set argument came from implicit argument?");
8614     Expr *E = FromExpr->IgnoreParens();
8615     if (isa<UnaryOperator>(E))
8616       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8617     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8618 
8619     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8620       << (unsigned) FnKind << FnDesc
8621       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8622       << ToTy << Name << I+1;
8623     MaybeEmitInheritedConstructorNote(S, Fn);
8624     return;
8625   }
8626 
8627   // Do some hand-waving analysis to see if the non-viability is due
8628   // to a qualifier mismatch.
8629   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8630   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8631   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8632     CToTy = RT->getPointeeType();
8633   else {
8634     // TODO: detect and diagnose the full richness of const mismatches.
8635     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8636       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8637         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8638   }
8639 
8640   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8641       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8642     Qualifiers FromQs = CFromTy.getQualifiers();
8643     Qualifiers ToQs = CToTy.getQualifiers();
8644 
8645     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8646       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8647         << (unsigned) FnKind << FnDesc
8648         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8649         << FromTy
8650         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8651         << (unsigned) isObjectArgument << I+1;
8652       MaybeEmitInheritedConstructorNote(S, Fn);
8653       return;
8654     }
8655 
8656     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8657       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8658         << (unsigned) FnKind << FnDesc
8659         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8660         << FromTy
8661         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8662         << (unsigned) isObjectArgument << I+1;
8663       MaybeEmitInheritedConstructorNote(S, Fn);
8664       return;
8665     }
8666 
8667     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8668       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8669       << (unsigned) FnKind << FnDesc
8670       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8671       << FromTy
8672       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8673       << (unsigned) isObjectArgument << I+1;
8674       MaybeEmitInheritedConstructorNote(S, Fn);
8675       return;
8676     }
8677 
8678     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8679     assert(CVR && "unexpected qualifiers mismatch");
8680 
8681     if (isObjectArgument) {
8682       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8683         << (unsigned) FnKind << FnDesc
8684         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8685         << FromTy << (CVR - 1);
8686     } else {
8687       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8688         << (unsigned) FnKind << FnDesc
8689         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8690         << FromTy << (CVR - 1) << I+1;
8691     }
8692     MaybeEmitInheritedConstructorNote(S, Fn);
8693     return;
8694   }
8695 
8696   // Special diagnostic for failure to convert an initializer list, since
8697   // telling the user that it has type void is not useful.
8698   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8699     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8700       << (unsigned) FnKind << FnDesc
8701       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8702       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8703     MaybeEmitInheritedConstructorNote(S, Fn);
8704     return;
8705   }
8706 
8707   // Diagnose references or pointers to incomplete types differently,
8708   // since it's far from impossible that the incompleteness triggered
8709   // the failure.
8710   QualType TempFromTy = FromTy.getNonReferenceType();
8711   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8712     TempFromTy = PTy->getPointeeType();
8713   if (TempFromTy->isIncompleteType()) {
8714     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8715       << (unsigned) FnKind << FnDesc
8716       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8717       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8718     MaybeEmitInheritedConstructorNote(S, Fn);
8719     return;
8720   }
8721 
8722   // Diagnose base -> derived pointer conversions.
8723   unsigned BaseToDerivedConversion = 0;
8724   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8725     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8726       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8727                                                FromPtrTy->getPointeeType()) &&
8728           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8729           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8730           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8731                           FromPtrTy->getPointeeType()))
8732         BaseToDerivedConversion = 1;
8733     }
8734   } else if (const ObjCObjectPointerType *FromPtrTy
8735                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8736     if (const ObjCObjectPointerType *ToPtrTy
8737                                         = ToTy->getAs<ObjCObjectPointerType>())
8738       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8739         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8740           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8741                                                 FromPtrTy->getPointeeType()) &&
8742               FromIface->isSuperClassOf(ToIface))
8743             BaseToDerivedConversion = 2;
8744   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8745     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8746         !FromTy->isIncompleteType() &&
8747         !ToRefTy->getPointeeType()->isIncompleteType() &&
8748         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8749       BaseToDerivedConversion = 3;
8750     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8751                ToTy.getNonReferenceType().getCanonicalType() ==
8752                FromTy.getNonReferenceType().getCanonicalType()) {
8753       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8754         << (unsigned) FnKind << FnDesc
8755         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8756         << (unsigned) isObjectArgument << I + 1;
8757       MaybeEmitInheritedConstructorNote(S, Fn);
8758       return;
8759     }
8760   }
8761 
8762   if (BaseToDerivedConversion) {
8763     S.Diag(Fn->getLocation(),
8764            diag::note_ovl_candidate_bad_base_to_derived_conv)
8765       << (unsigned) FnKind << FnDesc
8766       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8767       << (BaseToDerivedConversion - 1)
8768       << FromTy << ToTy << I+1;
8769     MaybeEmitInheritedConstructorNote(S, Fn);
8770     return;
8771   }
8772 
8773   if (isa<ObjCObjectPointerType>(CFromTy) &&
8774       isa<PointerType>(CToTy)) {
8775       Qualifiers FromQs = CFromTy.getQualifiers();
8776       Qualifiers ToQs = CToTy.getQualifiers();
8777       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8778         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8779         << (unsigned) FnKind << FnDesc
8780         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8781         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8782         MaybeEmitInheritedConstructorNote(S, Fn);
8783         return;
8784       }
8785   }
8786 
8787   // Emit the generic diagnostic and, optionally, add the hints to it.
8788   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8789   FDiag << (unsigned) FnKind << FnDesc
8790     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8791     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8792     << (unsigned) (Cand->Fix.Kind);
8793 
8794   // If we can fix the conversion, suggest the FixIts.
8795   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8796        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8797     FDiag << *HI;
8798   S.Diag(Fn->getLocation(), FDiag);
8799 
8800   MaybeEmitInheritedConstructorNote(S, Fn);
8801 }
8802 
8803 /// Additional arity mismatch diagnosis specific to a function overload
8804 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8805 /// over a candidate in any candidate set.
8806 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8807                                unsigned NumArgs) {
8808   FunctionDecl *Fn = Cand->Function;
8809   unsigned MinParams = Fn->getMinRequiredArguments();
8810 
8811   // With invalid overloaded operators, it's possible that we think we
8812   // have an arity mismatch when in fact it looks like we have the
8813   // right number of arguments, because only overloaded operators have
8814   // the weird behavior of overloading member and non-member functions.
8815   // Just don't report anything.
8816   if (Fn->isInvalidDecl() &&
8817       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8818     return true;
8819 
8820   if (NumArgs < MinParams) {
8821     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8822            (Cand->FailureKind == ovl_fail_bad_deduction &&
8823             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8824   } else {
8825     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8826            (Cand->FailureKind == ovl_fail_bad_deduction &&
8827             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8828   }
8829 
8830   return false;
8831 }
8832 
8833 /// General arity mismatch diagnosis over a candidate in a candidate set.
8834 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8835   assert(isa<FunctionDecl>(D) &&
8836       "The templated declaration should at least be a function"
8837       " when diagnosing bad template argument deduction due to too many"
8838       " or too few arguments");
8839 
8840   FunctionDecl *Fn = cast<FunctionDecl>(D);
8841 
8842   // TODO: treat calls to a missing default constructor as a special case
8843   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8844   unsigned MinParams = Fn->getMinRequiredArguments();
8845 
8846   // at least / at most / exactly
8847   unsigned mode, modeCount;
8848   if (NumFormalArgs < MinParams) {
8849     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8850         FnTy->isTemplateVariadic())
8851       mode = 0; // "at least"
8852     else
8853       mode = 2; // "exactly"
8854     modeCount = MinParams;
8855   } else {
8856     if (MinParams != FnTy->getNumParams())
8857       mode = 1; // "at most"
8858     else
8859       mode = 2; // "exactly"
8860     modeCount = FnTy->getNumParams();
8861   }
8862 
8863   std::string Description;
8864   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8865 
8866   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8867     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8868       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8869       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8870   else
8871     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8872       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8873       << mode << modeCount << NumFormalArgs;
8874   MaybeEmitInheritedConstructorNote(S, Fn);
8875 }
8876 
8877 /// Arity mismatch diagnosis specific to a function overload candidate.
8878 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8879                                   unsigned NumFormalArgs) {
8880   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8881     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8882 }
8883 
8884 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8885   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8886     return FD->getDescribedFunctionTemplate();
8887   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8888     return RD->getDescribedClassTemplate();
8889 
8890   llvm_unreachable("Unsupported: Getting the described template declaration"
8891                    " for bad deduction diagnosis");
8892 }
8893 
8894 /// Diagnose a failed template-argument deduction.
8895 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8896                                  DeductionFailureInfo &DeductionFailure,
8897                                  unsigned NumArgs) {
8898   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8899   NamedDecl *ParamD;
8900   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8901   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8902   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8903   switch (DeductionFailure.Result) {
8904   case Sema::TDK_Success:
8905     llvm_unreachable("TDK_success while diagnosing bad deduction");
8906 
8907   case Sema::TDK_Incomplete: {
8908     assert(ParamD && "no parameter found for incomplete deduction result");
8909     S.Diag(Templated->getLocation(),
8910            diag::note_ovl_candidate_incomplete_deduction)
8911         << ParamD->getDeclName();
8912     MaybeEmitInheritedConstructorNote(S, Templated);
8913     return;
8914   }
8915 
8916   case Sema::TDK_Underqualified: {
8917     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8918     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8919 
8920     QualType Param = DeductionFailure.getFirstArg()->getAsType();
8921 
8922     // Param will have been canonicalized, but it should just be a
8923     // qualified version of ParamD, so move the qualifiers to that.
8924     QualifierCollector Qs;
8925     Qs.strip(Param);
8926     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8927     assert(S.Context.hasSameType(Param, NonCanonParam));
8928 
8929     // Arg has also been canonicalized, but there's nothing we can do
8930     // about that.  It also doesn't matter as much, because it won't
8931     // have any template parameters in it (because deduction isn't
8932     // done on dependent types).
8933     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8934 
8935     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8936         << ParamD->getDeclName() << Arg << NonCanonParam;
8937     MaybeEmitInheritedConstructorNote(S, Templated);
8938     return;
8939   }
8940 
8941   case Sema::TDK_Inconsistent: {
8942     assert(ParamD && "no parameter found for inconsistent deduction result");
8943     int which = 0;
8944     if (isa<TemplateTypeParmDecl>(ParamD))
8945       which = 0;
8946     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8947       which = 1;
8948     else {
8949       which = 2;
8950     }
8951 
8952     S.Diag(Templated->getLocation(),
8953            diag::note_ovl_candidate_inconsistent_deduction)
8954         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8955         << *DeductionFailure.getSecondArg();
8956     MaybeEmitInheritedConstructorNote(S, Templated);
8957     return;
8958   }
8959 
8960   case Sema::TDK_InvalidExplicitArguments:
8961     assert(ParamD && "no parameter found for invalid explicit arguments");
8962     if (ParamD->getDeclName())
8963       S.Diag(Templated->getLocation(),
8964              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8965           << ParamD->getDeclName();
8966     else {
8967       int index = 0;
8968       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8969         index = TTP->getIndex();
8970       else if (NonTypeTemplateParmDecl *NTTP
8971                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8972         index = NTTP->getIndex();
8973       else
8974         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8975       S.Diag(Templated->getLocation(),
8976              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8977           << (index + 1);
8978     }
8979     MaybeEmitInheritedConstructorNote(S, Templated);
8980     return;
8981 
8982   case Sema::TDK_TooManyArguments:
8983   case Sema::TDK_TooFewArguments:
8984     DiagnoseArityMismatch(S, Templated, NumArgs);
8985     return;
8986 
8987   case Sema::TDK_InstantiationDepth:
8988     S.Diag(Templated->getLocation(),
8989            diag::note_ovl_candidate_instantiation_depth);
8990     MaybeEmitInheritedConstructorNote(S, Templated);
8991     return;
8992 
8993   case Sema::TDK_SubstitutionFailure: {
8994     // Format the template argument list into the argument string.
8995     SmallString<128> TemplateArgString;
8996     if (TemplateArgumentList *Args =
8997             DeductionFailure.getTemplateArgumentList()) {
8998       TemplateArgString = " ";
8999       TemplateArgString += S.getTemplateArgumentBindingsText(
9000           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9001     }
9002 
9003     // If this candidate was disabled by enable_if, say so.
9004     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9005     if (PDiag && PDiag->second.getDiagID() ==
9006           diag::err_typename_nested_not_found_enable_if) {
9007       // FIXME: Use the source range of the condition, and the fully-qualified
9008       //        name of the enable_if template. These are both present in PDiag.
9009       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9010         << "'enable_if'" << TemplateArgString;
9011       return;
9012     }
9013 
9014     // Format the SFINAE diagnostic into the argument string.
9015     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9016     //        formatted message in another diagnostic.
9017     SmallString<128> SFINAEArgString;
9018     SourceRange R;
9019     if (PDiag) {
9020       SFINAEArgString = ": ";
9021       R = SourceRange(PDiag->first, PDiag->first);
9022       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9023     }
9024 
9025     S.Diag(Templated->getLocation(),
9026            diag::note_ovl_candidate_substitution_failure)
9027         << TemplateArgString << SFINAEArgString << R;
9028     MaybeEmitInheritedConstructorNote(S, Templated);
9029     return;
9030   }
9031 
9032   case Sema::TDK_FailedOverloadResolution: {
9033     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9034     S.Diag(Templated->getLocation(),
9035            diag::note_ovl_candidate_failed_overload_resolution)
9036         << R.Expression->getName();
9037     return;
9038   }
9039 
9040   case Sema::TDK_NonDeducedMismatch: {
9041     // FIXME: Provide a source location to indicate what we couldn't match.
9042     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9043     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9044     if (FirstTA.getKind() == TemplateArgument::Template &&
9045         SecondTA.getKind() == TemplateArgument::Template) {
9046       TemplateName FirstTN = FirstTA.getAsTemplate();
9047       TemplateName SecondTN = SecondTA.getAsTemplate();
9048       if (FirstTN.getKind() == TemplateName::Template &&
9049           SecondTN.getKind() == TemplateName::Template) {
9050         if (FirstTN.getAsTemplateDecl()->getName() ==
9051             SecondTN.getAsTemplateDecl()->getName()) {
9052           // FIXME: This fixes a bad diagnostic where both templates are named
9053           // the same.  This particular case is a bit difficult since:
9054           // 1) It is passed as a string to the diagnostic printer.
9055           // 2) The diagnostic printer only attempts to find a better
9056           //    name for types, not decls.
9057           // Ideally, this should folded into the diagnostic printer.
9058           S.Diag(Templated->getLocation(),
9059                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9060               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9061           return;
9062         }
9063       }
9064     }
9065     // FIXME: For generic lambda parameters, check if the function is a lambda
9066     // call operator, and if so, emit a prettier and more informative
9067     // diagnostic that mentions 'auto' and lambda in addition to
9068     // (or instead of?) the canonical template type parameters.
9069     S.Diag(Templated->getLocation(),
9070            diag::note_ovl_candidate_non_deduced_mismatch)
9071         << FirstTA << SecondTA;
9072     return;
9073   }
9074   // TODO: diagnose these individually, then kill off
9075   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9076   case Sema::TDK_MiscellaneousDeductionFailure:
9077     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9078     MaybeEmitInheritedConstructorNote(S, Templated);
9079     return;
9080   }
9081 }
9082 
9083 /// Diagnose a failed template-argument deduction, for function calls.
9084 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9085                                  unsigned NumArgs) {
9086   unsigned TDK = Cand->DeductionFailure.Result;
9087   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9088     if (CheckArityMismatch(S, Cand, NumArgs))
9089       return;
9090   }
9091   DiagnoseBadDeduction(S, Cand->Function, // pattern
9092                        Cand->DeductionFailure, NumArgs);
9093 }
9094 
9095 /// CUDA: diagnose an invalid call across targets.
9096 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9097   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9098   FunctionDecl *Callee = Cand->Function;
9099 
9100   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9101                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9102 
9103   std::string FnDesc;
9104   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9105 
9106   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9107       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9108 
9109   // This could be an implicit constructor for which we could not infer the
9110   // target due to a collsion. Diagnose that case.
9111   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9112   if (Meth != nullptr && Meth->isImplicit()) {
9113     CXXRecordDecl *ParentClass = Meth->getParent();
9114     Sema::CXXSpecialMember CSM;
9115 
9116     switch (FnKind) {
9117     default:
9118       return;
9119     case oc_implicit_default_constructor:
9120       CSM = Sema::CXXDefaultConstructor;
9121       break;
9122     case oc_implicit_copy_constructor:
9123       CSM = Sema::CXXCopyConstructor;
9124       break;
9125     case oc_implicit_move_constructor:
9126       CSM = Sema::CXXMoveConstructor;
9127       break;
9128     case oc_implicit_copy_assignment:
9129       CSM = Sema::CXXCopyAssignment;
9130       break;
9131     case oc_implicit_move_assignment:
9132       CSM = Sema::CXXMoveAssignment;
9133       break;
9134     };
9135 
9136     bool ConstRHS = false;
9137     if (Meth->getNumParams()) {
9138       if (const ReferenceType *RT =
9139               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9140         ConstRHS = RT->getPointeeType().isConstQualified();
9141       }
9142     }
9143 
9144     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9145                                               /* ConstRHS */ ConstRHS,
9146                                               /* Diagnose */ true);
9147   }
9148 }
9149 
9150 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9151   FunctionDecl *Callee = Cand->Function;
9152   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9153 
9154   S.Diag(Callee->getLocation(),
9155          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9156       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9157 }
9158 
9159 /// Generates a 'note' diagnostic for an overload candidate.  We've
9160 /// already generated a primary error at the call site.
9161 ///
9162 /// It really does need to be a single diagnostic with its caret
9163 /// pointed at the candidate declaration.  Yes, this creates some
9164 /// major challenges of technical writing.  Yes, this makes pointing
9165 /// out problems with specific arguments quite awkward.  It's still
9166 /// better than generating twenty screens of text for every failed
9167 /// overload.
9168 ///
9169 /// It would be great to be able to express per-candidate problems
9170 /// more richly for those diagnostic clients that cared, but we'd
9171 /// still have to be just as careful with the default diagnostics.
9172 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9173                                   unsigned NumArgs) {
9174   FunctionDecl *Fn = Cand->Function;
9175 
9176   // Note deleted candidates, but only if they're viable.
9177   if (Cand->Viable && (Fn->isDeleted() ||
9178       S.isFunctionConsideredUnavailable(Fn))) {
9179     std::string FnDesc;
9180     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9181 
9182     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9183       << FnKind << FnDesc
9184       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9185     MaybeEmitInheritedConstructorNote(S, Fn);
9186     return;
9187   }
9188 
9189   // We don't really have anything else to say about viable candidates.
9190   if (Cand->Viable) {
9191     S.NoteOverloadCandidate(Fn);
9192     return;
9193   }
9194 
9195   switch (Cand->FailureKind) {
9196   case ovl_fail_too_many_arguments:
9197   case ovl_fail_too_few_arguments:
9198     return DiagnoseArityMismatch(S, Cand, NumArgs);
9199 
9200   case ovl_fail_bad_deduction:
9201     return DiagnoseBadDeduction(S, Cand, NumArgs);
9202 
9203   case ovl_fail_trivial_conversion:
9204   case ovl_fail_bad_final_conversion:
9205   case ovl_fail_final_conversion_not_exact:
9206     return S.NoteOverloadCandidate(Fn);
9207 
9208   case ovl_fail_bad_conversion: {
9209     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9210     for (unsigned N = Cand->NumConversions; I != N; ++I)
9211       if (Cand->Conversions[I].isBad())
9212         return DiagnoseBadConversion(S, Cand, I);
9213 
9214     // FIXME: this currently happens when we're called from SemaInit
9215     // when user-conversion overload fails.  Figure out how to handle
9216     // those conditions and diagnose them well.
9217     return S.NoteOverloadCandidate(Fn);
9218   }
9219 
9220   case ovl_fail_bad_target:
9221     return DiagnoseBadTarget(S, Cand);
9222 
9223   case ovl_fail_enable_if:
9224     return DiagnoseFailedEnableIfAttr(S, Cand);
9225   }
9226 }
9227 
9228 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9229   // Desugar the type of the surrogate down to a function type,
9230   // retaining as many typedefs as possible while still showing
9231   // the function type (and, therefore, its parameter types).
9232   QualType FnType = Cand->Surrogate->getConversionType();
9233   bool isLValueReference = false;
9234   bool isRValueReference = false;
9235   bool isPointer = false;
9236   if (const LValueReferenceType *FnTypeRef =
9237         FnType->getAs<LValueReferenceType>()) {
9238     FnType = FnTypeRef->getPointeeType();
9239     isLValueReference = true;
9240   } else if (const RValueReferenceType *FnTypeRef =
9241                FnType->getAs<RValueReferenceType>()) {
9242     FnType = FnTypeRef->getPointeeType();
9243     isRValueReference = true;
9244   }
9245   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9246     FnType = FnTypePtr->getPointeeType();
9247     isPointer = true;
9248   }
9249   // Desugar down to a function type.
9250   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9251   // Reconstruct the pointer/reference as appropriate.
9252   if (isPointer) FnType = S.Context.getPointerType(FnType);
9253   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9254   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9255 
9256   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9257     << FnType;
9258   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9259 }
9260 
9261 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9262                                          SourceLocation OpLoc,
9263                                          OverloadCandidate *Cand) {
9264   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9265   std::string TypeStr("operator");
9266   TypeStr += Opc;
9267   TypeStr += "(";
9268   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9269   if (Cand->NumConversions == 1) {
9270     TypeStr += ")";
9271     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9272   } else {
9273     TypeStr += ", ";
9274     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9275     TypeStr += ")";
9276     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9277   }
9278 }
9279 
9280 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9281                                          OverloadCandidate *Cand) {
9282   unsigned NoOperands = Cand->NumConversions;
9283   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9284     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9285     if (ICS.isBad()) break; // all meaningless after first invalid
9286     if (!ICS.isAmbiguous()) continue;
9287 
9288     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9289                               S.PDiag(diag::note_ambiguous_type_conversion));
9290   }
9291 }
9292 
9293 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9294   if (Cand->Function)
9295     return Cand->Function->getLocation();
9296   if (Cand->IsSurrogate)
9297     return Cand->Surrogate->getLocation();
9298   return SourceLocation();
9299 }
9300 
9301 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9302   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9303   case Sema::TDK_Success:
9304     llvm_unreachable("TDK_success while diagnosing bad deduction");
9305 
9306   case Sema::TDK_Invalid:
9307   case Sema::TDK_Incomplete:
9308     return 1;
9309 
9310   case Sema::TDK_Underqualified:
9311   case Sema::TDK_Inconsistent:
9312     return 2;
9313 
9314   case Sema::TDK_SubstitutionFailure:
9315   case Sema::TDK_NonDeducedMismatch:
9316   case Sema::TDK_MiscellaneousDeductionFailure:
9317     return 3;
9318 
9319   case Sema::TDK_InstantiationDepth:
9320   case Sema::TDK_FailedOverloadResolution:
9321     return 4;
9322 
9323   case Sema::TDK_InvalidExplicitArguments:
9324     return 5;
9325 
9326   case Sema::TDK_TooManyArguments:
9327   case Sema::TDK_TooFewArguments:
9328     return 6;
9329   }
9330   llvm_unreachable("Unhandled deduction result");
9331 }
9332 
9333 namespace {
9334 struct CompareOverloadCandidatesForDisplay {
9335   Sema &S;
9336   size_t NumArgs;
9337 
9338   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9339       : S(S), NumArgs(nArgs) {}
9340 
9341   bool operator()(const OverloadCandidate *L,
9342                   const OverloadCandidate *R) {
9343     // Fast-path this check.
9344     if (L == R) return false;
9345 
9346     // Order first by viability.
9347     if (L->Viable) {
9348       if (!R->Viable) return true;
9349 
9350       // TODO: introduce a tri-valued comparison for overload
9351       // candidates.  Would be more worthwhile if we had a sort
9352       // that could exploit it.
9353       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9354       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9355     } else if (R->Viable)
9356       return false;
9357 
9358     assert(L->Viable == R->Viable);
9359 
9360     // Criteria by which we can sort non-viable candidates:
9361     if (!L->Viable) {
9362       // 1. Arity mismatches come after other candidates.
9363       if (L->FailureKind == ovl_fail_too_many_arguments ||
9364           L->FailureKind == ovl_fail_too_few_arguments) {
9365         if (R->FailureKind == ovl_fail_too_many_arguments ||
9366             R->FailureKind == ovl_fail_too_few_arguments) {
9367           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9368           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9369           if (LDist == RDist) {
9370             if (L->FailureKind == R->FailureKind)
9371               // Sort non-surrogates before surrogates.
9372               return !L->IsSurrogate && R->IsSurrogate;
9373             // Sort candidates requiring fewer parameters than there were
9374             // arguments given after candidates requiring more parameters
9375             // than there were arguments given.
9376             return L->FailureKind == ovl_fail_too_many_arguments;
9377           }
9378           return LDist < RDist;
9379         }
9380         return false;
9381       }
9382       if (R->FailureKind == ovl_fail_too_many_arguments ||
9383           R->FailureKind == ovl_fail_too_few_arguments)
9384         return true;
9385 
9386       // 2. Bad conversions come first and are ordered by the number
9387       // of bad conversions and quality of good conversions.
9388       if (L->FailureKind == ovl_fail_bad_conversion) {
9389         if (R->FailureKind != ovl_fail_bad_conversion)
9390           return true;
9391 
9392         // The conversion that can be fixed with a smaller number of changes,
9393         // comes first.
9394         unsigned numLFixes = L->Fix.NumConversionsFixed;
9395         unsigned numRFixes = R->Fix.NumConversionsFixed;
9396         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9397         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9398         if (numLFixes != numRFixes) {
9399           if (numLFixes < numRFixes)
9400             return true;
9401           else
9402             return false;
9403         }
9404 
9405         // If there's any ordering between the defined conversions...
9406         // FIXME: this might not be transitive.
9407         assert(L->NumConversions == R->NumConversions);
9408 
9409         int leftBetter = 0;
9410         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9411         for (unsigned E = L->NumConversions; I != E; ++I) {
9412           switch (CompareImplicitConversionSequences(S,
9413                                                      L->Conversions[I],
9414                                                      R->Conversions[I])) {
9415           case ImplicitConversionSequence::Better:
9416             leftBetter++;
9417             break;
9418 
9419           case ImplicitConversionSequence::Worse:
9420             leftBetter--;
9421             break;
9422 
9423           case ImplicitConversionSequence::Indistinguishable:
9424             break;
9425           }
9426         }
9427         if (leftBetter > 0) return true;
9428         if (leftBetter < 0) return false;
9429 
9430       } else if (R->FailureKind == ovl_fail_bad_conversion)
9431         return false;
9432 
9433       if (L->FailureKind == ovl_fail_bad_deduction) {
9434         if (R->FailureKind != ovl_fail_bad_deduction)
9435           return true;
9436 
9437         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9438           return RankDeductionFailure(L->DeductionFailure)
9439                < RankDeductionFailure(R->DeductionFailure);
9440       } else if (R->FailureKind == ovl_fail_bad_deduction)
9441         return false;
9442 
9443       // TODO: others?
9444     }
9445 
9446     // Sort everything else by location.
9447     SourceLocation LLoc = GetLocationForCandidate(L);
9448     SourceLocation RLoc = GetLocationForCandidate(R);
9449 
9450     // Put candidates without locations (e.g. builtins) at the end.
9451     if (LLoc.isInvalid()) return false;
9452     if (RLoc.isInvalid()) return true;
9453 
9454     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9455   }
9456 };
9457 }
9458 
9459 /// CompleteNonViableCandidate - Normally, overload resolution only
9460 /// computes up to the first. Produces the FixIt set if possible.
9461 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9462                                        ArrayRef<Expr *> Args) {
9463   assert(!Cand->Viable);
9464 
9465   // Don't do anything on failures other than bad conversion.
9466   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9467 
9468   // We only want the FixIts if all the arguments can be corrected.
9469   bool Unfixable = false;
9470   // Use a implicit copy initialization to check conversion fixes.
9471   Cand->Fix.setConversionChecker(TryCopyInitialization);
9472 
9473   // Skip forward to the first bad conversion.
9474   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9475   unsigned ConvCount = Cand->NumConversions;
9476   while (true) {
9477     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9478     ConvIdx++;
9479     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9480       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9481       break;
9482     }
9483   }
9484 
9485   if (ConvIdx == ConvCount)
9486     return;
9487 
9488   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9489          "remaining conversion is initialized?");
9490 
9491   // FIXME: this should probably be preserved from the overload
9492   // operation somehow.
9493   bool SuppressUserConversions = false;
9494 
9495   const FunctionProtoType* Proto;
9496   unsigned ArgIdx = ConvIdx;
9497 
9498   if (Cand->IsSurrogate) {
9499     QualType ConvType
9500       = Cand->Surrogate->getConversionType().getNonReferenceType();
9501     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9502       ConvType = ConvPtrType->getPointeeType();
9503     Proto = ConvType->getAs<FunctionProtoType>();
9504     ArgIdx--;
9505   } else if (Cand->Function) {
9506     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9507     if (isa<CXXMethodDecl>(Cand->Function) &&
9508         !isa<CXXConstructorDecl>(Cand->Function))
9509       ArgIdx--;
9510   } else {
9511     // Builtin binary operator with a bad first conversion.
9512     assert(ConvCount <= 3);
9513     for (; ConvIdx != ConvCount; ++ConvIdx)
9514       Cand->Conversions[ConvIdx]
9515         = TryCopyInitialization(S, Args[ConvIdx],
9516                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9517                                 SuppressUserConversions,
9518                                 /*InOverloadResolution*/ true,
9519                                 /*AllowObjCWritebackConversion=*/
9520                                   S.getLangOpts().ObjCAutoRefCount);
9521     return;
9522   }
9523 
9524   // Fill in the rest of the conversions.
9525   unsigned NumParams = Proto->getNumParams();
9526   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9527     if (ArgIdx < NumParams) {
9528       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9529           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9530           /*InOverloadResolution=*/true,
9531           /*AllowObjCWritebackConversion=*/
9532           S.getLangOpts().ObjCAutoRefCount);
9533       // Store the FixIt in the candidate if it exists.
9534       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9535         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9536     }
9537     else
9538       Cand->Conversions[ConvIdx].setEllipsis();
9539   }
9540 }
9541 
9542 /// PrintOverloadCandidates - When overload resolution fails, prints
9543 /// diagnostic messages containing the candidates in the candidate
9544 /// set.
9545 void OverloadCandidateSet::NoteCandidates(Sema &S,
9546                                           OverloadCandidateDisplayKind OCD,
9547                                           ArrayRef<Expr *> Args,
9548                                           StringRef Opc,
9549                                           SourceLocation OpLoc) {
9550   // Sort the candidates by viability and position.  Sorting directly would
9551   // be prohibitive, so we make a set of pointers and sort those.
9552   SmallVector<OverloadCandidate*, 32> Cands;
9553   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9554   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9555     if (Cand->Viable)
9556       Cands.push_back(Cand);
9557     else if (OCD == OCD_AllCandidates) {
9558       CompleteNonViableCandidate(S, Cand, Args);
9559       if (Cand->Function || Cand->IsSurrogate)
9560         Cands.push_back(Cand);
9561       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9562       // want to list every possible builtin candidate.
9563     }
9564   }
9565 
9566   std::sort(Cands.begin(), Cands.end(),
9567             CompareOverloadCandidatesForDisplay(S, Args.size()));
9568 
9569   bool ReportedAmbiguousConversions = false;
9570 
9571   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9572   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9573   unsigned CandsShown = 0;
9574   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9575     OverloadCandidate *Cand = *I;
9576 
9577     // Set an arbitrary limit on the number of candidate functions we'll spam
9578     // the user with.  FIXME: This limit should depend on details of the
9579     // candidate list.
9580     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9581       break;
9582     }
9583     ++CandsShown;
9584 
9585     if (Cand->Function)
9586       NoteFunctionCandidate(S, Cand, Args.size());
9587     else if (Cand->IsSurrogate)
9588       NoteSurrogateCandidate(S, Cand);
9589     else {
9590       assert(Cand->Viable &&
9591              "Non-viable built-in candidates are not added to Cands.");
9592       // Generally we only see ambiguities including viable builtin
9593       // operators if overload resolution got screwed up by an
9594       // ambiguous user-defined conversion.
9595       //
9596       // FIXME: It's quite possible for different conversions to see
9597       // different ambiguities, though.
9598       if (!ReportedAmbiguousConversions) {
9599         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9600         ReportedAmbiguousConversions = true;
9601       }
9602 
9603       // If this is a viable builtin, print it.
9604       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9605     }
9606   }
9607 
9608   if (I != E)
9609     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9610 }
9611 
9612 static SourceLocation
9613 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9614   return Cand->Specialization ? Cand->Specialization->getLocation()
9615                               : SourceLocation();
9616 }
9617 
9618 namespace {
9619 struct CompareTemplateSpecCandidatesForDisplay {
9620   Sema &S;
9621   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9622 
9623   bool operator()(const TemplateSpecCandidate *L,
9624                   const TemplateSpecCandidate *R) {
9625     // Fast-path this check.
9626     if (L == R)
9627       return false;
9628 
9629     // Assuming that both candidates are not matches...
9630 
9631     // Sort by the ranking of deduction failures.
9632     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9633       return RankDeductionFailure(L->DeductionFailure) <
9634              RankDeductionFailure(R->DeductionFailure);
9635 
9636     // Sort everything else by location.
9637     SourceLocation LLoc = GetLocationForCandidate(L);
9638     SourceLocation RLoc = GetLocationForCandidate(R);
9639 
9640     // Put candidates without locations (e.g. builtins) at the end.
9641     if (LLoc.isInvalid())
9642       return false;
9643     if (RLoc.isInvalid())
9644       return true;
9645 
9646     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9647   }
9648 };
9649 }
9650 
9651 /// Diagnose a template argument deduction failure.
9652 /// We are treating these failures as overload failures due to bad
9653 /// deductions.
9654 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9655   DiagnoseBadDeduction(S, Specialization, // pattern
9656                        DeductionFailure, /*NumArgs=*/0);
9657 }
9658 
9659 void TemplateSpecCandidateSet::destroyCandidates() {
9660   for (iterator i = begin(), e = end(); i != e; ++i) {
9661     i->DeductionFailure.Destroy();
9662   }
9663 }
9664 
9665 void TemplateSpecCandidateSet::clear() {
9666   destroyCandidates();
9667   Candidates.clear();
9668 }
9669 
9670 /// NoteCandidates - When no template specialization match is found, prints
9671 /// diagnostic messages containing the non-matching specializations that form
9672 /// the candidate set.
9673 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9674 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9675 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9676   // Sort the candidates by position (assuming no candidate is a match).
9677   // Sorting directly would be prohibitive, so we make a set of pointers
9678   // and sort those.
9679   SmallVector<TemplateSpecCandidate *, 32> Cands;
9680   Cands.reserve(size());
9681   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9682     if (Cand->Specialization)
9683       Cands.push_back(Cand);
9684     // Otherwise, this is a non-matching builtin candidate.  We do not,
9685     // in general, want to list every possible builtin candidate.
9686   }
9687 
9688   std::sort(Cands.begin(), Cands.end(),
9689             CompareTemplateSpecCandidatesForDisplay(S));
9690 
9691   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9692   // for generalization purposes (?).
9693   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9694 
9695   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9696   unsigned CandsShown = 0;
9697   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9698     TemplateSpecCandidate *Cand = *I;
9699 
9700     // Set an arbitrary limit on the number of candidates we'll spam
9701     // the user with.  FIXME: This limit should depend on details of the
9702     // candidate list.
9703     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9704       break;
9705     ++CandsShown;
9706 
9707     assert(Cand->Specialization &&
9708            "Non-matching built-in candidates are not added to Cands.");
9709     Cand->NoteDeductionFailure(S);
9710   }
9711 
9712   if (I != E)
9713     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9714 }
9715 
9716 // [PossiblyAFunctionType]  -->   [Return]
9717 // NonFunctionType --> NonFunctionType
9718 // R (A) --> R(A)
9719 // R (*)(A) --> R (A)
9720 // R (&)(A) --> R (A)
9721 // R (S::*)(A) --> R (A)
9722 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9723   QualType Ret = PossiblyAFunctionType;
9724   if (const PointerType *ToTypePtr =
9725     PossiblyAFunctionType->getAs<PointerType>())
9726     Ret = ToTypePtr->getPointeeType();
9727   else if (const ReferenceType *ToTypeRef =
9728     PossiblyAFunctionType->getAs<ReferenceType>())
9729     Ret = ToTypeRef->getPointeeType();
9730   else if (const MemberPointerType *MemTypePtr =
9731     PossiblyAFunctionType->getAs<MemberPointerType>())
9732     Ret = MemTypePtr->getPointeeType();
9733   Ret =
9734     Context.getCanonicalType(Ret).getUnqualifiedType();
9735   return Ret;
9736 }
9737 
9738 namespace {
9739 // A helper class to help with address of function resolution
9740 // - allows us to avoid passing around all those ugly parameters
9741 class AddressOfFunctionResolver {
9742   Sema& S;
9743   Expr* SourceExpr;
9744   const QualType& TargetType;
9745   QualType TargetFunctionType; // Extracted function type from target type
9746 
9747   bool Complain;
9748   //DeclAccessPair& ResultFunctionAccessPair;
9749   ASTContext& Context;
9750 
9751   bool TargetTypeIsNonStaticMemberFunction;
9752   bool FoundNonTemplateFunction;
9753   bool StaticMemberFunctionFromBoundPointer;
9754 
9755   OverloadExpr::FindResult OvlExprInfo;
9756   OverloadExpr *OvlExpr;
9757   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9758   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9759   TemplateSpecCandidateSet FailedCandidates;
9760 
9761 public:
9762   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9763                             const QualType &TargetType, bool Complain)
9764       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9765         Complain(Complain), Context(S.getASTContext()),
9766         TargetTypeIsNonStaticMemberFunction(
9767             !!TargetType->getAs<MemberPointerType>()),
9768         FoundNonTemplateFunction(false),
9769         StaticMemberFunctionFromBoundPointer(false),
9770         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9771         OvlExpr(OvlExprInfo.Expression),
9772         FailedCandidates(OvlExpr->getNameLoc()) {
9773     ExtractUnqualifiedFunctionTypeFromTargetType();
9774 
9775     if (TargetFunctionType->isFunctionType()) {
9776       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9777         if (!UME->isImplicitAccess() &&
9778             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9779           StaticMemberFunctionFromBoundPointer = true;
9780     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9781       DeclAccessPair dap;
9782       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9783               OvlExpr, false, &dap)) {
9784         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9785           if (!Method->isStatic()) {
9786             // If the target type is a non-function type and the function found
9787             // is a non-static member function, pretend as if that was the
9788             // target, it's the only possible type to end up with.
9789             TargetTypeIsNonStaticMemberFunction = true;
9790 
9791             // And skip adding the function if its not in the proper form.
9792             // We'll diagnose this due to an empty set of functions.
9793             if (!OvlExprInfo.HasFormOfMemberPointer)
9794               return;
9795           }
9796 
9797         Matches.push_back(std::make_pair(dap, Fn));
9798       }
9799       return;
9800     }
9801 
9802     if (OvlExpr->hasExplicitTemplateArgs())
9803       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9804 
9805     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9806       // C++ [over.over]p4:
9807       //   If more than one function is selected, [...]
9808       if (Matches.size() > 1) {
9809         if (FoundNonTemplateFunction)
9810           EliminateAllTemplateMatches();
9811         else
9812           EliminateAllExceptMostSpecializedTemplate();
9813       }
9814     }
9815   }
9816 
9817 private:
9818   bool isTargetTypeAFunction() const {
9819     return TargetFunctionType->isFunctionType();
9820   }
9821 
9822   // [ToType]     [Return]
9823 
9824   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9825   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9826   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9827   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9828     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9829   }
9830 
9831   // return true if any matching specializations were found
9832   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9833                                    const DeclAccessPair& CurAccessFunPair) {
9834     if (CXXMethodDecl *Method
9835               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9836       // Skip non-static function templates when converting to pointer, and
9837       // static when converting to member pointer.
9838       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9839         return false;
9840     }
9841     else if (TargetTypeIsNonStaticMemberFunction)
9842       return false;
9843 
9844     // C++ [over.over]p2:
9845     //   If the name is a function template, template argument deduction is
9846     //   done (14.8.2.2), and if the argument deduction succeeds, the
9847     //   resulting template argument list is used to generate a single
9848     //   function template specialization, which is added to the set of
9849     //   overloaded functions considered.
9850     FunctionDecl *Specialization = nullptr;
9851     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9852     if (Sema::TemplateDeductionResult Result
9853           = S.DeduceTemplateArguments(FunctionTemplate,
9854                                       &OvlExplicitTemplateArgs,
9855                                       TargetFunctionType, Specialization,
9856                                       Info, /*InOverloadResolution=*/true)) {
9857       // Make a note of the failed deduction for diagnostics.
9858       FailedCandidates.addCandidate()
9859           .set(FunctionTemplate->getTemplatedDecl(),
9860                MakeDeductionFailureInfo(Context, Result, Info));
9861       return false;
9862     }
9863 
9864     // Template argument deduction ensures that we have an exact match or
9865     // compatible pointer-to-function arguments that would be adjusted by ICS.
9866     // This function template specicalization works.
9867     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9868     assert(S.isSameOrCompatibleFunctionType(
9869               Context.getCanonicalType(Specialization->getType()),
9870               Context.getCanonicalType(TargetFunctionType)));
9871     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9872     return true;
9873   }
9874 
9875   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9876                                       const DeclAccessPair& CurAccessFunPair) {
9877     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9878       // Skip non-static functions when converting to pointer, and static
9879       // when converting to member pointer.
9880       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9881         return false;
9882     }
9883     else if (TargetTypeIsNonStaticMemberFunction)
9884       return false;
9885 
9886     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9887       if (S.getLangOpts().CUDA)
9888         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9889           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
9890             return false;
9891 
9892       // If any candidate has a placeholder return type, trigger its deduction
9893       // now.
9894       if (S.getLangOpts().CPlusPlus14 &&
9895           FunDecl->getReturnType()->isUndeducedType() &&
9896           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9897         return false;
9898 
9899       QualType ResultTy;
9900       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9901                                          FunDecl->getType()) ||
9902           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9903                                  ResultTy)) {
9904         Matches.push_back(std::make_pair(CurAccessFunPair,
9905           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9906         FoundNonTemplateFunction = true;
9907         return true;
9908       }
9909     }
9910 
9911     return false;
9912   }
9913 
9914   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9915     bool Ret = false;
9916 
9917     // If the overload expression doesn't have the form of a pointer to
9918     // member, don't try to convert it to a pointer-to-member type.
9919     if (IsInvalidFormOfPointerToMemberFunction())
9920       return false;
9921 
9922     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9923                                E = OvlExpr->decls_end();
9924          I != E; ++I) {
9925       // Look through any using declarations to find the underlying function.
9926       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9927 
9928       // C++ [over.over]p3:
9929       //   Non-member functions and static member functions match
9930       //   targets of type "pointer-to-function" or "reference-to-function."
9931       //   Nonstatic member functions match targets of
9932       //   type "pointer-to-member-function."
9933       // Note that according to DR 247, the containing class does not matter.
9934       if (FunctionTemplateDecl *FunctionTemplate
9935                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9936         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9937           Ret = true;
9938       }
9939       // If we have explicit template arguments supplied, skip non-templates.
9940       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9941                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9942         Ret = true;
9943     }
9944     assert(Ret || Matches.empty());
9945     return Ret;
9946   }
9947 
9948   void EliminateAllExceptMostSpecializedTemplate() {
9949     //   [...] and any given function template specialization F1 is
9950     //   eliminated if the set contains a second function template
9951     //   specialization whose function template is more specialized
9952     //   than the function template of F1 according to the partial
9953     //   ordering rules of 14.5.5.2.
9954 
9955     // The algorithm specified above is quadratic. We instead use a
9956     // two-pass algorithm (similar to the one used to identify the
9957     // best viable function in an overload set) that identifies the
9958     // best function template (if it exists).
9959 
9960     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9961     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9962       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9963 
9964     // TODO: It looks like FailedCandidates does not serve much purpose
9965     // here, since the no_viable diagnostic has index 0.
9966     UnresolvedSetIterator Result = S.getMostSpecialized(
9967         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9968         SourceExpr->getLocStart(), S.PDiag(),
9969         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9970                                                      .second->getDeclName(),
9971         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9972         Complain, TargetFunctionType);
9973 
9974     if (Result != MatchesCopy.end()) {
9975       // Make it the first and only element
9976       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9977       Matches[0].second = cast<FunctionDecl>(*Result);
9978       Matches.resize(1);
9979     }
9980   }
9981 
9982   void EliminateAllTemplateMatches() {
9983     //   [...] any function template specializations in the set are
9984     //   eliminated if the set also contains a non-template function, [...]
9985     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9986       if (Matches[I].second->getPrimaryTemplate() == nullptr)
9987         ++I;
9988       else {
9989         Matches[I] = Matches[--N];
9990         Matches.set_size(N);
9991       }
9992     }
9993   }
9994 
9995 public:
9996   void ComplainNoMatchesFound() const {
9997     assert(Matches.empty());
9998     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9999         << OvlExpr->getName() << TargetFunctionType
10000         << OvlExpr->getSourceRange();
10001     if (FailedCandidates.empty())
10002       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10003     else {
10004       // We have some deduction failure messages. Use them to diagnose
10005       // the function templates, and diagnose the non-template candidates
10006       // normally.
10007       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10008                                  IEnd = OvlExpr->decls_end();
10009            I != IEnd; ++I)
10010         if (FunctionDecl *Fun =
10011                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10012           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10013       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10014     }
10015   }
10016 
10017   bool IsInvalidFormOfPointerToMemberFunction() const {
10018     return TargetTypeIsNonStaticMemberFunction &&
10019       !OvlExprInfo.HasFormOfMemberPointer;
10020   }
10021 
10022   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10023       // TODO: Should we condition this on whether any functions might
10024       // have matched, or is it more appropriate to do that in callers?
10025       // TODO: a fixit wouldn't hurt.
10026       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10027         << TargetType << OvlExpr->getSourceRange();
10028   }
10029 
10030   bool IsStaticMemberFunctionFromBoundPointer() const {
10031     return StaticMemberFunctionFromBoundPointer;
10032   }
10033 
10034   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10035     S.Diag(OvlExpr->getLocStart(),
10036            diag::err_invalid_form_pointer_member_function)
10037       << OvlExpr->getSourceRange();
10038   }
10039 
10040   void ComplainOfInvalidConversion() const {
10041     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10042       << OvlExpr->getName() << TargetType;
10043   }
10044 
10045   void ComplainMultipleMatchesFound() const {
10046     assert(Matches.size() > 1);
10047     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10048       << OvlExpr->getName()
10049       << OvlExpr->getSourceRange();
10050     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10051   }
10052 
10053   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10054 
10055   int getNumMatches() const { return Matches.size(); }
10056 
10057   FunctionDecl* getMatchingFunctionDecl() const {
10058     if (Matches.size() != 1) return nullptr;
10059     return Matches[0].second;
10060   }
10061 
10062   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10063     if (Matches.size() != 1) return nullptr;
10064     return &Matches[0].first;
10065   }
10066 };
10067 }
10068 
10069 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10070 /// an overloaded function (C++ [over.over]), where @p From is an
10071 /// expression with overloaded function type and @p ToType is the type
10072 /// we're trying to resolve to. For example:
10073 ///
10074 /// @code
10075 /// int f(double);
10076 /// int f(int);
10077 ///
10078 /// int (*pfd)(double) = f; // selects f(double)
10079 /// @endcode
10080 ///
10081 /// This routine returns the resulting FunctionDecl if it could be
10082 /// resolved, and NULL otherwise. When @p Complain is true, this
10083 /// routine will emit diagnostics if there is an error.
10084 FunctionDecl *
10085 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10086                                          QualType TargetType,
10087                                          bool Complain,
10088                                          DeclAccessPair &FoundResult,
10089                                          bool *pHadMultipleCandidates) {
10090   assert(AddressOfExpr->getType() == Context.OverloadTy);
10091 
10092   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10093                                      Complain);
10094   int NumMatches = Resolver.getNumMatches();
10095   FunctionDecl *Fn = nullptr;
10096   if (NumMatches == 0 && Complain) {
10097     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10098       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10099     else
10100       Resolver.ComplainNoMatchesFound();
10101   }
10102   else if (NumMatches > 1 && Complain)
10103     Resolver.ComplainMultipleMatchesFound();
10104   else if (NumMatches == 1) {
10105     Fn = Resolver.getMatchingFunctionDecl();
10106     assert(Fn);
10107     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10108     if (Complain) {
10109       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10110         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10111       else
10112         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10113     }
10114   }
10115 
10116   if (pHadMultipleCandidates)
10117     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10118   return Fn;
10119 }
10120 
10121 /// \brief Given an expression that refers to an overloaded function, try to
10122 /// resolve that overloaded function expression down to a single function.
10123 ///
10124 /// This routine can only resolve template-ids that refer to a single function
10125 /// template, where that template-id refers to a single template whose template
10126 /// arguments are either provided by the template-id or have defaults,
10127 /// as described in C++0x [temp.arg.explicit]p3.
10128 ///
10129 /// If no template-ids are found, no diagnostics are emitted and NULL is
10130 /// returned.
10131 FunctionDecl *
10132 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10133                                                   bool Complain,
10134                                                   DeclAccessPair *FoundResult) {
10135   // C++ [over.over]p1:
10136   //   [...] [Note: any redundant set of parentheses surrounding the
10137   //   overloaded function name is ignored (5.1). ]
10138   // C++ [over.over]p1:
10139   //   [...] The overloaded function name can be preceded by the &
10140   //   operator.
10141 
10142   // If we didn't actually find any template-ids, we're done.
10143   if (!ovl->hasExplicitTemplateArgs())
10144     return nullptr;
10145 
10146   TemplateArgumentListInfo ExplicitTemplateArgs;
10147   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10148   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10149 
10150   // Look through all of the overloaded functions, searching for one
10151   // whose type matches exactly.
10152   FunctionDecl *Matched = nullptr;
10153   for (UnresolvedSetIterator I = ovl->decls_begin(),
10154          E = ovl->decls_end(); I != E; ++I) {
10155     // C++0x [temp.arg.explicit]p3:
10156     //   [...] In contexts where deduction is done and fails, or in contexts
10157     //   where deduction is not done, if a template argument list is
10158     //   specified and it, along with any default template arguments,
10159     //   identifies a single function template specialization, then the
10160     //   template-id is an lvalue for the function template specialization.
10161     FunctionTemplateDecl *FunctionTemplate
10162       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10163 
10164     // C++ [over.over]p2:
10165     //   If the name is a function template, template argument deduction is
10166     //   done (14.8.2.2), and if the argument deduction succeeds, the
10167     //   resulting template argument list is used to generate a single
10168     //   function template specialization, which is added to the set of
10169     //   overloaded functions considered.
10170     FunctionDecl *Specialization = nullptr;
10171     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10172     if (TemplateDeductionResult Result
10173           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10174                                     Specialization, Info,
10175                                     /*InOverloadResolution=*/true)) {
10176       // Make a note of the failed deduction for diagnostics.
10177       // TODO: Actually use the failed-deduction info?
10178       FailedCandidates.addCandidate()
10179           .set(FunctionTemplate->getTemplatedDecl(),
10180                MakeDeductionFailureInfo(Context, Result, Info));
10181       continue;
10182     }
10183 
10184     assert(Specialization && "no specialization and no error?");
10185 
10186     // Multiple matches; we can't resolve to a single declaration.
10187     if (Matched) {
10188       if (Complain) {
10189         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10190           << ovl->getName();
10191         NoteAllOverloadCandidates(ovl);
10192       }
10193       return nullptr;
10194     }
10195 
10196     Matched = Specialization;
10197     if (FoundResult) *FoundResult = I.getPair();
10198   }
10199 
10200   if (Matched && getLangOpts().CPlusPlus14 &&
10201       Matched->getReturnType()->isUndeducedType() &&
10202       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10203     return nullptr;
10204 
10205   return Matched;
10206 }
10207 
10208 
10209 
10210 
10211 // Resolve and fix an overloaded expression that can be resolved
10212 // because it identifies a single function template specialization.
10213 //
10214 // Last three arguments should only be supplied if Complain = true
10215 //
10216 // Return true if it was logically possible to so resolve the
10217 // expression, regardless of whether or not it succeeded.  Always
10218 // returns true if 'complain' is set.
10219 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10220                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10221                    bool complain, const SourceRange& OpRangeForComplaining,
10222                                            QualType DestTypeForComplaining,
10223                                             unsigned DiagIDForComplaining) {
10224   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10225 
10226   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10227 
10228   DeclAccessPair found;
10229   ExprResult SingleFunctionExpression;
10230   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10231                            ovl.Expression, /*complain*/ false, &found)) {
10232     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10233       SrcExpr = ExprError();
10234       return true;
10235     }
10236 
10237     // It is only correct to resolve to an instance method if we're
10238     // resolving a form that's permitted to be a pointer to member.
10239     // Otherwise we'll end up making a bound member expression, which
10240     // is illegal in all the contexts we resolve like this.
10241     if (!ovl.HasFormOfMemberPointer &&
10242         isa<CXXMethodDecl>(fn) &&
10243         cast<CXXMethodDecl>(fn)->isInstance()) {
10244       if (!complain) return false;
10245 
10246       Diag(ovl.Expression->getExprLoc(),
10247            diag::err_bound_member_function)
10248         << 0 << ovl.Expression->getSourceRange();
10249 
10250       // TODO: I believe we only end up here if there's a mix of
10251       // static and non-static candidates (otherwise the expression
10252       // would have 'bound member' type, not 'overload' type).
10253       // Ideally we would note which candidate was chosen and why
10254       // the static candidates were rejected.
10255       SrcExpr = ExprError();
10256       return true;
10257     }
10258 
10259     // Fix the expression to refer to 'fn'.
10260     SingleFunctionExpression =
10261         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10262 
10263     // If desired, do function-to-pointer decay.
10264     if (doFunctionPointerConverion) {
10265       SingleFunctionExpression =
10266         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10267       if (SingleFunctionExpression.isInvalid()) {
10268         SrcExpr = ExprError();
10269         return true;
10270       }
10271     }
10272   }
10273 
10274   if (!SingleFunctionExpression.isUsable()) {
10275     if (complain) {
10276       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10277         << ovl.Expression->getName()
10278         << DestTypeForComplaining
10279         << OpRangeForComplaining
10280         << ovl.Expression->getQualifierLoc().getSourceRange();
10281       NoteAllOverloadCandidates(SrcExpr.get());
10282 
10283       SrcExpr = ExprError();
10284       return true;
10285     }
10286 
10287     return false;
10288   }
10289 
10290   SrcExpr = SingleFunctionExpression;
10291   return true;
10292 }
10293 
10294 /// \brief Add a single candidate to the overload set.
10295 static void AddOverloadedCallCandidate(Sema &S,
10296                                        DeclAccessPair FoundDecl,
10297                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10298                                        ArrayRef<Expr *> Args,
10299                                        OverloadCandidateSet &CandidateSet,
10300                                        bool PartialOverloading,
10301                                        bool KnownValid) {
10302   NamedDecl *Callee = FoundDecl.getDecl();
10303   if (isa<UsingShadowDecl>(Callee))
10304     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10305 
10306   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10307     if (ExplicitTemplateArgs) {
10308       assert(!KnownValid && "Explicit template arguments?");
10309       return;
10310     }
10311     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10312                            PartialOverloading);
10313     return;
10314   }
10315 
10316   if (FunctionTemplateDecl *FuncTemplate
10317       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10318     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10319                                    ExplicitTemplateArgs, Args, CandidateSet);
10320     return;
10321   }
10322 
10323   assert(!KnownValid && "unhandled case in overloaded call candidate");
10324 }
10325 
10326 /// \brief Add the overload candidates named by callee and/or found by argument
10327 /// dependent lookup to the given overload set.
10328 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10329                                        ArrayRef<Expr *> Args,
10330                                        OverloadCandidateSet &CandidateSet,
10331                                        bool PartialOverloading) {
10332 
10333 #ifndef NDEBUG
10334   // Verify that ArgumentDependentLookup is consistent with the rules
10335   // in C++0x [basic.lookup.argdep]p3:
10336   //
10337   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10338   //   and let Y be the lookup set produced by argument dependent
10339   //   lookup (defined as follows). If X contains
10340   //
10341   //     -- a declaration of a class member, or
10342   //
10343   //     -- a block-scope function declaration that is not a
10344   //        using-declaration, or
10345   //
10346   //     -- a declaration that is neither a function or a function
10347   //        template
10348   //
10349   //   then Y is empty.
10350 
10351   if (ULE->requiresADL()) {
10352     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10353            E = ULE->decls_end(); I != E; ++I) {
10354       assert(!(*I)->getDeclContext()->isRecord());
10355       assert(isa<UsingShadowDecl>(*I) ||
10356              !(*I)->getDeclContext()->isFunctionOrMethod());
10357       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10358     }
10359   }
10360 #endif
10361 
10362   // It would be nice to avoid this copy.
10363   TemplateArgumentListInfo TABuffer;
10364   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10365   if (ULE->hasExplicitTemplateArgs()) {
10366     ULE->copyTemplateArgumentsInto(TABuffer);
10367     ExplicitTemplateArgs = &TABuffer;
10368   }
10369 
10370   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10371          E = ULE->decls_end(); I != E; ++I)
10372     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10373                                CandidateSet, PartialOverloading,
10374                                /*KnownValid*/ true);
10375 
10376   if (ULE->requiresADL())
10377     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10378                                          Args, ExplicitTemplateArgs,
10379                                          CandidateSet, PartialOverloading);
10380 }
10381 
10382 /// Determine whether a declaration with the specified name could be moved into
10383 /// a different namespace.
10384 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10385   switch (Name.getCXXOverloadedOperator()) {
10386   case OO_New: case OO_Array_New:
10387   case OO_Delete: case OO_Array_Delete:
10388     return false;
10389 
10390   default:
10391     return true;
10392   }
10393 }
10394 
10395 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10396 /// template, where the non-dependent name was declared after the template
10397 /// was defined. This is common in code written for a compilers which do not
10398 /// correctly implement two-stage name lookup.
10399 ///
10400 /// Returns true if a viable candidate was found and a diagnostic was issued.
10401 static bool
10402 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10403                        const CXXScopeSpec &SS, LookupResult &R,
10404                        OverloadCandidateSet::CandidateSetKind CSK,
10405                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10406                        ArrayRef<Expr *> Args) {
10407   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10408     return false;
10409 
10410   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10411     if (DC->isTransparentContext())
10412       continue;
10413 
10414     SemaRef.LookupQualifiedName(R, DC);
10415 
10416     if (!R.empty()) {
10417       R.suppressDiagnostics();
10418 
10419       if (isa<CXXRecordDecl>(DC)) {
10420         // Don't diagnose names we find in classes; we get much better
10421         // diagnostics for these from DiagnoseEmptyLookup.
10422         R.clear();
10423         return false;
10424       }
10425 
10426       OverloadCandidateSet Candidates(FnLoc, CSK);
10427       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10428         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10429                                    ExplicitTemplateArgs, Args,
10430                                    Candidates, false, /*KnownValid*/ false);
10431 
10432       OverloadCandidateSet::iterator Best;
10433       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10434         // No viable functions. Don't bother the user with notes for functions
10435         // which don't work and shouldn't be found anyway.
10436         R.clear();
10437         return false;
10438       }
10439 
10440       // Find the namespaces where ADL would have looked, and suggest
10441       // declaring the function there instead.
10442       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10443       Sema::AssociatedClassSet AssociatedClasses;
10444       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10445                                                  AssociatedNamespaces,
10446                                                  AssociatedClasses);
10447       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10448       if (canBeDeclaredInNamespace(R.getLookupName())) {
10449         DeclContext *Std = SemaRef.getStdNamespace();
10450         for (Sema::AssociatedNamespaceSet::iterator
10451                it = AssociatedNamespaces.begin(),
10452                end = AssociatedNamespaces.end(); it != end; ++it) {
10453           // Never suggest declaring a function within namespace 'std'.
10454           if (Std && Std->Encloses(*it))
10455             continue;
10456 
10457           // Never suggest declaring a function within a namespace with a
10458           // reserved name, like __gnu_cxx.
10459           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10460           if (NS &&
10461               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10462             continue;
10463 
10464           SuggestedNamespaces.insert(*it);
10465         }
10466       }
10467 
10468       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10469         << R.getLookupName();
10470       if (SuggestedNamespaces.empty()) {
10471         SemaRef.Diag(Best->Function->getLocation(),
10472                      diag::note_not_found_by_two_phase_lookup)
10473           << R.getLookupName() << 0;
10474       } else if (SuggestedNamespaces.size() == 1) {
10475         SemaRef.Diag(Best->Function->getLocation(),
10476                      diag::note_not_found_by_two_phase_lookup)
10477           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10478       } else {
10479         // FIXME: It would be useful to list the associated namespaces here,
10480         // but the diagnostics infrastructure doesn't provide a way to produce
10481         // a localized representation of a list of items.
10482         SemaRef.Diag(Best->Function->getLocation(),
10483                      diag::note_not_found_by_two_phase_lookup)
10484           << R.getLookupName() << 2;
10485       }
10486 
10487       // Try to recover by calling this function.
10488       return true;
10489     }
10490 
10491     R.clear();
10492   }
10493 
10494   return false;
10495 }
10496 
10497 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10498 /// template, where the non-dependent operator was declared after the template
10499 /// was defined.
10500 ///
10501 /// Returns true if a viable candidate was found and a diagnostic was issued.
10502 static bool
10503 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10504                                SourceLocation OpLoc,
10505                                ArrayRef<Expr *> Args) {
10506   DeclarationName OpName =
10507     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10508   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10509   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10510                                 OverloadCandidateSet::CSK_Operator,
10511                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10512 }
10513 
10514 namespace {
10515 class BuildRecoveryCallExprRAII {
10516   Sema &SemaRef;
10517 public:
10518   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10519     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10520     SemaRef.IsBuildingRecoveryCallExpr = true;
10521   }
10522 
10523   ~BuildRecoveryCallExprRAII() {
10524     SemaRef.IsBuildingRecoveryCallExpr = false;
10525   }
10526 };
10527 
10528 }
10529 
10530 static std::unique_ptr<CorrectionCandidateCallback>
10531 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10532               bool HasTemplateArgs, bool AllowTypoCorrection) {
10533   if (!AllowTypoCorrection)
10534     return llvm::make_unique<NoTypoCorrectionCCC>();
10535   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10536                                                   HasTemplateArgs, ME);
10537 }
10538 
10539 /// Attempts to recover from a call where no functions were found.
10540 ///
10541 /// Returns true if new candidates were found.
10542 static ExprResult
10543 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10544                       UnresolvedLookupExpr *ULE,
10545                       SourceLocation LParenLoc,
10546                       MutableArrayRef<Expr *> Args,
10547                       SourceLocation RParenLoc,
10548                       bool EmptyLookup, bool AllowTypoCorrection) {
10549   // Do not try to recover if it is already building a recovery call.
10550   // This stops infinite loops for template instantiations like
10551   //
10552   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10553   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10554   //
10555   if (SemaRef.IsBuildingRecoveryCallExpr)
10556     return ExprError();
10557   BuildRecoveryCallExprRAII RCE(SemaRef);
10558 
10559   CXXScopeSpec SS;
10560   SS.Adopt(ULE->getQualifierLoc());
10561   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10562 
10563   TemplateArgumentListInfo TABuffer;
10564   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10565   if (ULE->hasExplicitTemplateArgs()) {
10566     ULE->copyTemplateArgumentsInto(TABuffer);
10567     ExplicitTemplateArgs = &TABuffer;
10568   }
10569 
10570   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10571                  Sema::LookupOrdinaryName);
10572   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10573                               OverloadCandidateSet::CSK_Normal,
10574                               ExplicitTemplateArgs, Args) &&
10575       (!EmptyLookup ||
10576        SemaRef.DiagnoseEmptyLookup(
10577            S, SS, R,
10578            MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10579                          ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10580            ExplicitTemplateArgs, Args)))
10581     return ExprError();
10582 
10583   assert(!R.empty() && "lookup results empty despite recovery");
10584 
10585   // Build an implicit member call if appropriate.  Just drop the
10586   // casts and such from the call, we don't really care.
10587   ExprResult NewFn = ExprError();
10588   if ((*R.begin())->isCXXClassMember())
10589     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10590                                                     R, ExplicitTemplateArgs);
10591   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10592     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10593                                         ExplicitTemplateArgs);
10594   else
10595     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10596 
10597   if (NewFn.isInvalid())
10598     return ExprError();
10599 
10600   // This shouldn't cause an infinite loop because we're giving it
10601   // an expression with viable lookup results, which should never
10602   // end up here.
10603   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10604                                MultiExprArg(Args.data(), Args.size()),
10605                                RParenLoc);
10606 }
10607 
10608 /// \brief Constructs and populates an OverloadedCandidateSet from
10609 /// the given function.
10610 /// \returns true when an the ExprResult output parameter has been set.
10611 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10612                                   UnresolvedLookupExpr *ULE,
10613                                   MultiExprArg Args,
10614                                   SourceLocation RParenLoc,
10615                                   OverloadCandidateSet *CandidateSet,
10616                                   ExprResult *Result) {
10617 #ifndef NDEBUG
10618   if (ULE->requiresADL()) {
10619     // To do ADL, we must have found an unqualified name.
10620     assert(!ULE->getQualifier() && "qualified name with ADL");
10621 
10622     // We don't perform ADL for implicit declarations of builtins.
10623     // Verify that this was correctly set up.
10624     FunctionDecl *F;
10625     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10626         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10627         F->getBuiltinID() && F->isImplicit())
10628       llvm_unreachable("performing ADL for builtin");
10629 
10630     // We don't perform ADL in C.
10631     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10632   }
10633 #endif
10634 
10635   UnbridgedCastsSet UnbridgedCasts;
10636   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10637     *Result = ExprError();
10638     return true;
10639   }
10640 
10641   // Add the functions denoted by the callee to the set of candidate
10642   // functions, including those from argument-dependent lookup.
10643   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10644 
10645   // If we found nothing, try to recover.
10646   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10647   // out if it fails.
10648   if (CandidateSet->empty()) {
10649     // In Microsoft mode, if we are inside a template class member function then
10650     // create a type dependent CallExpr. The goal is to postpone name lookup
10651     // to instantiation time to be able to search into type dependent base
10652     // classes.
10653     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10654         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10655       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10656                                             Context.DependentTy, VK_RValue,
10657                                             RParenLoc);
10658       CE->setTypeDependent(true);
10659       *Result = CE;
10660       return true;
10661     }
10662     return false;
10663   }
10664 
10665   UnbridgedCasts.restore();
10666   return false;
10667 }
10668 
10669 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10670 /// the completed call expression. If overload resolution fails, emits
10671 /// diagnostics and returns ExprError()
10672 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10673                                            UnresolvedLookupExpr *ULE,
10674                                            SourceLocation LParenLoc,
10675                                            MultiExprArg Args,
10676                                            SourceLocation RParenLoc,
10677                                            Expr *ExecConfig,
10678                                            OverloadCandidateSet *CandidateSet,
10679                                            OverloadCandidateSet::iterator *Best,
10680                                            OverloadingResult OverloadResult,
10681                                            bool AllowTypoCorrection) {
10682   if (CandidateSet->empty())
10683     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10684                                  RParenLoc, /*EmptyLookup=*/true,
10685                                  AllowTypoCorrection);
10686 
10687   switch (OverloadResult) {
10688   case OR_Success: {
10689     FunctionDecl *FDecl = (*Best)->Function;
10690     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10691     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10692       return ExprError();
10693     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10694     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10695                                          ExecConfig);
10696   }
10697 
10698   case OR_No_Viable_Function: {
10699     // Try to recover by looking for viable functions which the user might
10700     // have meant to call.
10701     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10702                                                 Args, RParenLoc,
10703                                                 /*EmptyLookup=*/false,
10704                                                 AllowTypoCorrection);
10705     if (!Recovery.isInvalid())
10706       return Recovery;
10707 
10708     SemaRef.Diag(Fn->getLocStart(),
10709          diag::err_ovl_no_viable_function_in_call)
10710       << ULE->getName() << Fn->getSourceRange();
10711     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10712     break;
10713   }
10714 
10715   case OR_Ambiguous:
10716     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10717       << ULE->getName() << Fn->getSourceRange();
10718     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10719     break;
10720 
10721   case OR_Deleted: {
10722     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10723       << (*Best)->Function->isDeleted()
10724       << ULE->getName()
10725       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10726       << Fn->getSourceRange();
10727     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10728 
10729     // We emitted an error for the unvailable/deleted function call but keep
10730     // the call in the AST.
10731     FunctionDecl *FDecl = (*Best)->Function;
10732     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10733     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10734                                          ExecConfig);
10735   }
10736   }
10737 
10738   // Overload resolution failed.
10739   return ExprError();
10740 }
10741 
10742 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10743 /// (which eventually refers to the declaration Func) and the call
10744 /// arguments Args/NumArgs, attempt to resolve the function call down
10745 /// to a specific function. If overload resolution succeeds, returns
10746 /// the call expression produced by overload resolution.
10747 /// Otherwise, emits diagnostics and returns ExprError.
10748 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10749                                          UnresolvedLookupExpr *ULE,
10750                                          SourceLocation LParenLoc,
10751                                          MultiExprArg Args,
10752                                          SourceLocation RParenLoc,
10753                                          Expr *ExecConfig,
10754                                          bool AllowTypoCorrection) {
10755   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10756                                     OverloadCandidateSet::CSK_Normal);
10757   ExprResult result;
10758 
10759   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10760                              &result))
10761     return result;
10762 
10763   OverloadCandidateSet::iterator Best;
10764   OverloadingResult OverloadResult =
10765       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10766 
10767   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10768                                   RParenLoc, ExecConfig, &CandidateSet,
10769                                   &Best, OverloadResult,
10770                                   AllowTypoCorrection);
10771 }
10772 
10773 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10774   return Functions.size() > 1 ||
10775     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10776 }
10777 
10778 /// \brief Create a unary operation that may resolve to an overloaded
10779 /// operator.
10780 ///
10781 /// \param OpLoc The location of the operator itself (e.g., '*').
10782 ///
10783 /// \param OpcIn The UnaryOperator::Opcode that describes this
10784 /// operator.
10785 ///
10786 /// \param Fns The set of non-member functions that will be
10787 /// considered by overload resolution. The caller needs to build this
10788 /// set based on the context using, e.g.,
10789 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10790 /// set should not contain any member functions; those will be added
10791 /// by CreateOverloadedUnaryOp().
10792 ///
10793 /// \param Input The input argument.
10794 ExprResult
10795 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10796                               const UnresolvedSetImpl &Fns,
10797                               Expr *Input) {
10798   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10799 
10800   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10801   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10802   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10803   // TODO: provide better source location info.
10804   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10805 
10806   if (checkPlaceholderForOverload(*this, Input))
10807     return ExprError();
10808 
10809   Expr *Args[2] = { Input, nullptr };
10810   unsigned NumArgs = 1;
10811 
10812   // For post-increment and post-decrement, add the implicit '0' as
10813   // the second argument, so that we know this is a post-increment or
10814   // post-decrement.
10815   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10816     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10817     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10818                                      SourceLocation());
10819     NumArgs = 2;
10820   }
10821 
10822   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10823 
10824   if (Input->isTypeDependent()) {
10825     if (Fns.empty())
10826       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10827                                          VK_RValue, OK_Ordinary, OpLoc);
10828 
10829     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10830     UnresolvedLookupExpr *Fn
10831       = UnresolvedLookupExpr::Create(Context, NamingClass,
10832                                      NestedNameSpecifierLoc(), OpNameInfo,
10833                                      /*ADL*/ true, IsOverloaded(Fns),
10834                                      Fns.begin(), Fns.end());
10835     return new (Context)
10836         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10837                             VK_RValue, OpLoc, false);
10838   }
10839 
10840   // Build an empty overload set.
10841   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10842 
10843   // Add the candidates from the given function set.
10844   AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10845 
10846   // Add operator candidates that are member functions.
10847   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10848 
10849   // Add candidates from ADL.
10850   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10851                                        /*ExplicitTemplateArgs*/nullptr,
10852                                        CandidateSet);
10853 
10854   // Add builtin operator candidates.
10855   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10856 
10857   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10858 
10859   // Perform overload resolution.
10860   OverloadCandidateSet::iterator Best;
10861   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10862   case OR_Success: {
10863     // We found a built-in operator or an overloaded operator.
10864     FunctionDecl *FnDecl = Best->Function;
10865 
10866     if (FnDecl) {
10867       // We matched an overloaded operator. Build a call to that
10868       // operator.
10869 
10870       // Convert the arguments.
10871       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10872         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10873 
10874         ExprResult InputRes =
10875           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10876                                               Best->FoundDecl, Method);
10877         if (InputRes.isInvalid())
10878           return ExprError();
10879         Input = InputRes.get();
10880       } else {
10881         // Convert the arguments.
10882         ExprResult InputInit
10883           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10884                                                       Context,
10885                                                       FnDecl->getParamDecl(0)),
10886                                       SourceLocation(),
10887                                       Input);
10888         if (InputInit.isInvalid())
10889           return ExprError();
10890         Input = InputInit.get();
10891       }
10892 
10893       // Build the actual expression node.
10894       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10895                                                 HadMultipleCandidates, OpLoc);
10896       if (FnExpr.isInvalid())
10897         return ExprError();
10898 
10899       // Determine the result type.
10900       QualType ResultTy = FnDecl->getReturnType();
10901       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10902       ResultTy = ResultTy.getNonLValueExprType(Context);
10903 
10904       Args[0] = Input;
10905       CallExpr *TheCall =
10906         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
10907                                           ResultTy, VK, OpLoc, false);
10908 
10909       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
10910         return ExprError();
10911 
10912       return MaybeBindToTemporary(TheCall);
10913     } else {
10914       // We matched a built-in operator. Convert the arguments, then
10915       // break out so that we will build the appropriate built-in
10916       // operator node.
10917       ExprResult InputRes =
10918         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10919                                   Best->Conversions[0], AA_Passing);
10920       if (InputRes.isInvalid())
10921         return ExprError();
10922       Input = InputRes.get();
10923       break;
10924     }
10925   }
10926 
10927   case OR_No_Viable_Function:
10928     // This is an erroneous use of an operator which can be overloaded by
10929     // a non-member function. Check for non-member operators which were
10930     // defined too late to be candidates.
10931     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10932       // FIXME: Recover by calling the found function.
10933       return ExprError();
10934 
10935     // No viable function; fall through to handling this as a
10936     // built-in operator, which will produce an error message for us.
10937     break;
10938 
10939   case OR_Ambiguous:
10940     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10941         << UnaryOperator::getOpcodeStr(Opc)
10942         << Input->getType()
10943         << Input->getSourceRange();
10944     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10945                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10946     return ExprError();
10947 
10948   case OR_Deleted:
10949     Diag(OpLoc, diag::err_ovl_deleted_oper)
10950       << Best->Function->isDeleted()
10951       << UnaryOperator::getOpcodeStr(Opc)
10952       << getDeletedOrUnavailableSuffix(Best->Function)
10953       << Input->getSourceRange();
10954     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10955                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10956     return ExprError();
10957   }
10958 
10959   // Either we found no viable overloaded operator or we matched a
10960   // built-in operator. In either case, fall through to trying to
10961   // build a built-in operation.
10962   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10963 }
10964 
10965 /// \brief Create a binary operation that may resolve to an overloaded
10966 /// operator.
10967 ///
10968 /// \param OpLoc The location of the operator itself (e.g., '+').
10969 ///
10970 /// \param OpcIn The BinaryOperator::Opcode that describes this
10971 /// operator.
10972 ///
10973 /// \param Fns The set of non-member functions that will be
10974 /// considered by overload resolution. The caller needs to build this
10975 /// set based on the context using, e.g.,
10976 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10977 /// set should not contain any member functions; those will be added
10978 /// by CreateOverloadedBinOp().
10979 ///
10980 /// \param LHS Left-hand argument.
10981 /// \param RHS Right-hand argument.
10982 ExprResult
10983 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10984                             unsigned OpcIn,
10985                             const UnresolvedSetImpl &Fns,
10986                             Expr *LHS, Expr *RHS) {
10987   Expr *Args[2] = { LHS, RHS };
10988   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
10989 
10990   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10991   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10992   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10993 
10994   // If either side is type-dependent, create an appropriate dependent
10995   // expression.
10996   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10997     if (Fns.empty()) {
10998       // If there are no functions to store, just build a dependent
10999       // BinaryOperator or CompoundAssignment.
11000       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11001         return new (Context) BinaryOperator(
11002             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11003             OpLoc, FPFeatures.fp_contract);
11004 
11005       return new (Context) CompoundAssignOperator(
11006           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11007           Context.DependentTy, Context.DependentTy, OpLoc,
11008           FPFeatures.fp_contract);
11009     }
11010 
11011     // FIXME: save results of ADL from here?
11012     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11013     // TODO: provide better source location info in DNLoc component.
11014     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11015     UnresolvedLookupExpr *Fn
11016       = UnresolvedLookupExpr::Create(Context, NamingClass,
11017                                      NestedNameSpecifierLoc(), OpNameInfo,
11018                                      /*ADL*/ true, IsOverloaded(Fns),
11019                                      Fns.begin(), Fns.end());
11020     return new (Context)
11021         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11022                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11023   }
11024 
11025   // Always do placeholder-like conversions on the RHS.
11026   if (checkPlaceholderForOverload(*this, Args[1]))
11027     return ExprError();
11028 
11029   // Do placeholder-like conversion on the LHS; note that we should
11030   // not get here with a PseudoObject LHS.
11031   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11032   if (checkPlaceholderForOverload(*this, Args[0]))
11033     return ExprError();
11034 
11035   // If this is the assignment operator, we only perform overload resolution
11036   // if the left-hand side is a class or enumeration type. This is actually
11037   // a hack. The standard requires that we do overload resolution between the
11038   // various built-in candidates, but as DR507 points out, this can lead to
11039   // problems. So we do it this way, which pretty much follows what GCC does.
11040   // Note that we go the traditional code path for compound assignment forms.
11041   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11042     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11043 
11044   // If this is the .* operator, which is not overloadable, just
11045   // create a built-in binary operator.
11046   if (Opc == BO_PtrMemD)
11047     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11048 
11049   // Build an empty overload set.
11050   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11051 
11052   // Add the candidates from the given function set.
11053   AddFunctionCandidates(Fns, Args, CandidateSet, false);
11054 
11055   // Add operator candidates that are member functions.
11056   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11057 
11058   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11059   // performed for an assignment operator (nor for operator[] nor operator->,
11060   // which don't get here).
11061   if (Opc != BO_Assign)
11062     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11063                                          /*ExplicitTemplateArgs*/ nullptr,
11064                                          CandidateSet);
11065 
11066   // Add builtin operator candidates.
11067   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11068 
11069   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11070 
11071   // Perform overload resolution.
11072   OverloadCandidateSet::iterator Best;
11073   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11074     case OR_Success: {
11075       // We found a built-in operator or an overloaded operator.
11076       FunctionDecl *FnDecl = Best->Function;
11077 
11078       if (FnDecl) {
11079         // We matched an overloaded operator. Build a call to that
11080         // operator.
11081 
11082         // Convert the arguments.
11083         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11084           // Best->Access is only meaningful for class members.
11085           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11086 
11087           ExprResult Arg1 =
11088             PerformCopyInitialization(
11089               InitializedEntity::InitializeParameter(Context,
11090                                                      FnDecl->getParamDecl(0)),
11091               SourceLocation(), Args[1]);
11092           if (Arg1.isInvalid())
11093             return ExprError();
11094 
11095           ExprResult Arg0 =
11096             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11097                                                 Best->FoundDecl, Method);
11098           if (Arg0.isInvalid())
11099             return ExprError();
11100           Args[0] = Arg0.getAs<Expr>();
11101           Args[1] = RHS = Arg1.getAs<Expr>();
11102         } else {
11103           // Convert the arguments.
11104           ExprResult Arg0 = PerformCopyInitialization(
11105             InitializedEntity::InitializeParameter(Context,
11106                                                    FnDecl->getParamDecl(0)),
11107             SourceLocation(), Args[0]);
11108           if (Arg0.isInvalid())
11109             return ExprError();
11110 
11111           ExprResult Arg1 =
11112             PerformCopyInitialization(
11113               InitializedEntity::InitializeParameter(Context,
11114                                                      FnDecl->getParamDecl(1)),
11115               SourceLocation(), Args[1]);
11116           if (Arg1.isInvalid())
11117             return ExprError();
11118           Args[0] = LHS = Arg0.getAs<Expr>();
11119           Args[1] = RHS = Arg1.getAs<Expr>();
11120         }
11121 
11122         // Build the actual expression node.
11123         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11124                                                   Best->FoundDecl,
11125                                                   HadMultipleCandidates, OpLoc);
11126         if (FnExpr.isInvalid())
11127           return ExprError();
11128 
11129         // Determine the result type.
11130         QualType ResultTy = FnDecl->getReturnType();
11131         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11132         ResultTy = ResultTy.getNonLValueExprType(Context);
11133 
11134         CXXOperatorCallExpr *TheCall =
11135           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11136                                             Args, ResultTy, VK, OpLoc,
11137                                             FPFeatures.fp_contract);
11138 
11139         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11140                                 FnDecl))
11141           return ExprError();
11142 
11143         ArrayRef<const Expr *> ArgsArray(Args, 2);
11144         // Cut off the implicit 'this'.
11145         if (isa<CXXMethodDecl>(FnDecl))
11146           ArgsArray = ArgsArray.slice(1);
11147         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11148                   TheCall->getSourceRange(), VariadicDoesNotApply);
11149 
11150         return MaybeBindToTemporary(TheCall);
11151       } else {
11152         // We matched a built-in operator. Convert the arguments, then
11153         // break out so that we will build the appropriate built-in
11154         // operator node.
11155         ExprResult ArgsRes0 =
11156           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11157                                     Best->Conversions[0], AA_Passing);
11158         if (ArgsRes0.isInvalid())
11159           return ExprError();
11160         Args[0] = ArgsRes0.get();
11161 
11162         ExprResult ArgsRes1 =
11163           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11164                                     Best->Conversions[1], AA_Passing);
11165         if (ArgsRes1.isInvalid())
11166           return ExprError();
11167         Args[1] = ArgsRes1.get();
11168         break;
11169       }
11170     }
11171 
11172     case OR_No_Viable_Function: {
11173       // C++ [over.match.oper]p9:
11174       //   If the operator is the operator , [...] and there are no
11175       //   viable functions, then the operator is assumed to be the
11176       //   built-in operator and interpreted according to clause 5.
11177       if (Opc == BO_Comma)
11178         break;
11179 
11180       // For class as left operand for assignment or compound assigment
11181       // operator do not fall through to handling in built-in, but report that
11182       // no overloaded assignment operator found
11183       ExprResult Result = ExprError();
11184       if (Args[0]->getType()->isRecordType() &&
11185           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11186         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11187              << BinaryOperator::getOpcodeStr(Opc)
11188              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11189         if (Args[0]->getType()->isIncompleteType()) {
11190           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11191             << Args[0]->getType()
11192             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11193         }
11194       } else {
11195         // This is an erroneous use of an operator which can be overloaded by
11196         // a non-member function. Check for non-member operators which were
11197         // defined too late to be candidates.
11198         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11199           // FIXME: Recover by calling the found function.
11200           return ExprError();
11201 
11202         // No viable function; try to create a built-in operation, which will
11203         // produce an error. Then, show the non-viable candidates.
11204         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11205       }
11206       assert(Result.isInvalid() &&
11207              "C++ binary operator overloading is missing candidates!");
11208       if (Result.isInvalid())
11209         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11210                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11211       return Result;
11212     }
11213 
11214     case OR_Ambiguous:
11215       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11216           << BinaryOperator::getOpcodeStr(Opc)
11217           << Args[0]->getType() << Args[1]->getType()
11218           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11219       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11220                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11221       return ExprError();
11222 
11223     case OR_Deleted:
11224       if (isImplicitlyDeleted(Best->Function)) {
11225         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11226         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11227           << Context.getRecordType(Method->getParent())
11228           << getSpecialMember(Method);
11229 
11230         // The user probably meant to call this special member. Just
11231         // explain why it's deleted.
11232         NoteDeletedFunction(Method);
11233         return ExprError();
11234       } else {
11235         Diag(OpLoc, diag::err_ovl_deleted_oper)
11236           << Best->Function->isDeleted()
11237           << BinaryOperator::getOpcodeStr(Opc)
11238           << getDeletedOrUnavailableSuffix(Best->Function)
11239           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11240       }
11241       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11242                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11243       return ExprError();
11244   }
11245 
11246   // We matched a built-in operator; build it.
11247   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11248 }
11249 
11250 ExprResult
11251 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11252                                          SourceLocation RLoc,
11253                                          Expr *Base, Expr *Idx) {
11254   Expr *Args[2] = { Base, Idx };
11255   DeclarationName OpName =
11256       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11257 
11258   // If either side is type-dependent, create an appropriate dependent
11259   // expression.
11260   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11261 
11262     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11263     // CHECKME: no 'operator' keyword?
11264     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11265     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11266     UnresolvedLookupExpr *Fn
11267       = UnresolvedLookupExpr::Create(Context, NamingClass,
11268                                      NestedNameSpecifierLoc(), OpNameInfo,
11269                                      /*ADL*/ true, /*Overloaded*/ false,
11270                                      UnresolvedSetIterator(),
11271                                      UnresolvedSetIterator());
11272     // Can't add any actual overloads yet
11273 
11274     return new (Context)
11275         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11276                             Context.DependentTy, VK_RValue, RLoc, false);
11277   }
11278 
11279   // Handle placeholders on both operands.
11280   if (checkPlaceholderForOverload(*this, Args[0]))
11281     return ExprError();
11282   if (checkPlaceholderForOverload(*this, Args[1]))
11283     return ExprError();
11284 
11285   // Build an empty overload set.
11286   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11287 
11288   // Subscript can only be overloaded as a member function.
11289 
11290   // Add operator candidates that are member functions.
11291   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11292 
11293   // Add builtin operator candidates.
11294   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11295 
11296   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11297 
11298   // Perform overload resolution.
11299   OverloadCandidateSet::iterator Best;
11300   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11301     case OR_Success: {
11302       // We found a built-in operator or an overloaded operator.
11303       FunctionDecl *FnDecl = Best->Function;
11304 
11305       if (FnDecl) {
11306         // We matched an overloaded operator. Build a call to that
11307         // operator.
11308 
11309         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11310 
11311         // Convert the arguments.
11312         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11313         ExprResult Arg0 =
11314           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11315                                               Best->FoundDecl, Method);
11316         if (Arg0.isInvalid())
11317           return ExprError();
11318         Args[0] = Arg0.get();
11319 
11320         // Convert the arguments.
11321         ExprResult InputInit
11322           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11323                                                       Context,
11324                                                       FnDecl->getParamDecl(0)),
11325                                       SourceLocation(),
11326                                       Args[1]);
11327         if (InputInit.isInvalid())
11328           return ExprError();
11329 
11330         Args[1] = InputInit.getAs<Expr>();
11331 
11332         // Build the actual expression node.
11333         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11334         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11335         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11336                                                   Best->FoundDecl,
11337                                                   HadMultipleCandidates,
11338                                                   OpLocInfo.getLoc(),
11339                                                   OpLocInfo.getInfo());
11340         if (FnExpr.isInvalid())
11341           return ExprError();
11342 
11343         // Determine the result type
11344         QualType ResultTy = FnDecl->getReturnType();
11345         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11346         ResultTy = ResultTy.getNonLValueExprType(Context);
11347 
11348         CXXOperatorCallExpr *TheCall =
11349           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11350                                             FnExpr.get(), Args,
11351                                             ResultTy, VK, RLoc,
11352                                             false);
11353 
11354         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11355           return ExprError();
11356 
11357         return MaybeBindToTemporary(TheCall);
11358       } else {
11359         // We matched a built-in operator. Convert the arguments, then
11360         // break out so that we will build the appropriate built-in
11361         // operator node.
11362         ExprResult ArgsRes0 =
11363           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11364                                     Best->Conversions[0], AA_Passing);
11365         if (ArgsRes0.isInvalid())
11366           return ExprError();
11367         Args[0] = ArgsRes0.get();
11368 
11369         ExprResult ArgsRes1 =
11370           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11371                                     Best->Conversions[1], AA_Passing);
11372         if (ArgsRes1.isInvalid())
11373           return ExprError();
11374         Args[1] = ArgsRes1.get();
11375 
11376         break;
11377       }
11378     }
11379 
11380     case OR_No_Viable_Function: {
11381       if (CandidateSet.empty())
11382         Diag(LLoc, diag::err_ovl_no_oper)
11383           << Args[0]->getType() << /*subscript*/ 0
11384           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11385       else
11386         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11387           << Args[0]->getType()
11388           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11389       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11390                                   "[]", LLoc);
11391       return ExprError();
11392     }
11393 
11394     case OR_Ambiguous:
11395       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11396           << "[]"
11397           << Args[0]->getType() << Args[1]->getType()
11398           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11399       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11400                                   "[]", LLoc);
11401       return ExprError();
11402 
11403     case OR_Deleted:
11404       Diag(LLoc, diag::err_ovl_deleted_oper)
11405         << Best->Function->isDeleted() << "[]"
11406         << getDeletedOrUnavailableSuffix(Best->Function)
11407         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11408       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11409                                   "[]", LLoc);
11410       return ExprError();
11411     }
11412 
11413   // We matched a built-in operator; build it.
11414   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11415 }
11416 
11417 /// BuildCallToMemberFunction - Build a call to a member
11418 /// function. MemExpr is the expression that refers to the member
11419 /// function (and includes the object parameter), Args/NumArgs are the
11420 /// arguments to the function call (not including the object
11421 /// parameter). The caller needs to validate that the member
11422 /// expression refers to a non-static member function or an overloaded
11423 /// member function.
11424 ExprResult
11425 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11426                                 SourceLocation LParenLoc,
11427                                 MultiExprArg Args,
11428                                 SourceLocation RParenLoc) {
11429   assert(MemExprE->getType() == Context.BoundMemberTy ||
11430          MemExprE->getType() == Context.OverloadTy);
11431 
11432   // Dig out the member expression. This holds both the object
11433   // argument and the member function we're referring to.
11434   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11435 
11436   // Determine whether this is a call to a pointer-to-member function.
11437   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11438     assert(op->getType() == Context.BoundMemberTy);
11439     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11440 
11441     QualType fnType =
11442       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11443 
11444     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11445     QualType resultType = proto->getCallResultType(Context);
11446     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11447 
11448     // Check that the object type isn't more qualified than the
11449     // member function we're calling.
11450     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11451 
11452     QualType objectType = op->getLHS()->getType();
11453     if (op->getOpcode() == BO_PtrMemI)
11454       objectType = objectType->castAs<PointerType>()->getPointeeType();
11455     Qualifiers objectQuals = objectType.getQualifiers();
11456 
11457     Qualifiers difference = objectQuals - funcQuals;
11458     difference.removeObjCGCAttr();
11459     difference.removeAddressSpace();
11460     if (difference) {
11461       std::string qualsString = difference.getAsString();
11462       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11463         << fnType.getUnqualifiedType()
11464         << qualsString
11465         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11466     }
11467 
11468     if (resultType->isMemberPointerType())
11469       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11470         RequireCompleteType(LParenLoc, resultType, 0);
11471 
11472     CXXMemberCallExpr *call
11473       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11474                                         resultType, valueKind, RParenLoc);
11475 
11476     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11477                             call, nullptr))
11478       return ExprError();
11479 
11480     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11481       return ExprError();
11482 
11483     if (CheckOtherCall(call, proto))
11484       return ExprError();
11485 
11486     return MaybeBindToTemporary(call);
11487   }
11488 
11489   UnbridgedCastsSet UnbridgedCasts;
11490   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11491     return ExprError();
11492 
11493   MemberExpr *MemExpr;
11494   CXXMethodDecl *Method = nullptr;
11495   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11496   NestedNameSpecifier *Qualifier = nullptr;
11497   if (isa<MemberExpr>(NakedMemExpr)) {
11498     MemExpr = cast<MemberExpr>(NakedMemExpr);
11499     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11500     FoundDecl = MemExpr->getFoundDecl();
11501     Qualifier = MemExpr->getQualifier();
11502     UnbridgedCasts.restore();
11503   } else {
11504     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11505     Qualifier = UnresExpr->getQualifier();
11506 
11507     QualType ObjectType = UnresExpr->getBaseType();
11508     Expr::Classification ObjectClassification
11509       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11510                             : UnresExpr->getBase()->Classify(Context);
11511 
11512     // Add overload candidates
11513     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11514                                       OverloadCandidateSet::CSK_Normal);
11515 
11516     // FIXME: avoid copy.
11517     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11518     if (UnresExpr->hasExplicitTemplateArgs()) {
11519       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11520       TemplateArgs = &TemplateArgsBuffer;
11521     }
11522 
11523     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11524            E = UnresExpr->decls_end(); I != E; ++I) {
11525 
11526       NamedDecl *Func = *I;
11527       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11528       if (isa<UsingShadowDecl>(Func))
11529         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11530 
11531 
11532       // Microsoft supports direct constructor calls.
11533       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11534         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11535                              Args, CandidateSet);
11536       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11537         // If explicit template arguments were provided, we can't call a
11538         // non-template member function.
11539         if (TemplateArgs)
11540           continue;
11541 
11542         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11543                            ObjectClassification, Args, CandidateSet,
11544                            /*SuppressUserConversions=*/false);
11545       } else {
11546         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11547                                    I.getPair(), ActingDC, TemplateArgs,
11548                                    ObjectType,  ObjectClassification,
11549                                    Args, CandidateSet,
11550                                    /*SuppressUsedConversions=*/false);
11551       }
11552     }
11553 
11554     DeclarationName DeclName = UnresExpr->getMemberName();
11555 
11556     UnbridgedCasts.restore();
11557 
11558     OverloadCandidateSet::iterator Best;
11559     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11560                                             Best)) {
11561     case OR_Success:
11562       Method = cast<CXXMethodDecl>(Best->Function);
11563       FoundDecl = Best->FoundDecl;
11564       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11565       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11566         return ExprError();
11567       // If FoundDecl is different from Method (such as if one is a template
11568       // and the other a specialization), make sure DiagnoseUseOfDecl is
11569       // called on both.
11570       // FIXME: This would be more comprehensively addressed by modifying
11571       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11572       // being used.
11573       if (Method != FoundDecl.getDecl() &&
11574                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11575         return ExprError();
11576       break;
11577 
11578     case OR_No_Viable_Function:
11579       Diag(UnresExpr->getMemberLoc(),
11580            diag::err_ovl_no_viable_member_function_in_call)
11581         << DeclName << MemExprE->getSourceRange();
11582       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11583       // FIXME: Leaking incoming expressions!
11584       return ExprError();
11585 
11586     case OR_Ambiguous:
11587       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11588         << DeclName << MemExprE->getSourceRange();
11589       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11590       // FIXME: Leaking incoming expressions!
11591       return ExprError();
11592 
11593     case OR_Deleted:
11594       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11595         << Best->Function->isDeleted()
11596         << DeclName
11597         << getDeletedOrUnavailableSuffix(Best->Function)
11598         << MemExprE->getSourceRange();
11599       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11600       // FIXME: Leaking incoming expressions!
11601       return ExprError();
11602     }
11603 
11604     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11605 
11606     // If overload resolution picked a static member, build a
11607     // non-member call based on that function.
11608     if (Method->isStatic()) {
11609       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11610                                    RParenLoc);
11611     }
11612 
11613     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11614   }
11615 
11616   QualType ResultType = Method->getReturnType();
11617   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11618   ResultType = ResultType.getNonLValueExprType(Context);
11619 
11620   assert(Method && "Member call to something that isn't a method?");
11621   CXXMemberCallExpr *TheCall =
11622     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11623                                     ResultType, VK, RParenLoc);
11624 
11625   // (CUDA B.1): Check for invalid calls between targets.
11626   if (getLangOpts().CUDA) {
11627     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11628       if (CheckCUDATarget(Caller, Method)) {
11629         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11630             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11631             << IdentifyCUDATarget(Caller);
11632         return ExprError();
11633       }
11634     }
11635   }
11636 
11637   // Check for a valid return type.
11638   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11639                           TheCall, Method))
11640     return ExprError();
11641 
11642   // Convert the object argument (for a non-static member function call).
11643   // We only need to do this if there was actually an overload; otherwise
11644   // it was done at lookup.
11645   if (!Method->isStatic()) {
11646     ExprResult ObjectArg =
11647       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11648                                           FoundDecl, Method);
11649     if (ObjectArg.isInvalid())
11650       return ExprError();
11651     MemExpr->setBase(ObjectArg.get());
11652   }
11653 
11654   // Convert the rest of the arguments
11655   const FunctionProtoType *Proto =
11656     Method->getType()->getAs<FunctionProtoType>();
11657   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11658                               RParenLoc))
11659     return ExprError();
11660 
11661   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11662 
11663   if (CheckFunctionCall(Method, TheCall, Proto))
11664     return ExprError();
11665 
11666   if ((isa<CXXConstructorDecl>(CurContext) ||
11667        isa<CXXDestructorDecl>(CurContext)) &&
11668       TheCall->getMethodDecl()->isPure()) {
11669     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11670 
11671     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11672       Diag(MemExpr->getLocStart(),
11673            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11674         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11675         << MD->getParent()->getDeclName();
11676 
11677       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11678     }
11679   }
11680   return MaybeBindToTemporary(TheCall);
11681 }
11682 
11683 /// BuildCallToObjectOfClassType - Build a call to an object of class
11684 /// type (C++ [over.call.object]), which can end up invoking an
11685 /// overloaded function call operator (@c operator()) or performing a
11686 /// user-defined conversion on the object argument.
11687 ExprResult
11688 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11689                                    SourceLocation LParenLoc,
11690                                    MultiExprArg Args,
11691                                    SourceLocation RParenLoc) {
11692   if (checkPlaceholderForOverload(*this, Obj))
11693     return ExprError();
11694   ExprResult Object = Obj;
11695 
11696   UnbridgedCastsSet UnbridgedCasts;
11697   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11698     return ExprError();
11699 
11700   assert(Object.get()->getType()->isRecordType() &&
11701          "Requires object type argument");
11702   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11703 
11704   // C++ [over.call.object]p1:
11705   //  If the primary-expression E in the function call syntax
11706   //  evaluates to a class object of type "cv T", then the set of
11707   //  candidate functions includes at least the function call
11708   //  operators of T. The function call operators of T are obtained by
11709   //  ordinary lookup of the name operator() in the context of
11710   //  (E).operator().
11711   OverloadCandidateSet CandidateSet(LParenLoc,
11712                                     OverloadCandidateSet::CSK_Operator);
11713   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11714 
11715   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11716                           diag::err_incomplete_object_call, Object.get()))
11717     return true;
11718 
11719   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11720   LookupQualifiedName(R, Record->getDecl());
11721   R.suppressDiagnostics();
11722 
11723   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11724        Oper != OperEnd; ++Oper) {
11725     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11726                        Object.get()->Classify(Context),
11727                        Args, CandidateSet,
11728                        /*SuppressUserConversions=*/ false);
11729   }
11730 
11731   // C++ [over.call.object]p2:
11732   //   In addition, for each (non-explicit in C++0x) conversion function
11733   //   declared in T of the form
11734   //
11735   //        operator conversion-type-id () cv-qualifier;
11736   //
11737   //   where cv-qualifier is the same cv-qualification as, or a
11738   //   greater cv-qualification than, cv, and where conversion-type-id
11739   //   denotes the type "pointer to function of (P1,...,Pn) returning
11740   //   R", or the type "reference to pointer to function of
11741   //   (P1,...,Pn) returning R", or the type "reference to function
11742   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11743   //   is also considered as a candidate function. Similarly,
11744   //   surrogate call functions are added to the set of candidate
11745   //   functions for each conversion function declared in an
11746   //   accessible base class provided the function is not hidden
11747   //   within T by another intervening declaration.
11748   std::pair<CXXRecordDecl::conversion_iterator,
11749             CXXRecordDecl::conversion_iterator> Conversions
11750     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11751   for (CXXRecordDecl::conversion_iterator
11752          I = Conversions.first, E = Conversions.second; I != E; ++I) {
11753     NamedDecl *D = *I;
11754     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11755     if (isa<UsingShadowDecl>(D))
11756       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11757 
11758     // Skip over templated conversion functions; they aren't
11759     // surrogates.
11760     if (isa<FunctionTemplateDecl>(D))
11761       continue;
11762 
11763     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11764     if (!Conv->isExplicit()) {
11765       // Strip the reference type (if any) and then the pointer type (if
11766       // any) to get down to what might be a function type.
11767       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11768       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11769         ConvType = ConvPtrType->getPointeeType();
11770 
11771       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11772       {
11773         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11774                               Object.get(), Args, CandidateSet);
11775       }
11776     }
11777   }
11778 
11779   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11780 
11781   // Perform overload resolution.
11782   OverloadCandidateSet::iterator Best;
11783   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11784                              Best)) {
11785   case OR_Success:
11786     // Overload resolution succeeded; we'll build the appropriate call
11787     // below.
11788     break;
11789 
11790   case OR_No_Viable_Function:
11791     if (CandidateSet.empty())
11792       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11793         << Object.get()->getType() << /*call*/ 1
11794         << Object.get()->getSourceRange();
11795     else
11796       Diag(Object.get()->getLocStart(),
11797            diag::err_ovl_no_viable_object_call)
11798         << Object.get()->getType() << Object.get()->getSourceRange();
11799     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11800     break;
11801 
11802   case OR_Ambiguous:
11803     Diag(Object.get()->getLocStart(),
11804          diag::err_ovl_ambiguous_object_call)
11805       << Object.get()->getType() << Object.get()->getSourceRange();
11806     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11807     break;
11808 
11809   case OR_Deleted:
11810     Diag(Object.get()->getLocStart(),
11811          diag::err_ovl_deleted_object_call)
11812       << Best->Function->isDeleted()
11813       << Object.get()->getType()
11814       << getDeletedOrUnavailableSuffix(Best->Function)
11815       << Object.get()->getSourceRange();
11816     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11817     break;
11818   }
11819 
11820   if (Best == CandidateSet.end())
11821     return true;
11822 
11823   UnbridgedCasts.restore();
11824 
11825   if (Best->Function == nullptr) {
11826     // Since there is no function declaration, this is one of the
11827     // surrogate candidates. Dig out the conversion function.
11828     CXXConversionDecl *Conv
11829       = cast<CXXConversionDecl>(
11830                          Best->Conversions[0].UserDefined.ConversionFunction);
11831 
11832     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11833                               Best->FoundDecl);
11834     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11835       return ExprError();
11836     assert(Conv == Best->FoundDecl.getDecl() &&
11837              "Found Decl & conversion-to-functionptr should be same, right?!");
11838     // We selected one of the surrogate functions that converts the
11839     // object parameter to a function pointer. Perform the conversion
11840     // on the object argument, then let ActOnCallExpr finish the job.
11841 
11842     // Create an implicit member expr to refer to the conversion operator.
11843     // and then call it.
11844     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11845                                              Conv, HadMultipleCandidates);
11846     if (Call.isInvalid())
11847       return ExprError();
11848     // Record usage of conversion in an implicit cast.
11849     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11850                                     CK_UserDefinedConversion, Call.get(),
11851                                     nullptr, VK_RValue);
11852 
11853     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11854   }
11855 
11856   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11857 
11858   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11859   // that calls this method, using Object for the implicit object
11860   // parameter and passing along the remaining arguments.
11861   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11862 
11863   // An error diagnostic has already been printed when parsing the declaration.
11864   if (Method->isInvalidDecl())
11865     return ExprError();
11866 
11867   const FunctionProtoType *Proto =
11868     Method->getType()->getAs<FunctionProtoType>();
11869 
11870   unsigned NumParams = Proto->getNumParams();
11871 
11872   DeclarationNameInfo OpLocInfo(
11873                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11874   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11875   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11876                                            HadMultipleCandidates,
11877                                            OpLocInfo.getLoc(),
11878                                            OpLocInfo.getInfo());
11879   if (NewFn.isInvalid())
11880     return true;
11881 
11882   // Build the full argument list for the method call (the implicit object
11883   // parameter is placed at the beginning of the list).
11884   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11885   MethodArgs[0] = Object.get();
11886   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11887 
11888   // Once we've built TheCall, all of the expressions are properly
11889   // owned.
11890   QualType ResultTy = Method->getReturnType();
11891   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11892   ResultTy = ResultTy.getNonLValueExprType(Context);
11893 
11894   CXXOperatorCallExpr *TheCall = new (Context)
11895       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11896                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11897                           ResultTy, VK, RParenLoc, false);
11898   MethodArgs.reset();
11899 
11900   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
11901     return true;
11902 
11903   // We may have default arguments. If so, we need to allocate more
11904   // slots in the call for them.
11905   if (Args.size() < NumParams)
11906     TheCall->setNumArgs(Context, NumParams + 1);
11907 
11908   bool IsError = false;
11909 
11910   // Initialize the implicit object parameter.
11911   ExprResult ObjRes =
11912     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
11913                                         Best->FoundDecl, Method);
11914   if (ObjRes.isInvalid())
11915     IsError = true;
11916   else
11917     Object = ObjRes;
11918   TheCall->setArg(0, Object.get());
11919 
11920   // Check the argument types.
11921   for (unsigned i = 0; i != NumParams; i++) {
11922     Expr *Arg;
11923     if (i < Args.size()) {
11924       Arg = Args[i];
11925 
11926       // Pass the argument.
11927 
11928       ExprResult InputInit
11929         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11930                                                     Context,
11931                                                     Method->getParamDecl(i)),
11932                                     SourceLocation(), Arg);
11933 
11934       IsError |= InputInit.isInvalid();
11935       Arg = InputInit.getAs<Expr>();
11936     } else {
11937       ExprResult DefArg
11938         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11939       if (DefArg.isInvalid()) {
11940         IsError = true;
11941         break;
11942       }
11943 
11944       Arg = DefArg.getAs<Expr>();
11945     }
11946 
11947     TheCall->setArg(i + 1, Arg);
11948   }
11949 
11950   // If this is a variadic call, handle args passed through "...".
11951   if (Proto->isVariadic()) {
11952     // Promote the arguments (C99 6.5.2.2p7).
11953     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
11954       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11955                                                         nullptr);
11956       IsError |= Arg.isInvalid();
11957       TheCall->setArg(i + 1, Arg.get());
11958     }
11959   }
11960 
11961   if (IsError) return true;
11962 
11963   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11964 
11965   if (CheckFunctionCall(Method, TheCall, Proto))
11966     return true;
11967 
11968   return MaybeBindToTemporary(TheCall);
11969 }
11970 
11971 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11972 ///  (if one exists), where @c Base is an expression of class type and
11973 /// @c Member is the name of the member we're trying to find.
11974 ExprResult
11975 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11976                                bool *NoArrowOperatorFound) {
11977   assert(Base->getType()->isRecordType() &&
11978          "left-hand side must have class type");
11979 
11980   if (checkPlaceholderForOverload(*this, Base))
11981     return ExprError();
11982 
11983   SourceLocation Loc = Base->getExprLoc();
11984 
11985   // C++ [over.ref]p1:
11986   //
11987   //   [...] An expression x->m is interpreted as (x.operator->())->m
11988   //   for a class object x of type T if T::operator->() exists and if
11989   //   the operator is selected as the best match function by the
11990   //   overload resolution mechanism (13.3).
11991   DeclarationName OpName =
11992     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11993   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
11994   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11995 
11996   if (RequireCompleteType(Loc, Base->getType(),
11997                           diag::err_typecheck_incomplete_tag, Base))
11998     return ExprError();
11999 
12000   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12001   LookupQualifiedName(R, BaseRecord->getDecl());
12002   R.suppressDiagnostics();
12003 
12004   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12005        Oper != OperEnd; ++Oper) {
12006     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12007                        None, CandidateSet, /*SuppressUserConversions=*/false);
12008   }
12009 
12010   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12011 
12012   // Perform overload resolution.
12013   OverloadCandidateSet::iterator Best;
12014   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12015   case OR_Success:
12016     // Overload resolution succeeded; we'll build the call below.
12017     break;
12018 
12019   case OR_No_Viable_Function:
12020     if (CandidateSet.empty()) {
12021       QualType BaseType = Base->getType();
12022       if (NoArrowOperatorFound) {
12023         // Report this specific error to the caller instead of emitting a
12024         // diagnostic, as requested.
12025         *NoArrowOperatorFound = true;
12026         return ExprError();
12027       }
12028       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12029         << BaseType << Base->getSourceRange();
12030       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12031         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12032           << FixItHint::CreateReplacement(OpLoc, ".");
12033       }
12034     } else
12035       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12036         << "operator->" << Base->getSourceRange();
12037     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12038     return ExprError();
12039 
12040   case OR_Ambiguous:
12041     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12042       << "->" << Base->getType() << Base->getSourceRange();
12043     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12044     return ExprError();
12045 
12046   case OR_Deleted:
12047     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12048       << Best->Function->isDeleted()
12049       << "->"
12050       << getDeletedOrUnavailableSuffix(Best->Function)
12051       << Base->getSourceRange();
12052     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12053     return ExprError();
12054   }
12055 
12056   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12057 
12058   // Convert the object parameter.
12059   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12060   ExprResult BaseResult =
12061     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12062                                         Best->FoundDecl, Method);
12063   if (BaseResult.isInvalid())
12064     return ExprError();
12065   Base = BaseResult.get();
12066 
12067   // Build the operator call.
12068   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12069                                             HadMultipleCandidates, OpLoc);
12070   if (FnExpr.isInvalid())
12071     return ExprError();
12072 
12073   QualType ResultTy = Method->getReturnType();
12074   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12075   ResultTy = ResultTy.getNonLValueExprType(Context);
12076   CXXOperatorCallExpr *TheCall =
12077     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12078                                       Base, ResultTy, VK, OpLoc, false);
12079 
12080   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12081           return ExprError();
12082 
12083   return MaybeBindToTemporary(TheCall);
12084 }
12085 
12086 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12087 /// a literal operator described by the provided lookup results.
12088 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12089                                           DeclarationNameInfo &SuffixInfo,
12090                                           ArrayRef<Expr*> Args,
12091                                           SourceLocation LitEndLoc,
12092                                        TemplateArgumentListInfo *TemplateArgs) {
12093   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12094 
12095   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12096                                     OverloadCandidateSet::CSK_Normal);
12097   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
12098                         TemplateArgs);
12099 
12100   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12101 
12102   // Perform overload resolution. This will usually be trivial, but might need
12103   // to perform substitutions for a literal operator template.
12104   OverloadCandidateSet::iterator Best;
12105   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12106   case OR_Success:
12107   case OR_Deleted:
12108     break;
12109 
12110   case OR_No_Viable_Function:
12111     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12112       << R.getLookupName();
12113     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12114     return ExprError();
12115 
12116   case OR_Ambiguous:
12117     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12118     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12119     return ExprError();
12120   }
12121 
12122   FunctionDecl *FD = Best->Function;
12123   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12124                                         HadMultipleCandidates,
12125                                         SuffixInfo.getLoc(),
12126                                         SuffixInfo.getInfo());
12127   if (Fn.isInvalid())
12128     return true;
12129 
12130   // Check the argument types. This should almost always be a no-op, except
12131   // that array-to-pointer decay is applied to string literals.
12132   Expr *ConvArgs[2];
12133   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12134     ExprResult InputInit = PerformCopyInitialization(
12135       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12136       SourceLocation(), Args[ArgIdx]);
12137     if (InputInit.isInvalid())
12138       return true;
12139     ConvArgs[ArgIdx] = InputInit.get();
12140   }
12141 
12142   QualType ResultTy = FD->getReturnType();
12143   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12144   ResultTy = ResultTy.getNonLValueExprType(Context);
12145 
12146   UserDefinedLiteral *UDL =
12147     new (Context) UserDefinedLiteral(Context, Fn.get(),
12148                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12149                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12150 
12151   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12152     return ExprError();
12153 
12154   if (CheckFunctionCall(FD, UDL, nullptr))
12155     return ExprError();
12156 
12157   return MaybeBindToTemporary(UDL);
12158 }
12159 
12160 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12161 /// given LookupResult is non-empty, it is assumed to describe a member which
12162 /// will be invoked. Otherwise, the function will be found via argument
12163 /// dependent lookup.
12164 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12165 /// otherwise CallExpr is set to ExprError() and some non-success value
12166 /// is returned.
12167 Sema::ForRangeStatus
12168 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12169                                 SourceLocation RangeLoc, VarDecl *Decl,
12170                                 BeginEndFunction BEF,
12171                                 const DeclarationNameInfo &NameInfo,
12172                                 LookupResult &MemberLookup,
12173                                 OverloadCandidateSet *CandidateSet,
12174                                 Expr *Range, ExprResult *CallExpr) {
12175   CandidateSet->clear();
12176   if (!MemberLookup.empty()) {
12177     ExprResult MemberRef =
12178         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12179                                  /*IsPtr=*/false, CXXScopeSpec(),
12180                                  /*TemplateKWLoc=*/SourceLocation(),
12181                                  /*FirstQualifierInScope=*/nullptr,
12182                                  MemberLookup,
12183                                  /*TemplateArgs=*/nullptr);
12184     if (MemberRef.isInvalid()) {
12185       *CallExpr = ExprError();
12186       Diag(Range->getLocStart(), diag::note_in_for_range)
12187           << RangeLoc << BEF << Range->getType();
12188       return FRS_DiagnosticIssued;
12189     }
12190     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12191     if (CallExpr->isInvalid()) {
12192       *CallExpr = ExprError();
12193       Diag(Range->getLocStart(), diag::note_in_for_range)
12194           << RangeLoc << BEF << Range->getType();
12195       return FRS_DiagnosticIssued;
12196     }
12197   } else {
12198     UnresolvedSet<0> FoundNames;
12199     UnresolvedLookupExpr *Fn =
12200       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12201                                    NestedNameSpecifierLoc(), NameInfo,
12202                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12203                                    FoundNames.begin(), FoundNames.end());
12204 
12205     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12206                                                     CandidateSet, CallExpr);
12207     if (CandidateSet->empty() || CandidateSetError) {
12208       *CallExpr = ExprError();
12209       return FRS_NoViableFunction;
12210     }
12211     OverloadCandidateSet::iterator Best;
12212     OverloadingResult OverloadResult =
12213         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12214 
12215     if (OverloadResult == OR_No_Viable_Function) {
12216       *CallExpr = ExprError();
12217       return FRS_NoViableFunction;
12218     }
12219     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12220                                          Loc, nullptr, CandidateSet, &Best,
12221                                          OverloadResult,
12222                                          /*AllowTypoCorrection=*/false);
12223     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12224       *CallExpr = ExprError();
12225       Diag(Range->getLocStart(), diag::note_in_for_range)
12226           << RangeLoc << BEF << Range->getType();
12227       return FRS_DiagnosticIssued;
12228     }
12229   }
12230   return FRS_Success;
12231 }
12232 
12233 
12234 /// FixOverloadedFunctionReference - E is an expression that refers to
12235 /// a C++ overloaded function (possibly with some parentheses and
12236 /// perhaps a '&' around it). We have resolved the overloaded function
12237 /// to the function declaration Fn, so patch up the expression E to
12238 /// refer (possibly indirectly) to Fn. Returns the new expr.
12239 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12240                                            FunctionDecl *Fn) {
12241   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12242     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12243                                                    Found, Fn);
12244     if (SubExpr == PE->getSubExpr())
12245       return PE;
12246 
12247     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12248   }
12249 
12250   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12251     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12252                                                    Found, Fn);
12253     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12254                                SubExpr->getType()) &&
12255            "Implicit cast type cannot be determined from overload");
12256     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12257     if (SubExpr == ICE->getSubExpr())
12258       return ICE;
12259 
12260     return ImplicitCastExpr::Create(Context, ICE->getType(),
12261                                     ICE->getCastKind(),
12262                                     SubExpr, nullptr,
12263                                     ICE->getValueKind());
12264   }
12265 
12266   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12267     assert(UnOp->getOpcode() == UO_AddrOf &&
12268            "Can only take the address of an overloaded function");
12269     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12270       if (Method->isStatic()) {
12271         // Do nothing: static member functions aren't any different
12272         // from non-member functions.
12273       } else {
12274         // Fix the subexpression, which really has to be an
12275         // UnresolvedLookupExpr holding an overloaded member function
12276         // or template.
12277         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12278                                                        Found, Fn);
12279         if (SubExpr == UnOp->getSubExpr())
12280           return UnOp;
12281 
12282         assert(isa<DeclRefExpr>(SubExpr)
12283                && "fixed to something other than a decl ref");
12284         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12285                && "fixed to a member ref with no nested name qualifier");
12286 
12287         // We have taken the address of a pointer to member
12288         // function. Perform the computation here so that we get the
12289         // appropriate pointer to member type.
12290         QualType ClassType
12291           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12292         QualType MemPtrType
12293           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12294 
12295         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12296                                            VK_RValue, OK_Ordinary,
12297                                            UnOp->getOperatorLoc());
12298       }
12299     }
12300     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12301                                                    Found, Fn);
12302     if (SubExpr == UnOp->getSubExpr())
12303       return UnOp;
12304 
12305     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12306                                      Context.getPointerType(SubExpr->getType()),
12307                                        VK_RValue, OK_Ordinary,
12308                                        UnOp->getOperatorLoc());
12309   }
12310 
12311   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12312     // FIXME: avoid copy.
12313     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12314     if (ULE->hasExplicitTemplateArgs()) {
12315       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12316       TemplateArgs = &TemplateArgsBuffer;
12317     }
12318 
12319     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12320                                            ULE->getQualifierLoc(),
12321                                            ULE->getTemplateKeywordLoc(),
12322                                            Fn,
12323                                            /*enclosing*/ false, // FIXME?
12324                                            ULE->getNameLoc(),
12325                                            Fn->getType(),
12326                                            VK_LValue,
12327                                            Found.getDecl(),
12328                                            TemplateArgs);
12329     MarkDeclRefReferenced(DRE);
12330     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12331     return DRE;
12332   }
12333 
12334   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12335     // FIXME: avoid copy.
12336     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12337     if (MemExpr->hasExplicitTemplateArgs()) {
12338       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12339       TemplateArgs = &TemplateArgsBuffer;
12340     }
12341 
12342     Expr *Base;
12343 
12344     // If we're filling in a static method where we used to have an
12345     // implicit member access, rewrite to a simple decl ref.
12346     if (MemExpr->isImplicitAccess()) {
12347       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12348         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12349                                                MemExpr->getQualifierLoc(),
12350                                                MemExpr->getTemplateKeywordLoc(),
12351                                                Fn,
12352                                                /*enclosing*/ false,
12353                                                MemExpr->getMemberLoc(),
12354                                                Fn->getType(),
12355                                                VK_LValue,
12356                                                Found.getDecl(),
12357                                                TemplateArgs);
12358         MarkDeclRefReferenced(DRE);
12359         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12360         return DRE;
12361       } else {
12362         SourceLocation Loc = MemExpr->getMemberLoc();
12363         if (MemExpr->getQualifier())
12364           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12365         CheckCXXThisCapture(Loc);
12366         Base = new (Context) CXXThisExpr(Loc,
12367                                          MemExpr->getBaseType(),
12368                                          /*isImplicit=*/true);
12369       }
12370     } else
12371       Base = MemExpr->getBase();
12372 
12373     ExprValueKind valueKind;
12374     QualType type;
12375     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12376       valueKind = VK_LValue;
12377       type = Fn->getType();
12378     } else {
12379       valueKind = VK_RValue;
12380       type = Context.BoundMemberTy;
12381     }
12382 
12383     MemberExpr *ME = MemberExpr::Create(Context, Base,
12384                                         MemExpr->isArrow(),
12385                                         MemExpr->getQualifierLoc(),
12386                                         MemExpr->getTemplateKeywordLoc(),
12387                                         Fn,
12388                                         Found,
12389                                         MemExpr->getMemberNameInfo(),
12390                                         TemplateArgs,
12391                                         type, valueKind, OK_Ordinary);
12392     ME->setHadMultipleCandidates(true);
12393     MarkMemberReferenced(ME);
12394     return ME;
12395   }
12396 
12397   llvm_unreachable("Invalid reference to overloaded function");
12398 }
12399 
12400 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12401                                                 DeclAccessPair Found,
12402                                                 FunctionDecl *Fn) {
12403   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12404 }
12405