1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 /// A convenience routine for creating a decayed reference to a function.
42 static ExprResult
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44                       bool HadMultipleCandidates,
45                       SourceLocation Loc = SourceLocation(),
46                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
48     return ExprError();
49   // If FoundDecl is different from Fn (such as if one is a template
50   // and the other a specialization), make sure DiagnoseUseOfDecl is
51   // called on both.
52   // FIXME: This would be more comprehensively addressed by modifying
53   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54   // being used.
55   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
56     return ExprError();
57   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58                                                  VK_LValue, Loc, LocInfo);
59   if (HadMultipleCandidates)
60     DRE->setHadMultipleCandidates(true);
61 
62   S.MarkDeclRefReferenced(DRE);
63 
64   ExprResult E = DRE;
65   E = S.DefaultFunctionArrayConversion(E.get());
66   if (E.isInvalid())
67     return ExprError();
68   return E;
69 }
70 
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72                                  bool InOverloadResolution,
73                                  StandardConversionSequence &SCS,
74                                  bool CStyle,
75                                  bool AllowObjCWritebackConversion);
76 
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78                                                  QualType &ToType,
79                                                  bool InOverloadResolution,
80                                                  StandardConversionSequence &SCS,
81                                                  bool CStyle);
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84                         UserDefinedConversionSequence& User,
85                         OverloadCandidateSet& Conversions,
86                         bool AllowExplicit,
87                         bool AllowObjCConversionOnExplicit);
88 
89 
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92                                    const StandardConversionSequence& SCS1,
93                                    const StandardConversionSequence& SCS2);
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97                                 const StandardConversionSequence& SCS1,
98                                 const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 /// GetConversionRank - Retrieve the implicit conversion rank
106 /// corresponding to the given implicit conversion kind.
107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
108   static const ImplicitConversionRank
109     Rank[(int)ICK_Num_Conversion_Kinds] = {
110     ICR_Exact_Match,
111     ICR_Exact_Match,
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Promotion,
117     ICR_Promotion,
118     ICR_Promotion,
119     ICR_Conversion,
120     ICR_Conversion,
121     ICR_Conversion,
122     ICR_Conversion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Complex_Real_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Writeback_Conversion
134   };
135   return Rank[(int)Kind];
136 }
137 
138 /// GetImplicitConversionName - Return the name of this kind of
139 /// implicit conversion.
140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
141   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
142     "No conversion",
143     "Lvalue-to-rvalue",
144     "Array-to-pointer",
145     "Function-to-pointer",
146     "Noreturn adjustment",
147     "Qualification",
148     "Integral promotion",
149     "Floating point promotion",
150     "Complex promotion",
151     "Integral conversion",
152     "Floating conversion",
153     "Complex conversion",
154     "Floating-integral conversion",
155     "Pointer conversion",
156     "Pointer-to-member conversion",
157     "Boolean conversion",
158     "Compatible-types conversion",
159     "Derived-to-base conversion",
160     "Vector conversion",
161     "Vector splat",
162     "Complex-real conversion",
163     "Block Pointer conversion",
164     "Transparent Union Conversion",
165     "Writeback conversion"
166   };
167   return Name[Kind];
168 }
169 
170 /// StandardConversionSequence - Set the standard conversion
171 /// sequence to the identity conversion.
172 void StandardConversionSequence::setAsIdentityConversion() {
173   First = ICK_Identity;
174   Second = ICK_Identity;
175   Third = ICK_Identity;
176   DeprecatedStringLiteralToCharPtr = false;
177   QualificationIncludesObjCLifetime = false;
178   ReferenceBinding = false;
179   DirectBinding = false;
180   IsLvalueReference = true;
181   BindsToFunctionLvalue = false;
182   BindsToRvalue = false;
183   BindsImplicitObjectArgumentWithoutRefQualifier = false;
184   ObjCLifetimeConversionBinding = false;
185   CopyConstructor = nullptr;
186 }
187 
188 /// getRank - Retrieve the rank of this standard conversion sequence
189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190 /// implicit conversions.
191 ImplicitConversionRank StandardConversionSequence::getRank() const {
192   ImplicitConversionRank Rank = ICR_Exact_Match;
193   if  (GetConversionRank(First) > Rank)
194     Rank = GetConversionRank(First);
195   if  (GetConversionRank(Second) > Rank)
196     Rank = GetConversionRank(Second);
197   if  (GetConversionRank(Third) > Rank)
198     Rank = GetConversionRank(Third);
199   return Rank;
200 }
201 
202 /// isPointerConversionToBool - Determines whether this conversion is
203 /// a conversion of a pointer or pointer-to-member to bool. This is
204 /// used as part of the ranking of standard conversion sequences
205 /// (C++ 13.3.3.2p4).
206 bool StandardConversionSequence::isPointerConversionToBool() const {
207   // Note that FromType has not necessarily been transformed by the
208   // array-to-pointer or function-to-pointer implicit conversions, so
209   // check for their presence as well as checking whether FromType is
210   // a pointer.
211   if (getToType(1)->isBooleanType() &&
212       (getFromType()->isPointerType() ||
213        getFromType()->isObjCObjectPointerType() ||
214        getFromType()->isBlockPointerType() ||
215        getFromType()->isNullPtrType() ||
216        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217     return true;
218 
219   return false;
220 }
221 
222 /// isPointerConversionToVoidPointer - Determines whether this
223 /// conversion is a conversion of a pointer to a void pointer. This is
224 /// used as part of the ranking of standard conversion sequences (C++
225 /// 13.3.3.2p4).
226 bool
227 StandardConversionSequence::
228 isPointerConversionToVoidPointer(ASTContext& Context) const {
229   QualType FromType = getFromType();
230   QualType ToType = getToType(1);
231 
232   // Note that FromType has not necessarily been transformed by the
233   // array-to-pointer implicit conversion, so check for its presence
234   // and redo the conversion to get a pointer.
235   if (First == ICK_Array_To_Pointer)
236     FromType = Context.getArrayDecayedType(FromType);
237 
238   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
239     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
240       return ToPtrType->getPointeeType()->isVoidType();
241 
242   return false;
243 }
244 
245 /// Skip any implicit casts which could be either part of a narrowing conversion
246 /// or after one in an implicit conversion.
247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249     switch (ICE->getCastKind()) {
250     case CK_NoOp:
251     case CK_IntegralCast:
252     case CK_IntegralToBoolean:
253     case CK_IntegralToFloating:
254     case CK_FloatingToIntegral:
255     case CK_FloatingToBoolean:
256     case CK_FloatingCast:
257       Converted = ICE->getSubExpr();
258       continue;
259 
260     default:
261       return Converted;
262     }
263   }
264 
265   return Converted;
266 }
267 
268 /// Check if this standard conversion sequence represents a narrowing
269 /// conversion, according to C++11 [dcl.init.list]p7.
270 ///
271 /// \param Ctx  The AST context.
272 /// \param Converted  The result of applying this standard conversion sequence.
273 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
274 ///        value of the expression prior to the narrowing conversion.
275 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
276 ///        type of the expression prior to the narrowing conversion.
277 NarrowingKind
278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279                                              const Expr *Converted,
280                                              APValue &ConstantValue,
281                                              QualType &ConstantType) const {
282   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
283 
284   // C++11 [dcl.init.list]p7:
285   //   A narrowing conversion is an implicit conversion ...
286   QualType FromType = getToType(0);
287   QualType ToType = getToType(1);
288   switch (Second) {
289   // 'bool' is an integral type; dispatch to the right place to handle it.
290   case ICK_Boolean_Conversion:
291     if (FromType->isRealFloatingType())
292       goto FloatingIntegralConversion;
293     if (FromType->isIntegralOrUnscopedEnumerationType())
294       goto IntegralConversion;
295     // Boolean conversions can be from pointers and pointers to members
296     // [conv.bool], and those aren't considered narrowing conversions.
297     return NK_Not_Narrowing;
298 
299   // -- from a floating-point type to an integer type, or
300   //
301   // -- from an integer type or unscoped enumeration type to a floating-point
302   //    type, except where the source is a constant expression and the actual
303   //    value after conversion will fit into the target type and will produce
304   //    the original value when converted back to the original type, or
305   case ICK_Floating_Integral:
306   FloatingIntegralConversion:
307     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308       return NK_Type_Narrowing;
309     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310       llvm::APSInt IntConstantValue;
311       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
312       if (Initializer &&
313           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314         // Convert the integer to the floating type.
315         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317                                 llvm::APFloat::rmNearestTiesToEven);
318         // And back.
319         llvm::APSInt ConvertedValue = IntConstantValue;
320         bool ignored;
321         Result.convertToInteger(ConvertedValue,
322                                 llvm::APFloat::rmTowardZero, &ignored);
323         // If the resulting value is different, this was a narrowing conversion.
324         if (IntConstantValue != ConvertedValue) {
325           ConstantValue = APValue(IntConstantValue);
326           ConstantType = Initializer->getType();
327           return NK_Constant_Narrowing;
328         }
329       } else {
330         // Variables are always narrowings.
331         return NK_Variable_Narrowing;
332       }
333     }
334     return NK_Not_Narrowing;
335 
336   // -- from long double to double or float, or from double to float, except
337   //    where the source is a constant expression and the actual value after
338   //    conversion is within the range of values that can be represented (even
339   //    if it cannot be represented exactly), or
340   case ICK_Floating_Conversion:
341     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343       // FromType is larger than ToType.
344       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346         // Constant!
347         assert(ConstantValue.isFloat());
348         llvm::APFloat FloatVal = ConstantValue.getFloat();
349         // Convert the source value into the target type.
350         bool ignored;
351         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352           Ctx.getFloatTypeSemantics(ToType),
353           llvm::APFloat::rmNearestTiesToEven, &ignored);
354         // If there was no overflow, the source value is within the range of
355         // values that can be represented.
356         if (ConvertStatus & llvm::APFloat::opOverflow) {
357           ConstantType = Initializer->getType();
358           return NK_Constant_Narrowing;
359         }
360       } else {
361         return NK_Variable_Narrowing;
362       }
363     }
364     return NK_Not_Narrowing;
365 
366   // -- from an integer type or unscoped enumeration type to an integer type
367   //    that cannot represent all the values of the original type, except where
368   //    the source is a constant expression and the actual value after
369   //    conversion will fit into the target type and will produce the original
370   //    value when converted back to the original type.
371   case ICK_Integral_Conversion:
372   IntegralConversion: {
373     assert(FromType->isIntegralOrUnscopedEnumerationType());
374     assert(ToType->isIntegralOrUnscopedEnumerationType());
375     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376     const unsigned FromWidth = Ctx.getIntWidth(FromType);
377     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378     const unsigned ToWidth = Ctx.getIntWidth(ToType);
379 
380     if (FromWidth > ToWidth ||
381         (FromWidth == ToWidth && FromSigned != ToSigned) ||
382         (FromSigned && !ToSigned)) {
383       // Not all values of FromType can be represented in ToType.
384       llvm::APSInt InitializerValue;
385       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
386       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387         // Such conversions on variables are always narrowing.
388         return NK_Variable_Narrowing;
389       }
390       bool Narrowing = false;
391       if (FromWidth < ToWidth) {
392         // Negative -> unsigned is narrowing. Otherwise, more bits is never
393         // narrowing.
394         if (InitializerValue.isSigned() && InitializerValue.isNegative())
395           Narrowing = true;
396       } else {
397         // Add a bit to the InitializerValue so we don't have to worry about
398         // signed vs. unsigned comparisons.
399         InitializerValue = InitializerValue.extend(
400           InitializerValue.getBitWidth() + 1);
401         // Convert the initializer to and from the target width and signed-ness.
402         llvm::APSInt ConvertedValue = InitializerValue;
403         ConvertedValue = ConvertedValue.trunc(ToWidth);
404         ConvertedValue.setIsSigned(ToSigned);
405         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406         ConvertedValue.setIsSigned(InitializerValue.isSigned());
407         // If the result is different, this was a narrowing conversion.
408         if (ConvertedValue != InitializerValue)
409           Narrowing = true;
410       }
411       if (Narrowing) {
412         ConstantType = Initializer->getType();
413         ConstantValue = APValue(InitializerValue);
414         return NK_Constant_Narrowing;
415       }
416     }
417     return NK_Not_Narrowing;
418   }
419 
420   default:
421     // Other kinds of conversions are not narrowings.
422     return NK_Not_Narrowing;
423   }
424 }
425 
426 /// dump - Print this standard conversion sequence to standard
427 /// error. Useful for debugging overloading issues.
428 void StandardConversionSequence::dump() const {
429   raw_ostream &OS = llvm::errs();
430   bool PrintedSomething = false;
431   if (First != ICK_Identity) {
432     OS << GetImplicitConversionName(First);
433     PrintedSomething = true;
434   }
435 
436   if (Second != ICK_Identity) {
437     if (PrintedSomething) {
438       OS << " -> ";
439     }
440     OS << GetImplicitConversionName(Second);
441 
442     if (CopyConstructor) {
443       OS << " (by copy constructor)";
444     } else if (DirectBinding) {
445       OS << " (direct reference binding)";
446     } else if (ReferenceBinding) {
447       OS << " (reference binding)";
448     }
449     PrintedSomething = true;
450   }
451 
452   if (Third != ICK_Identity) {
453     if (PrintedSomething) {
454       OS << " -> ";
455     }
456     OS << GetImplicitConversionName(Third);
457     PrintedSomething = true;
458   }
459 
460   if (!PrintedSomething) {
461     OS << "No conversions required";
462   }
463 }
464 
465 /// dump - Print this user-defined conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 void UserDefinedConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   if (Before.First || Before.Second || Before.Third) {
470     Before.dump();
471     OS << " -> ";
472   }
473   if (ConversionFunction)
474     OS << '\'' << *ConversionFunction << '\'';
475   else
476     OS << "aggregate initialization";
477   if (After.First || After.Second || After.Third) {
478     OS << " -> ";
479     After.dump();
480   }
481 }
482 
483 /// dump - Print this implicit conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 void ImplicitConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   if (isStdInitializerListElement())
488     OS << "Worst std::initializer_list element conversion: ";
489   switch (ConversionKind) {
490   case StandardConversion:
491     OS << "Standard conversion: ";
492     Standard.dump();
493     break;
494   case UserDefinedConversion:
495     OS << "User-defined conversion: ";
496     UserDefined.dump();
497     break;
498   case EllipsisConversion:
499     OS << "Ellipsis conversion";
500     break;
501   case AmbiguousConversion:
502     OS << "Ambiguous conversion";
503     break;
504   case BadConversion:
505     OS << "Bad conversion";
506     break;
507   }
508 
509   OS << "\n";
510 }
511 
512 void AmbiguousConversionSequence::construct() {
513   new (&conversions()) ConversionSet();
514 }
515 
516 void AmbiguousConversionSequence::destruct() {
517   conversions().~ConversionSet();
518 }
519 
520 void
521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522   FromTypePtr = O.FromTypePtr;
523   ToTypePtr = O.ToTypePtr;
524   new (&conversions()) ConversionSet(O.conversions());
525 }
526 
527 namespace {
528   // Structure used by DeductionFailureInfo to store
529   // template argument information.
530   struct DFIArguments {
531     TemplateArgument FirstArg;
532     TemplateArgument SecondArg;
533   };
534   // Structure used by DeductionFailureInfo to store
535   // template parameter and template argument information.
536   struct DFIParamWithArguments : DFIArguments {
537     TemplateParameter Param;
538   };
539 }
540 
541 /// \brief Convert from Sema's representation of template deduction information
542 /// to the form used in overload-candidate information.
543 DeductionFailureInfo
544 clang::MakeDeductionFailureInfo(ASTContext &Context,
545                                 Sema::TemplateDeductionResult TDK,
546                                 TemplateDeductionInfo &Info) {
547   DeductionFailureInfo Result;
548   Result.Result = static_cast<unsigned>(TDK);
549   Result.HasDiagnostic = false;
550   Result.Data = nullptr;
551   switch (TDK) {
552   case Sema::TDK_Success:
553   case Sema::TDK_Invalid:
554   case Sema::TDK_InstantiationDepth:
555   case Sema::TDK_TooManyArguments:
556   case Sema::TDK_TooFewArguments:
557     break;
558 
559   case Sema::TDK_Incomplete:
560   case Sema::TDK_InvalidExplicitArguments:
561     Result.Data = Info.Param.getOpaqueValue();
562     break;
563 
564   case Sema::TDK_NonDeducedMismatch: {
565     // FIXME: Should allocate from normal heap so that we can free this later.
566     DFIArguments *Saved = new (Context) DFIArguments;
567     Saved->FirstArg = Info.FirstArg;
568     Saved->SecondArg = Info.SecondArg;
569     Result.Data = Saved;
570     break;
571   }
572 
573   case Sema::TDK_Inconsistent:
574   case Sema::TDK_Underqualified: {
575     // FIXME: Should allocate from normal heap so that we can free this later.
576     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
577     Saved->Param = Info.Param;
578     Saved->FirstArg = Info.FirstArg;
579     Saved->SecondArg = Info.SecondArg;
580     Result.Data = Saved;
581     break;
582   }
583 
584   case Sema::TDK_SubstitutionFailure:
585     Result.Data = Info.take();
586     if (Info.hasSFINAEDiagnostic()) {
587       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588           SourceLocation(), PartialDiagnostic::NullDiagnostic());
589       Info.takeSFINAEDiagnostic(*Diag);
590       Result.HasDiagnostic = true;
591     }
592     break;
593 
594   case Sema::TDK_FailedOverloadResolution:
595     Result.Data = Info.Expression;
596     break;
597 
598   case Sema::TDK_MiscellaneousDeductionFailure:
599     break;
600   }
601 
602   return Result;
603 }
604 
605 void DeductionFailureInfo::Destroy() {
606   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607   case Sema::TDK_Success:
608   case Sema::TDK_Invalid:
609   case Sema::TDK_InstantiationDepth:
610   case Sema::TDK_Incomplete:
611   case Sema::TDK_TooManyArguments:
612   case Sema::TDK_TooFewArguments:
613   case Sema::TDK_InvalidExplicitArguments:
614   case Sema::TDK_FailedOverloadResolution:
615     break;
616 
617   case Sema::TDK_Inconsistent:
618   case Sema::TDK_Underqualified:
619   case Sema::TDK_NonDeducedMismatch:
620     // FIXME: Destroy the data?
621     Data = nullptr;
622     break;
623 
624   case Sema::TDK_SubstitutionFailure:
625     // FIXME: Destroy the template argument list?
626     Data = nullptr;
627     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628       Diag->~PartialDiagnosticAt();
629       HasDiagnostic = false;
630     }
631     break;
632 
633   // Unhandled
634   case Sema::TDK_MiscellaneousDeductionFailure:
635     break;
636   }
637 }
638 
639 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
640   if (HasDiagnostic)
641     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
642   return nullptr;
643 }
644 
645 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
646   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647   case Sema::TDK_Success:
648   case Sema::TDK_Invalid:
649   case Sema::TDK_InstantiationDepth:
650   case Sema::TDK_TooManyArguments:
651   case Sema::TDK_TooFewArguments:
652   case Sema::TDK_SubstitutionFailure:
653   case Sema::TDK_NonDeducedMismatch:
654   case Sema::TDK_FailedOverloadResolution:
655     return TemplateParameter();
656 
657   case Sema::TDK_Incomplete:
658   case Sema::TDK_InvalidExplicitArguments:
659     return TemplateParameter::getFromOpaqueValue(Data);
660 
661   case Sema::TDK_Inconsistent:
662   case Sema::TDK_Underqualified:
663     return static_cast<DFIParamWithArguments*>(Data)->Param;
664 
665   // Unhandled
666   case Sema::TDK_MiscellaneousDeductionFailure:
667     break;
668   }
669 
670   return TemplateParameter();
671 }
672 
673 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
674   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
675   case Sema::TDK_Success:
676   case Sema::TDK_Invalid:
677   case Sema::TDK_InstantiationDepth:
678   case Sema::TDK_TooManyArguments:
679   case Sema::TDK_TooFewArguments:
680   case Sema::TDK_Incomplete:
681   case Sema::TDK_InvalidExplicitArguments:
682   case Sema::TDK_Inconsistent:
683   case Sema::TDK_Underqualified:
684   case Sema::TDK_NonDeducedMismatch:
685   case Sema::TDK_FailedOverloadResolution:
686     return nullptr;
687 
688   case Sema::TDK_SubstitutionFailure:
689     return static_cast<TemplateArgumentList*>(Data);
690 
691   // Unhandled
692   case Sema::TDK_MiscellaneousDeductionFailure:
693     break;
694   }
695 
696   return nullptr;
697 }
698 
699 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
700   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701   case Sema::TDK_Success:
702   case Sema::TDK_Invalid:
703   case Sema::TDK_InstantiationDepth:
704   case Sema::TDK_Incomplete:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_InvalidExplicitArguments:
708   case Sema::TDK_SubstitutionFailure:
709   case Sema::TDK_FailedOverloadResolution:
710     return nullptr;
711 
712   case Sema::TDK_Inconsistent:
713   case Sema::TDK_Underqualified:
714   case Sema::TDK_NonDeducedMismatch:
715     return &static_cast<DFIArguments*>(Data)->FirstArg;
716 
717   // Unhandled
718   case Sema::TDK_MiscellaneousDeductionFailure:
719     break;
720   }
721 
722   return nullptr;
723 }
724 
725 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
726   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727   case Sema::TDK_Success:
728   case Sema::TDK_Invalid:
729   case Sema::TDK_InstantiationDepth:
730   case Sema::TDK_Incomplete:
731   case Sema::TDK_TooManyArguments:
732   case Sema::TDK_TooFewArguments:
733   case Sema::TDK_InvalidExplicitArguments:
734   case Sema::TDK_SubstitutionFailure:
735   case Sema::TDK_FailedOverloadResolution:
736     return nullptr;
737 
738   case Sema::TDK_Inconsistent:
739   case Sema::TDK_Underqualified:
740   case Sema::TDK_NonDeducedMismatch:
741     return &static_cast<DFIArguments*>(Data)->SecondArg;
742 
743   // Unhandled
744   case Sema::TDK_MiscellaneousDeductionFailure:
745     break;
746   }
747 
748   return nullptr;
749 }
750 
751 Expr *DeductionFailureInfo::getExpr() {
752   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753         Sema::TDK_FailedOverloadResolution)
754     return static_cast<Expr*>(Data);
755 
756   return nullptr;
757 }
758 
759 void OverloadCandidateSet::destroyCandidates() {
760   for (iterator i = begin(), e = end(); i != e; ++i) {
761     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762       i->Conversions[ii].~ImplicitConversionSequence();
763     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764       i->DeductionFailure.Destroy();
765   }
766 }
767 
768 void OverloadCandidateSet::clear() {
769   destroyCandidates();
770   NumInlineSequences = 0;
771   Candidates.clear();
772   Functions.clear();
773 }
774 
775 namespace {
776   class UnbridgedCastsSet {
777     struct Entry {
778       Expr **Addr;
779       Expr *Saved;
780     };
781     SmallVector<Entry, 2> Entries;
782 
783   public:
784     void save(Sema &S, Expr *&E) {
785       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786       Entry entry = { &E, E };
787       Entries.push_back(entry);
788       E = S.stripARCUnbridgedCast(E);
789     }
790 
791     void restore() {
792       for (SmallVectorImpl<Entry>::iterator
793              i = Entries.begin(), e = Entries.end(); i != e; ++i)
794         *i->Addr = i->Saved;
795     }
796   };
797 }
798 
799 /// checkPlaceholderForOverload - Do any interesting placeholder-like
800 /// preprocessing on the given expression.
801 ///
802 /// \param unbridgedCasts a collection to which to add unbridged casts;
803 ///   without this, they will be immediately diagnosed as errors
804 ///
805 /// Return true on unrecoverable error.
806 static bool
807 checkPlaceholderForOverload(Sema &S, Expr *&E,
808                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
809   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
810     // We can't handle overloaded expressions here because overload
811     // resolution might reasonably tweak them.
812     if (placeholder->getKind() == BuiltinType::Overload) return false;
813 
814     // If the context potentially accepts unbridged ARC casts, strip
815     // the unbridged cast and add it to the collection for later restoration.
816     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
817         unbridgedCasts) {
818       unbridgedCasts->save(S, E);
819       return false;
820     }
821 
822     // Go ahead and check everything else.
823     ExprResult result = S.CheckPlaceholderExpr(E);
824     if (result.isInvalid())
825       return true;
826 
827     E = result.get();
828     return false;
829   }
830 
831   // Nothing to do.
832   return false;
833 }
834 
835 /// checkArgPlaceholdersForOverload - Check a set of call operands for
836 /// placeholders.
837 static bool checkArgPlaceholdersForOverload(Sema &S,
838                                             MultiExprArg Args,
839                                             UnbridgedCastsSet &unbridged) {
840   for (unsigned i = 0, e = Args.size(); i != e; ++i)
841     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
842       return true;
843 
844   return false;
845 }
846 
847 // IsOverload - Determine whether the given New declaration is an
848 // overload of the declarations in Old. This routine returns false if
849 // New and Old cannot be overloaded, e.g., if New has the same
850 // signature as some function in Old (C++ 1.3.10) or if the Old
851 // declarations aren't functions (or function templates) at all. When
852 // it does return false, MatchedDecl will point to the decl that New
853 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
854 // top of the underlying declaration.
855 //
856 // Example: Given the following input:
857 //
858 //   void f(int, float); // #1
859 //   void f(int, int); // #2
860 //   int f(int, int); // #3
861 //
862 // When we process #1, there is no previous declaration of "f",
863 // so IsOverload will not be used.
864 //
865 // When we process #2, Old contains only the FunctionDecl for #1.  By
866 // comparing the parameter types, we see that #1 and #2 are overloaded
867 // (since they have different signatures), so this routine returns
868 // false; MatchedDecl is unchanged.
869 //
870 // When we process #3, Old is an overload set containing #1 and #2. We
871 // compare the signatures of #3 to #1 (they're overloaded, so we do
872 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873 // identical (return types of functions are not part of the
874 // signature), IsOverload returns false and MatchedDecl will be set to
875 // point to the FunctionDecl for #2.
876 //
877 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878 // into a class by a using declaration.  The rules for whether to hide
879 // shadow declarations ignore some properties which otherwise figure
880 // into a function template's signature.
881 Sema::OverloadKind
882 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883                     NamedDecl *&Match, bool NewIsUsingDecl) {
884   for (LookupResult::iterator I = Old.begin(), E = Old.end();
885          I != E; ++I) {
886     NamedDecl *OldD = *I;
887 
888     bool OldIsUsingDecl = false;
889     if (isa<UsingShadowDecl>(OldD)) {
890       OldIsUsingDecl = true;
891 
892       // We can always introduce two using declarations into the same
893       // context, even if they have identical signatures.
894       if (NewIsUsingDecl) continue;
895 
896       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
897     }
898 
899     // A using-declaration does not conflict with another declaration
900     // if one of them is hidden.
901     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
902       continue;
903 
904     // If either declaration was introduced by a using declaration,
905     // we'll need to use slightly different rules for matching.
906     // Essentially, these rules are the normal rules, except that
907     // function templates hide function templates with different
908     // return types or template parameter lists.
909     bool UseMemberUsingDeclRules =
910       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
911       !New->getFriendObjectKind();
912 
913     if (FunctionDecl *OldF = OldD->getAsFunction()) {
914       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
915         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
916           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
917           continue;
918         }
919 
920         if (!isa<FunctionTemplateDecl>(OldD) &&
921             !shouldLinkPossiblyHiddenDecl(*I, New))
922           continue;
923 
924         Match = *I;
925         return Ovl_Match;
926       }
927     } else if (isa<UsingDecl>(OldD)) {
928       // We can overload with these, which can show up when doing
929       // redeclaration checks for UsingDecls.
930       assert(Old.getLookupKind() == LookupUsingDeclName);
931     } else if (isa<TagDecl>(OldD)) {
932       // We can always overload with tags by hiding them.
933     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
934       // Optimistically assume that an unresolved using decl will
935       // overload; if it doesn't, we'll have to diagnose during
936       // template instantiation.
937     } else {
938       // (C++ 13p1):
939       //   Only function declarations can be overloaded; object and type
940       //   declarations cannot be overloaded.
941       Match = *I;
942       return Ovl_NonFunction;
943     }
944   }
945 
946   return Ovl_Overload;
947 }
948 
949 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
950                       bool UseUsingDeclRules) {
951   // C++ [basic.start.main]p2: This function shall not be overloaded.
952   if (New->isMain())
953     return false;
954 
955   // MSVCRT user defined entry points cannot be overloaded.
956   if (New->isMSVCRTEntryPoint())
957     return false;
958 
959   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
960   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
961 
962   // C++ [temp.fct]p2:
963   //   A function template can be overloaded with other function templates
964   //   and with normal (non-template) functions.
965   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
966     return true;
967 
968   // Is the function New an overload of the function Old?
969   QualType OldQType = Context.getCanonicalType(Old->getType());
970   QualType NewQType = Context.getCanonicalType(New->getType());
971 
972   // Compare the signatures (C++ 1.3.10) of the two functions to
973   // determine whether they are overloads. If we find any mismatch
974   // in the signature, they are overloads.
975 
976   // If either of these functions is a K&R-style function (no
977   // prototype), then we consider them to have matching signatures.
978   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
979       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
980     return false;
981 
982   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
983   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
984 
985   // The signature of a function includes the types of its
986   // parameters (C++ 1.3.10), which includes the presence or absence
987   // of the ellipsis; see C++ DR 357).
988   if (OldQType != NewQType &&
989       (OldType->getNumParams() != NewType->getNumParams() ||
990        OldType->isVariadic() != NewType->isVariadic() ||
991        !FunctionParamTypesAreEqual(OldType, NewType)))
992     return true;
993 
994   // C++ [temp.over.link]p4:
995   //   The signature of a function template consists of its function
996   //   signature, its return type and its template parameter list. The names
997   //   of the template parameters are significant only for establishing the
998   //   relationship between the template parameters and the rest of the
999   //   signature.
1000   //
1001   // We check the return type and template parameter lists for function
1002   // templates first; the remaining checks follow.
1003   //
1004   // However, we don't consider either of these when deciding whether
1005   // a member introduced by a shadow declaration is hidden.
1006   if (!UseUsingDeclRules && NewTemplate &&
1007       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1008                                        OldTemplate->getTemplateParameters(),
1009                                        false, TPL_TemplateMatch) ||
1010        OldType->getReturnType() != NewType->getReturnType()))
1011     return true;
1012 
1013   // If the function is a class member, its signature includes the
1014   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1015   //
1016   // As part of this, also check whether one of the member functions
1017   // is static, in which case they are not overloads (C++
1018   // 13.1p2). While not part of the definition of the signature,
1019   // this check is important to determine whether these functions
1020   // can be overloaded.
1021   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1022   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1023   if (OldMethod && NewMethod &&
1024       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1025     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1026       if (!UseUsingDeclRules &&
1027           (OldMethod->getRefQualifier() == RQ_None ||
1028            NewMethod->getRefQualifier() == RQ_None)) {
1029         // C++0x [over.load]p2:
1030         //   - Member function declarations with the same name and the same
1031         //     parameter-type-list as well as member function template
1032         //     declarations with the same name, the same parameter-type-list, and
1033         //     the same template parameter lists cannot be overloaded if any of
1034         //     them, but not all, have a ref-qualifier (8.3.5).
1035         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1036           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1037         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1038       }
1039       return true;
1040     }
1041 
1042     // We may not have applied the implicit const for a constexpr member
1043     // function yet (because we haven't yet resolved whether this is a static
1044     // or non-static member function). Add it now, on the assumption that this
1045     // is a redeclaration of OldMethod.
1046     unsigned OldQuals = OldMethod->getTypeQualifiers();
1047     unsigned NewQuals = NewMethod->getTypeQualifiers();
1048     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1049         !isa<CXXConstructorDecl>(NewMethod))
1050       NewQuals |= Qualifiers::Const;
1051 
1052     // We do not allow overloading based off of '__restrict'.
1053     OldQuals &= ~Qualifiers::Restrict;
1054     NewQuals &= ~Qualifiers::Restrict;
1055     if (OldQuals != NewQuals)
1056       return true;
1057   }
1058 
1059   // enable_if attributes are an order-sensitive part of the signature.
1060   for (specific_attr_iterator<EnableIfAttr>
1061          NewI = New->specific_attr_begin<EnableIfAttr>(),
1062          NewE = New->specific_attr_end<EnableIfAttr>(),
1063          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1064          OldE = Old->specific_attr_end<EnableIfAttr>();
1065        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1066     if (NewI == NewE || OldI == OldE)
1067       return true;
1068     llvm::FoldingSetNodeID NewID, OldID;
1069     NewI->getCond()->Profile(NewID, Context, true);
1070     OldI->getCond()->Profile(OldID, Context, true);
1071     if (NewID != OldID)
1072       return true;
1073   }
1074 
1075   if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1076     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1077                        OldTarget = IdentifyCUDATarget(Old);
1078     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1079       return false;
1080 
1081     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1082 
1083     // Don't allow mixing of HD with other kinds. This guarantees that
1084     // we have only one viable function with this signature on any
1085     // side of CUDA compilation .
1086     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1087       return false;
1088 
1089     // Allow overloading of functions with same signature, but
1090     // different CUDA target attributes.
1091     return NewTarget != OldTarget;
1092   }
1093 
1094   // The signatures match; this is not an overload.
1095   return false;
1096 }
1097 
1098 /// \brief Checks availability of the function depending on the current
1099 /// function context. Inside an unavailable function, unavailability is ignored.
1100 ///
1101 /// \returns true if \arg FD is unavailable and current context is inside
1102 /// an available function, false otherwise.
1103 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1104   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1105 }
1106 
1107 /// \brief Tries a user-defined conversion from From to ToType.
1108 ///
1109 /// Produces an implicit conversion sequence for when a standard conversion
1110 /// is not an option. See TryImplicitConversion for more information.
1111 static ImplicitConversionSequence
1112 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1113                          bool SuppressUserConversions,
1114                          bool AllowExplicit,
1115                          bool InOverloadResolution,
1116                          bool CStyle,
1117                          bool AllowObjCWritebackConversion,
1118                          bool AllowObjCConversionOnExplicit) {
1119   ImplicitConversionSequence ICS;
1120 
1121   if (SuppressUserConversions) {
1122     // We're not in the case above, so there is no conversion that
1123     // we can perform.
1124     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1125     return ICS;
1126   }
1127 
1128   // Attempt user-defined conversion.
1129   OverloadCandidateSet Conversions(From->getExprLoc(),
1130                                    OverloadCandidateSet::CSK_Normal);
1131   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1132                                   Conversions, AllowExplicit,
1133                                   AllowObjCConversionOnExplicit)) {
1134   case OR_Success:
1135   case OR_Deleted:
1136     ICS.setUserDefined();
1137     ICS.UserDefined.Before.setAsIdentityConversion();
1138     // C++ [over.ics.user]p4:
1139     //   A conversion of an expression of class type to the same class
1140     //   type is given Exact Match rank, and a conversion of an
1141     //   expression of class type to a base class of that type is
1142     //   given Conversion rank, in spite of the fact that a copy
1143     //   constructor (i.e., a user-defined conversion function) is
1144     //   called for those cases.
1145     if (CXXConstructorDecl *Constructor
1146           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1147       QualType FromCanon
1148         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1149       QualType ToCanon
1150         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1151       if (Constructor->isCopyConstructor() &&
1152           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1153         // Turn this into a "standard" conversion sequence, so that it
1154         // gets ranked with standard conversion sequences.
1155         ICS.setStandard();
1156         ICS.Standard.setAsIdentityConversion();
1157         ICS.Standard.setFromType(From->getType());
1158         ICS.Standard.setAllToTypes(ToType);
1159         ICS.Standard.CopyConstructor = Constructor;
1160         if (ToCanon != FromCanon)
1161           ICS.Standard.Second = ICK_Derived_To_Base;
1162       }
1163     }
1164     break;
1165 
1166   case OR_Ambiguous:
1167     ICS.setAmbiguous();
1168     ICS.Ambiguous.setFromType(From->getType());
1169     ICS.Ambiguous.setToType(ToType);
1170     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1171          Cand != Conversions.end(); ++Cand)
1172       if (Cand->Viable)
1173         ICS.Ambiguous.addConversion(Cand->Function);
1174     break;
1175 
1176     // Fall through.
1177   case OR_No_Viable_Function:
1178     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1179     break;
1180   }
1181 
1182   return ICS;
1183 }
1184 
1185 /// TryImplicitConversion - Attempt to perform an implicit conversion
1186 /// from the given expression (Expr) to the given type (ToType). This
1187 /// function returns an implicit conversion sequence that can be used
1188 /// to perform the initialization. Given
1189 ///
1190 ///   void f(float f);
1191 ///   void g(int i) { f(i); }
1192 ///
1193 /// this routine would produce an implicit conversion sequence to
1194 /// describe the initialization of f from i, which will be a standard
1195 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1196 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1197 //
1198 /// Note that this routine only determines how the conversion can be
1199 /// performed; it does not actually perform the conversion. As such,
1200 /// it will not produce any diagnostics if no conversion is available,
1201 /// but will instead return an implicit conversion sequence of kind
1202 /// "BadConversion".
1203 ///
1204 /// If @p SuppressUserConversions, then user-defined conversions are
1205 /// not permitted.
1206 /// If @p AllowExplicit, then explicit user-defined conversions are
1207 /// permitted.
1208 ///
1209 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1210 /// writeback conversion, which allows __autoreleasing id* parameters to
1211 /// be initialized with __strong id* or __weak id* arguments.
1212 static ImplicitConversionSequence
1213 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1214                       bool SuppressUserConversions,
1215                       bool AllowExplicit,
1216                       bool InOverloadResolution,
1217                       bool CStyle,
1218                       bool AllowObjCWritebackConversion,
1219                       bool AllowObjCConversionOnExplicit) {
1220   ImplicitConversionSequence ICS;
1221   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1222                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1223     ICS.setStandard();
1224     return ICS;
1225   }
1226 
1227   if (!S.getLangOpts().CPlusPlus) {
1228     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1229     return ICS;
1230   }
1231 
1232   // C++ [over.ics.user]p4:
1233   //   A conversion of an expression of class type to the same class
1234   //   type is given Exact Match rank, and a conversion of an
1235   //   expression of class type to a base class of that type is
1236   //   given Conversion rank, in spite of the fact that a copy/move
1237   //   constructor (i.e., a user-defined conversion function) is
1238   //   called for those cases.
1239   QualType FromType = From->getType();
1240   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1241       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1242        S.IsDerivedFrom(FromType, ToType))) {
1243     ICS.setStandard();
1244     ICS.Standard.setAsIdentityConversion();
1245     ICS.Standard.setFromType(FromType);
1246     ICS.Standard.setAllToTypes(ToType);
1247 
1248     // We don't actually check at this point whether there is a valid
1249     // copy/move constructor, since overloading just assumes that it
1250     // exists. When we actually perform initialization, we'll find the
1251     // appropriate constructor to copy the returned object, if needed.
1252     ICS.Standard.CopyConstructor = nullptr;
1253 
1254     // Determine whether this is considered a derived-to-base conversion.
1255     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1256       ICS.Standard.Second = ICK_Derived_To_Base;
1257 
1258     return ICS;
1259   }
1260 
1261   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1262                                   AllowExplicit, InOverloadResolution, CStyle,
1263                                   AllowObjCWritebackConversion,
1264                                   AllowObjCConversionOnExplicit);
1265 }
1266 
1267 ImplicitConversionSequence
1268 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1269                             bool SuppressUserConversions,
1270                             bool AllowExplicit,
1271                             bool InOverloadResolution,
1272                             bool CStyle,
1273                             bool AllowObjCWritebackConversion) {
1274   return ::TryImplicitConversion(*this, From, ToType,
1275                                  SuppressUserConversions, AllowExplicit,
1276                                  InOverloadResolution, CStyle,
1277                                  AllowObjCWritebackConversion,
1278                                  /*AllowObjCConversionOnExplicit=*/false);
1279 }
1280 
1281 /// PerformImplicitConversion - Perform an implicit conversion of the
1282 /// expression From to the type ToType. Returns the
1283 /// converted expression. Flavor is the kind of conversion we're
1284 /// performing, used in the error message. If @p AllowExplicit,
1285 /// explicit user-defined conversions are permitted.
1286 ExprResult
1287 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1288                                 AssignmentAction Action, bool AllowExplicit) {
1289   ImplicitConversionSequence ICS;
1290   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1291 }
1292 
1293 ExprResult
1294 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1295                                 AssignmentAction Action, bool AllowExplicit,
1296                                 ImplicitConversionSequence& ICS) {
1297   if (checkPlaceholderForOverload(*this, From))
1298     return ExprError();
1299 
1300   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1301   bool AllowObjCWritebackConversion
1302     = getLangOpts().ObjCAutoRefCount &&
1303       (Action == AA_Passing || Action == AA_Sending);
1304   if (getLangOpts().ObjC1)
1305     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1306                                       ToType, From->getType(), From);
1307   ICS = ::TryImplicitConversion(*this, From, ToType,
1308                                 /*SuppressUserConversions=*/false,
1309                                 AllowExplicit,
1310                                 /*InOverloadResolution=*/false,
1311                                 /*CStyle=*/false,
1312                                 AllowObjCWritebackConversion,
1313                                 /*AllowObjCConversionOnExplicit=*/false);
1314   return PerformImplicitConversion(From, ToType, ICS, Action);
1315 }
1316 
1317 /// \brief Determine whether the conversion from FromType to ToType is a valid
1318 /// conversion that strips "noreturn" off the nested function type.
1319 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1320                                 QualType &ResultTy) {
1321   if (Context.hasSameUnqualifiedType(FromType, ToType))
1322     return false;
1323 
1324   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1325   // where F adds one of the following at most once:
1326   //   - a pointer
1327   //   - a member pointer
1328   //   - a block pointer
1329   CanQualType CanTo = Context.getCanonicalType(ToType);
1330   CanQualType CanFrom = Context.getCanonicalType(FromType);
1331   Type::TypeClass TyClass = CanTo->getTypeClass();
1332   if (TyClass != CanFrom->getTypeClass()) return false;
1333   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1334     if (TyClass == Type::Pointer) {
1335       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1336       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1337     } else if (TyClass == Type::BlockPointer) {
1338       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1339       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1340     } else if (TyClass == Type::MemberPointer) {
1341       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1342       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1343     } else {
1344       return false;
1345     }
1346 
1347     TyClass = CanTo->getTypeClass();
1348     if (TyClass != CanFrom->getTypeClass()) return false;
1349     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1350       return false;
1351   }
1352 
1353   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1354   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1355   if (!EInfo.getNoReturn()) return false;
1356 
1357   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1358   assert(QualType(FromFn, 0).isCanonical());
1359   if (QualType(FromFn, 0) != CanTo) return false;
1360 
1361   ResultTy = ToType;
1362   return true;
1363 }
1364 
1365 /// \brief Determine whether the conversion from FromType to ToType is a valid
1366 /// vector conversion.
1367 ///
1368 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1369 /// conversion.
1370 static bool IsVectorConversion(Sema &S, QualType FromType,
1371                                QualType ToType, ImplicitConversionKind &ICK) {
1372   // We need at least one of these types to be a vector type to have a vector
1373   // conversion.
1374   if (!ToType->isVectorType() && !FromType->isVectorType())
1375     return false;
1376 
1377   // Identical types require no conversions.
1378   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1379     return false;
1380 
1381   // There are no conversions between extended vector types, only identity.
1382   if (ToType->isExtVectorType()) {
1383     // There are no conversions between extended vector types other than the
1384     // identity conversion.
1385     if (FromType->isExtVectorType())
1386       return false;
1387 
1388     // Vector splat from any arithmetic type to a vector.
1389     if (FromType->isArithmeticType()) {
1390       ICK = ICK_Vector_Splat;
1391       return true;
1392     }
1393   }
1394 
1395   // We can perform the conversion between vector types in the following cases:
1396   // 1)vector types are equivalent AltiVec and GCC vector types
1397   // 2)lax vector conversions are permitted and the vector types are of the
1398   //   same size
1399   if (ToType->isVectorType() && FromType->isVectorType()) {
1400     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1401         S.isLaxVectorConversion(FromType, ToType)) {
1402       ICK = ICK_Vector_Conversion;
1403       return true;
1404     }
1405   }
1406 
1407   return false;
1408 }
1409 
1410 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1411                                 bool InOverloadResolution,
1412                                 StandardConversionSequence &SCS,
1413                                 bool CStyle);
1414 
1415 /// IsStandardConversion - Determines whether there is a standard
1416 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1417 /// expression From to the type ToType. Standard conversion sequences
1418 /// only consider non-class types; for conversions that involve class
1419 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1420 /// contain the standard conversion sequence required to perform this
1421 /// conversion and this routine will return true. Otherwise, this
1422 /// routine will return false and the value of SCS is unspecified.
1423 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1424                                  bool InOverloadResolution,
1425                                  StandardConversionSequence &SCS,
1426                                  bool CStyle,
1427                                  bool AllowObjCWritebackConversion) {
1428   QualType FromType = From->getType();
1429 
1430   // Standard conversions (C++ [conv])
1431   SCS.setAsIdentityConversion();
1432   SCS.IncompatibleObjC = false;
1433   SCS.setFromType(FromType);
1434   SCS.CopyConstructor = nullptr;
1435 
1436   // There are no standard conversions for class types in C++, so
1437   // abort early. When overloading in C, however, we do permit
1438   if (FromType->isRecordType() || ToType->isRecordType()) {
1439     if (S.getLangOpts().CPlusPlus)
1440       return false;
1441 
1442     // When we're overloading in C, we allow, as standard conversions,
1443   }
1444 
1445   // The first conversion can be an lvalue-to-rvalue conversion,
1446   // array-to-pointer conversion, or function-to-pointer conversion
1447   // (C++ 4p1).
1448 
1449   if (FromType == S.Context.OverloadTy) {
1450     DeclAccessPair AccessPair;
1451     if (FunctionDecl *Fn
1452           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1453                                                  AccessPair)) {
1454       // We were able to resolve the address of the overloaded function,
1455       // so we can convert to the type of that function.
1456       FromType = Fn->getType();
1457       SCS.setFromType(FromType);
1458 
1459       // we can sometimes resolve &foo<int> regardless of ToType, so check
1460       // if the type matches (identity) or we are converting to bool
1461       if (!S.Context.hasSameUnqualifiedType(
1462                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1463         QualType resultTy;
1464         // if the function type matches except for [[noreturn]], it's ok
1465         if (!S.IsNoReturnConversion(FromType,
1466               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1467           // otherwise, only a boolean conversion is standard
1468           if (!ToType->isBooleanType())
1469             return false;
1470       }
1471 
1472       // Check if the "from" expression is taking the address of an overloaded
1473       // function and recompute the FromType accordingly. Take advantage of the
1474       // fact that non-static member functions *must* have such an address-of
1475       // expression.
1476       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1477       if (Method && !Method->isStatic()) {
1478         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1479                "Non-unary operator on non-static member address");
1480         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1481                == UO_AddrOf &&
1482                "Non-address-of operator on non-static member address");
1483         const Type *ClassType
1484           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1485         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1486       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1487         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1488                UO_AddrOf &&
1489                "Non-address-of operator for overloaded function expression");
1490         FromType = S.Context.getPointerType(FromType);
1491       }
1492 
1493       // Check that we've computed the proper type after overload resolution.
1494       assert(S.Context.hasSameType(
1495         FromType,
1496         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1497     } else {
1498       return false;
1499     }
1500   }
1501   // Lvalue-to-rvalue conversion (C++11 4.1):
1502   //   A glvalue (3.10) of a non-function, non-array type T can
1503   //   be converted to a prvalue.
1504   bool argIsLValue = From->isGLValue();
1505   if (argIsLValue &&
1506       !FromType->isFunctionType() && !FromType->isArrayType() &&
1507       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1508     SCS.First = ICK_Lvalue_To_Rvalue;
1509 
1510     // C11 6.3.2.1p2:
1511     //   ... if the lvalue has atomic type, the value has the non-atomic version
1512     //   of the type of the lvalue ...
1513     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1514       FromType = Atomic->getValueType();
1515 
1516     // If T is a non-class type, the type of the rvalue is the
1517     // cv-unqualified version of T. Otherwise, the type of the rvalue
1518     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1519     // just strip the qualifiers because they don't matter.
1520     FromType = FromType.getUnqualifiedType();
1521   } else if (FromType->isArrayType()) {
1522     // Array-to-pointer conversion (C++ 4.2)
1523     SCS.First = ICK_Array_To_Pointer;
1524 
1525     // An lvalue or rvalue of type "array of N T" or "array of unknown
1526     // bound of T" can be converted to an rvalue of type "pointer to
1527     // T" (C++ 4.2p1).
1528     FromType = S.Context.getArrayDecayedType(FromType);
1529 
1530     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1531       // This conversion is deprecated in C++03 (D.4)
1532       SCS.DeprecatedStringLiteralToCharPtr = true;
1533 
1534       // For the purpose of ranking in overload resolution
1535       // (13.3.3.1.1), this conversion is considered an
1536       // array-to-pointer conversion followed by a qualification
1537       // conversion (4.4). (C++ 4.2p2)
1538       SCS.Second = ICK_Identity;
1539       SCS.Third = ICK_Qualification;
1540       SCS.QualificationIncludesObjCLifetime = false;
1541       SCS.setAllToTypes(FromType);
1542       return true;
1543     }
1544   } else if (FromType->isFunctionType() && argIsLValue) {
1545     // Function-to-pointer conversion (C++ 4.3).
1546     SCS.First = ICK_Function_To_Pointer;
1547 
1548     // An lvalue of function type T can be converted to an rvalue of
1549     // type "pointer to T." The result is a pointer to the
1550     // function. (C++ 4.3p1).
1551     FromType = S.Context.getPointerType(FromType);
1552   } else {
1553     // We don't require any conversions for the first step.
1554     SCS.First = ICK_Identity;
1555   }
1556   SCS.setToType(0, FromType);
1557 
1558   // The second conversion can be an integral promotion, floating
1559   // point promotion, integral conversion, floating point conversion,
1560   // floating-integral conversion, pointer conversion,
1561   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1562   // For overloading in C, this can also be a "compatible-type"
1563   // conversion.
1564   bool IncompatibleObjC = false;
1565   ImplicitConversionKind SecondICK = ICK_Identity;
1566   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1567     // The unqualified versions of the types are the same: there's no
1568     // conversion to do.
1569     SCS.Second = ICK_Identity;
1570   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1571     // Integral promotion (C++ 4.5).
1572     SCS.Second = ICK_Integral_Promotion;
1573     FromType = ToType.getUnqualifiedType();
1574   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1575     // Floating point promotion (C++ 4.6).
1576     SCS.Second = ICK_Floating_Promotion;
1577     FromType = ToType.getUnqualifiedType();
1578   } else if (S.IsComplexPromotion(FromType, ToType)) {
1579     // Complex promotion (Clang extension)
1580     SCS.Second = ICK_Complex_Promotion;
1581     FromType = ToType.getUnqualifiedType();
1582   } else if (ToType->isBooleanType() &&
1583              (FromType->isArithmeticType() ||
1584               FromType->isAnyPointerType() ||
1585               FromType->isBlockPointerType() ||
1586               FromType->isMemberPointerType() ||
1587               FromType->isNullPtrType())) {
1588     // Boolean conversions (C++ 4.12).
1589     SCS.Second = ICK_Boolean_Conversion;
1590     FromType = S.Context.BoolTy;
1591   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1592              ToType->isIntegralType(S.Context)) {
1593     // Integral conversions (C++ 4.7).
1594     SCS.Second = ICK_Integral_Conversion;
1595     FromType = ToType.getUnqualifiedType();
1596   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1597     // Complex conversions (C99 6.3.1.6)
1598     SCS.Second = ICK_Complex_Conversion;
1599     FromType = ToType.getUnqualifiedType();
1600   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1601              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1602     // Complex-real conversions (C99 6.3.1.7)
1603     SCS.Second = ICK_Complex_Real;
1604     FromType = ToType.getUnqualifiedType();
1605   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1606     // Floating point conversions (C++ 4.8).
1607     SCS.Second = ICK_Floating_Conversion;
1608     FromType = ToType.getUnqualifiedType();
1609   } else if ((FromType->isRealFloatingType() &&
1610               ToType->isIntegralType(S.Context)) ||
1611              (FromType->isIntegralOrUnscopedEnumerationType() &&
1612               ToType->isRealFloatingType())) {
1613     // Floating-integral conversions (C++ 4.9).
1614     SCS.Second = ICK_Floating_Integral;
1615     FromType = ToType.getUnqualifiedType();
1616   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1617     SCS.Second = ICK_Block_Pointer_Conversion;
1618   } else if (AllowObjCWritebackConversion &&
1619              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1620     SCS.Second = ICK_Writeback_Conversion;
1621   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1622                                    FromType, IncompatibleObjC)) {
1623     // Pointer conversions (C++ 4.10).
1624     SCS.Second = ICK_Pointer_Conversion;
1625     SCS.IncompatibleObjC = IncompatibleObjC;
1626     FromType = FromType.getUnqualifiedType();
1627   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1628                                          InOverloadResolution, FromType)) {
1629     // Pointer to member conversions (4.11).
1630     SCS.Second = ICK_Pointer_Member;
1631   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1632     SCS.Second = SecondICK;
1633     FromType = ToType.getUnqualifiedType();
1634   } else if (!S.getLangOpts().CPlusPlus &&
1635              S.Context.typesAreCompatible(ToType, FromType)) {
1636     // Compatible conversions (Clang extension for C function overloading)
1637     SCS.Second = ICK_Compatible_Conversion;
1638     FromType = ToType.getUnqualifiedType();
1639   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1640     // Treat a conversion that strips "noreturn" as an identity conversion.
1641     SCS.Second = ICK_NoReturn_Adjustment;
1642   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1643                                              InOverloadResolution,
1644                                              SCS, CStyle)) {
1645     SCS.Second = ICK_TransparentUnionConversion;
1646     FromType = ToType;
1647   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1648                                  CStyle)) {
1649     // tryAtomicConversion has updated the standard conversion sequence
1650     // appropriately.
1651     return true;
1652   } else if (ToType->isEventT() &&
1653              From->isIntegerConstantExpr(S.getASTContext()) &&
1654              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1655     SCS.Second = ICK_Zero_Event_Conversion;
1656     FromType = ToType;
1657   } else {
1658     // No second conversion required.
1659     SCS.Second = ICK_Identity;
1660   }
1661   SCS.setToType(1, FromType);
1662 
1663   QualType CanonFrom;
1664   QualType CanonTo;
1665   // The third conversion can be a qualification conversion (C++ 4p1).
1666   bool ObjCLifetimeConversion;
1667   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1668                                   ObjCLifetimeConversion)) {
1669     SCS.Third = ICK_Qualification;
1670     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1671     FromType = ToType;
1672     CanonFrom = S.Context.getCanonicalType(FromType);
1673     CanonTo = S.Context.getCanonicalType(ToType);
1674   } else {
1675     // No conversion required
1676     SCS.Third = ICK_Identity;
1677 
1678     // C++ [over.best.ics]p6:
1679     //   [...] Any difference in top-level cv-qualification is
1680     //   subsumed by the initialization itself and does not constitute
1681     //   a conversion. [...]
1682     CanonFrom = S.Context.getCanonicalType(FromType);
1683     CanonTo = S.Context.getCanonicalType(ToType);
1684     if (CanonFrom.getLocalUnqualifiedType()
1685                                        == CanonTo.getLocalUnqualifiedType() &&
1686         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1687       FromType = ToType;
1688       CanonFrom = CanonTo;
1689     }
1690   }
1691   SCS.setToType(2, FromType);
1692 
1693   // If we have not converted the argument type to the parameter type,
1694   // this is a bad conversion sequence.
1695   if (CanonFrom != CanonTo)
1696     return false;
1697 
1698   return true;
1699 }
1700 
1701 static bool
1702 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1703                                      QualType &ToType,
1704                                      bool InOverloadResolution,
1705                                      StandardConversionSequence &SCS,
1706                                      bool CStyle) {
1707 
1708   const RecordType *UT = ToType->getAsUnionType();
1709   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1710     return false;
1711   // The field to initialize within the transparent union.
1712   RecordDecl *UD = UT->getDecl();
1713   // It's compatible if the expression matches any of the fields.
1714   for (const auto *it : UD->fields()) {
1715     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1716                              CStyle, /*ObjCWritebackConversion=*/false)) {
1717       ToType = it->getType();
1718       return true;
1719     }
1720   }
1721   return false;
1722 }
1723 
1724 /// IsIntegralPromotion - Determines whether the conversion from the
1725 /// expression From (whose potentially-adjusted type is FromType) to
1726 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1727 /// sets PromotedType to the promoted type.
1728 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1729   const BuiltinType *To = ToType->getAs<BuiltinType>();
1730   // All integers are built-in.
1731   if (!To) {
1732     return false;
1733   }
1734 
1735   // An rvalue of type char, signed char, unsigned char, short int, or
1736   // unsigned short int can be converted to an rvalue of type int if
1737   // int can represent all the values of the source type; otherwise,
1738   // the source rvalue can be converted to an rvalue of type unsigned
1739   // int (C++ 4.5p1).
1740   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1741       !FromType->isEnumeralType()) {
1742     if (// We can promote any signed, promotable integer type to an int
1743         (FromType->isSignedIntegerType() ||
1744          // We can promote any unsigned integer type whose size is
1745          // less than int to an int.
1746          (!FromType->isSignedIntegerType() &&
1747           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1748       return To->getKind() == BuiltinType::Int;
1749     }
1750 
1751     return To->getKind() == BuiltinType::UInt;
1752   }
1753 
1754   // C++11 [conv.prom]p3:
1755   //   A prvalue of an unscoped enumeration type whose underlying type is not
1756   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1757   //   following types that can represent all the values of the enumeration
1758   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1759   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1760   //   long long int. If none of the types in that list can represent all the
1761   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1762   //   type can be converted to an rvalue a prvalue of the extended integer type
1763   //   with lowest integer conversion rank (4.13) greater than the rank of long
1764   //   long in which all the values of the enumeration can be represented. If
1765   //   there are two such extended types, the signed one is chosen.
1766   // C++11 [conv.prom]p4:
1767   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1768   //   can be converted to a prvalue of its underlying type. Moreover, if
1769   //   integral promotion can be applied to its underlying type, a prvalue of an
1770   //   unscoped enumeration type whose underlying type is fixed can also be
1771   //   converted to a prvalue of the promoted underlying type.
1772   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1773     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1774     // provided for a scoped enumeration.
1775     if (FromEnumType->getDecl()->isScoped())
1776       return false;
1777 
1778     // We can perform an integral promotion to the underlying type of the enum,
1779     // even if that's not the promoted type. Note that the check for promoting
1780     // the underlying type is based on the type alone, and does not consider
1781     // the bitfield-ness of the actual source expression.
1782     if (FromEnumType->getDecl()->isFixed()) {
1783       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1784       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1785              IsIntegralPromotion(nullptr, Underlying, ToType);
1786     }
1787 
1788     // We have already pre-calculated the promotion type, so this is trivial.
1789     if (ToType->isIntegerType() &&
1790         !RequireCompleteType(From->getLocStart(), FromType, 0))
1791       return Context.hasSameUnqualifiedType(
1792           ToType, FromEnumType->getDecl()->getPromotionType());
1793   }
1794 
1795   // C++0x [conv.prom]p2:
1796   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1797   //   to an rvalue a prvalue of the first of the following types that can
1798   //   represent all the values of its underlying type: int, unsigned int,
1799   //   long int, unsigned long int, long long int, or unsigned long long int.
1800   //   If none of the types in that list can represent all the values of its
1801   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1802   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1803   //   type.
1804   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1805       ToType->isIntegerType()) {
1806     // Determine whether the type we're converting from is signed or
1807     // unsigned.
1808     bool FromIsSigned = FromType->isSignedIntegerType();
1809     uint64_t FromSize = Context.getTypeSize(FromType);
1810 
1811     // The types we'll try to promote to, in the appropriate
1812     // order. Try each of these types.
1813     QualType PromoteTypes[6] = {
1814       Context.IntTy, Context.UnsignedIntTy,
1815       Context.LongTy, Context.UnsignedLongTy ,
1816       Context.LongLongTy, Context.UnsignedLongLongTy
1817     };
1818     for (int Idx = 0; Idx < 6; ++Idx) {
1819       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1820       if (FromSize < ToSize ||
1821           (FromSize == ToSize &&
1822            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1823         // We found the type that we can promote to. If this is the
1824         // type we wanted, we have a promotion. Otherwise, no
1825         // promotion.
1826         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1827       }
1828     }
1829   }
1830 
1831   // An rvalue for an integral bit-field (9.6) can be converted to an
1832   // rvalue of type int if int can represent all the values of the
1833   // bit-field; otherwise, it can be converted to unsigned int if
1834   // unsigned int can represent all the values of the bit-field. If
1835   // the bit-field is larger yet, no integral promotion applies to
1836   // it. If the bit-field has an enumerated type, it is treated as any
1837   // other value of that type for promotion purposes (C++ 4.5p3).
1838   // FIXME: We should delay checking of bit-fields until we actually perform the
1839   // conversion.
1840   if (From) {
1841     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1842       llvm::APSInt BitWidth;
1843       if (FromType->isIntegralType(Context) &&
1844           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1845         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1846         ToSize = Context.getTypeSize(ToType);
1847 
1848         // Are we promoting to an int from a bitfield that fits in an int?
1849         if (BitWidth < ToSize ||
1850             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1851           return To->getKind() == BuiltinType::Int;
1852         }
1853 
1854         // Are we promoting to an unsigned int from an unsigned bitfield
1855         // that fits into an unsigned int?
1856         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1857           return To->getKind() == BuiltinType::UInt;
1858         }
1859 
1860         return false;
1861       }
1862     }
1863   }
1864 
1865   // An rvalue of type bool can be converted to an rvalue of type int,
1866   // with false becoming zero and true becoming one (C++ 4.5p4).
1867   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1868     return true;
1869   }
1870 
1871   return false;
1872 }
1873 
1874 /// IsFloatingPointPromotion - Determines whether the conversion from
1875 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1876 /// returns true and sets PromotedType to the promoted type.
1877 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1878   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1879     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1880       /// An rvalue of type float can be converted to an rvalue of type
1881       /// double. (C++ 4.6p1).
1882       if (FromBuiltin->getKind() == BuiltinType::Float &&
1883           ToBuiltin->getKind() == BuiltinType::Double)
1884         return true;
1885 
1886       // C99 6.3.1.5p1:
1887       //   When a float is promoted to double or long double, or a
1888       //   double is promoted to long double [...].
1889       if (!getLangOpts().CPlusPlus &&
1890           (FromBuiltin->getKind() == BuiltinType::Float ||
1891            FromBuiltin->getKind() == BuiltinType::Double) &&
1892           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1893         return true;
1894 
1895       // Half can be promoted to float.
1896       if (!getLangOpts().NativeHalfType &&
1897            FromBuiltin->getKind() == BuiltinType::Half &&
1898           ToBuiltin->getKind() == BuiltinType::Float)
1899         return true;
1900     }
1901 
1902   return false;
1903 }
1904 
1905 /// \brief Determine if a conversion is a complex promotion.
1906 ///
1907 /// A complex promotion is defined as a complex -> complex conversion
1908 /// where the conversion between the underlying real types is a
1909 /// floating-point or integral promotion.
1910 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1911   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1912   if (!FromComplex)
1913     return false;
1914 
1915   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1916   if (!ToComplex)
1917     return false;
1918 
1919   return IsFloatingPointPromotion(FromComplex->getElementType(),
1920                                   ToComplex->getElementType()) ||
1921     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1922                         ToComplex->getElementType());
1923 }
1924 
1925 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1926 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1927 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1928 /// if non-empty, will be a pointer to ToType that may or may not have
1929 /// the right set of qualifiers on its pointee.
1930 ///
1931 static QualType
1932 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1933                                    QualType ToPointee, QualType ToType,
1934                                    ASTContext &Context,
1935                                    bool StripObjCLifetime = false) {
1936   assert((FromPtr->getTypeClass() == Type::Pointer ||
1937           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1938          "Invalid similarly-qualified pointer type");
1939 
1940   /// Conversions to 'id' subsume cv-qualifier conversions.
1941   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1942     return ToType.getUnqualifiedType();
1943 
1944   QualType CanonFromPointee
1945     = Context.getCanonicalType(FromPtr->getPointeeType());
1946   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1947   Qualifiers Quals = CanonFromPointee.getQualifiers();
1948 
1949   if (StripObjCLifetime)
1950     Quals.removeObjCLifetime();
1951 
1952   // Exact qualifier match -> return the pointer type we're converting to.
1953   if (CanonToPointee.getLocalQualifiers() == Quals) {
1954     // ToType is exactly what we need. Return it.
1955     if (!ToType.isNull())
1956       return ToType.getUnqualifiedType();
1957 
1958     // Build a pointer to ToPointee. It has the right qualifiers
1959     // already.
1960     if (isa<ObjCObjectPointerType>(ToType))
1961       return Context.getObjCObjectPointerType(ToPointee);
1962     return Context.getPointerType(ToPointee);
1963   }
1964 
1965   // Just build a canonical type that has the right qualifiers.
1966   QualType QualifiedCanonToPointee
1967     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1968 
1969   if (isa<ObjCObjectPointerType>(ToType))
1970     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1971   return Context.getPointerType(QualifiedCanonToPointee);
1972 }
1973 
1974 static bool isNullPointerConstantForConversion(Expr *Expr,
1975                                                bool InOverloadResolution,
1976                                                ASTContext &Context) {
1977   // Handle value-dependent integral null pointer constants correctly.
1978   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1979   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1980       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1981     return !InOverloadResolution;
1982 
1983   return Expr->isNullPointerConstant(Context,
1984                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1985                                         : Expr::NPC_ValueDependentIsNull);
1986 }
1987 
1988 /// IsPointerConversion - Determines whether the conversion of the
1989 /// expression From, which has the (possibly adjusted) type FromType,
1990 /// can be converted to the type ToType via a pointer conversion (C++
1991 /// 4.10). If so, returns true and places the converted type (that
1992 /// might differ from ToType in its cv-qualifiers at some level) into
1993 /// ConvertedType.
1994 ///
1995 /// This routine also supports conversions to and from block pointers
1996 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1997 /// pointers to interfaces. FIXME: Once we've determined the
1998 /// appropriate overloading rules for Objective-C, we may want to
1999 /// split the Objective-C checks into a different routine; however,
2000 /// GCC seems to consider all of these conversions to be pointer
2001 /// conversions, so for now they live here. IncompatibleObjC will be
2002 /// set if the conversion is an allowed Objective-C conversion that
2003 /// should result in a warning.
2004 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2005                                bool InOverloadResolution,
2006                                QualType& ConvertedType,
2007                                bool &IncompatibleObjC) {
2008   IncompatibleObjC = false;
2009   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2010                               IncompatibleObjC))
2011     return true;
2012 
2013   // Conversion from a null pointer constant to any Objective-C pointer type.
2014   if (ToType->isObjCObjectPointerType() &&
2015       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2016     ConvertedType = ToType;
2017     return true;
2018   }
2019 
2020   // Blocks: Block pointers can be converted to void*.
2021   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2022       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2023     ConvertedType = ToType;
2024     return true;
2025   }
2026   // Blocks: A null pointer constant can be converted to a block
2027   // pointer type.
2028   if (ToType->isBlockPointerType() &&
2029       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2030     ConvertedType = ToType;
2031     return true;
2032   }
2033 
2034   // If the left-hand-side is nullptr_t, the right side can be a null
2035   // pointer constant.
2036   if (ToType->isNullPtrType() &&
2037       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2038     ConvertedType = ToType;
2039     return true;
2040   }
2041 
2042   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2043   if (!ToTypePtr)
2044     return false;
2045 
2046   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2047   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2048     ConvertedType = ToType;
2049     return true;
2050   }
2051 
2052   // Beyond this point, both types need to be pointers
2053   // , including objective-c pointers.
2054   QualType ToPointeeType = ToTypePtr->getPointeeType();
2055   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2056       !getLangOpts().ObjCAutoRefCount) {
2057     ConvertedType = BuildSimilarlyQualifiedPointerType(
2058                                       FromType->getAs<ObjCObjectPointerType>(),
2059                                                        ToPointeeType,
2060                                                        ToType, Context);
2061     return true;
2062   }
2063   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2064   if (!FromTypePtr)
2065     return false;
2066 
2067   QualType FromPointeeType = FromTypePtr->getPointeeType();
2068 
2069   // If the unqualified pointee types are the same, this can't be a
2070   // pointer conversion, so don't do all of the work below.
2071   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2072     return false;
2073 
2074   // An rvalue of type "pointer to cv T," where T is an object type,
2075   // can be converted to an rvalue of type "pointer to cv void" (C++
2076   // 4.10p2).
2077   if (FromPointeeType->isIncompleteOrObjectType() &&
2078       ToPointeeType->isVoidType()) {
2079     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2080                                                        ToPointeeType,
2081                                                        ToType, Context,
2082                                                    /*StripObjCLifetime=*/true);
2083     return true;
2084   }
2085 
2086   // MSVC allows implicit function to void* type conversion.
2087   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2088       ToPointeeType->isVoidType()) {
2089     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2090                                                        ToPointeeType,
2091                                                        ToType, Context);
2092     return true;
2093   }
2094 
2095   // When we're overloading in C, we allow a special kind of pointer
2096   // conversion for compatible-but-not-identical pointee types.
2097   if (!getLangOpts().CPlusPlus &&
2098       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2099     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2100                                                        ToPointeeType,
2101                                                        ToType, Context);
2102     return true;
2103   }
2104 
2105   // C++ [conv.ptr]p3:
2106   //
2107   //   An rvalue of type "pointer to cv D," where D is a class type,
2108   //   can be converted to an rvalue of type "pointer to cv B," where
2109   //   B is a base class (clause 10) of D. If B is an inaccessible
2110   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2111   //   necessitates this conversion is ill-formed. The result of the
2112   //   conversion is a pointer to the base class sub-object of the
2113   //   derived class object. The null pointer value is converted to
2114   //   the null pointer value of the destination type.
2115   //
2116   // Note that we do not check for ambiguity or inaccessibility
2117   // here. That is handled by CheckPointerConversion.
2118   if (getLangOpts().CPlusPlus &&
2119       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2120       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2121       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2122       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2123     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2124                                                        ToPointeeType,
2125                                                        ToType, Context);
2126     return true;
2127   }
2128 
2129   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2130       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2131     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2132                                                        ToPointeeType,
2133                                                        ToType, Context);
2134     return true;
2135   }
2136 
2137   return false;
2138 }
2139 
2140 /// \brief Adopt the given qualifiers for the given type.
2141 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2142   Qualifiers TQs = T.getQualifiers();
2143 
2144   // Check whether qualifiers already match.
2145   if (TQs == Qs)
2146     return T;
2147 
2148   if (Qs.compatiblyIncludes(TQs))
2149     return Context.getQualifiedType(T, Qs);
2150 
2151   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2152 }
2153 
2154 /// isObjCPointerConversion - Determines whether this is an
2155 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2156 /// with the same arguments and return values.
2157 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2158                                    QualType& ConvertedType,
2159                                    bool &IncompatibleObjC) {
2160   if (!getLangOpts().ObjC1)
2161     return false;
2162 
2163   // The set of qualifiers on the type we're converting from.
2164   Qualifiers FromQualifiers = FromType.getQualifiers();
2165 
2166   // First, we handle all conversions on ObjC object pointer types.
2167   const ObjCObjectPointerType* ToObjCPtr =
2168     ToType->getAs<ObjCObjectPointerType>();
2169   const ObjCObjectPointerType *FromObjCPtr =
2170     FromType->getAs<ObjCObjectPointerType>();
2171 
2172   if (ToObjCPtr && FromObjCPtr) {
2173     // If the pointee types are the same (ignoring qualifications),
2174     // then this is not a pointer conversion.
2175     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2176                                        FromObjCPtr->getPointeeType()))
2177       return false;
2178 
2179     // Conversion between Objective-C pointers.
2180     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2181       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2182       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2183       if (getLangOpts().CPlusPlus && LHS && RHS &&
2184           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2185                                                 FromObjCPtr->getPointeeType()))
2186         return false;
2187       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2188                                                    ToObjCPtr->getPointeeType(),
2189                                                          ToType, Context);
2190       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2191       return true;
2192     }
2193 
2194     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2195       // Okay: this is some kind of implicit downcast of Objective-C
2196       // interfaces, which is permitted. However, we're going to
2197       // complain about it.
2198       IncompatibleObjC = true;
2199       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2200                                                    ToObjCPtr->getPointeeType(),
2201                                                          ToType, Context);
2202       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2203       return true;
2204     }
2205   }
2206   // Beyond this point, both types need to be C pointers or block pointers.
2207   QualType ToPointeeType;
2208   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2209     ToPointeeType = ToCPtr->getPointeeType();
2210   else if (const BlockPointerType *ToBlockPtr =
2211             ToType->getAs<BlockPointerType>()) {
2212     // Objective C++: We're able to convert from a pointer to any object
2213     // to a block pointer type.
2214     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2215       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2216       return true;
2217     }
2218     ToPointeeType = ToBlockPtr->getPointeeType();
2219   }
2220   else if (FromType->getAs<BlockPointerType>() &&
2221            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2222     // Objective C++: We're able to convert from a block pointer type to a
2223     // pointer to any object.
2224     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2225     return true;
2226   }
2227   else
2228     return false;
2229 
2230   QualType FromPointeeType;
2231   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2232     FromPointeeType = FromCPtr->getPointeeType();
2233   else if (const BlockPointerType *FromBlockPtr =
2234            FromType->getAs<BlockPointerType>())
2235     FromPointeeType = FromBlockPtr->getPointeeType();
2236   else
2237     return false;
2238 
2239   // If we have pointers to pointers, recursively check whether this
2240   // is an Objective-C conversion.
2241   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2242       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2243                               IncompatibleObjC)) {
2244     // We always complain about this conversion.
2245     IncompatibleObjC = true;
2246     ConvertedType = Context.getPointerType(ConvertedType);
2247     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2248     return true;
2249   }
2250   // Allow conversion of pointee being objective-c pointer to another one;
2251   // as in I* to id.
2252   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2253       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2254       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2255                               IncompatibleObjC)) {
2256 
2257     ConvertedType = Context.getPointerType(ConvertedType);
2258     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2259     return true;
2260   }
2261 
2262   // If we have pointers to functions or blocks, check whether the only
2263   // differences in the argument and result types are in Objective-C
2264   // pointer conversions. If so, we permit the conversion (but
2265   // complain about it).
2266   const FunctionProtoType *FromFunctionType
2267     = FromPointeeType->getAs<FunctionProtoType>();
2268   const FunctionProtoType *ToFunctionType
2269     = ToPointeeType->getAs<FunctionProtoType>();
2270   if (FromFunctionType && ToFunctionType) {
2271     // If the function types are exactly the same, this isn't an
2272     // Objective-C pointer conversion.
2273     if (Context.getCanonicalType(FromPointeeType)
2274           == Context.getCanonicalType(ToPointeeType))
2275       return false;
2276 
2277     // Perform the quick checks that will tell us whether these
2278     // function types are obviously different.
2279     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2280         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2281         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2282       return false;
2283 
2284     bool HasObjCConversion = false;
2285     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2286         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2287       // Okay, the types match exactly. Nothing to do.
2288     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2289                                        ToFunctionType->getReturnType(),
2290                                        ConvertedType, IncompatibleObjC)) {
2291       // Okay, we have an Objective-C pointer conversion.
2292       HasObjCConversion = true;
2293     } else {
2294       // Function types are too different. Abort.
2295       return false;
2296     }
2297 
2298     // Check argument types.
2299     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2300          ArgIdx != NumArgs; ++ArgIdx) {
2301       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2302       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2303       if (Context.getCanonicalType(FromArgType)
2304             == Context.getCanonicalType(ToArgType)) {
2305         // Okay, the types match exactly. Nothing to do.
2306       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2307                                          ConvertedType, IncompatibleObjC)) {
2308         // Okay, we have an Objective-C pointer conversion.
2309         HasObjCConversion = true;
2310       } else {
2311         // Argument types are too different. Abort.
2312         return false;
2313       }
2314     }
2315 
2316     if (HasObjCConversion) {
2317       // We had an Objective-C conversion. Allow this pointer
2318       // conversion, but complain about it.
2319       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2320       IncompatibleObjC = true;
2321       return true;
2322     }
2323   }
2324 
2325   return false;
2326 }
2327 
2328 /// \brief Determine whether this is an Objective-C writeback conversion,
2329 /// used for parameter passing when performing automatic reference counting.
2330 ///
2331 /// \param FromType The type we're converting form.
2332 ///
2333 /// \param ToType The type we're converting to.
2334 ///
2335 /// \param ConvertedType The type that will be produced after applying
2336 /// this conversion.
2337 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2338                                      QualType &ConvertedType) {
2339   if (!getLangOpts().ObjCAutoRefCount ||
2340       Context.hasSameUnqualifiedType(FromType, ToType))
2341     return false;
2342 
2343   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2344   QualType ToPointee;
2345   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2346     ToPointee = ToPointer->getPointeeType();
2347   else
2348     return false;
2349 
2350   Qualifiers ToQuals = ToPointee.getQualifiers();
2351   if (!ToPointee->isObjCLifetimeType() ||
2352       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2353       !ToQuals.withoutObjCLifetime().empty())
2354     return false;
2355 
2356   // Argument must be a pointer to __strong to __weak.
2357   QualType FromPointee;
2358   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2359     FromPointee = FromPointer->getPointeeType();
2360   else
2361     return false;
2362 
2363   Qualifiers FromQuals = FromPointee.getQualifiers();
2364   if (!FromPointee->isObjCLifetimeType() ||
2365       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2366        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2367     return false;
2368 
2369   // Make sure that we have compatible qualifiers.
2370   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2371   if (!ToQuals.compatiblyIncludes(FromQuals))
2372     return false;
2373 
2374   // Remove qualifiers from the pointee type we're converting from; they
2375   // aren't used in the compatibility check belong, and we'll be adding back
2376   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2377   FromPointee = FromPointee.getUnqualifiedType();
2378 
2379   // The unqualified form of the pointee types must be compatible.
2380   ToPointee = ToPointee.getUnqualifiedType();
2381   bool IncompatibleObjC;
2382   if (Context.typesAreCompatible(FromPointee, ToPointee))
2383     FromPointee = ToPointee;
2384   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2385                                     IncompatibleObjC))
2386     return false;
2387 
2388   /// \brief Construct the type we're converting to, which is a pointer to
2389   /// __autoreleasing pointee.
2390   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2391   ConvertedType = Context.getPointerType(FromPointee);
2392   return true;
2393 }
2394 
2395 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2396                                     QualType& ConvertedType) {
2397   QualType ToPointeeType;
2398   if (const BlockPointerType *ToBlockPtr =
2399         ToType->getAs<BlockPointerType>())
2400     ToPointeeType = ToBlockPtr->getPointeeType();
2401   else
2402     return false;
2403 
2404   QualType FromPointeeType;
2405   if (const BlockPointerType *FromBlockPtr =
2406       FromType->getAs<BlockPointerType>())
2407     FromPointeeType = FromBlockPtr->getPointeeType();
2408   else
2409     return false;
2410   // We have pointer to blocks, check whether the only
2411   // differences in the argument and result types are in Objective-C
2412   // pointer conversions. If so, we permit the conversion.
2413 
2414   const FunctionProtoType *FromFunctionType
2415     = FromPointeeType->getAs<FunctionProtoType>();
2416   const FunctionProtoType *ToFunctionType
2417     = ToPointeeType->getAs<FunctionProtoType>();
2418 
2419   if (!FromFunctionType || !ToFunctionType)
2420     return false;
2421 
2422   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2423     return true;
2424 
2425   // Perform the quick checks that will tell us whether these
2426   // function types are obviously different.
2427   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2428       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2429     return false;
2430 
2431   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2432   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2433   if (FromEInfo != ToEInfo)
2434     return false;
2435 
2436   bool IncompatibleObjC = false;
2437   if (Context.hasSameType(FromFunctionType->getReturnType(),
2438                           ToFunctionType->getReturnType())) {
2439     // Okay, the types match exactly. Nothing to do.
2440   } else {
2441     QualType RHS = FromFunctionType->getReturnType();
2442     QualType LHS = ToFunctionType->getReturnType();
2443     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2444         !RHS.hasQualifiers() && LHS.hasQualifiers())
2445        LHS = LHS.getUnqualifiedType();
2446 
2447      if (Context.hasSameType(RHS,LHS)) {
2448        // OK exact match.
2449      } else if (isObjCPointerConversion(RHS, LHS,
2450                                         ConvertedType, IncompatibleObjC)) {
2451      if (IncompatibleObjC)
2452        return false;
2453      // Okay, we have an Objective-C pointer conversion.
2454      }
2455      else
2456        return false;
2457    }
2458 
2459    // Check argument types.
2460    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2461         ArgIdx != NumArgs; ++ArgIdx) {
2462      IncompatibleObjC = false;
2463      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2464      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2465      if (Context.hasSameType(FromArgType, ToArgType)) {
2466        // Okay, the types match exactly. Nothing to do.
2467      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2468                                         ConvertedType, IncompatibleObjC)) {
2469        if (IncompatibleObjC)
2470          return false;
2471        // Okay, we have an Objective-C pointer conversion.
2472      } else
2473        // Argument types are too different. Abort.
2474        return false;
2475    }
2476    if (LangOpts.ObjCAutoRefCount &&
2477        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2478                                                     ToFunctionType))
2479      return false;
2480 
2481    ConvertedType = ToType;
2482    return true;
2483 }
2484 
2485 enum {
2486   ft_default,
2487   ft_different_class,
2488   ft_parameter_arity,
2489   ft_parameter_mismatch,
2490   ft_return_type,
2491   ft_qualifer_mismatch
2492 };
2493 
2494 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2495 /// function types.  Catches different number of parameter, mismatch in
2496 /// parameter types, and different return types.
2497 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2498                                       QualType FromType, QualType ToType) {
2499   // If either type is not valid, include no extra info.
2500   if (FromType.isNull() || ToType.isNull()) {
2501     PDiag << ft_default;
2502     return;
2503   }
2504 
2505   // Get the function type from the pointers.
2506   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2507     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2508                             *ToMember = ToType->getAs<MemberPointerType>();
2509     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2510       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2511             << QualType(FromMember->getClass(), 0);
2512       return;
2513     }
2514     FromType = FromMember->getPointeeType();
2515     ToType = ToMember->getPointeeType();
2516   }
2517 
2518   if (FromType->isPointerType())
2519     FromType = FromType->getPointeeType();
2520   if (ToType->isPointerType())
2521     ToType = ToType->getPointeeType();
2522 
2523   // Remove references.
2524   FromType = FromType.getNonReferenceType();
2525   ToType = ToType.getNonReferenceType();
2526 
2527   // Don't print extra info for non-specialized template functions.
2528   if (FromType->isInstantiationDependentType() &&
2529       !FromType->getAs<TemplateSpecializationType>()) {
2530     PDiag << ft_default;
2531     return;
2532   }
2533 
2534   // No extra info for same types.
2535   if (Context.hasSameType(FromType, ToType)) {
2536     PDiag << ft_default;
2537     return;
2538   }
2539 
2540   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2541                           *ToFunction = ToType->getAs<FunctionProtoType>();
2542 
2543   // Both types need to be function types.
2544   if (!FromFunction || !ToFunction) {
2545     PDiag << ft_default;
2546     return;
2547   }
2548 
2549   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2550     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2551           << FromFunction->getNumParams();
2552     return;
2553   }
2554 
2555   // Handle different parameter types.
2556   unsigned ArgPos;
2557   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2558     PDiag << ft_parameter_mismatch << ArgPos + 1
2559           << ToFunction->getParamType(ArgPos)
2560           << FromFunction->getParamType(ArgPos);
2561     return;
2562   }
2563 
2564   // Handle different return type.
2565   if (!Context.hasSameType(FromFunction->getReturnType(),
2566                            ToFunction->getReturnType())) {
2567     PDiag << ft_return_type << ToFunction->getReturnType()
2568           << FromFunction->getReturnType();
2569     return;
2570   }
2571 
2572   unsigned FromQuals = FromFunction->getTypeQuals(),
2573            ToQuals = ToFunction->getTypeQuals();
2574   if (FromQuals != ToQuals) {
2575     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2576     return;
2577   }
2578 
2579   // Unable to find a difference, so add no extra info.
2580   PDiag << ft_default;
2581 }
2582 
2583 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2584 /// for equality of their argument types. Caller has already checked that
2585 /// they have same number of arguments.  If the parameters are different,
2586 /// ArgPos will have the parameter index of the first different parameter.
2587 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2588                                       const FunctionProtoType *NewType,
2589                                       unsigned *ArgPos) {
2590   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2591                                               N = NewType->param_type_begin(),
2592                                               E = OldType->param_type_end();
2593        O && (O != E); ++O, ++N) {
2594     if (!Context.hasSameType(O->getUnqualifiedType(),
2595                              N->getUnqualifiedType())) {
2596       if (ArgPos)
2597         *ArgPos = O - OldType->param_type_begin();
2598       return false;
2599     }
2600   }
2601   return true;
2602 }
2603 
2604 /// CheckPointerConversion - Check the pointer conversion from the
2605 /// expression From to the type ToType. This routine checks for
2606 /// ambiguous or inaccessible derived-to-base pointer
2607 /// conversions for which IsPointerConversion has already returned
2608 /// true. It returns true and produces a diagnostic if there was an
2609 /// error, or returns false otherwise.
2610 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2611                                   CastKind &Kind,
2612                                   CXXCastPath& BasePath,
2613                                   bool IgnoreBaseAccess) {
2614   QualType FromType = From->getType();
2615   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2616 
2617   Kind = CK_BitCast;
2618 
2619   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2620       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2621       Expr::NPCK_ZeroExpression) {
2622     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2623       DiagRuntimeBehavior(From->getExprLoc(), From,
2624                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2625                             << ToType << From->getSourceRange());
2626     else if (!isUnevaluatedContext())
2627       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2628         << ToType << From->getSourceRange();
2629   }
2630   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2631     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2632       QualType FromPointeeType = FromPtrType->getPointeeType(),
2633                ToPointeeType   = ToPtrType->getPointeeType();
2634 
2635       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2636           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2637         // We must have a derived-to-base conversion. Check an
2638         // ambiguous or inaccessible conversion.
2639         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2640                                          From->getExprLoc(),
2641                                          From->getSourceRange(), &BasePath,
2642                                          IgnoreBaseAccess))
2643           return true;
2644 
2645         // The conversion was successful.
2646         Kind = CK_DerivedToBase;
2647       }
2648     }
2649   } else if (const ObjCObjectPointerType *ToPtrType =
2650                ToType->getAs<ObjCObjectPointerType>()) {
2651     if (const ObjCObjectPointerType *FromPtrType =
2652           FromType->getAs<ObjCObjectPointerType>()) {
2653       // Objective-C++ conversions are always okay.
2654       // FIXME: We should have a different class of conversions for the
2655       // Objective-C++ implicit conversions.
2656       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2657         return false;
2658     } else if (FromType->isBlockPointerType()) {
2659       Kind = CK_BlockPointerToObjCPointerCast;
2660     } else {
2661       Kind = CK_CPointerToObjCPointerCast;
2662     }
2663   } else if (ToType->isBlockPointerType()) {
2664     if (!FromType->isBlockPointerType())
2665       Kind = CK_AnyPointerToBlockPointerCast;
2666   }
2667 
2668   // We shouldn't fall into this case unless it's valid for other
2669   // reasons.
2670   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2671     Kind = CK_NullToPointer;
2672 
2673   return false;
2674 }
2675 
2676 /// IsMemberPointerConversion - Determines whether the conversion of the
2677 /// expression From, which has the (possibly adjusted) type FromType, can be
2678 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2679 /// If so, returns true and places the converted type (that might differ from
2680 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2681 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2682                                      QualType ToType,
2683                                      bool InOverloadResolution,
2684                                      QualType &ConvertedType) {
2685   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2686   if (!ToTypePtr)
2687     return false;
2688 
2689   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2690   if (From->isNullPointerConstant(Context,
2691                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2692                                         : Expr::NPC_ValueDependentIsNull)) {
2693     ConvertedType = ToType;
2694     return true;
2695   }
2696 
2697   // Otherwise, both types have to be member pointers.
2698   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2699   if (!FromTypePtr)
2700     return false;
2701 
2702   // A pointer to member of B can be converted to a pointer to member of D,
2703   // where D is derived from B (C++ 4.11p2).
2704   QualType FromClass(FromTypePtr->getClass(), 0);
2705   QualType ToClass(ToTypePtr->getClass(), 0);
2706 
2707   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2708       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2709       IsDerivedFrom(ToClass, FromClass)) {
2710     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2711                                                  ToClass.getTypePtr());
2712     return true;
2713   }
2714 
2715   return false;
2716 }
2717 
2718 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2719 /// expression From to the type ToType. This routine checks for ambiguous or
2720 /// virtual or inaccessible base-to-derived member pointer conversions
2721 /// for which IsMemberPointerConversion has already returned true. It returns
2722 /// true and produces a diagnostic if there was an error, or returns false
2723 /// otherwise.
2724 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2725                                         CastKind &Kind,
2726                                         CXXCastPath &BasePath,
2727                                         bool IgnoreBaseAccess) {
2728   QualType FromType = From->getType();
2729   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2730   if (!FromPtrType) {
2731     // This must be a null pointer to member pointer conversion
2732     assert(From->isNullPointerConstant(Context,
2733                                        Expr::NPC_ValueDependentIsNull) &&
2734            "Expr must be null pointer constant!");
2735     Kind = CK_NullToMemberPointer;
2736     return false;
2737   }
2738 
2739   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2740   assert(ToPtrType && "No member pointer cast has a target type "
2741                       "that is not a member pointer.");
2742 
2743   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2744   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2745 
2746   // FIXME: What about dependent types?
2747   assert(FromClass->isRecordType() && "Pointer into non-class.");
2748   assert(ToClass->isRecordType() && "Pointer into non-class.");
2749 
2750   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2751                      /*DetectVirtual=*/true);
2752   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2753   assert(DerivationOkay &&
2754          "Should not have been called if derivation isn't OK.");
2755   (void)DerivationOkay;
2756 
2757   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2758                                   getUnqualifiedType())) {
2759     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2760     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2761       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2762     return true;
2763   }
2764 
2765   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2766     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2767       << FromClass << ToClass << QualType(VBase, 0)
2768       << From->getSourceRange();
2769     return true;
2770   }
2771 
2772   if (!IgnoreBaseAccess)
2773     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2774                          Paths.front(),
2775                          diag::err_downcast_from_inaccessible_base);
2776 
2777   // Must be a base to derived member conversion.
2778   BuildBasePathArray(Paths, BasePath);
2779   Kind = CK_BaseToDerivedMemberPointer;
2780   return false;
2781 }
2782 
2783 /// Determine whether the lifetime conversion between the two given
2784 /// qualifiers sets is nontrivial.
2785 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2786                                                Qualifiers ToQuals) {
2787   // Converting anything to const __unsafe_unretained is trivial.
2788   if (ToQuals.hasConst() &&
2789       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2790     return false;
2791 
2792   return true;
2793 }
2794 
2795 /// IsQualificationConversion - Determines whether the conversion from
2796 /// an rvalue of type FromType to ToType is a qualification conversion
2797 /// (C++ 4.4).
2798 ///
2799 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2800 /// when the qualification conversion involves a change in the Objective-C
2801 /// object lifetime.
2802 bool
2803 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2804                                 bool CStyle, bool &ObjCLifetimeConversion) {
2805   FromType = Context.getCanonicalType(FromType);
2806   ToType = Context.getCanonicalType(ToType);
2807   ObjCLifetimeConversion = false;
2808 
2809   // If FromType and ToType are the same type, this is not a
2810   // qualification conversion.
2811   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2812     return false;
2813 
2814   // (C++ 4.4p4):
2815   //   A conversion can add cv-qualifiers at levels other than the first
2816   //   in multi-level pointers, subject to the following rules: [...]
2817   bool PreviousToQualsIncludeConst = true;
2818   bool UnwrappedAnyPointer = false;
2819   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2820     // Within each iteration of the loop, we check the qualifiers to
2821     // determine if this still looks like a qualification
2822     // conversion. Then, if all is well, we unwrap one more level of
2823     // pointers or pointers-to-members and do it all again
2824     // until there are no more pointers or pointers-to-members left to
2825     // unwrap.
2826     UnwrappedAnyPointer = true;
2827 
2828     Qualifiers FromQuals = FromType.getQualifiers();
2829     Qualifiers ToQuals = ToType.getQualifiers();
2830 
2831     // Objective-C ARC:
2832     //   Check Objective-C lifetime conversions.
2833     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2834         UnwrappedAnyPointer) {
2835       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2836         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2837           ObjCLifetimeConversion = true;
2838         FromQuals.removeObjCLifetime();
2839         ToQuals.removeObjCLifetime();
2840       } else {
2841         // Qualification conversions cannot cast between different
2842         // Objective-C lifetime qualifiers.
2843         return false;
2844       }
2845     }
2846 
2847     // Allow addition/removal of GC attributes but not changing GC attributes.
2848     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2849         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2850       FromQuals.removeObjCGCAttr();
2851       ToQuals.removeObjCGCAttr();
2852     }
2853 
2854     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2855     //      2,j, and similarly for volatile.
2856     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2857       return false;
2858 
2859     //   -- if the cv 1,j and cv 2,j are different, then const is in
2860     //      every cv for 0 < k < j.
2861     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2862         && !PreviousToQualsIncludeConst)
2863       return false;
2864 
2865     // Keep track of whether all prior cv-qualifiers in the "to" type
2866     // include const.
2867     PreviousToQualsIncludeConst
2868       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2869   }
2870 
2871   // We are left with FromType and ToType being the pointee types
2872   // after unwrapping the original FromType and ToType the same number
2873   // of types. If we unwrapped any pointers, and if FromType and
2874   // ToType have the same unqualified type (since we checked
2875   // qualifiers above), then this is a qualification conversion.
2876   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2877 }
2878 
2879 /// \brief - Determine whether this is a conversion from a scalar type to an
2880 /// atomic type.
2881 ///
2882 /// If successful, updates \c SCS's second and third steps in the conversion
2883 /// sequence to finish the conversion.
2884 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2885                                 bool InOverloadResolution,
2886                                 StandardConversionSequence &SCS,
2887                                 bool CStyle) {
2888   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2889   if (!ToAtomic)
2890     return false;
2891 
2892   StandardConversionSequence InnerSCS;
2893   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2894                             InOverloadResolution, InnerSCS,
2895                             CStyle, /*AllowObjCWritebackConversion=*/false))
2896     return false;
2897 
2898   SCS.Second = InnerSCS.Second;
2899   SCS.setToType(1, InnerSCS.getToType(1));
2900   SCS.Third = InnerSCS.Third;
2901   SCS.QualificationIncludesObjCLifetime
2902     = InnerSCS.QualificationIncludesObjCLifetime;
2903   SCS.setToType(2, InnerSCS.getToType(2));
2904   return true;
2905 }
2906 
2907 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2908                                               CXXConstructorDecl *Constructor,
2909                                               QualType Type) {
2910   const FunctionProtoType *CtorType =
2911       Constructor->getType()->getAs<FunctionProtoType>();
2912   if (CtorType->getNumParams() > 0) {
2913     QualType FirstArg = CtorType->getParamType(0);
2914     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2915       return true;
2916   }
2917   return false;
2918 }
2919 
2920 static OverloadingResult
2921 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2922                                        CXXRecordDecl *To,
2923                                        UserDefinedConversionSequence &User,
2924                                        OverloadCandidateSet &CandidateSet,
2925                                        bool AllowExplicit) {
2926   DeclContext::lookup_result R = S.LookupConstructors(To);
2927   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2928        Con != ConEnd; ++Con) {
2929     NamedDecl *D = *Con;
2930     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2931 
2932     // Find the constructor (which may be a template).
2933     CXXConstructorDecl *Constructor = nullptr;
2934     FunctionTemplateDecl *ConstructorTmpl
2935       = dyn_cast<FunctionTemplateDecl>(D);
2936     if (ConstructorTmpl)
2937       Constructor
2938         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2939     else
2940       Constructor = cast<CXXConstructorDecl>(D);
2941 
2942     bool Usable = !Constructor->isInvalidDecl() &&
2943                   S.isInitListConstructor(Constructor) &&
2944                   (AllowExplicit || !Constructor->isExplicit());
2945     if (Usable) {
2946       // If the first argument is (a reference to) the target type,
2947       // suppress conversions.
2948       bool SuppressUserConversions =
2949           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2950       if (ConstructorTmpl)
2951         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2952                                        /*ExplicitArgs*/ nullptr,
2953                                        From, CandidateSet,
2954                                        SuppressUserConversions);
2955       else
2956         S.AddOverloadCandidate(Constructor, FoundDecl,
2957                                From, CandidateSet,
2958                                SuppressUserConversions);
2959     }
2960   }
2961 
2962   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2963 
2964   OverloadCandidateSet::iterator Best;
2965   switch (auto Result =
2966             CandidateSet.BestViableFunction(S, From->getLocStart(),
2967                                             Best, true)) {
2968   case OR_Deleted:
2969   case OR_Success: {
2970     // Record the standard conversion we used and the conversion function.
2971     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2972     QualType ThisType = Constructor->getThisType(S.Context);
2973     // Initializer lists don't have conversions as such.
2974     User.Before.setAsIdentityConversion();
2975     User.HadMultipleCandidates = HadMultipleCandidates;
2976     User.ConversionFunction = Constructor;
2977     User.FoundConversionFunction = Best->FoundDecl;
2978     User.After.setAsIdentityConversion();
2979     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2980     User.After.setAllToTypes(ToType);
2981     return Result;
2982   }
2983 
2984   case OR_No_Viable_Function:
2985     return OR_No_Viable_Function;
2986   case OR_Ambiguous:
2987     return OR_Ambiguous;
2988   }
2989 
2990   llvm_unreachable("Invalid OverloadResult!");
2991 }
2992 
2993 /// Determines whether there is a user-defined conversion sequence
2994 /// (C++ [over.ics.user]) that converts expression From to the type
2995 /// ToType. If such a conversion exists, User will contain the
2996 /// user-defined conversion sequence that performs such a conversion
2997 /// and this routine will return true. Otherwise, this routine returns
2998 /// false and User is unspecified.
2999 ///
3000 /// \param AllowExplicit  true if the conversion should consider C++0x
3001 /// "explicit" conversion functions as well as non-explicit conversion
3002 /// functions (C++0x [class.conv.fct]p2).
3003 ///
3004 /// \param AllowObjCConversionOnExplicit true if the conversion should
3005 /// allow an extra Objective-C pointer conversion on uses of explicit
3006 /// constructors. Requires \c AllowExplicit to also be set.
3007 static OverloadingResult
3008 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3009                         UserDefinedConversionSequence &User,
3010                         OverloadCandidateSet &CandidateSet,
3011                         bool AllowExplicit,
3012                         bool AllowObjCConversionOnExplicit) {
3013   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3014 
3015   // Whether we will only visit constructors.
3016   bool ConstructorsOnly = false;
3017 
3018   // If the type we are conversion to is a class type, enumerate its
3019   // constructors.
3020   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3021     // C++ [over.match.ctor]p1:
3022     //   When objects of class type are direct-initialized (8.5), or
3023     //   copy-initialized from an expression of the same or a
3024     //   derived class type (8.5), overload resolution selects the
3025     //   constructor. [...] For copy-initialization, the candidate
3026     //   functions are all the converting constructors (12.3.1) of
3027     //   that class. The argument list is the expression-list within
3028     //   the parentheses of the initializer.
3029     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3030         (From->getType()->getAs<RecordType>() &&
3031          S.IsDerivedFrom(From->getType(), ToType)))
3032       ConstructorsOnly = true;
3033 
3034     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3035     // RequireCompleteType may have returned true due to some invalid decl
3036     // during template instantiation, but ToType may be complete enough now
3037     // to try to recover.
3038     if (ToType->isIncompleteType()) {
3039       // We're not going to find any constructors.
3040     } else if (CXXRecordDecl *ToRecordDecl
3041                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3042 
3043       Expr **Args = &From;
3044       unsigned NumArgs = 1;
3045       bool ListInitializing = false;
3046       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3047         // But first, see if there is an init-list-constructor that will work.
3048         OverloadingResult Result = IsInitializerListConstructorConversion(
3049             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3050         if (Result != OR_No_Viable_Function)
3051           return Result;
3052         // Never mind.
3053         CandidateSet.clear();
3054 
3055         // If we're list-initializing, we pass the individual elements as
3056         // arguments, not the entire list.
3057         Args = InitList->getInits();
3058         NumArgs = InitList->getNumInits();
3059         ListInitializing = true;
3060       }
3061 
3062       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3063       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3064            Con != ConEnd; ++Con) {
3065         NamedDecl *D = *Con;
3066         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3067 
3068         // Find the constructor (which may be a template).
3069         CXXConstructorDecl *Constructor = nullptr;
3070         FunctionTemplateDecl *ConstructorTmpl
3071           = dyn_cast<FunctionTemplateDecl>(D);
3072         if (ConstructorTmpl)
3073           Constructor
3074             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3075         else
3076           Constructor = cast<CXXConstructorDecl>(D);
3077 
3078         bool Usable = !Constructor->isInvalidDecl();
3079         if (ListInitializing)
3080           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3081         else
3082           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3083         if (Usable) {
3084           bool SuppressUserConversions = !ConstructorsOnly;
3085           if (SuppressUserConversions && ListInitializing) {
3086             SuppressUserConversions = false;
3087             if (NumArgs == 1) {
3088               // If the first argument is (a reference to) the target type,
3089               // suppress conversions.
3090               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3091                                                 S.Context, Constructor, ToType);
3092             }
3093           }
3094           if (ConstructorTmpl)
3095             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3096                                            /*ExplicitArgs*/ nullptr,
3097                                            llvm::makeArrayRef(Args, NumArgs),
3098                                            CandidateSet, SuppressUserConversions);
3099           else
3100             // Allow one user-defined conversion when user specifies a
3101             // From->ToType conversion via an static cast (c-style, etc).
3102             S.AddOverloadCandidate(Constructor, FoundDecl,
3103                                    llvm::makeArrayRef(Args, NumArgs),
3104                                    CandidateSet, SuppressUserConversions);
3105         }
3106       }
3107     }
3108   }
3109 
3110   // Enumerate conversion functions, if we're allowed to.
3111   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3112   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3113     // No conversion functions from incomplete types.
3114   } else if (const RecordType *FromRecordType
3115                                    = From->getType()->getAs<RecordType>()) {
3116     if (CXXRecordDecl *FromRecordDecl
3117          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3118       // Add all of the conversion functions as candidates.
3119       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3120       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3121         DeclAccessPair FoundDecl = I.getPair();
3122         NamedDecl *D = FoundDecl.getDecl();
3123         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3124         if (isa<UsingShadowDecl>(D))
3125           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3126 
3127         CXXConversionDecl *Conv;
3128         FunctionTemplateDecl *ConvTemplate;
3129         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3130           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3131         else
3132           Conv = cast<CXXConversionDecl>(D);
3133 
3134         if (AllowExplicit || !Conv->isExplicit()) {
3135           if (ConvTemplate)
3136             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3137                                              ActingContext, From, ToType,
3138                                              CandidateSet,
3139                                              AllowObjCConversionOnExplicit);
3140           else
3141             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3142                                      From, ToType, CandidateSet,
3143                                      AllowObjCConversionOnExplicit);
3144         }
3145       }
3146     }
3147   }
3148 
3149   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3150 
3151   OverloadCandidateSet::iterator Best;
3152   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3153                                                         Best, true)) {
3154   case OR_Success:
3155   case OR_Deleted:
3156     // Record the standard conversion we used and the conversion function.
3157     if (CXXConstructorDecl *Constructor
3158           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3159       // C++ [over.ics.user]p1:
3160       //   If the user-defined conversion is specified by a
3161       //   constructor (12.3.1), the initial standard conversion
3162       //   sequence converts the source type to the type required by
3163       //   the argument of the constructor.
3164       //
3165       QualType ThisType = Constructor->getThisType(S.Context);
3166       if (isa<InitListExpr>(From)) {
3167         // Initializer lists don't have conversions as such.
3168         User.Before.setAsIdentityConversion();
3169       } else {
3170         if (Best->Conversions[0].isEllipsis())
3171           User.EllipsisConversion = true;
3172         else {
3173           User.Before = Best->Conversions[0].Standard;
3174           User.EllipsisConversion = false;
3175         }
3176       }
3177       User.HadMultipleCandidates = HadMultipleCandidates;
3178       User.ConversionFunction = Constructor;
3179       User.FoundConversionFunction = Best->FoundDecl;
3180       User.After.setAsIdentityConversion();
3181       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3182       User.After.setAllToTypes(ToType);
3183       return Result;
3184     }
3185     if (CXXConversionDecl *Conversion
3186                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3187       // C++ [over.ics.user]p1:
3188       //
3189       //   [...] If the user-defined conversion is specified by a
3190       //   conversion function (12.3.2), the initial standard
3191       //   conversion sequence converts the source type to the
3192       //   implicit object parameter of the conversion function.
3193       User.Before = Best->Conversions[0].Standard;
3194       User.HadMultipleCandidates = HadMultipleCandidates;
3195       User.ConversionFunction = Conversion;
3196       User.FoundConversionFunction = Best->FoundDecl;
3197       User.EllipsisConversion = false;
3198 
3199       // C++ [over.ics.user]p2:
3200       //   The second standard conversion sequence converts the
3201       //   result of the user-defined conversion to the target type
3202       //   for the sequence. Since an implicit conversion sequence
3203       //   is an initialization, the special rules for
3204       //   initialization by user-defined conversion apply when
3205       //   selecting the best user-defined conversion for a
3206       //   user-defined conversion sequence (see 13.3.3 and
3207       //   13.3.3.1).
3208       User.After = Best->FinalConversion;
3209       return Result;
3210     }
3211     llvm_unreachable("Not a constructor or conversion function?");
3212 
3213   case OR_No_Viable_Function:
3214     return OR_No_Viable_Function;
3215 
3216   case OR_Ambiguous:
3217     return OR_Ambiguous;
3218   }
3219 
3220   llvm_unreachable("Invalid OverloadResult!");
3221 }
3222 
3223 bool
3224 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3225   ImplicitConversionSequence ICS;
3226   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3227                                     OverloadCandidateSet::CSK_Normal);
3228   OverloadingResult OvResult =
3229     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3230                             CandidateSet, false, false);
3231   if (OvResult == OR_Ambiguous)
3232     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3233         << From->getType() << ToType << From->getSourceRange();
3234   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3235     if (!RequireCompleteType(From->getLocStart(), ToType,
3236                              diag::err_typecheck_nonviable_condition_incomplete,
3237                              From->getType(), From->getSourceRange()))
3238       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3239           << false << From->getType() << From->getSourceRange() << ToType;
3240   } else
3241     return false;
3242   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3243   return true;
3244 }
3245 
3246 /// \brief Compare the user-defined conversion functions or constructors
3247 /// of two user-defined conversion sequences to determine whether any ordering
3248 /// is possible.
3249 static ImplicitConversionSequence::CompareKind
3250 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3251                            FunctionDecl *Function2) {
3252   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3253     return ImplicitConversionSequence::Indistinguishable;
3254 
3255   // Objective-C++:
3256   //   If both conversion functions are implicitly-declared conversions from
3257   //   a lambda closure type to a function pointer and a block pointer,
3258   //   respectively, always prefer the conversion to a function pointer,
3259   //   because the function pointer is more lightweight and is more likely
3260   //   to keep code working.
3261   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3262   if (!Conv1)
3263     return ImplicitConversionSequence::Indistinguishable;
3264 
3265   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3266   if (!Conv2)
3267     return ImplicitConversionSequence::Indistinguishable;
3268 
3269   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3270     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3271     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3272     if (Block1 != Block2)
3273       return Block1 ? ImplicitConversionSequence::Worse
3274                     : ImplicitConversionSequence::Better;
3275   }
3276 
3277   return ImplicitConversionSequence::Indistinguishable;
3278 }
3279 
3280 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3281     const ImplicitConversionSequence &ICS) {
3282   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3283          (ICS.isUserDefined() &&
3284           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3285 }
3286 
3287 /// CompareImplicitConversionSequences - Compare two implicit
3288 /// conversion sequences to determine whether one is better than the
3289 /// other or if they are indistinguishable (C++ 13.3.3.2).
3290 static ImplicitConversionSequence::CompareKind
3291 CompareImplicitConversionSequences(Sema &S,
3292                                    const ImplicitConversionSequence& ICS1,
3293                                    const ImplicitConversionSequence& ICS2)
3294 {
3295   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3296   // conversion sequences (as defined in 13.3.3.1)
3297   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3298   //      conversion sequence than a user-defined conversion sequence or
3299   //      an ellipsis conversion sequence, and
3300   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3301   //      conversion sequence than an ellipsis conversion sequence
3302   //      (13.3.3.1.3).
3303   //
3304   // C++0x [over.best.ics]p10:
3305   //   For the purpose of ranking implicit conversion sequences as
3306   //   described in 13.3.3.2, the ambiguous conversion sequence is
3307   //   treated as a user-defined sequence that is indistinguishable
3308   //   from any other user-defined conversion sequence.
3309 
3310   // String literal to 'char *' conversion has been deprecated in C++03. It has
3311   // been removed from C++11. We still accept this conversion, if it happens at
3312   // the best viable function. Otherwise, this conversion is considered worse
3313   // than ellipsis conversion. Consider this as an extension; this is not in the
3314   // standard. For example:
3315   //
3316   // int &f(...);    // #1
3317   // void f(char*);  // #2
3318   // void g() { int &r = f("foo"); }
3319   //
3320   // In C++03, we pick #2 as the best viable function.
3321   // In C++11, we pick #1 as the best viable function, because ellipsis
3322   // conversion is better than string-literal to char* conversion (since there
3323   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3324   // convert arguments, #2 would be the best viable function in C++11.
3325   // If the best viable function has this conversion, a warning will be issued
3326   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3327 
3328   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3329       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3330       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3331     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3332                ? ImplicitConversionSequence::Worse
3333                : ImplicitConversionSequence::Better;
3334 
3335   if (ICS1.getKindRank() < ICS2.getKindRank())
3336     return ImplicitConversionSequence::Better;
3337   if (ICS2.getKindRank() < ICS1.getKindRank())
3338     return ImplicitConversionSequence::Worse;
3339 
3340   // The following checks require both conversion sequences to be of
3341   // the same kind.
3342   if (ICS1.getKind() != ICS2.getKind())
3343     return ImplicitConversionSequence::Indistinguishable;
3344 
3345   ImplicitConversionSequence::CompareKind Result =
3346       ImplicitConversionSequence::Indistinguishable;
3347 
3348   // Two implicit conversion sequences of the same form are
3349   // indistinguishable conversion sequences unless one of the
3350   // following rules apply: (C++ 13.3.3.2p3):
3351 
3352   // List-initialization sequence L1 is a better conversion sequence than
3353   // list-initialization sequence L2 if:
3354   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3355   //   if not that,
3356   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3357   //   and N1 is smaller than N2.,
3358   // even if one of the other rules in this paragraph would otherwise apply.
3359   if (!ICS1.isBad()) {
3360     if (ICS1.isStdInitializerListElement() &&
3361         !ICS2.isStdInitializerListElement())
3362       return ImplicitConversionSequence::Better;
3363     if (!ICS1.isStdInitializerListElement() &&
3364         ICS2.isStdInitializerListElement())
3365       return ImplicitConversionSequence::Worse;
3366   }
3367 
3368   if (ICS1.isStandard())
3369     // Standard conversion sequence S1 is a better conversion sequence than
3370     // standard conversion sequence S2 if [...]
3371     Result = CompareStandardConversionSequences(S,
3372                                                 ICS1.Standard, ICS2.Standard);
3373   else if (ICS1.isUserDefined()) {
3374     // User-defined conversion sequence U1 is a better conversion
3375     // sequence than another user-defined conversion sequence U2 if
3376     // they contain the same user-defined conversion function or
3377     // constructor and if the second standard conversion sequence of
3378     // U1 is better than the second standard conversion sequence of
3379     // U2 (C++ 13.3.3.2p3).
3380     if (ICS1.UserDefined.ConversionFunction ==
3381           ICS2.UserDefined.ConversionFunction)
3382       Result = CompareStandardConversionSequences(S,
3383                                                   ICS1.UserDefined.After,
3384                                                   ICS2.UserDefined.After);
3385     else
3386       Result = compareConversionFunctions(S,
3387                                           ICS1.UserDefined.ConversionFunction,
3388                                           ICS2.UserDefined.ConversionFunction);
3389   }
3390 
3391   return Result;
3392 }
3393 
3394 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3395   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3396     Qualifiers Quals;
3397     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3398     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3399   }
3400 
3401   return Context.hasSameUnqualifiedType(T1, T2);
3402 }
3403 
3404 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3405 // determine if one is a proper subset of the other.
3406 static ImplicitConversionSequence::CompareKind
3407 compareStandardConversionSubsets(ASTContext &Context,
3408                                  const StandardConversionSequence& SCS1,
3409                                  const StandardConversionSequence& SCS2) {
3410   ImplicitConversionSequence::CompareKind Result
3411     = ImplicitConversionSequence::Indistinguishable;
3412 
3413   // the identity conversion sequence is considered to be a subsequence of
3414   // any non-identity conversion sequence
3415   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3416     return ImplicitConversionSequence::Better;
3417   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3418     return ImplicitConversionSequence::Worse;
3419 
3420   if (SCS1.Second != SCS2.Second) {
3421     if (SCS1.Second == ICK_Identity)
3422       Result = ImplicitConversionSequence::Better;
3423     else if (SCS2.Second == ICK_Identity)
3424       Result = ImplicitConversionSequence::Worse;
3425     else
3426       return ImplicitConversionSequence::Indistinguishable;
3427   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3428     return ImplicitConversionSequence::Indistinguishable;
3429 
3430   if (SCS1.Third == SCS2.Third) {
3431     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3432                              : ImplicitConversionSequence::Indistinguishable;
3433   }
3434 
3435   if (SCS1.Third == ICK_Identity)
3436     return Result == ImplicitConversionSequence::Worse
3437              ? ImplicitConversionSequence::Indistinguishable
3438              : ImplicitConversionSequence::Better;
3439 
3440   if (SCS2.Third == ICK_Identity)
3441     return Result == ImplicitConversionSequence::Better
3442              ? ImplicitConversionSequence::Indistinguishable
3443              : ImplicitConversionSequence::Worse;
3444 
3445   return ImplicitConversionSequence::Indistinguishable;
3446 }
3447 
3448 /// \brief Determine whether one of the given reference bindings is better
3449 /// than the other based on what kind of bindings they are.
3450 static bool
3451 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3452                              const StandardConversionSequence &SCS2) {
3453   // C++0x [over.ics.rank]p3b4:
3454   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3455   //      implicit object parameter of a non-static member function declared
3456   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3457   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3458   //      lvalue reference to a function lvalue and S2 binds an rvalue
3459   //      reference*.
3460   //
3461   // FIXME: Rvalue references. We're going rogue with the above edits,
3462   // because the semantics in the current C++0x working paper (N3225 at the
3463   // time of this writing) break the standard definition of std::forward
3464   // and std::reference_wrapper when dealing with references to functions.
3465   // Proposed wording changes submitted to CWG for consideration.
3466   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3467       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3468     return false;
3469 
3470   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3471           SCS2.IsLvalueReference) ||
3472          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3473           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3474 }
3475 
3476 /// CompareStandardConversionSequences - Compare two standard
3477 /// conversion sequences to determine whether one is better than the
3478 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3479 static ImplicitConversionSequence::CompareKind
3480 CompareStandardConversionSequences(Sema &S,
3481                                    const StandardConversionSequence& SCS1,
3482                                    const StandardConversionSequence& SCS2)
3483 {
3484   // Standard conversion sequence S1 is a better conversion sequence
3485   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3486 
3487   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3488   //     sequences in the canonical form defined by 13.3.3.1.1,
3489   //     excluding any Lvalue Transformation; the identity conversion
3490   //     sequence is considered to be a subsequence of any
3491   //     non-identity conversion sequence) or, if not that,
3492   if (ImplicitConversionSequence::CompareKind CK
3493         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3494     return CK;
3495 
3496   //  -- the rank of S1 is better than the rank of S2 (by the rules
3497   //     defined below), or, if not that,
3498   ImplicitConversionRank Rank1 = SCS1.getRank();
3499   ImplicitConversionRank Rank2 = SCS2.getRank();
3500   if (Rank1 < Rank2)
3501     return ImplicitConversionSequence::Better;
3502   else if (Rank2 < Rank1)
3503     return ImplicitConversionSequence::Worse;
3504 
3505   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3506   // are indistinguishable unless one of the following rules
3507   // applies:
3508 
3509   //   A conversion that is not a conversion of a pointer, or
3510   //   pointer to member, to bool is better than another conversion
3511   //   that is such a conversion.
3512   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3513     return SCS2.isPointerConversionToBool()
3514              ? ImplicitConversionSequence::Better
3515              : ImplicitConversionSequence::Worse;
3516 
3517   // C++ [over.ics.rank]p4b2:
3518   //
3519   //   If class B is derived directly or indirectly from class A,
3520   //   conversion of B* to A* is better than conversion of B* to
3521   //   void*, and conversion of A* to void* is better than conversion
3522   //   of B* to void*.
3523   bool SCS1ConvertsToVoid
3524     = SCS1.isPointerConversionToVoidPointer(S.Context);
3525   bool SCS2ConvertsToVoid
3526     = SCS2.isPointerConversionToVoidPointer(S.Context);
3527   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3528     // Exactly one of the conversion sequences is a conversion to
3529     // a void pointer; it's the worse conversion.
3530     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3531                               : ImplicitConversionSequence::Worse;
3532   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3533     // Neither conversion sequence converts to a void pointer; compare
3534     // their derived-to-base conversions.
3535     if (ImplicitConversionSequence::CompareKind DerivedCK
3536           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3537       return DerivedCK;
3538   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3539              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3540     // Both conversion sequences are conversions to void
3541     // pointers. Compare the source types to determine if there's an
3542     // inheritance relationship in their sources.
3543     QualType FromType1 = SCS1.getFromType();
3544     QualType FromType2 = SCS2.getFromType();
3545 
3546     // Adjust the types we're converting from via the array-to-pointer
3547     // conversion, if we need to.
3548     if (SCS1.First == ICK_Array_To_Pointer)
3549       FromType1 = S.Context.getArrayDecayedType(FromType1);
3550     if (SCS2.First == ICK_Array_To_Pointer)
3551       FromType2 = S.Context.getArrayDecayedType(FromType2);
3552 
3553     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3554     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3555 
3556     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3557       return ImplicitConversionSequence::Better;
3558     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3559       return ImplicitConversionSequence::Worse;
3560 
3561     // Objective-C++: If one interface is more specific than the
3562     // other, it is the better one.
3563     const ObjCObjectPointerType* FromObjCPtr1
3564       = FromType1->getAs<ObjCObjectPointerType>();
3565     const ObjCObjectPointerType* FromObjCPtr2
3566       = FromType2->getAs<ObjCObjectPointerType>();
3567     if (FromObjCPtr1 && FromObjCPtr2) {
3568       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3569                                                           FromObjCPtr2);
3570       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3571                                                            FromObjCPtr1);
3572       if (AssignLeft != AssignRight) {
3573         return AssignLeft? ImplicitConversionSequence::Better
3574                          : ImplicitConversionSequence::Worse;
3575       }
3576     }
3577   }
3578 
3579   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3580   // bullet 3).
3581   if (ImplicitConversionSequence::CompareKind QualCK
3582         = CompareQualificationConversions(S, SCS1, SCS2))
3583     return QualCK;
3584 
3585   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3586     // Check for a better reference binding based on the kind of bindings.
3587     if (isBetterReferenceBindingKind(SCS1, SCS2))
3588       return ImplicitConversionSequence::Better;
3589     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3590       return ImplicitConversionSequence::Worse;
3591 
3592     // C++ [over.ics.rank]p3b4:
3593     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3594     //      which the references refer are the same type except for
3595     //      top-level cv-qualifiers, and the type to which the reference
3596     //      initialized by S2 refers is more cv-qualified than the type
3597     //      to which the reference initialized by S1 refers.
3598     QualType T1 = SCS1.getToType(2);
3599     QualType T2 = SCS2.getToType(2);
3600     T1 = S.Context.getCanonicalType(T1);
3601     T2 = S.Context.getCanonicalType(T2);
3602     Qualifiers T1Quals, T2Quals;
3603     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3604     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3605     if (UnqualT1 == UnqualT2) {
3606       // Objective-C++ ARC: If the references refer to objects with different
3607       // lifetimes, prefer bindings that don't change lifetime.
3608       if (SCS1.ObjCLifetimeConversionBinding !=
3609                                           SCS2.ObjCLifetimeConversionBinding) {
3610         return SCS1.ObjCLifetimeConversionBinding
3611                                            ? ImplicitConversionSequence::Worse
3612                                            : ImplicitConversionSequence::Better;
3613       }
3614 
3615       // If the type is an array type, promote the element qualifiers to the
3616       // type for comparison.
3617       if (isa<ArrayType>(T1) && T1Quals)
3618         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3619       if (isa<ArrayType>(T2) && T2Quals)
3620         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3621       if (T2.isMoreQualifiedThan(T1))
3622         return ImplicitConversionSequence::Better;
3623       else if (T1.isMoreQualifiedThan(T2))
3624         return ImplicitConversionSequence::Worse;
3625     }
3626   }
3627 
3628   // In Microsoft mode, prefer an integral conversion to a
3629   // floating-to-integral conversion if the integral conversion
3630   // is between types of the same size.
3631   // For example:
3632   // void f(float);
3633   // void f(int);
3634   // int main {
3635   //    long a;
3636   //    f(a);
3637   // }
3638   // Here, MSVC will call f(int) instead of generating a compile error
3639   // as clang will do in standard mode.
3640   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3641       SCS2.Second == ICK_Floating_Integral &&
3642       S.Context.getTypeSize(SCS1.getFromType()) ==
3643           S.Context.getTypeSize(SCS1.getToType(2)))
3644     return ImplicitConversionSequence::Better;
3645 
3646   return ImplicitConversionSequence::Indistinguishable;
3647 }
3648 
3649 /// CompareQualificationConversions - Compares two standard conversion
3650 /// sequences to determine whether they can be ranked based on their
3651 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3652 static ImplicitConversionSequence::CompareKind
3653 CompareQualificationConversions(Sema &S,
3654                                 const StandardConversionSequence& SCS1,
3655                                 const StandardConversionSequence& SCS2) {
3656   // C++ 13.3.3.2p3:
3657   //  -- S1 and S2 differ only in their qualification conversion and
3658   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3659   //     cv-qualification signature of type T1 is a proper subset of
3660   //     the cv-qualification signature of type T2, and S1 is not the
3661   //     deprecated string literal array-to-pointer conversion (4.2).
3662   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3663       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3664     return ImplicitConversionSequence::Indistinguishable;
3665 
3666   // FIXME: the example in the standard doesn't use a qualification
3667   // conversion (!)
3668   QualType T1 = SCS1.getToType(2);
3669   QualType T2 = SCS2.getToType(2);
3670   T1 = S.Context.getCanonicalType(T1);
3671   T2 = S.Context.getCanonicalType(T2);
3672   Qualifiers T1Quals, T2Quals;
3673   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3674   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3675 
3676   // If the types are the same, we won't learn anything by unwrapped
3677   // them.
3678   if (UnqualT1 == UnqualT2)
3679     return ImplicitConversionSequence::Indistinguishable;
3680 
3681   // If the type is an array type, promote the element qualifiers to the type
3682   // for comparison.
3683   if (isa<ArrayType>(T1) && T1Quals)
3684     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3685   if (isa<ArrayType>(T2) && T2Quals)
3686     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3687 
3688   ImplicitConversionSequence::CompareKind Result
3689     = ImplicitConversionSequence::Indistinguishable;
3690 
3691   // Objective-C++ ARC:
3692   //   Prefer qualification conversions not involving a change in lifetime
3693   //   to qualification conversions that do not change lifetime.
3694   if (SCS1.QualificationIncludesObjCLifetime !=
3695                                       SCS2.QualificationIncludesObjCLifetime) {
3696     Result = SCS1.QualificationIncludesObjCLifetime
3697                ? ImplicitConversionSequence::Worse
3698                : ImplicitConversionSequence::Better;
3699   }
3700 
3701   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3702     // Within each iteration of the loop, we check the qualifiers to
3703     // determine if this still looks like a qualification
3704     // conversion. Then, if all is well, we unwrap one more level of
3705     // pointers or pointers-to-members and do it all again
3706     // until there are no more pointers or pointers-to-members left
3707     // to unwrap. This essentially mimics what
3708     // IsQualificationConversion does, but here we're checking for a
3709     // strict subset of qualifiers.
3710     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3711       // The qualifiers are the same, so this doesn't tell us anything
3712       // about how the sequences rank.
3713       ;
3714     else if (T2.isMoreQualifiedThan(T1)) {
3715       // T1 has fewer qualifiers, so it could be the better sequence.
3716       if (Result == ImplicitConversionSequence::Worse)
3717         // Neither has qualifiers that are a subset of the other's
3718         // qualifiers.
3719         return ImplicitConversionSequence::Indistinguishable;
3720 
3721       Result = ImplicitConversionSequence::Better;
3722     } else if (T1.isMoreQualifiedThan(T2)) {
3723       // T2 has fewer qualifiers, so it could be the better sequence.
3724       if (Result == ImplicitConversionSequence::Better)
3725         // Neither has qualifiers that are a subset of the other's
3726         // qualifiers.
3727         return ImplicitConversionSequence::Indistinguishable;
3728 
3729       Result = ImplicitConversionSequence::Worse;
3730     } else {
3731       // Qualifiers are disjoint.
3732       return ImplicitConversionSequence::Indistinguishable;
3733     }
3734 
3735     // If the types after this point are equivalent, we're done.
3736     if (S.Context.hasSameUnqualifiedType(T1, T2))
3737       break;
3738   }
3739 
3740   // Check that the winning standard conversion sequence isn't using
3741   // the deprecated string literal array to pointer conversion.
3742   switch (Result) {
3743   case ImplicitConversionSequence::Better:
3744     if (SCS1.DeprecatedStringLiteralToCharPtr)
3745       Result = ImplicitConversionSequence::Indistinguishable;
3746     break;
3747 
3748   case ImplicitConversionSequence::Indistinguishable:
3749     break;
3750 
3751   case ImplicitConversionSequence::Worse:
3752     if (SCS2.DeprecatedStringLiteralToCharPtr)
3753       Result = ImplicitConversionSequence::Indistinguishable;
3754     break;
3755   }
3756 
3757   return Result;
3758 }
3759 
3760 /// CompareDerivedToBaseConversions - Compares two standard conversion
3761 /// sequences to determine whether they can be ranked based on their
3762 /// various kinds of derived-to-base conversions (C++
3763 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3764 /// conversions between Objective-C interface types.
3765 static ImplicitConversionSequence::CompareKind
3766 CompareDerivedToBaseConversions(Sema &S,
3767                                 const StandardConversionSequence& SCS1,
3768                                 const StandardConversionSequence& SCS2) {
3769   QualType FromType1 = SCS1.getFromType();
3770   QualType ToType1 = SCS1.getToType(1);
3771   QualType FromType2 = SCS2.getFromType();
3772   QualType ToType2 = SCS2.getToType(1);
3773 
3774   // Adjust the types we're converting from via the array-to-pointer
3775   // conversion, if we need to.
3776   if (SCS1.First == ICK_Array_To_Pointer)
3777     FromType1 = S.Context.getArrayDecayedType(FromType1);
3778   if (SCS2.First == ICK_Array_To_Pointer)
3779     FromType2 = S.Context.getArrayDecayedType(FromType2);
3780 
3781   // Canonicalize all of the types.
3782   FromType1 = S.Context.getCanonicalType(FromType1);
3783   ToType1 = S.Context.getCanonicalType(ToType1);
3784   FromType2 = S.Context.getCanonicalType(FromType2);
3785   ToType2 = S.Context.getCanonicalType(ToType2);
3786 
3787   // C++ [over.ics.rank]p4b3:
3788   //
3789   //   If class B is derived directly or indirectly from class A and
3790   //   class C is derived directly or indirectly from B,
3791   //
3792   // Compare based on pointer conversions.
3793   if (SCS1.Second == ICK_Pointer_Conversion &&
3794       SCS2.Second == ICK_Pointer_Conversion &&
3795       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3796       FromType1->isPointerType() && FromType2->isPointerType() &&
3797       ToType1->isPointerType() && ToType2->isPointerType()) {
3798     QualType FromPointee1
3799       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3800     QualType ToPointee1
3801       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3802     QualType FromPointee2
3803       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3804     QualType ToPointee2
3805       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3806 
3807     //   -- conversion of C* to B* is better than conversion of C* to A*,
3808     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3809       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3810         return ImplicitConversionSequence::Better;
3811       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3812         return ImplicitConversionSequence::Worse;
3813     }
3814 
3815     //   -- conversion of B* to A* is better than conversion of C* to A*,
3816     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3817       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3818         return ImplicitConversionSequence::Better;
3819       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3820         return ImplicitConversionSequence::Worse;
3821     }
3822   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3823              SCS2.Second == ICK_Pointer_Conversion) {
3824     const ObjCObjectPointerType *FromPtr1
3825       = FromType1->getAs<ObjCObjectPointerType>();
3826     const ObjCObjectPointerType *FromPtr2
3827       = FromType2->getAs<ObjCObjectPointerType>();
3828     const ObjCObjectPointerType *ToPtr1
3829       = ToType1->getAs<ObjCObjectPointerType>();
3830     const ObjCObjectPointerType *ToPtr2
3831       = ToType2->getAs<ObjCObjectPointerType>();
3832 
3833     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3834       // Apply the same conversion ranking rules for Objective-C pointer types
3835       // that we do for C++ pointers to class types. However, we employ the
3836       // Objective-C pseudo-subtyping relationship used for assignment of
3837       // Objective-C pointer types.
3838       bool FromAssignLeft
3839         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3840       bool FromAssignRight
3841         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3842       bool ToAssignLeft
3843         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3844       bool ToAssignRight
3845         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3846 
3847       // A conversion to an a non-id object pointer type or qualified 'id'
3848       // type is better than a conversion to 'id'.
3849       if (ToPtr1->isObjCIdType() &&
3850           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3851         return ImplicitConversionSequence::Worse;
3852       if (ToPtr2->isObjCIdType() &&
3853           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3854         return ImplicitConversionSequence::Better;
3855 
3856       // A conversion to a non-id object pointer type is better than a
3857       // conversion to a qualified 'id' type
3858       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3859         return ImplicitConversionSequence::Worse;
3860       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3861         return ImplicitConversionSequence::Better;
3862 
3863       // A conversion to an a non-Class object pointer type or qualified 'Class'
3864       // type is better than a conversion to 'Class'.
3865       if (ToPtr1->isObjCClassType() &&
3866           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3867         return ImplicitConversionSequence::Worse;
3868       if (ToPtr2->isObjCClassType() &&
3869           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3870         return ImplicitConversionSequence::Better;
3871 
3872       // A conversion to a non-Class object pointer type is better than a
3873       // conversion to a qualified 'Class' type.
3874       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3875         return ImplicitConversionSequence::Worse;
3876       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3877         return ImplicitConversionSequence::Better;
3878 
3879       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3880       if (S.Context.hasSameType(FromType1, FromType2) &&
3881           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3882           (ToAssignLeft != ToAssignRight))
3883         return ToAssignLeft? ImplicitConversionSequence::Worse
3884                            : ImplicitConversionSequence::Better;
3885 
3886       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3887       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3888           (FromAssignLeft != FromAssignRight))
3889         return FromAssignLeft? ImplicitConversionSequence::Better
3890         : ImplicitConversionSequence::Worse;
3891     }
3892   }
3893 
3894   // Ranking of member-pointer types.
3895   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3896       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3897       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3898     const MemberPointerType * FromMemPointer1 =
3899                                         FromType1->getAs<MemberPointerType>();
3900     const MemberPointerType * ToMemPointer1 =
3901                                           ToType1->getAs<MemberPointerType>();
3902     const MemberPointerType * FromMemPointer2 =
3903                                           FromType2->getAs<MemberPointerType>();
3904     const MemberPointerType * ToMemPointer2 =
3905                                           ToType2->getAs<MemberPointerType>();
3906     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3907     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3908     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3909     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3910     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3911     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3912     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3913     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3914     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3915     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3916       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3917         return ImplicitConversionSequence::Worse;
3918       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3919         return ImplicitConversionSequence::Better;
3920     }
3921     // conversion of B::* to C::* is better than conversion of A::* to C::*
3922     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3923       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3924         return ImplicitConversionSequence::Better;
3925       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3926         return ImplicitConversionSequence::Worse;
3927     }
3928   }
3929 
3930   if (SCS1.Second == ICK_Derived_To_Base) {
3931     //   -- conversion of C to B is better than conversion of C to A,
3932     //   -- binding of an expression of type C to a reference of type
3933     //      B& is better than binding an expression of type C to a
3934     //      reference of type A&,
3935     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3936         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3937       if (S.IsDerivedFrom(ToType1, ToType2))
3938         return ImplicitConversionSequence::Better;
3939       else if (S.IsDerivedFrom(ToType2, ToType1))
3940         return ImplicitConversionSequence::Worse;
3941     }
3942 
3943     //   -- conversion of B to A is better than conversion of C to A.
3944     //   -- binding of an expression of type B to a reference of type
3945     //      A& is better than binding an expression of type C to a
3946     //      reference of type A&,
3947     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3948         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3949       if (S.IsDerivedFrom(FromType2, FromType1))
3950         return ImplicitConversionSequence::Better;
3951       else if (S.IsDerivedFrom(FromType1, FromType2))
3952         return ImplicitConversionSequence::Worse;
3953     }
3954   }
3955 
3956   return ImplicitConversionSequence::Indistinguishable;
3957 }
3958 
3959 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3960 /// C++ class.
3961 static bool isTypeValid(QualType T) {
3962   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3963     return !Record->isInvalidDecl();
3964 
3965   return true;
3966 }
3967 
3968 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3969 /// determine whether they are reference-related,
3970 /// reference-compatible, reference-compatible with added
3971 /// qualification, or incompatible, for use in C++ initialization by
3972 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3973 /// type, and the first type (T1) is the pointee type of the reference
3974 /// type being initialized.
3975 Sema::ReferenceCompareResult
3976 Sema::CompareReferenceRelationship(SourceLocation Loc,
3977                                    QualType OrigT1, QualType OrigT2,
3978                                    bool &DerivedToBase,
3979                                    bool &ObjCConversion,
3980                                    bool &ObjCLifetimeConversion) {
3981   assert(!OrigT1->isReferenceType() &&
3982     "T1 must be the pointee type of the reference type");
3983   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3984 
3985   QualType T1 = Context.getCanonicalType(OrigT1);
3986   QualType T2 = Context.getCanonicalType(OrigT2);
3987   Qualifiers T1Quals, T2Quals;
3988   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3989   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3990 
3991   // C++ [dcl.init.ref]p4:
3992   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3993   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3994   //   T1 is a base class of T2.
3995   DerivedToBase = false;
3996   ObjCConversion = false;
3997   ObjCLifetimeConversion = false;
3998   if (UnqualT1 == UnqualT2) {
3999     // Nothing to do.
4000   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
4001              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4002              IsDerivedFrom(UnqualT2, UnqualT1))
4003     DerivedToBase = true;
4004   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4005            UnqualT2->isObjCObjectOrInterfaceType() &&
4006            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4007     ObjCConversion = true;
4008   else
4009     return Ref_Incompatible;
4010 
4011   // At this point, we know that T1 and T2 are reference-related (at
4012   // least).
4013 
4014   // If the type is an array type, promote the element qualifiers to the type
4015   // for comparison.
4016   if (isa<ArrayType>(T1) && T1Quals)
4017     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4018   if (isa<ArrayType>(T2) && T2Quals)
4019     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4020 
4021   // C++ [dcl.init.ref]p4:
4022   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4023   //   reference-related to T2 and cv1 is the same cv-qualification
4024   //   as, or greater cv-qualification than, cv2. For purposes of
4025   //   overload resolution, cases for which cv1 is greater
4026   //   cv-qualification than cv2 are identified as
4027   //   reference-compatible with added qualification (see 13.3.3.2).
4028   //
4029   // Note that we also require equivalence of Objective-C GC and address-space
4030   // qualifiers when performing these computations, so that e.g., an int in
4031   // address space 1 is not reference-compatible with an int in address
4032   // space 2.
4033   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4034       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4035     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4036       ObjCLifetimeConversion = true;
4037 
4038     T1Quals.removeObjCLifetime();
4039     T2Quals.removeObjCLifetime();
4040   }
4041 
4042   if (T1Quals == T2Quals)
4043     return Ref_Compatible;
4044   else if (T1Quals.compatiblyIncludes(T2Quals))
4045     return Ref_Compatible_With_Added_Qualification;
4046   else
4047     return Ref_Related;
4048 }
4049 
4050 /// \brief Look for a user-defined conversion to an value reference-compatible
4051 ///        with DeclType. Return true if something definite is found.
4052 static bool
4053 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4054                          QualType DeclType, SourceLocation DeclLoc,
4055                          Expr *Init, QualType T2, bool AllowRvalues,
4056                          bool AllowExplicit) {
4057   assert(T2->isRecordType() && "Can only find conversions of record types.");
4058   CXXRecordDecl *T2RecordDecl
4059     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4060 
4061   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4062   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4063   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4064     NamedDecl *D = *I;
4065     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4066     if (isa<UsingShadowDecl>(D))
4067       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4068 
4069     FunctionTemplateDecl *ConvTemplate
4070       = dyn_cast<FunctionTemplateDecl>(D);
4071     CXXConversionDecl *Conv;
4072     if (ConvTemplate)
4073       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4074     else
4075       Conv = cast<CXXConversionDecl>(D);
4076 
4077     // If this is an explicit conversion, and we're not allowed to consider
4078     // explicit conversions, skip it.
4079     if (!AllowExplicit && Conv->isExplicit())
4080       continue;
4081 
4082     if (AllowRvalues) {
4083       bool DerivedToBase = false;
4084       bool ObjCConversion = false;
4085       bool ObjCLifetimeConversion = false;
4086 
4087       // If we are initializing an rvalue reference, don't permit conversion
4088       // functions that return lvalues.
4089       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4090         const ReferenceType *RefType
4091           = Conv->getConversionType()->getAs<LValueReferenceType>();
4092         if (RefType && !RefType->getPointeeType()->isFunctionType())
4093           continue;
4094       }
4095 
4096       if (!ConvTemplate &&
4097           S.CompareReferenceRelationship(
4098             DeclLoc,
4099             Conv->getConversionType().getNonReferenceType()
4100               .getUnqualifiedType(),
4101             DeclType.getNonReferenceType().getUnqualifiedType(),
4102             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4103           Sema::Ref_Incompatible)
4104         continue;
4105     } else {
4106       // If the conversion function doesn't return a reference type,
4107       // it can't be considered for this conversion. An rvalue reference
4108       // is only acceptable if its referencee is a function type.
4109 
4110       const ReferenceType *RefType =
4111         Conv->getConversionType()->getAs<ReferenceType>();
4112       if (!RefType ||
4113           (!RefType->isLValueReferenceType() &&
4114            !RefType->getPointeeType()->isFunctionType()))
4115         continue;
4116     }
4117 
4118     if (ConvTemplate)
4119       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4120                                        Init, DeclType, CandidateSet,
4121                                        /*AllowObjCConversionOnExplicit=*/false);
4122     else
4123       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4124                                DeclType, CandidateSet,
4125                                /*AllowObjCConversionOnExplicit=*/false);
4126   }
4127 
4128   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4129 
4130   OverloadCandidateSet::iterator Best;
4131   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4132   case OR_Success:
4133     // C++ [over.ics.ref]p1:
4134     //
4135     //   [...] If the parameter binds directly to the result of
4136     //   applying a conversion function to the argument
4137     //   expression, the implicit conversion sequence is a
4138     //   user-defined conversion sequence (13.3.3.1.2), with the
4139     //   second standard conversion sequence either an identity
4140     //   conversion or, if the conversion function returns an
4141     //   entity of a type that is a derived class of the parameter
4142     //   type, a derived-to-base Conversion.
4143     if (!Best->FinalConversion.DirectBinding)
4144       return false;
4145 
4146     ICS.setUserDefined();
4147     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4148     ICS.UserDefined.After = Best->FinalConversion;
4149     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4150     ICS.UserDefined.ConversionFunction = Best->Function;
4151     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4152     ICS.UserDefined.EllipsisConversion = false;
4153     assert(ICS.UserDefined.After.ReferenceBinding &&
4154            ICS.UserDefined.After.DirectBinding &&
4155            "Expected a direct reference binding!");
4156     return true;
4157 
4158   case OR_Ambiguous:
4159     ICS.setAmbiguous();
4160     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4161          Cand != CandidateSet.end(); ++Cand)
4162       if (Cand->Viable)
4163         ICS.Ambiguous.addConversion(Cand->Function);
4164     return true;
4165 
4166   case OR_No_Viable_Function:
4167   case OR_Deleted:
4168     // There was no suitable conversion, or we found a deleted
4169     // conversion; continue with other checks.
4170     return false;
4171   }
4172 
4173   llvm_unreachable("Invalid OverloadResult!");
4174 }
4175 
4176 /// \brief Compute an implicit conversion sequence for reference
4177 /// initialization.
4178 static ImplicitConversionSequence
4179 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4180                  SourceLocation DeclLoc,
4181                  bool SuppressUserConversions,
4182                  bool AllowExplicit) {
4183   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4184 
4185   // Most paths end in a failed conversion.
4186   ImplicitConversionSequence ICS;
4187   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4188 
4189   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4190   QualType T2 = Init->getType();
4191 
4192   // If the initializer is the address of an overloaded function, try
4193   // to resolve the overloaded function. If all goes well, T2 is the
4194   // type of the resulting function.
4195   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4196     DeclAccessPair Found;
4197     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4198                                                                 false, Found))
4199       T2 = Fn->getType();
4200   }
4201 
4202   // Compute some basic properties of the types and the initializer.
4203   bool isRValRef = DeclType->isRValueReferenceType();
4204   bool DerivedToBase = false;
4205   bool ObjCConversion = false;
4206   bool ObjCLifetimeConversion = false;
4207   Expr::Classification InitCategory = Init->Classify(S.Context);
4208   Sema::ReferenceCompareResult RefRelationship
4209     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4210                                      ObjCConversion, ObjCLifetimeConversion);
4211 
4212 
4213   // C++0x [dcl.init.ref]p5:
4214   //   A reference to type "cv1 T1" is initialized by an expression
4215   //   of type "cv2 T2" as follows:
4216 
4217   //     -- If reference is an lvalue reference and the initializer expression
4218   if (!isRValRef) {
4219     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4220     //        reference-compatible with "cv2 T2," or
4221     //
4222     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4223     if (InitCategory.isLValue() &&
4224         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4225       // C++ [over.ics.ref]p1:
4226       //   When a parameter of reference type binds directly (8.5.3)
4227       //   to an argument expression, the implicit conversion sequence
4228       //   is the identity conversion, unless the argument expression
4229       //   has a type that is a derived class of the parameter type,
4230       //   in which case the implicit conversion sequence is a
4231       //   derived-to-base Conversion (13.3.3.1).
4232       ICS.setStandard();
4233       ICS.Standard.First = ICK_Identity;
4234       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4235                          : ObjCConversion? ICK_Compatible_Conversion
4236                          : ICK_Identity;
4237       ICS.Standard.Third = ICK_Identity;
4238       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4239       ICS.Standard.setToType(0, T2);
4240       ICS.Standard.setToType(1, T1);
4241       ICS.Standard.setToType(2, T1);
4242       ICS.Standard.ReferenceBinding = true;
4243       ICS.Standard.DirectBinding = true;
4244       ICS.Standard.IsLvalueReference = !isRValRef;
4245       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4246       ICS.Standard.BindsToRvalue = false;
4247       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4248       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4249       ICS.Standard.CopyConstructor = nullptr;
4250       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4251 
4252       // Nothing more to do: the inaccessibility/ambiguity check for
4253       // derived-to-base conversions is suppressed when we're
4254       // computing the implicit conversion sequence (C++
4255       // [over.best.ics]p2).
4256       return ICS;
4257     }
4258 
4259     //       -- has a class type (i.e., T2 is a class type), where T1 is
4260     //          not reference-related to T2, and can be implicitly
4261     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4262     //          is reference-compatible with "cv3 T3" 92) (this
4263     //          conversion is selected by enumerating the applicable
4264     //          conversion functions (13.3.1.6) and choosing the best
4265     //          one through overload resolution (13.3)),
4266     if (!SuppressUserConversions && T2->isRecordType() &&
4267         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4268         RefRelationship == Sema::Ref_Incompatible) {
4269       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4270                                    Init, T2, /*AllowRvalues=*/false,
4271                                    AllowExplicit))
4272         return ICS;
4273     }
4274   }
4275 
4276   //     -- Otherwise, the reference shall be an lvalue reference to a
4277   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4278   //        shall be an rvalue reference.
4279   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4280     return ICS;
4281 
4282   //       -- If the initializer expression
4283   //
4284   //            -- is an xvalue, class prvalue, array prvalue or function
4285   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4286   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4287       (InitCategory.isXValue() ||
4288       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4289       (InitCategory.isLValue() && T2->isFunctionType()))) {
4290     ICS.setStandard();
4291     ICS.Standard.First = ICK_Identity;
4292     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4293                       : ObjCConversion? ICK_Compatible_Conversion
4294                       : ICK_Identity;
4295     ICS.Standard.Third = ICK_Identity;
4296     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4297     ICS.Standard.setToType(0, T2);
4298     ICS.Standard.setToType(1, T1);
4299     ICS.Standard.setToType(2, T1);
4300     ICS.Standard.ReferenceBinding = true;
4301     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4302     // binding unless we're binding to a class prvalue.
4303     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4304     // allow the use of rvalue references in C++98/03 for the benefit of
4305     // standard library implementors; therefore, we need the xvalue check here.
4306     ICS.Standard.DirectBinding =
4307       S.getLangOpts().CPlusPlus11 ||
4308       !(InitCategory.isPRValue() || T2->isRecordType());
4309     ICS.Standard.IsLvalueReference = !isRValRef;
4310     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4311     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4312     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4313     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4314     ICS.Standard.CopyConstructor = nullptr;
4315     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4316     return ICS;
4317   }
4318 
4319   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4320   //               reference-related to T2, and can be implicitly converted to
4321   //               an xvalue, class prvalue, or function lvalue of type
4322   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4323   //               "cv3 T3",
4324   //
4325   //          then the reference is bound to the value of the initializer
4326   //          expression in the first case and to the result of the conversion
4327   //          in the second case (or, in either case, to an appropriate base
4328   //          class subobject).
4329   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4330       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4331       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4332                                Init, T2, /*AllowRvalues=*/true,
4333                                AllowExplicit)) {
4334     // In the second case, if the reference is an rvalue reference
4335     // and the second standard conversion sequence of the
4336     // user-defined conversion sequence includes an lvalue-to-rvalue
4337     // conversion, the program is ill-formed.
4338     if (ICS.isUserDefined() && isRValRef &&
4339         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4340       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4341 
4342     return ICS;
4343   }
4344 
4345   // A temporary of function type cannot be created; don't even try.
4346   if (T1->isFunctionType())
4347     return ICS;
4348 
4349   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4350   //          initialized from the initializer expression using the
4351   //          rules for a non-reference copy initialization (8.5). The
4352   //          reference is then bound to the temporary. If T1 is
4353   //          reference-related to T2, cv1 must be the same
4354   //          cv-qualification as, or greater cv-qualification than,
4355   //          cv2; otherwise, the program is ill-formed.
4356   if (RefRelationship == Sema::Ref_Related) {
4357     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4358     // we would be reference-compatible or reference-compatible with
4359     // added qualification. But that wasn't the case, so the reference
4360     // initialization fails.
4361     //
4362     // Note that we only want to check address spaces and cvr-qualifiers here.
4363     // ObjC GC and lifetime qualifiers aren't important.
4364     Qualifiers T1Quals = T1.getQualifiers();
4365     Qualifiers T2Quals = T2.getQualifiers();
4366     T1Quals.removeObjCGCAttr();
4367     T1Quals.removeObjCLifetime();
4368     T2Quals.removeObjCGCAttr();
4369     T2Quals.removeObjCLifetime();
4370     if (!T1Quals.compatiblyIncludes(T2Quals))
4371       return ICS;
4372   }
4373 
4374   // If at least one of the types is a class type, the types are not
4375   // related, and we aren't allowed any user conversions, the
4376   // reference binding fails. This case is important for breaking
4377   // recursion, since TryImplicitConversion below will attempt to
4378   // create a temporary through the use of a copy constructor.
4379   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4380       (T1->isRecordType() || T2->isRecordType()))
4381     return ICS;
4382 
4383   // If T1 is reference-related to T2 and the reference is an rvalue
4384   // reference, the initializer expression shall not be an lvalue.
4385   if (RefRelationship >= Sema::Ref_Related &&
4386       isRValRef && Init->Classify(S.Context).isLValue())
4387     return ICS;
4388 
4389   // C++ [over.ics.ref]p2:
4390   //   When a parameter of reference type is not bound directly to
4391   //   an argument expression, the conversion sequence is the one
4392   //   required to convert the argument expression to the
4393   //   underlying type of the reference according to
4394   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4395   //   to copy-initializing a temporary of the underlying type with
4396   //   the argument expression. Any difference in top-level
4397   //   cv-qualification is subsumed by the initialization itself
4398   //   and does not constitute a conversion.
4399   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4400                               /*AllowExplicit=*/false,
4401                               /*InOverloadResolution=*/false,
4402                               /*CStyle=*/false,
4403                               /*AllowObjCWritebackConversion=*/false,
4404                               /*AllowObjCConversionOnExplicit=*/false);
4405 
4406   // Of course, that's still a reference binding.
4407   if (ICS.isStandard()) {
4408     ICS.Standard.ReferenceBinding = true;
4409     ICS.Standard.IsLvalueReference = !isRValRef;
4410     ICS.Standard.BindsToFunctionLvalue = false;
4411     ICS.Standard.BindsToRvalue = true;
4412     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4413     ICS.Standard.ObjCLifetimeConversionBinding = false;
4414   } else if (ICS.isUserDefined()) {
4415     const ReferenceType *LValRefType =
4416         ICS.UserDefined.ConversionFunction->getReturnType()
4417             ->getAs<LValueReferenceType>();
4418 
4419     // C++ [over.ics.ref]p3:
4420     //   Except for an implicit object parameter, for which see 13.3.1, a
4421     //   standard conversion sequence cannot be formed if it requires [...]
4422     //   binding an rvalue reference to an lvalue other than a function
4423     //   lvalue.
4424     // Note that the function case is not possible here.
4425     if (DeclType->isRValueReferenceType() && LValRefType) {
4426       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4427       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4428       // reference to an rvalue!
4429       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4430       return ICS;
4431     }
4432 
4433     ICS.UserDefined.Before.setAsIdentityConversion();
4434     ICS.UserDefined.After.ReferenceBinding = true;
4435     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4436     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4437     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4438     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4439     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4440   }
4441 
4442   return ICS;
4443 }
4444 
4445 static ImplicitConversionSequence
4446 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4447                       bool SuppressUserConversions,
4448                       bool InOverloadResolution,
4449                       bool AllowObjCWritebackConversion,
4450                       bool AllowExplicit = false);
4451 
4452 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4453 /// initializer list From.
4454 static ImplicitConversionSequence
4455 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4456                   bool SuppressUserConversions,
4457                   bool InOverloadResolution,
4458                   bool AllowObjCWritebackConversion) {
4459   // C++11 [over.ics.list]p1:
4460   //   When an argument is an initializer list, it is not an expression and
4461   //   special rules apply for converting it to a parameter type.
4462 
4463   ImplicitConversionSequence Result;
4464   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4465 
4466   // We need a complete type for what follows. Incomplete types can never be
4467   // initialized from init lists.
4468   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4469     return Result;
4470 
4471   // Per DR1467:
4472   //   If the parameter type is a class X and the initializer list has a single
4473   //   element of type cv U, where U is X or a class derived from X, the
4474   //   implicit conversion sequence is the one required to convert the element
4475   //   to the parameter type.
4476   //
4477   //   Otherwise, if the parameter type is a character array [... ]
4478   //   and the initializer list has a single element that is an
4479   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4480   //   implicit conversion sequence is the identity conversion.
4481   if (From->getNumInits() == 1) {
4482     if (ToType->isRecordType()) {
4483       QualType InitType = From->getInit(0)->getType();
4484       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4485           S.IsDerivedFrom(InitType, ToType))
4486         return TryCopyInitialization(S, From->getInit(0), ToType,
4487                                      SuppressUserConversions,
4488                                      InOverloadResolution,
4489                                      AllowObjCWritebackConversion);
4490     }
4491     // FIXME: Check the other conditions here: array of character type,
4492     // initializer is a string literal.
4493     if (ToType->isArrayType()) {
4494       InitializedEntity Entity =
4495         InitializedEntity::InitializeParameter(S.Context, ToType,
4496                                                /*Consumed=*/false);
4497       if (S.CanPerformCopyInitialization(Entity, From)) {
4498         Result.setStandard();
4499         Result.Standard.setAsIdentityConversion();
4500         Result.Standard.setFromType(ToType);
4501         Result.Standard.setAllToTypes(ToType);
4502         return Result;
4503       }
4504     }
4505   }
4506 
4507   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4508   // C++11 [over.ics.list]p2:
4509   //   If the parameter type is std::initializer_list<X> or "array of X" and
4510   //   all the elements can be implicitly converted to X, the implicit
4511   //   conversion sequence is the worst conversion necessary to convert an
4512   //   element of the list to X.
4513   //
4514   // C++14 [over.ics.list]p3:
4515   //   Otherwise, if the parameter type is "array of N X", if the initializer
4516   //   list has exactly N elements or if it has fewer than N elements and X is
4517   //   default-constructible, and if all the elements of the initializer list
4518   //   can be implicitly converted to X, the implicit conversion sequence is
4519   //   the worst conversion necessary to convert an element of the list to X.
4520   //
4521   // FIXME: We're missing a lot of these checks.
4522   bool toStdInitializerList = false;
4523   QualType X;
4524   if (ToType->isArrayType())
4525     X = S.Context.getAsArrayType(ToType)->getElementType();
4526   else
4527     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4528   if (!X.isNull()) {
4529     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4530       Expr *Init = From->getInit(i);
4531       ImplicitConversionSequence ICS =
4532           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4533                                 InOverloadResolution,
4534                                 AllowObjCWritebackConversion);
4535       // If a single element isn't convertible, fail.
4536       if (ICS.isBad()) {
4537         Result = ICS;
4538         break;
4539       }
4540       // Otherwise, look for the worst conversion.
4541       if (Result.isBad() ||
4542           CompareImplicitConversionSequences(S, ICS, Result) ==
4543               ImplicitConversionSequence::Worse)
4544         Result = ICS;
4545     }
4546 
4547     // For an empty list, we won't have computed any conversion sequence.
4548     // Introduce the identity conversion sequence.
4549     if (From->getNumInits() == 0) {
4550       Result.setStandard();
4551       Result.Standard.setAsIdentityConversion();
4552       Result.Standard.setFromType(ToType);
4553       Result.Standard.setAllToTypes(ToType);
4554     }
4555 
4556     Result.setStdInitializerListElement(toStdInitializerList);
4557     return Result;
4558   }
4559 
4560   // C++14 [over.ics.list]p4:
4561   // C++11 [over.ics.list]p3:
4562   //   Otherwise, if the parameter is a non-aggregate class X and overload
4563   //   resolution chooses a single best constructor [...] the implicit
4564   //   conversion sequence is a user-defined conversion sequence. If multiple
4565   //   constructors are viable but none is better than the others, the
4566   //   implicit conversion sequence is a user-defined conversion sequence.
4567   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4568     // This function can deal with initializer lists.
4569     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4570                                     /*AllowExplicit=*/false,
4571                                     InOverloadResolution, /*CStyle=*/false,
4572                                     AllowObjCWritebackConversion,
4573                                     /*AllowObjCConversionOnExplicit=*/false);
4574   }
4575 
4576   // C++14 [over.ics.list]p5:
4577   // C++11 [over.ics.list]p4:
4578   //   Otherwise, if the parameter has an aggregate type which can be
4579   //   initialized from the initializer list [...] the implicit conversion
4580   //   sequence is a user-defined conversion sequence.
4581   if (ToType->isAggregateType()) {
4582     // Type is an aggregate, argument is an init list. At this point it comes
4583     // down to checking whether the initialization works.
4584     // FIXME: Find out whether this parameter is consumed or not.
4585     InitializedEntity Entity =
4586         InitializedEntity::InitializeParameter(S.Context, ToType,
4587                                                /*Consumed=*/false);
4588     if (S.CanPerformCopyInitialization(Entity, From)) {
4589       Result.setUserDefined();
4590       Result.UserDefined.Before.setAsIdentityConversion();
4591       // Initializer lists don't have a type.
4592       Result.UserDefined.Before.setFromType(QualType());
4593       Result.UserDefined.Before.setAllToTypes(QualType());
4594 
4595       Result.UserDefined.After.setAsIdentityConversion();
4596       Result.UserDefined.After.setFromType(ToType);
4597       Result.UserDefined.After.setAllToTypes(ToType);
4598       Result.UserDefined.ConversionFunction = nullptr;
4599     }
4600     return Result;
4601   }
4602 
4603   // C++14 [over.ics.list]p6:
4604   // C++11 [over.ics.list]p5:
4605   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4606   if (ToType->isReferenceType()) {
4607     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4608     // mention initializer lists in any way. So we go by what list-
4609     // initialization would do and try to extrapolate from that.
4610 
4611     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4612 
4613     // If the initializer list has a single element that is reference-related
4614     // to the parameter type, we initialize the reference from that.
4615     if (From->getNumInits() == 1) {
4616       Expr *Init = From->getInit(0);
4617 
4618       QualType T2 = Init->getType();
4619 
4620       // If the initializer is the address of an overloaded function, try
4621       // to resolve the overloaded function. If all goes well, T2 is the
4622       // type of the resulting function.
4623       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4624         DeclAccessPair Found;
4625         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4626                                    Init, ToType, false, Found))
4627           T2 = Fn->getType();
4628       }
4629 
4630       // Compute some basic properties of the types and the initializer.
4631       bool dummy1 = false;
4632       bool dummy2 = false;
4633       bool dummy3 = false;
4634       Sema::ReferenceCompareResult RefRelationship
4635         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4636                                          dummy2, dummy3);
4637 
4638       if (RefRelationship >= Sema::Ref_Related) {
4639         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4640                                 SuppressUserConversions,
4641                                 /*AllowExplicit=*/false);
4642       }
4643     }
4644 
4645     // Otherwise, we bind the reference to a temporary created from the
4646     // initializer list.
4647     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4648                                InOverloadResolution,
4649                                AllowObjCWritebackConversion);
4650     if (Result.isFailure())
4651       return Result;
4652     assert(!Result.isEllipsis() &&
4653            "Sub-initialization cannot result in ellipsis conversion.");
4654 
4655     // Can we even bind to a temporary?
4656     if (ToType->isRValueReferenceType() ||
4657         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4658       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4659                                             Result.UserDefined.After;
4660       SCS.ReferenceBinding = true;
4661       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4662       SCS.BindsToRvalue = true;
4663       SCS.BindsToFunctionLvalue = false;
4664       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4665       SCS.ObjCLifetimeConversionBinding = false;
4666     } else
4667       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4668                     From, ToType);
4669     return Result;
4670   }
4671 
4672   // C++14 [over.ics.list]p7:
4673   // C++11 [over.ics.list]p6:
4674   //   Otherwise, if the parameter type is not a class:
4675   if (!ToType->isRecordType()) {
4676     //    - if the initializer list has one element that is not itself an
4677     //      initializer list, the implicit conversion sequence is the one
4678     //      required to convert the element to the parameter type.
4679     unsigned NumInits = From->getNumInits();
4680     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4681       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4682                                      SuppressUserConversions,
4683                                      InOverloadResolution,
4684                                      AllowObjCWritebackConversion);
4685     //    - if the initializer list has no elements, the implicit conversion
4686     //      sequence is the identity conversion.
4687     else if (NumInits == 0) {
4688       Result.setStandard();
4689       Result.Standard.setAsIdentityConversion();
4690       Result.Standard.setFromType(ToType);
4691       Result.Standard.setAllToTypes(ToType);
4692     }
4693     return Result;
4694   }
4695 
4696   // C++14 [over.ics.list]p8:
4697   // C++11 [over.ics.list]p7:
4698   //   In all cases other than those enumerated above, no conversion is possible
4699   return Result;
4700 }
4701 
4702 /// TryCopyInitialization - Try to copy-initialize a value of type
4703 /// ToType from the expression From. Return the implicit conversion
4704 /// sequence required to pass this argument, which may be a bad
4705 /// conversion sequence (meaning that the argument cannot be passed to
4706 /// a parameter of this type). If @p SuppressUserConversions, then we
4707 /// do not permit any user-defined conversion sequences.
4708 static ImplicitConversionSequence
4709 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4710                       bool SuppressUserConversions,
4711                       bool InOverloadResolution,
4712                       bool AllowObjCWritebackConversion,
4713                       bool AllowExplicit) {
4714   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4715     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4716                              InOverloadResolution,AllowObjCWritebackConversion);
4717 
4718   if (ToType->isReferenceType())
4719     return TryReferenceInit(S, From, ToType,
4720                             /*FIXME:*/From->getLocStart(),
4721                             SuppressUserConversions,
4722                             AllowExplicit);
4723 
4724   return TryImplicitConversion(S, From, ToType,
4725                                SuppressUserConversions,
4726                                /*AllowExplicit=*/false,
4727                                InOverloadResolution,
4728                                /*CStyle=*/false,
4729                                AllowObjCWritebackConversion,
4730                                /*AllowObjCConversionOnExplicit=*/false);
4731 }
4732 
4733 static bool TryCopyInitialization(const CanQualType FromQTy,
4734                                   const CanQualType ToQTy,
4735                                   Sema &S,
4736                                   SourceLocation Loc,
4737                                   ExprValueKind FromVK) {
4738   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4739   ImplicitConversionSequence ICS =
4740     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4741 
4742   return !ICS.isBad();
4743 }
4744 
4745 /// TryObjectArgumentInitialization - Try to initialize the object
4746 /// parameter of the given member function (@c Method) from the
4747 /// expression @p From.
4748 static ImplicitConversionSequence
4749 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4750                                 Expr::Classification FromClassification,
4751                                 CXXMethodDecl *Method,
4752                                 CXXRecordDecl *ActingContext) {
4753   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4754   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4755   //                 const volatile object.
4756   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4757     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4758   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4759 
4760   // Set up the conversion sequence as a "bad" conversion, to allow us
4761   // to exit early.
4762   ImplicitConversionSequence ICS;
4763 
4764   // We need to have an object of class type.
4765   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4766     FromType = PT->getPointeeType();
4767 
4768     // When we had a pointer, it's implicitly dereferenced, so we
4769     // better have an lvalue.
4770     assert(FromClassification.isLValue());
4771   }
4772 
4773   assert(FromType->isRecordType());
4774 
4775   // C++0x [over.match.funcs]p4:
4776   //   For non-static member functions, the type of the implicit object
4777   //   parameter is
4778   //
4779   //     - "lvalue reference to cv X" for functions declared without a
4780   //        ref-qualifier or with the & ref-qualifier
4781   //     - "rvalue reference to cv X" for functions declared with the &&
4782   //        ref-qualifier
4783   //
4784   // where X is the class of which the function is a member and cv is the
4785   // cv-qualification on the member function declaration.
4786   //
4787   // However, when finding an implicit conversion sequence for the argument, we
4788   // are not allowed to create temporaries or perform user-defined conversions
4789   // (C++ [over.match.funcs]p5). We perform a simplified version of
4790   // reference binding here, that allows class rvalues to bind to
4791   // non-constant references.
4792 
4793   // First check the qualifiers.
4794   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4795   if (ImplicitParamType.getCVRQualifiers()
4796                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4797       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4798     ICS.setBad(BadConversionSequence::bad_qualifiers,
4799                FromType, ImplicitParamType);
4800     return ICS;
4801   }
4802 
4803   // Check that we have either the same type or a derived type. It
4804   // affects the conversion rank.
4805   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4806   ImplicitConversionKind SecondKind;
4807   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4808     SecondKind = ICK_Identity;
4809   } else if (S.IsDerivedFrom(FromType, ClassType))
4810     SecondKind = ICK_Derived_To_Base;
4811   else {
4812     ICS.setBad(BadConversionSequence::unrelated_class,
4813                FromType, ImplicitParamType);
4814     return ICS;
4815   }
4816 
4817   // Check the ref-qualifier.
4818   switch (Method->getRefQualifier()) {
4819   case RQ_None:
4820     // Do nothing; we don't care about lvalueness or rvalueness.
4821     break;
4822 
4823   case RQ_LValue:
4824     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4825       // non-const lvalue reference cannot bind to an rvalue
4826       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4827                  ImplicitParamType);
4828       return ICS;
4829     }
4830     break;
4831 
4832   case RQ_RValue:
4833     if (!FromClassification.isRValue()) {
4834       // rvalue reference cannot bind to an lvalue
4835       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4836                  ImplicitParamType);
4837       return ICS;
4838     }
4839     break;
4840   }
4841 
4842   // Success. Mark this as a reference binding.
4843   ICS.setStandard();
4844   ICS.Standard.setAsIdentityConversion();
4845   ICS.Standard.Second = SecondKind;
4846   ICS.Standard.setFromType(FromType);
4847   ICS.Standard.setAllToTypes(ImplicitParamType);
4848   ICS.Standard.ReferenceBinding = true;
4849   ICS.Standard.DirectBinding = true;
4850   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4851   ICS.Standard.BindsToFunctionLvalue = false;
4852   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4853   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4854     = (Method->getRefQualifier() == RQ_None);
4855   return ICS;
4856 }
4857 
4858 /// PerformObjectArgumentInitialization - Perform initialization of
4859 /// the implicit object parameter for the given Method with the given
4860 /// expression.
4861 ExprResult
4862 Sema::PerformObjectArgumentInitialization(Expr *From,
4863                                           NestedNameSpecifier *Qualifier,
4864                                           NamedDecl *FoundDecl,
4865                                           CXXMethodDecl *Method) {
4866   QualType FromRecordType, DestType;
4867   QualType ImplicitParamRecordType  =
4868     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4869 
4870   Expr::Classification FromClassification;
4871   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4872     FromRecordType = PT->getPointeeType();
4873     DestType = Method->getThisType(Context);
4874     FromClassification = Expr::Classification::makeSimpleLValue();
4875   } else {
4876     FromRecordType = From->getType();
4877     DestType = ImplicitParamRecordType;
4878     FromClassification = From->Classify(Context);
4879   }
4880 
4881   // Note that we always use the true parent context when performing
4882   // the actual argument initialization.
4883   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4884       *this, From->getType(), FromClassification, Method, Method->getParent());
4885   if (ICS.isBad()) {
4886     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4887       Qualifiers FromQs = FromRecordType.getQualifiers();
4888       Qualifiers ToQs = DestType.getQualifiers();
4889       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4890       if (CVR) {
4891         Diag(From->getLocStart(),
4892              diag::err_member_function_call_bad_cvr)
4893           << Method->getDeclName() << FromRecordType << (CVR - 1)
4894           << From->getSourceRange();
4895         Diag(Method->getLocation(), diag::note_previous_decl)
4896           << Method->getDeclName();
4897         return ExprError();
4898       }
4899     }
4900 
4901     return Diag(From->getLocStart(),
4902                 diag::err_implicit_object_parameter_init)
4903        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4904   }
4905 
4906   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4907     ExprResult FromRes =
4908       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4909     if (FromRes.isInvalid())
4910       return ExprError();
4911     From = FromRes.get();
4912   }
4913 
4914   if (!Context.hasSameType(From->getType(), DestType))
4915     From = ImpCastExprToType(From, DestType, CK_NoOp,
4916                              From->getValueKind()).get();
4917   return From;
4918 }
4919 
4920 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4921 /// expression From to bool (C++0x [conv]p3).
4922 static ImplicitConversionSequence
4923 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4924   return TryImplicitConversion(S, From, S.Context.BoolTy,
4925                                /*SuppressUserConversions=*/false,
4926                                /*AllowExplicit=*/true,
4927                                /*InOverloadResolution=*/false,
4928                                /*CStyle=*/false,
4929                                /*AllowObjCWritebackConversion=*/false,
4930                                /*AllowObjCConversionOnExplicit=*/false);
4931 }
4932 
4933 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4934 /// of the expression From to bool (C++0x [conv]p3).
4935 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4936   if (checkPlaceholderForOverload(*this, From))
4937     return ExprError();
4938 
4939   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4940   if (!ICS.isBad())
4941     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4942 
4943   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4944     return Diag(From->getLocStart(),
4945                 diag::err_typecheck_bool_condition)
4946                   << From->getType() << From->getSourceRange();
4947   return ExprError();
4948 }
4949 
4950 /// Check that the specified conversion is permitted in a converted constant
4951 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4952 /// is acceptable.
4953 static bool CheckConvertedConstantConversions(Sema &S,
4954                                               StandardConversionSequence &SCS) {
4955   // Since we know that the target type is an integral or unscoped enumeration
4956   // type, most conversion kinds are impossible. All possible First and Third
4957   // conversions are fine.
4958   switch (SCS.Second) {
4959   case ICK_Identity:
4960   case ICK_NoReturn_Adjustment:
4961   case ICK_Integral_Promotion:
4962   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4963     return true;
4964 
4965   case ICK_Boolean_Conversion:
4966     // Conversion from an integral or unscoped enumeration type to bool is
4967     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4968     // conversion, so we allow it in a converted constant expression.
4969     //
4970     // FIXME: Per core issue 1407, we should not allow this, but that breaks
4971     // a lot of popular code. We should at least add a warning for this
4972     // (non-conforming) extension.
4973     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4974            SCS.getToType(2)->isBooleanType();
4975 
4976   case ICK_Pointer_Conversion:
4977   case ICK_Pointer_Member:
4978     // C++1z: null pointer conversions and null member pointer conversions are
4979     // only permitted if the source type is std::nullptr_t.
4980     return SCS.getFromType()->isNullPtrType();
4981 
4982   case ICK_Floating_Promotion:
4983   case ICK_Complex_Promotion:
4984   case ICK_Floating_Conversion:
4985   case ICK_Complex_Conversion:
4986   case ICK_Floating_Integral:
4987   case ICK_Compatible_Conversion:
4988   case ICK_Derived_To_Base:
4989   case ICK_Vector_Conversion:
4990   case ICK_Vector_Splat:
4991   case ICK_Complex_Real:
4992   case ICK_Block_Pointer_Conversion:
4993   case ICK_TransparentUnionConversion:
4994   case ICK_Writeback_Conversion:
4995   case ICK_Zero_Event_Conversion:
4996     return false;
4997 
4998   case ICK_Lvalue_To_Rvalue:
4999   case ICK_Array_To_Pointer:
5000   case ICK_Function_To_Pointer:
5001     llvm_unreachable("found a first conversion kind in Second");
5002 
5003   case ICK_Qualification:
5004     llvm_unreachable("found a third conversion kind in Second");
5005 
5006   case ICK_Num_Conversion_Kinds:
5007     break;
5008   }
5009 
5010   llvm_unreachable("unknown conversion kind");
5011 }
5012 
5013 /// CheckConvertedConstantExpression - Check that the expression From is a
5014 /// converted constant expression of type T, perform the conversion and produce
5015 /// the converted expression, per C++11 [expr.const]p3.
5016 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5017                                                    QualType T, APValue &Value,
5018                                                    Sema::CCEKind CCE,
5019                                                    bool RequireInt) {
5020   assert(S.getLangOpts().CPlusPlus11 &&
5021          "converted constant expression outside C++11");
5022 
5023   if (checkPlaceholderForOverload(S, From))
5024     return ExprError();
5025 
5026   // C++1z [expr.const]p3:
5027   //  A converted constant expression of type T is an expression,
5028   //  implicitly converted to type T, where the converted
5029   //  expression is a constant expression and the implicit conversion
5030   //  sequence contains only [... list of conversions ...].
5031   ImplicitConversionSequence ICS =
5032     TryCopyInitialization(S, From, T,
5033                           /*SuppressUserConversions=*/false,
5034                           /*InOverloadResolution=*/false,
5035                           /*AllowObjcWritebackConversion=*/false,
5036                           /*AllowExplicit=*/false);
5037   StandardConversionSequence *SCS = nullptr;
5038   switch (ICS.getKind()) {
5039   case ImplicitConversionSequence::StandardConversion:
5040     SCS = &ICS.Standard;
5041     break;
5042   case ImplicitConversionSequence::UserDefinedConversion:
5043     // We are converting to a non-class type, so the Before sequence
5044     // must be trivial.
5045     SCS = &ICS.UserDefined.After;
5046     break;
5047   case ImplicitConversionSequence::AmbiguousConversion:
5048   case ImplicitConversionSequence::BadConversion:
5049     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5050       return S.Diag(From->getLocStart(),
5051                     diag::err_typecheck_converted_constant_expression)
5052                 << From->getType() << From->getSourceRange() << T;
5053     return ExprError();
5054 
5055   case ImplicitConversionSequence::EllipsisConversion:
5056     llvm_unreachable("ellipsis conversion in converted constant expression");
5057   }
5058 
5059   // Check that we would only use permitted conversions.
5060   if (!CheckConvertedConstantConversions(S, *SCS)) {
5061     return S.Diag(From->getLocStart(),
5062                   diag::err_typecheck_converted_constant_expression_disallowed)
5063              << From->getType() << From->getSourceRange() << T;
5064   }
5065   // [...] and where the reference binding (if any) binds directly.
5066   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5067     return S.Diag(From->getLocStart(),
5068                   diag::err_typecheck_converted_constant_expression_indirect)
5069              << From->getType() << From->getSourceRange() << T;
5070   }
5071 
5072   ExprResult Result =
5073       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5074   if (Result.isInvalid())
5075     return Result;
5076 
5077   // Check for a narrowing implicit conversion.
5078   APValue PreNarrowingValue;
5079   QualType PreNarrowingType;
5080   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5081                                 PreNarrowingType)) {
5082   case NK_Variable_Narrowing:
5083     // Implicit conversion to a narrower type, and the value is not a constant
5084     // expression. We'll diagnose this in a moment.
5085   case NK_Not_Narrowing:
5086     break;
5087 
5088   case NK_Constant_Narrowing:
5089     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5090       << CCE << /*Constant*/1
5091       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5092     break;
5093 
5094   case NK_Type_Narrowing:
5095     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5096       << CCE << /*Constant*/0 << From->getType() << T;
5097     break;
5098   }
5099 
5100   // Check the expression is a constant expression.
5101   SmallVector<PartialDiagnosticAt, 8> Notes;
5102   Expr::EvalResult Eval;
5103   Eval.Diag = &Notes;
5104 
5105   if ((T->isReferenceType()
5106            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5107            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5108       (RequireInt && !Eval.Val.isInt())) {
5109     // The expression can't be folded, so we can't keep it at this position in
5110     // the AST.
5111     Result = ExprError();
5112   } else {
5113     Value = Eval.Val;
5114 
5115     if (Notes.empty()) {
5116       // It's a constant expression.
5117       return Result;
5118     }
5119   }
5120 
5121   // It's not a constant expression. Produce an appropriate diagnostic.
5122   if (Notes.size() == 1 &&
5123       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5124     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5125   else {
5126     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5127       << CCE << From->getSourceRange();
5128     for (unsigned I = 0; I < Notes.size(); ++I)
5129       S.Diag(Notes[I].first, Notes[I].second);
5130   }
5131   return ExprError();
5132 }
5133 
5134 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5135                                                   APValue &Value, CCEKind CCE) {
5136   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5137 }
5138 
5139 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5140                                                   llvm::APSInt &Value,
5141                                                   CCEKind CCE) {
5142   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5143 
5144   APValue V;
5145   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5146   if (!R.isInvalid())
5147     Value = V.getInt();
5148   return R;
5149 }
5150 
5151 
5152 /// dropPointerConversions - If the given standard conversion sequence
5153 /// involves any pointer conversions, remove them.  This may change
5154 /// the result type of the conversion sequence.
5155 static void dropPointerConversion(StandardConversionSequence &SCS) {
5156   if (SCS.Second == ICK_Pointer_Conversion) {
5157     SCS.Second = ICK_Identity;
5158     SCS.Third = ICK_Identity;
5159     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5160   }
5161 }
5162 
5163 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5164 /// convert the expression From to an Objective-C pointer type.
5165 static ImplicitConversionSequence
5166 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5167   // Do an implicit conversion to 'id'.
5168   QualType Ty = S.Context.getObjCIdType();
5169   ImplicitConversionSequence ICS
5170     = TryImplicitConversion(S, From, Ty,
5171                             // FIXME: Are these flags correct?
5172                             /*SuppressUserConversions=*/false,
5173                             /*AllowExplicit=*/true,
5174                             /*InOverloadResolution=*/false,
5175                             /*CStyle=*/false,
5176                             /*AllowObjCWritebackConversion=*/false,
5177                             /*AllowObjCConversionOnExplicit=*/true);
5178 
5179   // Strip off any final conversions to 'id'.
5180   switch (ICS.getKind()) {
5181   case ImplicitConversionSequence::BadConversion:
5182   case ImplicitConversionSequence::AmbiguousConversion:
5183   case ImplicitConversionSequence::EllipsisConversion:
5184     break;
5185 
5186   case ImplicitConversionSequence::UserDefinedConversion:
5187     dropPointerConversion(ICS.UserDefined.After);
5188     break;
5189 
5190   case ImplicitConversionSequence::StandardConversion:
5191     dropPointerConversion(ICS.Standard);
5192     break;
5193   }
5194 
5195   return ICS;
5196 }
5197 
5198 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5199 /// conversion of the expression From to an Objective-C pointer type.
5200 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5201   if (checkPlaceholderForOverload(*this, From))
5202     return ExprError();
5203 
5204   QualType Ty = Context.getObjCIdType();
5205   ImplicitConversionSequence ICS =
5206     TryContextuallyConvertToObjCPointer(*this, From);
5207   if (!ICS.isBad())
5208     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5209   return ExprError();
5210 }
5211 
5212 /// Determine whether the provided type is an integral type, or an enumeration
5213 /// type of a permitted flavor.
5214 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5215   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5216                                  : T->isIntegralOrUnscopedEnumerationType();
5217 }
5218 
5219 static ExprResult
5220 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5221                             Sema::ContextualImplicitConverter &Converter,
5222                             QualType T, UnresolvedSetImpl &ViableConversions) {
5223 
5224   if (Converter.Suppress)
5225     return ExprError();
5226 
5227   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5228   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5229     CXXConversionDecl *Conv =
5230         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5231     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5232     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5233   }
5234   return From;
5235 }
5236 
5237 static bool
5238 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5239                            Sema::ContextualImplicitConverter &Converter,
5240                            QualType T, bool HadMultipleCandidates,
5241                            UnresolvedSetImpl &ExplicitConversions) {
5242   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5243     DeclAccessPair Found = ExplicitConversions[0];
5244     CXXConversionDecl *Conversion =
5245         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5246 
5247     // The user probably meant to invoke the given explicit
5248     // conversion; use it.
5249     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5250     std::string TypeStr;
5251     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5252 
5253     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5254         << FixItHint::CreateInsertion(From->getLocStart(),
5255                                       "static_cast<" + TypeStr + ">(")
5256         << FixItHint::CreateInsertion(
5257                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5258     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5259 
5260     // If we aren't in a SFINAE context, build a call to the
5261     // explicit conversion function.
5262     if (SemaRef.isSFINAEContext())
5263       return true;
5264 
5265     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5266     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5267                                                        HadMultipleCandidates);
5268     if (Result.isInvalid())
5269       return true;
5270     // Record usage of conversion in an implicit cast.
5271     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5272                                     CK_UserDefinedConversion, Result.get(),
5273                                     nullptr, Result.get()->getValueKind());
5274   }
5275   return false;
5276 }
5277 
5278 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5279                              Sema::ContextualImplicitConverter &Converter,
5280                              QualType T, bool HadMultipleCandidates,
5281                              DeclAccessPair &Found) {
5282   CXXConversionDecl *Conversion =
5283       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5284   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5285 
5286   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5287   if (!Converter.SuppressConversion) {
5288     if (SemaRef.isSFINAEContext())
5289       return true;
5290 
5291     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5292         << From->getSourceRange();
5293   }
5294 
5295   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5296                                                      HadMultipleCandidates);
5297   if (Result.isInvalid())
5298     return true;
5299   // Record usage of conversion in an implicit cast.
5300   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5301                                   CK_UserDefinedConversion, Result.get(),
5302                                   nullptr, Result.get()->getValueKind());
5303   return false;
5304 }
5305 
5306 static ExprResult finishContextualImplicitConversion(
5307     Sema &SemaRef, SourceLocation Loc, Expr *From,
5308     Sema::ContextualImplicitConverter &Converter) {
5309   if (!Converter.match(From->getType()) && !Converter.Suppress)
5310     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5311         << From->getSourceRange();
5312 
5313   return SemaRef.DefaultLvalueConversion(From);
5314 }
5315 
5316 static void
5317 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5318                                   UnresolvedSetImpl &ViableConversions,
5319                                   OverloadCandidateSet &CandidateSet) {
5320   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5321     DeclAccessPair FoundDecl = ViableConversions[I];
5322     NamedDecl *D = FoundDecl.getDecl();
5323     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5324     if (isa<UsingShadowDecl>(D))
5325       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5326 
5327     CXXConversionDecl *Conv;
5328     FunctionTemplateDecl *ConvTemplate;
5329     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5330       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5331     else
5332       Conv = cast<CXXConversionDecl>(D);
5333 
5334     if (ConvTemplate)
5335       SemaRef.AddTemplateConversionCandidate(
5336         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5337         /*AllowObjCConversionOnExplicit=*/false);
5338     else
5339       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5340                                      ToType, CandidateSet,
5341                                      /*AllowObjCConversionOnExplicit=*/false);
5342   }
5343 }
5344 
5345 /// \brief Attempt to convert the given expression to a type which is accepted
5346 /// by the given converter.
5347 ///
5348 /// This routine will attempt to convert an expression of class type to a
5349 /// type accepted by the specified converter. In C++11 and before, the class
5350 /// must have a single non-explicit conversion function converting to a matching
5351 /// type. In C++1y, there can be multiple such conversion functions, but only
5352 /// one target type.
5353 ///
5354 /// \param Loc The source location of the construct that requires the
5355 /// conversion.
5356 ///
5357 /// \param From The expression we're converting from.
5358 ///
5359 /// \param Converter Used to control and diagnose the conversion process.
5360 ///
5361 /// \returns The expression, converted to an integral or enumeration type if
5362 /// successful.
5363 ExprResult Sema::PerformContextualImplicitConversion(
5364     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5365   // We can't perform any more checking for type-dependent expressions.
5366   if (From->isTypeDependent())
5367     return From;
5368 
5369   // Process placeholders immediately.
5370   if (From->hasPlaceholderType()) {
5371     ExprResult result = CheckPlaceholderExpr(From);
5372     if (result.isInvalid())
5373       return result;
5374     From = result.get();
5375   }
5376 
5377   // If the expression already has a matching type, we're golden.
5378   QualType T = From->getType();
5379   if (Converter.match(T))
5380     return DefaultLvalueConversion(From);
5381 
5382   // FIXME: Check for missing '()' if T is a function type?
5383 
5384   // We can only perform contextual implicit conversions on objects of class
5385   // type.
5386   const RecordType *RecordTy = T->getAs<RecordType>();
5387   if (!RecordTy || !getLangOpts().CPlusPlus) {
5388     if (!Converter.Suppress)
5389       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5390     return From;
5391   }
5392 
5393   // We must have a complete class type.
5394   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5395     ContextualImplicitConverter &Converter;
5396     Expr *From;
5397 
5398     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5399         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5400 
5401     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5402       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5403     }
5404   } IncompleteDiagnoser(Converter, From);
5405 
5406   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5407     return From;
5408 
5409   // Look for a conversion to an integral or enumeration type.
5410   UnresolvedSet<4>
5411       ViableConversions; // These are *potentially* viable in C++1y.
5412   UnresolvedSet<4> ExplicitConversions;
5413   const auto &Conversions =
5414       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5415 
5416   bool HadMultipleCandidates =
5417       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5418 
5419   // To check that there is only one target type, in C++1y:
5420   QualType ToType;
5421   bool HasUniqueTargetType = true;
5422 
5423   // Collect explicit or viable (potentially in C++1y) conversions.
5424   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5425     NamedDecl *D = (*I)->getUnderlyingDecl();
5426     CXXConversionDecl *Conversion;
5427     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5428     if (ConvTemplate) {
5429       if (getLangOpts().CPlusPlus14)
5430         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5431       else
5432         continue; // C++11 does not consider conversion operator templates(?).
5433     } else
5434       Conversion = cast<CXXConversionDecl>(D);
5435 
5436     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5437            "Conversion operator templates are considered potentially "
5438            "viable in C++1y");
5439 
5440     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5441     if (Converter.match(CurToType) || ConvTemplate) {
5442 
5443       if (Conversion->isExplicit()) {
5444         // FIXME: For C++1y, do we need this restriction?
5445         // cf. diagnoseNoViableConversion()
5446         if (!ConvTemplate)
5447           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5448       } else {
5449         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5450           if (ToType.isNull())
5451             ToType = CurToType.getUnqualifiedType();
5452           else if (HasUniqueTargetType &&
5453                    (CurToType.getUnqualifiedType() != ToType))
5454             HasUniqueTargetType = false;
5455         }
5456         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5457       }
5458     }
5459   }
5460 
5461   if (getLangOpts().CPlusPlus14) {
5462     // C++1y [conv]p6:
5463     // ... An expression e of class type E appearing in such a context
5464     // is said to be contextually implicitly converted to a specified
5465     // type T and is well-formed if and only if e can be implicitly
5466     // converted to a type T that is determined as follows: E is searched
5467     // for conversion functions whose return type is cv T or reference to
5468     // cv T such that T is allowed by the context. There shall be
5469     // exactly one such T.
5470 
5471     // If no unique T is found:
5472     if (ToType.isNull()) {
5473       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5474                                      HadMultipleCandidates,
5475                                      ExplicitConversions))
5476         return ExprError();
5477       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5478     }
5479 
5480     // If more than one unique Ts are found:
5481     if (!HasUniqueTargetType)
5482       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5483                                          ViableConversions);
5484 
5485     // If one unique T is found:
5486     // First, build a candidate set from the previously recorded
5487     // potentially viable conversions.
5488     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5489     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5490                                       CandidateSet);
5491 
5492     // Then, perform overload resolution over the candidate set.
5493     OverloadCandidateSet::iterator Best;
5494     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5495     case OR_Success: {
5496       // Apply this conversion.
5497       DeclAccessPair Found =
5498           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5499       if (recordConversion(*this, Loc, From, Converter, T,
5500                            HadMultipleCandidates, Found))
5501         return ExprError();
5502       break;
5503     }
5504     case OR_Ambiguous:
5505       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5506                                          ViableConversions);
5507     case OR_No_Viable_Function:
5508       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5509                                      HadMultipleCandidates,
5510                                      ExplicitConversions))
5511         return ExprError();
5512     // fall through 'OR_Deleted' case.
5513     case OR_Deleted:
5514       // We'll complain below about a non-integral condition type.
5515       break;
5516     }
5517   } else {
5518     switch (ViableConversions.size()) {
5519     case 0: {
5520       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5521                                      HadMultipleCandidates,
5522                                      ExplicitConversions))
5523         return ExprError();
5524 
5525       // We'll complain below about a non-integral condition type.
5526       break;
5527     }
5528     case 1: {
5529       // Apply this conversion.
5530       DeclAccessPair Found = ViableConversions[0];
5531       if (recordConversion(*this, Loc, From, Converter, T,
5532                            HadMultipleCandidates, Found))
5533         return ExprError();
5534       break;
5535     }
5536     default:
5537       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5538                                          ViableConversions);
5539     }
5540   }
5541 
5542   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5543 }
5544 
5545 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5546 /// an acceptable non-member overloaded operator for a call whose
5547 /// arguments have types T1 (and, if non-empty, T2). This routine
5548 /// implements the check in C++ [over.match.oper]p3b2 concerning
5549 /// enumeration types.
5550 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5551                                                    FunctionDecl *Fn,
5552                                                    ArrayRef<Expr *> Args) {
5553   QualType T1 = Args[0]->getType();
5554   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5555 
5556   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5557     return true;
5558 
5559   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5560     return true;
5561 
5562   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5563   if (Proto->getNumParams() < 1)
5564     return false;
5565 
5566   if (T1->isEnumeralType()) {
5567     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5568     if (Context.hasSameUnqualifiedType(T1, ArgType))
5569       return true;
5570   }
5571 
5572   if (Proto->getNumParams() < 2)
5573     return false;
5574 
5575   if (!T2.isNull() && T2->isEnumeralType()) {
5576     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5577     if (Context.hasSameUnqualifiedType(T2, ArgType))
5578       return true;
5579   }
5580 
5581   return false;
5582 }
5583 
5584 /// AddOverloadCandidate - Adds the given function to the set of
5585 /// candidate functions, using the given function call arguments.  If
5586 /// @p SuppressUserConversions, then don't allow user-defined
5587 /// conversions via constructors or conversion operators.
5588 ///
5589 /// \param PartialOverloading true if we are performing "partial" overloading
5590 /// based on an incomplete set of function arguments. This feature is used by
5591 /// code completion.
5592 void
5593 Sema::AddOverloadCandidate(FunctionDecl *Function,
5594                            DeclAccessPair FoundDecl,
5595                            ArrayRef<Expr *> Args,
5596                            OverloadCandidateSet &CandidateSet,
5597                            bool SuppressUserConversions,
5598                            bool PartialOverloading,
5599                            bool AllowExplicit) {
5600   const FunctionProtoType *Proto
5601     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5602   assert(Proto && "Functions without a prototype cannot be overloaded");
5603   assert(!Function->getDescribedFunctionTemplate() &&
5604          "Use AddTemplateOverloadCandidate for function templates");
5605 
5606   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5607     if (!isa<CXXConstructorDecl>(Method)) {
5608       // If we get here, it's because we're calling a member function
5609       // that is named without a member access expression (e.g.,
5610       // "this->f") that was either written explicitly or created
5611       // implicitly. This can happen with a qualified call to a member
5612       // function, e.g., X::f(). We use an empty type for the implied
5613       // object argument (C++ [over.call.func]p3), and the acting context
5614       // is irrelevant.
5615       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5616                          QualType(), Expr::Classification::makeSimpleLValue(),
5617                          Args, CandidateSet, SuppressUserConversions,
5618                          PartialOverloading);
5619       return;
5620     }
5621     // We treat a constructor like a non-member function, since its object
5622     // argument doesn't participate in overload resolution.
5623   }
5624 
5625   if (!CandidateSet.isNewCandidate(Function))
5626     return;
5627 
5628   // C++ [over.match.oper]p3:
5629   //   if no operand has a class type, only those non-member functions in the
5630   //   lookup set that have a first parameter of type T1 or "reference to
5631   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5632   //   is a right operand) a second parameter of type T2 or "reference to
5633   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5634   //   candidate functions.
5635   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5636       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5637     return;
5638 
5639   // C++11 [class.copy]p11: [DR1402]
5640   //   A defaulted move constructor that is defined as deleted is ignored by
5641   //   overload resolution.
5642   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5643   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5644       Constructor->isMoveConstructor())
5645     return;
5646 
5647   // Overload resolution is always an unevaluated context.
5648   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5649 
5650   // Add this candidate
5651   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5652   Candidate.FoundDecl = FoundDecl;
5653   Candidate.Function = Function;
5654   Candidate.Viable = true;
5655   Candidate.IsSurrogate = false;
5656   Candidate.IgnoreObjectArgument = false;
5657   Candidate.ExplicitCallArguments = Args.size();
5658 
5659   if (Constructor) {
5660     // C++ [class.copy]p3:
5661     //   A member function template is never instantiated to perform the copy
5662     //   of a class object to an object of its class type.
5663     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5664     if (Args.size() == 1 &&
5665         Constructor->isSpecializationCopyingObject() &&
5666         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5667          IsDerivedFrom(Args[0]->getType(), ClassType))) {
5668       Candidate.Viable = false;
5669       Candidate.FailureKind = ovl_fail_illegal_constructor;
5670       return;
5671     }
5672   }
5673 
5674   unsigned NumParams = Proto->getNumParams();
5675 
5676   // (C++ 13.3.2p2): A candidate function having fewer than m
5677   // parameters is viable only if it has an ellipsis in its parameter
5678   // list (8.3.5).
5679   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5680       !Proto->isVariadic()) {
5681     Candidate.Viable = false;
5682     Candidate.FailureKind = ovl_fail_too_many_arguments;
5683     return;
5684   }
5685 
5686   // (C++ 13.3.2p2): A candidate function having more than m parameters
5687   // is viable only if the (m+1)st parameter has a default argument
5688   // (8.3.6). For the purposes of overload resolution, the
5689   // parameter list is truncated on the right, so that there are
5690   // exactly m parameters.
5691   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5692   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5693     // Not enough arguments.
5694     Candidate.Viable = false;
5695     Candidate.FailureKind = ovl_fail_too_few_arguments;
5696     return;
5697   }
5698 
5699   // (CUDA B.1): Check for invalid calls between targets.
5700   if (getLangOpts().CUDA)
5701     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5702       // Skip the check for callers that are implicit members, because in this
5703       // case we may not yet know what the member's target is; the target is
5704       // inferred for the member automatically, based on the bases and fields of
5705       // the class.
5706       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5707         Candidate.Viable = false;
5708         Candidate.FailureKind = ovl_fail_bad_target;
5709         return;
5710       }
5711 
5712   // Determine the implicit conversion sequences for each of the
5713   // arguments.
5714   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5715     if (ArgIdx < NumParams) {
5716       // (C++ 13.3.2p3): for F to be a viable function, there shall
5717       // exist for each argument an implicit conversion sequence
5718       // (13.3.3.1) that converts that argument to the corresponding
5719       // parameter of F.
5720       QualType ParamType = Proto->getParamType(ArgIdx);
5721       Candidate.Conversions[ArgIdx]
5722         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5723                                 SuppressUserConversions,
5724                                 /*InOverloadResolution=*/true,
5725                                 /*AllowObjCWritebackConversion=*/
5726                                   getLangOpts().ObjCAutoRefCount,
5727                                 AllowExplicit);
5728       if (Candidate.Conversions[ArgIdx].isBad()) {
5729         Candidate.Viable = false;
5730         Candidate.FailureKind = ovl_fail_bad_conversion;
5731         return;
5732       }
5733     } else {
5734       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5735       // argument for which there is no corresponding parameter is
5736       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5737       Candidate.Conversions[ArgIdx].setEllipsis();
5738     }
5739   }
5740 
5741   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5742     Candidate.Viable = false;
5743     Candidate.FailureKind = ovl_fail_enable_if;
5744     Candidate.DeductionFailure.Data = FailedAttr;
5745     return;
5746   }
5747 }
5748 
5749 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5750                                        bool IsInstance) {
5751   SmallVector<ObjCMethodDecl*, 4> Methods;
5752   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5753     return nullptr;
5754 
5755   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5756     bool Match = true;
5757     ObjCMethodDecl *Method = Methods[b];
5758     unsigned NumNamedArgs = Sel.getNumArgs();
5759     // Method might have more arguments than selector indicates. This is due
5760     // to addition of c-style arguments in method.
5761     if (Method->param_size() > NumNamedArgs)
5762       NumNamedArgs = Method->param_size();
5763     if (Args.size() < NumNamedArgs)
5764       continue;
5765 
5766     for (unsigned i = 0; i < NumNamedArgs; i++) {
5767       // We can't do any type-checking on a type-dependent argument.
5768       if (Args[i]->isTypeDependent()) {
5769         Match = false;
5770         break;
5771       }
5772 
5773       ParmVarDecl *param = Method->parameters()[i];
5774       Expr *argExpr = Args[i];
5775       assert(argExpr && "SelectBestMethod(): missing expression");
5776 
5777       // Strip the unbridged-cast placeholder expression off unless it's
5778       // a consumed argument.
5779       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5780           !param->hasAttr<CFConsumedAttr>())
5781         argExpr = stripARCUnbridgedCast(argExpr);
5782 
5783       // If the parameter is __unknown_anytype, move on to the next method.
5784       if (param->getType() == Context.UnknownAnyTy) {
5785         Match = false;
5786         break;
5787       }
5788 
5789       ImplicitConversionSequence ConversionState
5790         = TryCopyInitialization(*this, argExpr, param->getType(),
5791                                 /*SuppressUserConversions*/false,
5792                                 /*InOverloadResolution=*/true,
5793                                 /*AllowObjCWritebackConversion=*/
5794                                 getLangOpts().ObjCAutoRefCount,
5795                                 /*AllowExplicit*/false);
5796         if (ConversionState.isBad()) {
5797           Match = false;
5798           break;
5799         }
5800     }
5801     // Promote additional arguments to variadic methods.
5802     if (Match && Method->isVariadic()) {
5803       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5804         if (Args[i]->isTypeDependent()) {
5805           Match = false;
5806           break;
5807         }
5808         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5809                                                           nullptr);
5810         if (Arg.isInvalid()) {
5811           Match = false;
5812           break;
5813         }
5814       }
5815     } else {
5816       // Check for extra arguments to non-variadic methods.
5817       if (Args.size() != NumNamedArgs)
5818         Match = false;
5819       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5820         // Special case when selectors have no argument. In this case, select
5821         // one with the most general result type of 'id'.
5822         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5823           QualType ReturnT = Methods[b]->getReturnType();
5824           if (ReturnT->isObjCIdType())
5825             return Methods[b];
5826         }
5827       }
5828     }
5829 
5830     if (Match)
5831       return Method;
5832   }
5833   return nullptr;
5834 }
5835 
5836 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5837 
5838 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5839                                   bool MissingImplicitThis) {
5840   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5841   // we need to find the first failing one.
5842   if (!Function->hasAttrs())
5843     return nullptr;
5844   AttrVec Attrs = Function->getAttrs();
5845   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5846                                        IsNotEnableIfAttr);
5847   if (Attrs.begin() == E)
5848     return nullptr;
5849   std::reverse(Attrs.begin(), E);
5850 
5851   SFINAETrap Trap(*this);
5852 
5853   SmallVector<Expr *, 16> ConvertedArgs;
5854   bool InitializationFailed = false;
5855   bool ContainsValueDependentExpr = false;
5856 
5857   // Convert the arguments.
5858   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5859     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5860         !cast<CXXMethodDecl>(Function)->isStatic() &&
5861         !isa<CXXConstructorDecl>(Function)) {
5862       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5863       ExprResult R =
5864         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5865                                             Method, Method);
5866       if (R.isInvalid()) {
5867         InitializationFailed = true;
5868         break;
5869       }
5870       ContainsValueDependentExpr |= R.get()->isValueDependent();
5871       ConvertedArgs.push_back(R.get());
5872     } else {
5873       ExprResult R =
5874         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5875                                                 Context,
5876                                                 Function->getParamDecl(i)),
5877                                   SourceLocation(),
5878                                   Args[i]);
5879       if (R.isInvalid()) {
5880         InitializationFailed = true;
5881         break;
5882       }
5883       ContainsValueDependentExpr |= R.get()->isValueDependent();
5884       ConvertedArgs.push_back(R.get());
5885     }
5886   }
5887 
5888   if (InitializationFailed || Trap.hasErrorOccurred())
5889     return cast<EnableIfAttr>(Attrs[0]);
5890 
5891   // Push default arguments if needed.
5892   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5893     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5894       ParmVarDecl *P = Function->getParamDecl(i);
5895       ExprResult R = PerformCopyInitialization(
5896           InitializedEntity::InitializeParameter(Context,
5897                                                  Function->getParamDecl(i)),
5898           SourceLocation(),
5899           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5900                                            : P->getDefaultArg());
5901       if (R.isInvalid()) {
5902         InitializationFailed = true;
5903         break;
5904       }
5905       ContainsValueDependentExpr |= R.get()->isValueDependent();
5906       ConvertedArgs.push_back(R.get());
5907     }
5908 
5909     if (InitializationFailed || Trap.hasErrorOccurred())
5910       return cast<EnableIfAttr>(Attrs[0]);
5911   }
5912 
5913   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5914     APValue Result;
5915     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5916     if (EIA->getCond()->isValueDependent()) {
5917       // Don't even try now, we'll examine it after instantiation.
5918       continue;
5919     }
5920 
5921     if (!EIA->getCond()->EvaluateWithSubstitution(
5922             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5923       if (!ContainsValueDependentExpr)
5924         return EIA;
5925     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5926       return EIA;
5927     }
5928   }
5929   return nullptr;
5930 }
5931 
5932 /// \brief Add all of the function declarations in the given function set to
5933 /// the overload candidate set.
5934 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5935                                  ArrayRef<Expr *> Args,
5936                                  OverloadCandidateSet& CandidateSet,
5937                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5938                                  bool SuppressUserConversions,
5939                                  bool PartialOverloading) {
5940   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5941     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5942     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5943       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5944         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5945                            cast<CXXMethodDecl>(FD)->getParent(),
5946                            Args[0]->getType(), Args[0]->Classify(Context),
5947                            Args.slice(1), CandidateSet,
5948                            SuppressUserConversions, PartialOverloading);
5949       else
5950         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5951                              SuppressUserConversions, PartialOverloading);
5952     } else {
5953       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5954       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5955           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5956         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5957                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5958                                    ExplicitTemplateArgs,
5959                                    Args[0]->getType(),
5960                                    Args[0]->Classify(Context), Args.slice(1),
5961                                    CandidateSet, SuppressUserConversions,
5962                                    PartialOverloading);
5963       else
5964         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5965                                      ExplicitTemplateArgs, Args,
5966                                      CandidateSet, SuppressUserConversions,
5967                                      PartialOverloading);
5968     }
5969   }
5970 }
5971 
5972 /// AddMethodCandidate - Adds a named decl (which is some kind of
5973 /// method) as a method candidate to the given overload set.
5974 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5975                               QualType ObjectType,
5976                               Expr::Classification ObjectClassification,
5977                               ArrayRef<Expr *> Args,
5978                               OverloadCandidateSet& CandidateSet,
5979                               bool SuppressUserConversions) {
5980   NamedDecl *Decl = FoundDecl.getDecl();
5981   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5982 
5983   if (isa<UsingShadowDecl>(Decl))
5984     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5985 
5986   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5987     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5988            "Expected a member function template");
5989     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5990                                /*ExplicitArgs*/ nullptr,
5991                                ObjectType, ObjectClassification,
5992                                Args, CandidateSet,
5993                                SuppressUserConversions);
5994   } else {
5995     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5996                        ObjectType, ObjectClassification,
5997                        Args,
5998                        CandidateSet, SuppressUserConversions);
5999   }
6000 }
6001 
6002 /// AddMethodCandidate - Adds the given C++ member function to the set
6003 /// of candidate functions, using the given function call arguments
6004 /// and the object argument (@c Object). For example, in a call
6005 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6006 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6007 /// allow user-defined conversions via constructors or conversion
6008 /// operators.
6009 void
6010 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6011                          CXXRecordDecl *ActingContext, QualType ObjectType,
6012                          Expr::Classification ObjectClassification,
6013                          ArrayRef<Expr *> Args,
6014                          OverloadCandidateSet &CandidateSet,
6015                          bool SuppressUserConversions,
6016                          bool PartialOverloading) {
6017   const FunctionProtoType *Proto
6018     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6019   assert(Proto && "Methods without a prototype cannot be overloaded");
6020   assert(!isa<CXXConstructorDecl>(Method) &&
6021          "Use AddOverloadCandidate for constructors");
6022 
6023   if (!CandidateSet.isNewCandidate(Method))
6024     return;
6025 
6026   // C++11 [class.copy]p23: [DR1402]
6027   //   A defaulted move assignment operator that is defined as deleted is
6028   //   ignored by overload resolution.
6029   if (Method->isDefaulted() && Method->isDeleted() &&
6030       Method->isMoveAssignmentOperator())
6031     return;
6032 
6033   // Overload resolution is always an unevaluated context.
6034   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6035 
6036   // Add this candidate
6037   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6038   Candidate.FoundDecl = FoundDecl;
6039   Candidate.Function = Method;
6040   Candidate.IsSurrogate = false;
6041   Candidate.IgnoreObjectArgument = false;
6042   Candidate.ExplicitCallArguments = Args.size();
6043 
6044   unsigned NumParams = Proto->getNumParams();
6045 
6046   // (C++ 13.3.2p2): A candidate function having fewer than m
6047   // parameters is viable only if it has an ellipsis in its parameter
6048   // list (8.3.5).
6049   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6050       !Proto->isVariadic()) {
6051     Candidate.Viable = false;
6052     Candidate.FailureKind = ovl_fail_too_many_arguments;
6053     return;
6054   }
6055 
6056   // (C++ 13.3.2p2): A candidate function having more than m parameters
6057   // is viable only if the (m+1)st parameter has a default argument
6058   // (8.3.6). For the purposes of overload resolution, the
6059   // parameter list is truncated on the right, so that there are
6060   // exactly m parameters.
6061   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6062   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6063     // Not enough arguments.
6064     Candidate.Viable = false;
6065     Candidate.FailureKind = ovl_fail_too_few_arguments;
6066     return;
6067   }
6068 
6069   Candidate.Viable = true;
6070 
6071   if (Method->isStatic() || ObjectType.isNull())
6072     // The implicit object argument is ignored.
6073     Candidate.IgnoreObjectArgument = true;
6074   else {
6075     // Determine the implicit conversion sequence for the object
6076     // parameter.
6077     Candidate.Conversions[0]
6078       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6079                                         Method, ActingContext);
6080     if (Candidate.Conversions[0].isBad()) {
6081       Candidate.Viable = false;
6082       Candidate.FailureKind = ovl_fail_bad_conversion;
6083       return;
6084     }
6085   }
6086 
6087   // (CUDA B.1): Check for invalid calls between targets.
6088   if (getLangOpts().CUDA)
6089     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6090       if (CheckCUDATarget(Caller, Method)) {
6091         Candidate.Viable = false;
6092         Candidate.FailureKind = ovl_fail_bad_target;
6093         return;
6094       }
6095 
6096   // Determine the implicit conversion sequences for each of the
6097   // arguments.
6098   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6099     if (ArgIdx < NumParams) {
6100       // (C++ 13.3.2p3): for F to be a viable function, there shall
6101       // exist for each argument an implicit conversion sequence
6102       // (13.3.3.1) that converts that argument to the corresponding
6103       // parameter of F.
6104       QualType ParamType = Proto->getParamType(ArgIdx);
6105       Candidate.Conversions[ArgIdx + 1]
6106         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6107                                 SuppressUserConversions,
6108                                 /*InOverloadResolution=*/true,
6109                                 /*AllowObjCWritebackConversion=*/
6110                                   getLangOpts().ObjCAutoRefCount);
6111       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6112         Candidate.Viable = false;
6113         Candidate.FailureKind = ovl_fail_bad_conversion;
6114         return;
6115       }
6116     } else {
6117       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6118       // argument for which there is no corresponding parameter is
6119       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6120       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6121     }
6122   }
6123 
6124   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6125     Candidate.Viable = false;
6126     Candidate.FailureKind = ovl_fail_enable_if;
6127     Candidate.DeductionFailure.Data = FailedAttr;
6128     return;
6129   }
6130 }
6131 
6132 /// \brief Add a C++ member function template as a candidate to the candidate
6133 /// set, using template argument deduction to produce an appropriate member
6134 /// function template specialization.
6135 void
6136 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6137                                  DeclAccessPair FoundDecl,
6138                                  CXXRecordDecl *ActingContext,
6139                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6140                                  QualType ObjectType,
6141                                  Expr::Classification ObjectClassification,
6142                                  ArrayRef<Expr *> Args,
6143                                  OverloadCandidateSet& CandidateSet,
6144                                  bool SuppressUserConversions,
6145                                  bool PartialOverloading) {
6146   if (!CandidateSet.isNewCandidate(MethodTmpl))
6147     return;
6148 
6149   // C++ [over.match.funcs]p7:
6150   //   In each case where a candidate is a function template, candidate
6151   //   function template specializations are generated using template argument
6152   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6153   //   candidate functions in the usual way.113) A given name can refer to one
6154   //   or more function templates and also to a set of overloaded non-template
6155   //   functions. In such a case, the candidate functions generated from each
6156   //   function template are combined with the set of non-template candidate
6157   //   functions.
6158   TemplateDeductionInfo Info(CandidateSet.getLocation());
6159   FunctionDecl *Specialization = nullptr;
6160   if (TemplateDeductionResult Result
6161       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6162                                 Specialization, Info, PartialOverloading)) {
6163     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6164     Candidate.FoundDecl = FoundDecl;
6165     Candidate.Function = MethodTmpl->getTemplatedDecl();
6166     Candidate.Viable = false;
6167     Candidate.FailureKind = ovl_fail_bad_deduction;
6168     Candidate.IsSurrogate = false;
6169     Candidate.IgnoreObjectArgument = false;
6170     Candidate.ExplicitCallArguments = Args.size();
6171     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6172                                                           Info);
6173     return;
6174   }
6175 
6176   // Add the function template specialization produced by template argument
6177   // deduction as a candidate.
6178   assert(Specialization && "Missing member function template specialization?");
6179   assert(isa<CXXMethodDecl>(Specialization) &&
6180          "Specialization is not a member function?");
6181   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6182                      ActingContext, ObjectType, ObjectClassification, Args,
6183                      CandidateSet, SuppressUserConversions, PartialOverloading);
6184 }
6185 
6186 /// \brief Add a C++ function template specialization as a candidate
6187 /// in the candidate set, using template argument deduction to produce
6188 /// an appropriate function template specialization.
6189 void
6190 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6191                                    DeclAccessPair FoundDecl,
6192                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6193                                    ArrayRef<Expr *> Args,
6194                                    OverloadCandidateSet& CandidateSet,
6195                                    bool SuppressUserConversions,
6196                                    bool PartialOverloading) {
6197   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6198     return;
6199 
6200   // C++ [over.match.funcs]p7:
6201   //   In each case where a candidate is a function template, candidate
6202   //   function template specializations are generated using template argument
6203   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6204   //   candidate functions in the usual way.113) A given name can refer to one
6205   //   or more function templates and also to a set of overloaded non-template
6206   //   functions. In such a case, the candidate functions generated from each
6207   //   function template are combined with the set of non-template candidate
6208   //   functions.
6209   TemplateDeductionInfo Info(CandidateSet.getLocation());
6210   FunctionDecl *Specialization = nullptr;
6211   if (TemplateDeductionResult Result
6212         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6213                                   Specialization, Info, PartialOverloading)) {
6214     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6215     Candidate.FoundDecl = FoundDecl;
6216     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6217     Candidate.Viable = false;
6218     Candidate.FailureKind = ovl_fail_bad_deduction;
6219     Candidate.IsSurrogate = false;
6220     Candidate.IgnoreObjectArgument = false;
6221     Candidate.ExplicitCallArguments = Args.size();
6222     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6223                                                           Info);
6224     return;
6225   }
6226 
6227   // Add the function template specialization produced by template argument
6228   // deduction as a candidate.
6229   assert(Specialization && "Missing function template specialization?");
6230   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6231                        SuppressUserConversions, PartialOverloading);
6232 }
6233 
6234 /// Determine whether this is an allowable conversion from the result
6235 /// of an explicit conversion operator to the expected type, per C++
6236 /// [over.match.conv]p1 and [over.match.ref]p1.
6237 ///
6238 /// \param ConvType The return type of the conversion function.
6239 ///
6240 /// \param ToType The type we are converting to.
6241 ///
6242 /// \param AllowObjCPointerConversion Allow a conversion from one
6243 /// Objective-C pointer to another.
6244 ///
6245 /// \returns true if the conversion is allowable, false otherwise.
6246 static bool isAllowableExplicitConversion(Sema &S,
6247                                           QualType ConvType, QualType ToType,
6248                                           bool AllowObjCPointerConversion) {
6249   QualType ToNonRefType = ToType.getNonReferenceType();
6250 
6251   // Easy case: the types are the same.
6252   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6253     return true;
6254 
6255   // Allow qualification conversions.
6256   bool ObjCLifetimeConversion;
6257   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6258                                   ObjCLifetimeConversion))
6259     return true;
6260 
6261   // If we're not allowed to consider Objective-C pointer conversions,
6262   // we're done.
6263   if (!AllowObjCPointerConversion)
6264     return false;
6265 
6266   // Is this an Objective-C pointer conversion?
6267   bool IncompatibleObjC = false;
6268   QualType ConvertedType;
6269   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6270                                    IncompatibleObjC);
6271 }
6272 
6273 /// AddConversionCandidate - Add a C++ conversion function as a
6274 /// candidate in the candidate set (C++ [over.match.conv],
6275 /// C++ [over.match.copy]). From is the expression we're converting from,
6276 /// and ToType is the type that we're eventually trying to convert to
6277 /// (which may or may not be the same type as the type that the
6278 /// conversion function produces).
6279 void
6280 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6281                              DeclAccessPair FoundDecl,
6282                              CXXRecordDecl *ActingContext,
6283                              Expr *From, QualType ToType,
6284                              OverloadCandidateSet& CandidateSet,
6285                              bool AllowObjCConversionOnExplicit) {
6286   assert(!Conversion->getDescribedFunctionTemplate() &&
6287          "Conversion function templates use AddTemplateConversionCandidate");
6288   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6289   if (!CandidateSet.isNewCandidate(Conversion))
6290     return;
6291 
6292   // If the conversion function has an undeduced return type, trigger its
6293   // deduction now.
6294   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6295     if (DeduceReturnType(Conversion, From->getExprLoc()))
6296       return;
6297     ConvType = Conversion->getConversionType().getNonReferenceType();
6298   }
6299 
6300   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6301   // operator is only a candidate if its return type is the target type or
6302   // can be converted to the target type with a qualification conversion.
6303   if (Conversion->isExplicit() &&
6304       !isAllowableExplicitConversion(*this, ConvType, ToType,
6305                                      AllowObjCConversionOnExplicit))
6306     return;
6307 
6308   // Overload resolution is always an unevaluated context.
6309   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6310 
6311   // Add this candidate
6312   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6313   Candidate.FoundDecl = FoundDecl;
6314   Candidate.Function = Conversion;
6315   Candidate.IsSurrogate = false;
6316   Candidate.IgnoreObjectArgument = false;
6317   Candidate.FinalConversion.setAsIdentityConversion();
6318   Candidate.FinalConversion.setFromType(ConvType);
6319   Candidate.FinalConversion.setAllToTypes(ToType);
6320   Candidate.Viable = true;
6321   Candidate.ExplicitCallArguments = 1;
6322 
6323   // C++ [over.match.funcs]p4:
6324   //   For conversion functions, the function is considered to be a member of
6325   //   the class of the implicit implied object argument for the purpose of
6326   //   defining the type of the implicit object parameter.
6327   //
6328   // Determine the implicit conversion sequence for the implicit
6329   // object parameter.
6330   QualType ImplicitParamType = From->getType();
6331   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6332     ImplicitParamType = FromPtrType->getPointeeType();
6333   CXXRecordDecl *ConversionContext
6334     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6335 
6336   Candidate.Conversions[0]
6337     = TryObjectArgumentInitialization(*this, From->getType(),
6338                                       From->Classify(Context),
6339                                       Conversion, ConversionContext);
6340 
6341   if (Candidate.Conversions[0].isBad()) {
6342     Candidate.Viable = false;
6343     Candidate.FailureKind = ovl_fail_bad_conversion;
6344     return;
6345   }
6346 
6347   // We won't go through a user-defined type conversion function to convert a
6348   // derived to base as such conversions are given Conversion Rank. They only
6349   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6350   QualType FromCanon
6351     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6352   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6353   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6354     Candidate.Viable = false;
6355     Candidate.FailureKind = ovl_fail_trivial_conversion;
6356     return;
6357   }
6358 
6359   // To determine what the conversion from the result of calling the
6360   // conversion function to the type we're eventually trying to
6361   // convert to (ToType), we need to synthesize a call to the
6362   // conversion function and attempt copy initialization from it. This
6363   // makes sure that we get the right semantics with respect to
6364   // lvalues/rvalues and the type. Fortunately, we can allocate this
6365   // call on the stack and we don't need its arguments to be
6366   // well-formed.
6367   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6368                             VK_LValue, From->getLocStart());
6369   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6370                                 Context.getPointerType(Conversion->getType()),
6371                                 CK_FunctionToPointerDecay,
6372                                 &ConversionRef, VK_RValue);
6373 
6374   QualType ConversionType = Conversion->getConversionType();
6375   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6376     Candidate.Viable = false;
6377     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6378     return;
6379   }
6380 
6381   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6382 
6383   // Note that it is safe to allocate CallExpr on the stack here because
6384   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6385   // allocator).
6386   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6387   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6388                 From->getLocStart());
6389   ImplicitConversionSequence ICS =
6390     TryCopyInitialization(*this, &Call, ToType,
6391                           /*SuppressUserConversions=*/true,
6392                           /*InOverloadResolution=*/false,
6393                           /*AllowObjCWritebackConversion=*/false);
6394 
6395   switch (ICS.getKind()) {
6396   case ImplicitConversionSequence::StandardConversion:
6397     Candidate.FinalConversion = ICS.Standard;
6398 
6399     // C++ [over.ics.user]p3:
6400     //   If the user-defined conversion is specified by a specialization of a
6401     //   conversion function template, the second standard conversion sequence
6402     //   shall have exact match rank.
6403     if (Conversion->getPrimaryTemplate() &&
6404         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6405       Candidate.Viable = false;
6406       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6407       return;
6408     }
6409 
6410     // C++0x [dcl.init.ref]p5:
6411     //    In the second case, if the reference is an rvalue reference and
6412     //    the second standard conversion sequence of the user-defined
6413     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6414     //    program is ill-formed.
6415     if (ToType->isRValueReferenceType() &&
6416         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6417       Candidate.Viable = false;
6418       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6419       return;
6420     }
6421     break;
6422 
6423   case ImplicitConversionSequence::BadConversion:
6424     Candidate.Viable = false;
6425     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6426     return;
6427 
6428   default:
6429     llvm_unreachable(
6430            "Can only end up with a standard conversion sequence or failure");
6431   }
6432 
6433   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6434     Candidate.Viable = false;
6435     Candidate.FailureKind = ovl_fail_enable_if;
6436     Candidate.DeductionFailure.Data = FailedAttr;
6437     return;
6438   }
6439 }
6440 
6441 /// \brief Adds a conversion function template specialization
6442 /// candidate to the overload set, using template argument deduction
6443 /// to deduce the template arguments of the conversion function
6444 /// template from the type that we are converting to (C++
6445 /// [temp.deduct.conv]).
6446 void
6447 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6448                                      DeclAccessPair FoundDecl,
6449                                      CXXRecordDecl *ActingDC,
6450                                      Expr *From, QualType ToType,
6451                                      OverloadCandidateSet &CandidateSet,
6452                                      bool AllowObjCConversionOnExplicit) {
6453   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6454          "Only conversion function templates permitted here");
6455 
6456   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6457     return;
6458 
6459   TemplateDeductionInfo Info(CandidateSet.getLocation());
6460   CXXConversionDecl *Specialization = nullptr;
6461   if (TemplateDeductionResult Result
6462         = DeduceTemplateArguments(FunctionTemplate, ToType,
6463                                   Specialization, Info)) {
6464     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6465     Candidate.FoundDecl = FoundDecl;
6466     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6467     Candidate.Viable = false;
6468     Candidate.FailureKind = ovl_fail_bad_deduction;
6469     Candidate.IsSurrogate = false;
6470     Candidate.IgnoreObjectArgument = false;
6471     Candidate.ExplicitCallArguments = 1;
6472     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6473                                                           Info);
6474     return;
6475   }
6476 
6477   // Add the conversion function template specialization produced by
6478   // template argument deduction as a candidate.
6479   assert(Specialization && "Missing function template specialization?");
6480   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6481                          CandidateSet, AllowObjCConversionOnExplicit);
6482 }
6483 
6484 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6485 /// converts the given @c Object to a function pointer via the
6486 /// conversion function @c Conversion, and then attempts to call it
6487 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6488 /// the type of function that we'll eventually be calling.
6489 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6490                                  DeclAccessPair FoundDecl,
6491                                  CXXRecordDecl *ActingContext,
6492                                  const FunctionProtoType *Proto,
6493                                  Expr *Object,
6494                                  ArrayRef<Expr *> Args,
6495                                  OverloadCandidateSet& CandidateSet) {
6496   if (!CandidateSet.isNewCandidate(Conversion))
6497     return;
6498 
6499   // Overload resolution is always an unevaluated context.
6500   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6501 
6502   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6503   Candidate.FoundDecl = FoundDecl;
6504   Candidate.Function = nullptr;
6505   Candidate.Surrogate = Conversion;
6506   Candidate.Viable = true;
6507   Candidate.IsSurrogate = true;
6508   Candidate.IgnoreObjectArgument = false;
6509   Candidate.ExplicitCallArguments = Args.size();
6510 
6511   // Determine the implicit conversion sequence for the implicit
6512   // object parameter.
6513   ImplicitConversionSequence ObjectInit
6514     = TryObjectArgumentInitialization(*this, Object->getType(),
6515                                       Object->Classify(Context),
6516                                       Conversion, ActingContext);
6517   if (ObjectInit.isBad()) {
6518     Candidate.Viable = false;
6519     Candidate.FailureKind = ovl_fail_bad_conversion;
6520     Candidate.Conversions[0] = ObjectInit;
6521     return;
6522   }
6523 
6524   // The first conversion is actually a user-defined conversion whose
6525   // first conversion is ObjectInit's standard conversion (which is
6526   // effectively a reference binding). Record it as such.
6527   Candidate.Conversions[0].setUserDefined();
6528   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6529   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6530   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6531   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6532   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6533   Candidate.Conversions[0].UserDefined.After
6534     = Candidate.Conversions[0].UserDefined.Before;
6535   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6536 
6537   // Find the
6538   unsigned NumParams = Proto->getNumParams();
6539 
6540   // (C++ 13.3.2p2): A candidate function having fewer than m
6541   // parameters is viable only if it has an ellipsis in its parameter
6542   // list (8.3.5).
6543   if (Args.size() > NumParams && !Proto->isVariadic()) {
6544     Candidate.Viable = false;
6545     Candidate.FailureKind = ovl_fail_too_many_arguments;
6546     return;
6547   }
6548 
6549   // Function types don't have any default arguments, so just check if
6550   // we have enough arguments.
6551   if (Args.size() < NumParams) {
6552     // Not enough arguments.
6553     Candidate.Viable = false;
6554     Candidate.FailureKind = ovl_fail_too_few_arguments;
6555     return;
6556   }
6557 
6558   // Determine the implicit conversion sequences for each of the
6559   // arguments.
6560   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6561     if (ArgIdx < NumParams) {
6562       // (C++ 13.3.2p3): for F to be a viable function, there shall
6563       // exist for each argument an implicit conversion sequence
6564       // (13.3.3.1) that converts that argument to the corresponding
6565       // parameter of F.
6566       QualType ParamType = Proto->getParamType(ArgIdx);
6567       Candidate.Conversions[ArgIdx + 1]
6568         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6569                                 /*SuppressUserConversions=*/false,
6570                                 /*InOverloadResolution=*/false,
6571                                 /*AllowObjCWritebackConversion=*/
6572                                   getLangOpts().ObjCAutoRefCount);
6573       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6574         Candidate.Viable = false;
6575         Candidate.FailureKind = ovl_fail_bad_conversion;
6576         return;
6577       }
6578     } else {
6579       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6580       // argument for which there is no corresponding parameter is
6581       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6582       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6583     }
6584   }
6585 
6586   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6587     Candidate.Viable = false;
6588     Candidate.FailureKind = ovl_fail_enable_if;
6589     Candidate.DeductionFailure.Data = FailedAttr;
6590     return;
6591   }
6592 }
6593 
6594 /// \brief Add overload candidates for overloaded operators that are
6595 /// member functions.
6596 ///
6597 /// Add the overloaded operator candidates that are member functions
6598 /// for the operator Op that was used in an operator expression such
6599 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6600 /// CandidateSet will store the added overload candidates. (C++
6601 /// [over.match.oper]).
6602 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6603                                        SourceLocation OpLoc,
6604                                        ArrayRef<Expr *> Args,
6605                                        OverloadCandidateSet& CandidateSet,
6606                                        SourceRange OpRange) {
6607   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6608 
6609   // C++ [over.match.oper]p3:
6610   //   For a unary operator @ with an operand of a type whose
6611   //   cv-unqualified version is T1, and for a binary operator @ with
6612   //   a left operand of a type whose cv-unqualified version is T1 and
6613   //   a right operand of a type whose cv-unqualified version is T2,
6614   //   three sets of candidate functions, designated member
6615   //   candidates, non-member candidates and built-in candidates, are
6616   //   constructed as follows:
6617   QualType T1 = Args[0]->getType();
6618 
6619   //     -- If T1 is a complete class type or a class currently being
6620   //        defined, the set of member candidates is the result of the
6621   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6622   //        the set of member candidates is empty.
6623   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6624     // Complete the type if it can be completed.
6625     RequireCompleteType(OpLoc, T1, 0);
6626     // If the type is neither complete nor being defined, bail out now.
6627     if (!T1Rec->getDecl()->getDefinition())
6628       return;
6629 
6630     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6631     LookupQualifiedName(Operators, T1Rec->getDecl());
6632     Operators.suppressDiagnostics();
6633 
6634     for (LookupResult::iterator Oper = Operators.begin(),
6635                              OperEnd = Operators.end();
6636          Oper != OperEnd;
6637          ++Oper)
6638       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6639                          Args[0]->Classify(Context),
6640                          Args.slice(1),
6641                          CandidateSet,
6642                          /* SuppressUserConversions = */ false);
6643   }
6644 }
6645 
6646 /// AddBuiltinCandidate - Add a candidate for a built-in
6647 /// operator. ResultTy and ParamTys are the result and parameter types
6648 /// of the built-in candidate, respectively. Args and NumArgs are the
6649 /// arguments being passed to the candidate. IsAssignmentOperator
6650 /// should be true when this built-in candidate is an assignment
6651 /// operator. NumContextualBoolArguments is the number of arguments
6652 /// (at the beginning of the argument list) that will be contextually
6653 /// converted to bool.
6654 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6655                                ArrayRef<Expr *> Args,
6656                                OverloadCandidateSet& CandidateSet,
6657                                bool IsAssignmentOperator,
6658                                unsigned NumContextualBoolArguments) {
6659   // Overload resolution is always an unevaluated context.
6660   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6661 
6662   // Add this candidate
6663   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6664   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6665   Candidate.Function = nullptr;
6666   Candidate.IsSurrogate = false;
6667   Candidate.IgnoreObjectArgument = false;
6668   Candidate.BuiltinTypes.ResultTy = ResultTy;
6669   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6670     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6671 
6672   // Determine the implicit conversion sequences for each of the
6673   // arguments.
6674   Candidate.Viable = true;
6675   Candidate.ExplicitCallArguments = Args.size();
6676   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6677     // C++ [over.match.oper]p4:
6678     //   For the built-in assignment operators, conversions of the
6679     //   left operand are restricted as follows:
6680     //     -- no temporaries are introduced to hold the left operand, and
6681     //     -- no user-defined conversions are applied to the left
6682     //        operand to achieve a type match with the left-most
6683     //        parameter of a built-in candidate.
6684     //
6685     // We block these conversions by turning off user-defined
6686     // conversions, since that is the only way that initialization of
6687     // a reference to a non-class type can occur from something that
6688     // is not of the same type.
6689     if (ArgIdx < NumContextualBoolArguments) {
6690       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6691              "Contextual conversion to bool requires bool type");
6692       Candidate.Conversions[ArgIdx]
6693         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6694     } else {
6695       Candidate.Conversions[ArgIdx]
6696         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6697                                 ArgIdx == 0 && IsAssignmentOperator,
6698                                 /*InOverloadResolution=*/false,
6699                                 /*AllowObjCWritebackConversion=*/
6700                                   getLangOpts().ObjCAutoRefCount);
6701     }
6702     if (Candidate.Conversions[ArgIdx].isBad()) {
6703       Candidate.Viable = false;
6704       Candidate.FailureKind = ovl_fail_bad_conversion;
6705       break;
6706     }
6707   }
6708 }
6709 
6710 namespace {
6711 
6712 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6713 /// candidate operator functions for built-in operators (C++
6714 /// [over.built]). The types are separated into pointer types and
6715 /// enumeration types.
6716 class BuiltinCandidateTypeSet  {
6717   /// TypeSet - A set of types.
6718   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6719 
6720   /// PointerTypes - The set of pointer types that will be used in the
6721   /// built-in candidates.
6722   TypeSet PointerTypes;
6723 
6724   /// MemberPointerTypes - The set of member pointer types that will be
6725   /// used in the built-in candidates.
6726   TypeSet MemberPointerTypes;
6727 
6728   /// EnumerationTypes - The set of enumeration types that will be
6729   /// used in the built-in candidates.
6730   TypeSet EnumerationTypes;
6731 
6732   /// \brief The set of vector types that will be used in the built-in
6733   /// candidates.
6734   TypeSet VectorTypes;
6735 
6736   /// \brief A flag indicating non-record types are viable candidates
6737   bool HasNonRecordTypes;
6738 
6739   /// \brief A flag indicating whether either arithmetic or enumeration types
6740   /// were present in the candidate set.
6741   bool HasArithmeticOrEnumeralTypes;
6742 
6743   /// \brief A flag indicating whether the nullptr type was present in the
6744   /// candidate set.
6745   bool HasNullPtrType;
6746 
6747   /// Sema - The semantic analysis instance where we are building the
6748   /// candidate type set.
6749   Sema &SemaRef;
6750 
6751   /// Context - The AST context in which we will build the type sets.
6752   ASTContext &Context;
6753 
6754   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6755                                                const Qualifiers &VisibleQuals);
6756   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6757 
6758 public:
6759   /// iterator - Iterates through the types that are part of the set.
6760   typedef TypeSet::iterator iterator;
6761 
6762   BuiltinCandidateTypeSet(Sema &SemaRef)
6763     : HasNonRecordTypes(false),
6764       HasArithmeticOrEnumeralTypes(false),
6765       HasNullPtrType(false),
6766       SemaRef(SemaRef),
6767       Context(SemaRef.Context) { }
6768 
6769   void AddTypesConvertedFrom(QualType Ty,
6770                              SourceLocation Loc,
6771                              bool AllowUserConversions,
6772                              bool AllowExplicitConversions,
6773                              const Qualifiers &VisibleTypeConversionsQuals);
6774 
6775   /// pointer_begin - First pointer type found;
6776   iterator pointer_begin() { return PointerTypes.begin(); }
6777 
6778   /// pointer_end - Past the last pointer type found;
6779   iterator pointer_end() { return PointerTypes.end(); }
6780 
6781   /// member_pointer_begin - First member pointer type found;
6782   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6783 
6784   /// member_pointer_end - Past the last member pointer type found;
6785   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6786 
6787   /// enumeration_begin - First enumeration type found;
6788   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6789 
6790   /// enumeration_end - Past the last enumeration type found;
6791   iterator enumeration_end() { return EnumerationTypes.end(); }
6792 
6793   iterator vector_begin() { return VectorTypes.begin(); }
6794   iterator vector_end() { return VectorTypes.end(); }
6795 
6796   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6797   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6798   bool hasNullPtrType() const { return HasNullPtrType; }
6799 };
6800 
6801 } // end anonymous namespace
6802 
6803 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6804 /// the set of pointer types along with any more-qualified variants of
6805 /// that type. For example, if @p Ty is "int const *", this routine
6806 /// will add "int const *", "int const volatile *", "int const
6807 /// restrict *", and "int const volatile restrict *" to the set of
6808 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6809 /// false otherwise.
6810 ///
6811 /// FIXME: what to do about extended qualifiers?
6812 bool
6813 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6814                                              const Qualifiers &VisibleQuals) {
6815 
6816   // Insert this type.
6817   if (!PointerTypes.insert(Ty).second)
6818     return false;
6819 
6820   QualType PointeeTy;
6821   const PointerType *PointerTy = Ty->getAs<PointerType>();
6822   bool buildObjCPtr = false;
6823   if (!PointerTy) {
6824     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6825     PointeeTy = PTy->getPointeeType();
6826     buildObjCPtr = true;
6827   } else {
6828     PointeeTy = PointerTy->getPointeeType();
6829   }
6830 
6831   // Don't add qualified variants of arrays. For one, they're not allowed
6832   // (the qualifier would sink to the element type), and for another, the
6833   // only overload situation where it matters is subscript or pointer +- int,
6834   // and those shouldn't have qualifier variants anyway.
6835   if (PointeeTy->isArrayType())
6836     return true;
6837 
6838   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6839   bool hasVolatile = VisibleQuals.hasVolatile();
6840   bool hasRestrict = VisibleQuals.hasRestrict();
6841 
6842   // Iterate through all strict supersets of BaseCVR.
6843   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6844     if ((CVR | BaseCVR) != CVR) continue;
6845     // Skip over volatile if no volatile found anywhere in the types.
6846     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6847 
6848     // Skip over restrict if no restrict found anywhere in the types, or if
6849     // the type cannot be restrict-qualified.
6850     if ((CVR & Qualifiers::Restrict) &&
6851         (!hasRestrict ||
6852          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6853       continue;
6854 
6855     // Build qualified pointee type.
6856     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6857 
6858     // Build qualified pointer type.
6859     QualType QPointerTy;
6860     if (!buildObjCPtr)
6861       QPointerTy = Context.getPointerType(QPointeeTy);
6862     else
6863       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6864 
6865     // Insert qualified pointer type.
6866     PointerTypes.insert(QPointerTy);
6867   }
6868 
6869   return true;
6870 }
6871 
6872 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6873 /// to the set of pointer types along with any more-qualified variants of
6874 /// that type. For example, if @p Ty is "int const *", this routine
6875 /// will add "int const *", "int const volatile *", "int const
6876 /// restrict *", and "int const volatile restrict *" to the set of
6877 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6878 /// false otherwise.
6879 ///
6880 /// FIXME: what to do about extended qualifiers?
6881 bool
6882 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6883     QualType Ty) {
6884   // Insert this type.
6885   if (!MemberPointerTypes.insert(Ty).second)
6886     return false;
6887 
6888   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6889   assert(PointerTy && "type was not a member pointer type!");
6890 
6891   QualType PointeeTy = PointerTy->getPointeeType();
6892   // Don't add qualified variants of arrays. For one, they're not allowed
6893   // (the qualifier would sink to the element type), and for another, the
6894   // only overload situation where it matters is subscript or pointer +- int,
6895   // and those shouldn't have qualifier variants anyway.
6896   if (PointeeTy->isArrayType())
6897     return true;
6898   const Type *ClassTy = PointerTy->getClass();
6899 
6900   // Iterate through all strict supersets of the pointee type's CVR
6901   // qualifiers.
6902   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6903   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6904     if ((CVR | BaseCVR) != CVR) continue;
6905 
6906     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6907     MemberPointerTypes.insert(
6908       Context.getMemberPointerType(QPointeeTy, ClassTy));
6909   }
6910 
6911   return true;
6912 }
6913 
6914 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6915 /// Ty can be implicit converted to the given set of @p Types. We're
6916 /// primarily interested in pointer types and enumeration types. We also
6917 /// take member pointer types, for the conditional operator.
6918 /// AllowUserConversions is true if we should look at the conversion
6919 /// functions of a class type, and AllowExplicitConversions if we
6920 /// should also include the explicit conversion functions of a class
6921 /// type.
6922 void
6923 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6924                                                SourceLocation Loc,
6925                                                bool AllowUserConversions,
6926                                                bool AllowExplicitConversions,
6927                                                const Qualifiers &VisibleQuals) {
6928   // Only deal with canonical types.
6929   Ty = Context.getCanonicalType(Ty);
6930 
6931   // Look through reference types; they aren't part of the type of an
6932   // expression for the purposes of conversions.
6933   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6934     Ty = RefTy->getPointeeType();
6935 
6936   // If we're dealing with an array type, decay to the pointer.
6937   if (Ty->isArrayType())
6938     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6939 
6940   // Otherwise, we don't care about qualifiers on the type.
6941   Ty = Ty.getLocalUnqualifiedType();
6942 
6943   // Flag if we ever add a non-record type.
6944   const RecordType *TyRec = Ty->getAs<RecordType>();
6945   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6946 
6947   // Flag if we encounter an arithmetic type.
6948   HasArithmeticOrEnumeralTypes =
6949     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6950 
6951   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6952     PointerTypes.insert(Ty);
6953   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6954     // Insert our type, and its more-qualified variants, into the set
6955     // of types.
6956     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6957       return;
6958   } else if (Ty->isMemberPointerType()) {
6959     // Member pointers are far easier, since the pointee can't be converted.
6960     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6961       return;
6962   } else if (Ty->isEnumeralType()) {
6963     HasArithmeticOrEnumeralTypes = true;
6964     EnumerationTypes.insert(Ty);
6965   } else if (Ty->isVectorType()) {
6966     // We treat vector types as arithmetic types in many contexts as an
6967     // extension.
6968     HasArithmeticOrEnumeralTypes = true;
6969     VectorTypes.insert(Ty);
6970   } else if (Ty->isNullPtrType()) {
6971     HasNullPtrType = true;
6972   } else if (AllowUserConversions && TyRec) {
6973     // No conversion functions in incomplete types.
6974     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6975       return;
6976 
6977     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6978     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6979       if (isa<UsingShadowDecl>(D))
6980         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6981 
6982       // Skip conversion function templates; they don't tell us anything
6983       // about which builtin types we can convert to.
6984       if (isa<FunctionTemplateDecl>(D))
6985         continue;
6986 
6987       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6988       if (AllowExplicitConversions || !Conv->isExplicit()) {
6989         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6990                               VisibleQuals);
6991       }
6992     }
6993   }
6994 }
6995 
6996 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6997 /// the volatile- and non-volatile-qualified assignment operators for the
6998 /// given type to the candidate set.
6999 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7000                                                    QualType T,
7001                                                    ArrayRef<Expr *> Args,
7002                                     OverloadCandidateSet &CandidateSet) {
7003   QualType ParamTypes[2];
7004 
7005   // T& operator=(T&, T)
7006   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7007   ParamTypes[1] = T;
7008   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7009                         /*IsAssignmentOperator=*/true);
7010 
7011   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7012     // volatile T& operator=(volatile T&, T)
7013     ParamTypes[0]
7014       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7015     ParamTypes[1] = T;
7016     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7017                           /*IsAssignmentOperator=*/true);
7018   }
7019 }
7020 
7021 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7022 /// if any, found in visible type conversion functions found in ArgExpr's type.
7023 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7024     Qualifiers VRQuals;
7025     const RecordType *TyRec;
7026     if (const MemberPointerType *RHSMPType =
7027         ArgExpr->getType()->getAs<MemberPointerType>())
7028       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7029     else
7030       TyRec = ArgExpr->getType()->getAs<RecordType>();
7031     if (!TyRec) {
7032       // Just to be safe, assume the worst case.
7033       VRQuals.addVolatile();
7034       VRQuals.addRestrict();
7035       return VRQuals;
7036     }
7037 
7038     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7039     if (!ClassDecl->hasDefinition())
7040       return VRQuals;
7041 
7042     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7043       if (isa<UsingShadowDecl>(D))
7044         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7045       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7046         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7047         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7048           CanTy = ResTypeRef->getPointeeType();
7049         // Need to go down the pointer/mempointer chain and add qualifiers
7050         // as see them.
7051         bool done = false;
7052         while (!done) {
7053           if (CanTy.isRestrictQualified())
7054             VRQuals.addRestrict();
7055           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7056             CanTy = ResTypePtr->getPointeeType();
7057           else if (const MemberPointerType *ResTypeMPtr =
7058                 CanTy->getAs<MemberPointerType>())
7059             CanTy = ResTypeMPtr->getPointeeType();
7060           else
7061             done = true;
7062           if (CanTy.isVolatileQualified())
7063             VRQuals.addVolatile();
7064           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7065             return VRQuals;
7066         }
7067       }
7068     }
7069     return VRQuals;
7070 }
7071 
7072 namespace {
7073 
7074 /// \brief Helper class to manage the addition of builtin operator overload
7075 /// candidates. It provides shared state and utility methods used throughout
7076 /// the process, as well as a helper method to add each group of builtin
7077 /// operator overloads from the standard to a candidate set.
7078 class BuiltinOperatorOverloadBuilder {
7079   // Common instance state available to all overload candidate addition methods.
7080   Sema &S;
7081   ArrayRef<Expr *> Args;
7082   Qualifiers VisibleTypeConversionsQuals;
7083   bool HasArithmeticOrEnumeralCandidateType;
7084   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7085   OverloadCandidateSet &CandidateSet;
7086 
7087   // Define some constants used to index and iterate over the arithemetic types
7088   // provided via the getArithmeticType() method below.
7089   // The "promoted arithmetic types" are the arithmetic
7090   // types are that preserved by promotion (C++ [over.built]p2).
7091   static const unsigned FirstIntegralType = 3;
7092   static const unsigned LastIntegralType = 20;
7093   static const unsigned FirstPromotedIntegralType = 3,
7094                         LastPromotedIntegralType = 11;
7095   static const unsigned FirstPromotedArithmeticType = 0,
7096                         LastPromotedArithmeticType = 11;
7097   static const unsigned NumArithmeticTypes = 20;
7098 
7099   /// \brief Get the canonical type for a given arithmetic type index.
7100   CanQualType getArithmeticType(unsigned index) {
7101     assert(index < NumArithmeticTypes);
7102     static CanQualType ASTContext::* const
7103       ArithmeticTypes[NumArithmeticTypes] = {
7104       // Start of promoted types.
7105       &ASTContext::FloatTy,
7106       &ASTContext::DoubleTy,
7107       &ASTContext::LongDoubleTy,
7108 
7109       // Start of integral types.
7110       &ASTContext::IntTy,
7111       &ASTContext::LongTy,
7112       &ASTContext::LongLongTy,
7113       &ASTContext::Int128Ty,
7114       &ASTContext::UnsignedIntTy,
7115       &ASTContext::UnsignedLongTy,
7116       &ASTContext::UnsignedLongLongTy,
7117       &ASTContext::UnsignedInt128Ty,
7118       // End of promoted types.
7119 
7120       &ASTContext::BoolTy,
7121       &ASTContext::CharTy,
7122       &ASTContext::WCharTy,
7123       &ASTContext::Char16Ty,
7124       &ASTContext::Char32Ty,
7125       &ASTContext::SignedCharTy,
7126       &ASTContext::ShortTy,
7127       &ASTContext::UnsignedCharTy,
7128       &ASTContext::UnsignedShortTy,
7129       // End of integral types.
7130       // FIXME: What about complex? What about half?
7131     };
7132     return S.Context.*ArithmeticTypes[index];
7133   }
7134 
7135   /// \brief Gets the canonical type resulting from the usual arithemetic
7136   /// converions for the given arithmetic types.
7137   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7138     // Accelerator table for performing the usual arithmetic conversions.
7139     // The rules are basically:
7140     //   - if either is floating-point, use the wider floating-point
7141     //   - if same signedness, use the higher rank
7142     //   - if same size, use unsigned of the higher rank
7143     //   - use the larger type
7144     // These rules, together with the axiom that higher ranks are
7145     // never smaller, are sufficient to precompute all of these results
7146     // *except* when dealing with signed types of higher rank.
7147     // (we could precompute SLL x UI for all known platforms, but it's
7148     // better not to make any assumptions).
7149     // We assume that int128 has a higher rank than long long on all platforms.
7150     enum PromotedType {
7151             Dep=-1,
7152             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7153     };
7154     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7155                                         [LastPromotedArithmeticType] = {
7156 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7157 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7158 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7159 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7160 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7161 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7162 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7163 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7164 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7165 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7166 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7167     };
7168 
7169     assert(L < LastPromotedArithmeticType);
7170     assert(R < LastPromotedArithmeticType);
7171     int Idx = ConversionsTable[L][R];
7172 
7173     // Fast path: the table gives us a concrete answer.
7174     if (Idx != Dep) return getArithmeticType(Idx);
7175 
7176     // Slow path: we need to compare widths.
7177     // An invariant is that the signed type has higher rank.
7178     CanQualType LT = getArithmeticType(L),
7179                 RT = getArithmeticType(R);
7180     unsigned LW = S.Context.getIntWidth(LT),
7181              RW = S.Context.getIntWidth(RT);
7182 
7183     // If they're different widths, use the signed type.
7184     if (LW > RW) return LT;
7185     else if (LW < RW) return RT;
7186 
7187     // Otherwise, use the unsigned type of the signed type's rank.
7188     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7189     assert(L == SLL || R == SLL);
7190     return S.Context.UnsignedLongLongTy;
7191   }
7192 
7193   /// \brief Helper method to factor out the common pattern of adding overloads
7194   /// for '++' and '--' builtin operators.
7195   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7196                                            bool HasVolatile,
7197                                            bool HasRestrict) {
7198     QualType ParamTypes[2] = {
7199       S.Context.getLValueReferenceType(CandidateTy),
7200       S.Context.IntTy
7201     };
7202 
7203     // Non-volatile version.
7204     if (Args.size() == 1)
7205       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7206     else
7207       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7208 
7209     // Use a heuristic to reduce number of builtin candidates in the set:
7210     // add volatile version only if there are conversions to a volatile type.
7211     if (HasVolatile) {
7212       ParamTypes[0] =
7213         S.Context.getLValueReferenceType(
7214           S.Context.getVolatileType(CandidateTy));
7215       if (Args.size() == 1)
7216         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7217       else
7218         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7219     }
7220 
7221     // Add restrict version only if there are conversions to a restrict type
7222     // and our candidate type is a non-restrict-qualified pointer.
7223     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7224         !CandidateTy.isRestrictQualified()) {
7225       ParamTypes[0]
7226         = S.Context.getLValueReferenceType(
7227             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7228       if (Args.size() == 1)
7229         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7230       else
7231         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7232 
7233       if (HasVolatile) {
7234         ParamTypes[0]
7235           = S.Context.getLValueReferenceType(
7236               S.Context.getCVRQualifiedType(CandidateTy,
7237                                             (Qualifiers::Volatile |
7238                                              Qualifiers::Restrict)));
7239         if (Args.size() == 1)
7240           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7241         else
7242           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7243       }
7244     }
7245 
7246   }
7247 
7248 public:
7249   BuiltinOperatorOverloadBuilder(
7250     Sema &S, ArrayRef<Expr *> Args,
7251     Qualifiers VisibleTypeConversionsQuals,
7252     bool HasArithmeticOrEnumeralCandidateType,
7253     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7254     OverloadCandidateSet &CandidateSet)
7255     : S(S), Args(Args),
7256       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7257       HasArithmeticOrEnumeralCandidateType(
7258         HasArithmeticOrEnumeralCandidateType),
7259       CandidateTypes(CandidateTypes),
7260       CandidateSet(CandidateSet) {
7261     // Validate some of our static helper constants in debug builds.
7262     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7263            "Invalid first promoted integral type");
7264     assert(getArithmeticType(LastPromotedIntegralType - 1)
7265              == S.Context.UnsignedInt128Ty &&
7266            "Invalid last promoted integral type");
7267     assert(getArithmeticType(FirstPromotedArithmeticType)
7268              == S.Context.FloatTy &&
7269            "Invalid first promoted arithmetic type");
7270     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7271              == S.Context.UnsignedInt128Ty &&
7272            "Invalid last promoted arithmetic type");
7273   }
7274 
7275   // C++ [over.built]p3:
7276   //
7277   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7278   //   is either volatile or empty, there exist candidate operator
7279   //   functions of the form
7280   //
7281   //       VQ T&      operator++(VQ T&);
7282   //       T          operator++(VQ T&, int);
7283   //
7284   // C++ [over.built]p4:
7285   //
7286   //   For every pair (T, VQ), where T is an arithmetic type other
7287   //   than bool, and VQ is either volatile or empty, there exist
7288   //   candidate operator functions of the form
7289   //
7290   //       VQ T&      operator--(VQ T&);
7291   //       T          operator--(VQ T&, int);
7292   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7293     if (!HasArithmeticOrEnumeralCandidateType)
7294       return;
7295 
7296     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7297          Arith < NumArithmeticTypes; ++Arith) {
7298       addPlusPlusMinusMinusStyleOverloads(
7299         getArithmeticType(Arith),
7300         VisibleTypeConversionsQuals.hasVolatile(),
7301         VisibleTypeConversionsQuals.hasRestrict());
7302     }
7303   }
7304 
7305   // C++ [over.built]p5:
7306   //
7307   //   For every pair (T, VQ), where T is a cv-qualified or
7308   //   cv-unqualified object type, and VQ is either volatile or
7309   //   empty, there exist candidate operator functions of the form
7310   //
7311   //       T*VQ&      operator++(T*VQ&);
7312   //       T*VQ&      operator--(T*VQ&);
7313   //       T*         operator++(T*VQ&, int);
7314   //       T*         operator--(T*VQ&, int);
7315   void addPlusPlusMinusMinusPointerOverloads() {
7316     for (BuiltinCandidateTypeSet::iterator
7317               Ptr = CandidateTypes[0].pointer_begin(),
7318            PtrEnd = CandidateTypes[0].pointer_end();
7319          Ptr != PtrEnd; ++Ptr) {
7320       // Skip pointer types that aren't pointers to object types.
7321       if (!(*Ptr)->getPointeeType()->isObjectType())
7322         continue;
7323 
7324       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7325         (!(*Ptr).isVolatileQualified() &&
7326          VisibleTypeConversionsQuals.hasVolatile()),
7327         (!(*Ptr).isRestrictQualified() &&
7328          VisibleTypeConversionsQuals.hasRestrict()));
7329     }
7330   }
7331 
7332   // C++ [over.built]p6:
7333   //   For every cv-qualified or cv-unqualified object type T, there
7334   //   exist candidate operator functions of the form
7335   //
7336   //       T&         operator*(T*);
7337   //
7338   // C++ [over.built]p7:
7339   //   For every function type T that does not have cv-qualifiers or a
7340   //   ref-qualifier, there exist candidate operator functions of the form
7341   //       T&         operator*(T*);
7342   void addUnaryStarPointerOverloads() {
7343     for (BuiltinCandidateTypeSet::iterator
7344               Ptr = CandidateTypes[0].pointer_begin(),
7345            PtrEnd = CandidateTypes[0].pointer_end();
7346          Ptr != PtrEnd; ++Ptr) {
7347       QualType ParamTy = *Ptr;
7348       QualType PointeeTy = ParamTy->getPointeeType();
7349       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7350         continue;
7351 
7352       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7353         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7354           continue;
7355 
7356       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7357                             &ParamTy, Args, CandidateSet);
7358     }
7359   }
7360 
7361   // C++ [over.built]p9:
7362   //  For every promoted arithmetic type T, there exist candidate
7363   //  operator functions of the form
7364   //
7365   //       T         operator+(T);
7366   //       T         operator-(T);
7367   void addUnaryPlusOrMinusArithmeticOverloads() {
7368     if (!HasArithmeticOrEnumeralCandidateType)
7369       return;
7370 
7371     for (unsigned Arith = FirstPromotedArithmeticType;
7372          Arith < LastPromotedArithmeticType; ++Arith) {
7373       QualType ArithTy = getArithmeticType(Arith);
7374       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7375     }
7376 
7377     // Extension: We also add these operators for vector types.
7378     for (BuiltinCandidateTypeSet::iterator
7379               Vec = CandidateTypes[0].vector_begin(),
7380            VecEnd = CandidateTypes[0].vector_end();
7381          Vec != VecEnd; ++Vec) {
7382       QualType VecTy = *Vec;
7383       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7384     }
7385   }
7386 
7387   // C++ [over.built]p8:
7388   //   For every type T, there exist candidate operator functions of
7389   //   the form
7390   //
7391   //       T*         operator+(T*);
7392   void addUnaryPlusPointerOverloads() {
7393     for (BuiltinCandidateTypeSet::iterator
7394               Ptr = CandidateTypes[0].pointer_begin(),
7395            PtrEnd = CandidateTypes[0].pointer_end();
7396          Ptr != PtrEnd; ++Ptr) {
7397       QualType ParamTy = *Ptr;
7398       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7399     }
7400   }
7401 
7402   // C++ [over.built]p10:
7403   //   For every promoted integral type T, there exist candidate
7404   //   operator functions of the form
7405   //
7406   //        T         operator~(T);
7407   void addUnaryTildePromotedIntegralOverloads() {
7408     if (!HasArithmeticOrEnumeralCandidateType)
7409       return;
7410 
7411     for (unsigned Int = FirstPromotedIntegralType;
7412          Int < LastPromotedIntegralType; ++Int) {
7413       QualType IntTy = getArithmeticType(Int);
7414       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7415     }
7416 
7417     // Extension: We also add this operator for vector types.
7418     for (BuiltinCandidateTypeSet::iterator
7419               Vec = CandidateTypes[0].vector_begin(),
7420            VecEnd = CandidateTypes[0].vector_end();
7421          Vec != VecEnd; ++Vec) {
7422       QualType VecTy = *Vec;
7423       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7424     }
7425   }
7426 
7427   // C++ [over.match.oper]p16:
7428   //   For every pointer to member type T, there exist candidate operator
7429   //   functions of the form
7430   //
7431   //        bool operator==(T,T);
7432   //        bool operator!=(T,T);
7433   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7434     /// Set of (canonical) types that we've already handled.
7435     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7436 
7437     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7438       for (BuiltinCandidateTypeSet::iterator
7439                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7440              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7441            MemPtr != MemPtrEnd;
7442            ++MemPtr) {
7443         // Don't add the same builtin candidate twice.
7444         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7445           continue;
7446 
7447         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7448         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7449       }
7450     }
7451   }
7452 
7453   // C++ [over.built]p15:
7454   //
7455   //   For every T, where T is an enumeration type, a pointer type, or
7456   //   std::nullptr_t, there exist candidate operator functions of the form
7457   //
7458   //        bool       operator<(T, T);
7459   //        bool       operator>(T, T);
7460   //        bool       operator<=(T, T);
7461   //        bool       operator>=(T, T);
7462   //        bool       operator==(T, T);
7463   //        bool       operator!=(T, T);
7464   void addRelationalPointerOrEnumeralOverloads() {
7465     // C++ [over.match.oper]p3:
7466     //   [...]the built-in candidates include all of the candidate operator
7467     //   functions defined in 13.6 that, compared to the given operator, [...]
7468     //   do not have the same parameter-type-list as any non-template non-member
7469     //   candidate.
7470     //
7471     // Note that in practice, this only affects enumeration types because there
7472     // aren't any built-in candidates of record type, and a user-defined operator
7473     // must have an operand of record or enumeration type. Also, the only other
7474     // overloaded operator with enumeration arguments, operator=,
7475     // cannot be overloaded for enumeration types, so this is the only place
7476     // where we must suppress candidates like this.
7477     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7478       UserDefinedBinaryOperators;
7479 
7480     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7481       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7482           CandidateTypes[ArgIdx].enumeration_end()) {
7483         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7484                                          CEnd = CandidateSet.end();
7485              C != CEnd; ++C) {
7486           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7487             continue;
7488 
7489           if (C->Function->isFunctionTemplateSpecialization())
7490             continue;
7491 
7492           QualType FirstParamType =
7493             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7494           QualType SecondParamType =
7495             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7496 
7497           // Skip if either parameter isn't of enumeral type.
7498           if (!FirstParamType->isEnumeralType() ||
7499               !SecondParamType->isEnumeralType())
7500             continue;
7501 
7502           // Add this operator to the set of known user-defined operators.
7503           UserDefinedBinaryOperators.insert(
7504             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7505                            S.Context.getCanonicalType(SecondParamType)));
7506         }
7507       }
7508     }
7509 
7510     /// Set of (canonical) types that we've already handled.
7511     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7512 
7513     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7514       for (BuiltinCandidateTypeSet::iterator
7515                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7516              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7517            Ptr != PtrEnd; ++Ptr) {
7518         // Don't add the same builtin candidate twice.
7519         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7520           continue;
7521 
7522         QualType ParamTypes[2] = { *Ptr, *Ptr };
7523         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7524       }
7525       for (BuiltinCandidateTypeSet::iterator
7526                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7527              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7528            Enum != EnumEnd; ++Enum) {
7529         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7530 
7531         // Don't add the same builtin candidate twice, or if a user defined
7532         // candidate exists.
7533         if (!AddedTypes.insert(CanonType).second ||
7534             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7535                                                             CanonType)))
7536           continue;
7537 
7538         QualType ParamTypes[2] = { *Enum, *Enum };
7539         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7540       }
7541 
7542       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7543         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7544         if (AddedTypes.insert(NullPtrTy).second &&
7545             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7546                                                              NullPtrTy))) {
7547           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7548           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7549                                 CandidateSet);
7550         }
7551       }
7552     }
7553   }
7554 
7555   // C++ [over.built]p13:
7556   //
7557   //   For every cv-qualified or cv-unqualified object type T
7558   //   there exist candidate operator functions of the form
7559   //
7560   //      T*         operator+(T*, ptrdiff_t);
7561   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7562   //      T*         operator-(T*, ptrdiff_t);
7563   //      T*         operator+(ptrdiff_t, T*);
7564   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7565   //
7566   // C++ [over.built]p14:
7567   //
7568   //   For every T, where T is a pointer to object type, there
7569   //   exist candidate operator functions of the form
7570   //
7571   //      ptrdiff_t  operator-(T, T);
7572   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7573     /// Set of (canonical) types that we've already handled.
7574     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7575 
7576     for (int Arg = 0; Arg < 2; ++Arg) {
7577       QualType AsymmetricParamTypes[2] = {
7578         S.Context.getPointerDiffType(),
7579         S.Context.getPointerDiffType(),
7580       };
7581       for (BuiltinCandidateTypeSet::iterator
7582                 Ptr = CandidateTypes[Arg].pointer_begin(),
7583              PtrEnd = CandidateTypes[Arg].pointer_end();
7584            Ptr != PtrEnd; ++Ptr) {
7585         QualType PointeeTy = (*Ptr)->getPointeeType();
7586         if (!PointeeTy->isObjectType())
7587           continue;
7588 
7589         AsymmetricParamTypes[Arg] = *Ptr;
7590         if (Arg == 0 || Op == OO_Plus) {
7591           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7592           // T* operator+(ptrdiff_t, T*);
7593           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7594         }
7595         if (Op == OO_Minus) {
7596           // ptrdiff_t operator-(T, T);
7597           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7598             continue;
7599 
7600           QualType ParamTypes[2] = { *Ptr, *Ptr };
7601           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7602                                 Args, CandidateSet);
7603         }
7604       }
7605     }
7606   }
7607 
7608   // C++ [over.built]p12:
7609   //
7610   //   For every pair of promoted arithmetic types L and R, there
7611   //   exist candidate operator functions of the form
7612   //
7613   //        LR         operator*(L, R);
7614   //        LR         operator/(L, R);
7615   //        LR         operator+(L, R);
7616   //        LR         operator-(L, R);
7617   //        bool       operator<(L, R);
7618   //        bool       operator>(L, R);
7619   //        bool       operator<=(L, R);
7620   //        bool       operator>=(L, R);
7621   //        bool       operator==(L, R);
7622   //        bool       operator!=(L, R);
7623   //
7624   //   where LR is the result of the usual arithmetic conversions
7625   //   between types L and R.
7626   //
7627   // C++ [over.built]p24:
7628   //
7629   //   For every pair of promoted arithmetic types L and R, there exist
7630   //   candidate operator functions of the form
7631   //
7632   //        LR       operator?(bool, L, R);
7633   //
7634   //   where LR is the result of the usual arithmetic conversions
7635   //   between types L and R.
7636   // Our candidates ignore the first parameter.
7637   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7638     if (!HasArithmeticOrEnumeralCandidateType)
7639       return;
7640 
7641     for (unsigned Left = FirstPromotedArithmeticType;
7642          Left < LastPromotedArithmeticType; ++Left) {
7643       for (unsigned Right = FirstPromotedArithmeticType;
7644            Right < LastPromotedArithmeticType; ++Right) {
7645         QualType LandR[2] = { getArithmeticType(Left),
7646                               getArithmeticType(Right) };
7647         QualType Result =
7648           isComparison ? S.Context.BoolTy
7649                        : getUsualArithmeticConversions(Left, Right);
7650         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7651       }
7652     }
7653 
7654     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7655     // conditional operator for vector types.
7656     for (BuiltinCandidateTypeSet::iterator
7657               Vec1 = CandidateTypes[0].vector_begin(),
7658            Vec1End = CandidateTypes[0].vector_end();
7659          Vec1 != Vec1End; ++Vec1) {
7660       for (BuiltinCandidateTypeSet::iterator
7661                 Vec2 = CandidateTypes[1].vector_begin(),
7662              Vec2End = CandidateTypes[1].vector_end();
7663            Vec2 != Vec2End; ++Vec2) {
7664         QualType LandR[2] = { *Vec1, *Vec2 };
7665         QualType Result = S.Context.BoolTy;
7666         if (!isComparison) {
7667           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7668             Result = *Vec1;
7669           else
7670             Result = *Vec2;
7671         }
7672 
7673         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7674       }
7675     }
7676   }
7677 
7678   // C++ [over.built]p17:
7679   //
7680   //   For every pair of promoted integral types L and R, there
7681   //   exist candidate operator functions of the form
7682   //
7683   //      LR         operator%(L, R);
7684   //      LR         operator&(L, R);
7685   //      LR         operator^(L, R);
7686   //      LR         operator|(L, R);
7687   //      L          operator<<(L, R);
7688   //      L          operator>>(L, R);
7689   //
7690   //   where LR is the result of the usual arithmetic conversions
7691   //   between types L and R.
7692   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7693     if (!HasArithmeticOrEnumeralCandidateType)
7694       return;
7695 
7696     for (unsigned Left = FirstPromotedIntegralType;
7697          Left < LastPromotedIntegralType; ++Left) {
7698       for (unsigned Right = FirstPromotedIntegralType;
7699            Right < LastPromotedIntegralType; ++Right) {
7700         QualType LandR[2] = { getArithmeticType(Left),
7701                               getArithmeticType(Right) };
7702         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7703             ? LandR[0]
7704             : getUsualArithmeticConversions(Left, Right);
7705         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7706       }
7707     }
7708   }
7709 
7710   // C++ [over.built]p20:
7711   //
7712   //   For every pair (T, VQ), where T is an enumeration or
7713   //   pointer to member type and VQ is either volatile or
7714   //   empty, there exist candidate operator functions of the form
7715   //
7716   //        VQ T&      operator=(VQ T&, T);
7717   void addAssignmentMemberPointerOrEnumeralOverloads() {
7718     /// Set of (canonical) types that we've already handled.
7719     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7720 
7721     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7722       for (BuiltinCandidateTypeSet::iterator
7723                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7724              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7725            Enum != EnumEnd; ++Enum) {
7726         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7727           continue;
7728 
7729         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7730       }
7731 
7732       for (BuiltinCandidateTypeSet::iterator
7733                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7734              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7735            MemPtr != MemPtrEnd; ++MemPtr) {
7736         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7737           continue;
7738 
7739         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7740       }
7741     }
7742   }
7743 
7744   // C++ [over.built]p19:
7745   //
7746   //   For every pair (T, VQ), where T is any type and VQ is either
7747   //   volatile or empty, there exist candidate operator functions
7748   //   of the form
7749   //
7750   //        T*VQ&      operator=(T*VQ&, T*);
7751   //
7752   // C++ [over.built]p21:
7753   //
7754   //   For every pair (T, VQ), where T is a cv-qualified or
7755   //   cv-unqualified object type and VQ is either volatile or
7756   //   empty, there exist candidate operator functions of the form
7757   //
7758   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7759   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7760   void addAssignmentPointerOverloads(bool isEqualOp) {
7761     /// Set of (canonical) types that we've already handled.
7762     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7763 
7764     for (BuiltinCandidateTypeSet::iterator
7765               Ptr = CandidateTypes[0].pointer_begin(),
7766            PtrEnd = CandidateTypes[0].pointer_end();
7767          Ptr != PtrEnd; ++Ptr) {
7768       // If this is operator=, keep track of the builtin candidates we added.
7769       if (isEqualOp)
7770         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7771       else if (!(*Ptr)->getPointeeType()->isObjectType())
7772         continue;
7773 
7774       // non-volatile version
7775       QualType ParamTypes[2] = {
7776         S.Context.getLValueReferenceType(*Ptr),
7777         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7778       };
7779       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7780                             /*IsAssigmentOperator=*/ isEqualOp);
7781 
7782       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7783                           VisibleTypeConversionsQuals.hasVolatile();
7784       if (NeedVolatile) {
7785         // volatile version
7786         ParamTypes[0] =
7787           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7788         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7789                               /*IsAssigmentOperator=*/isEqualOp);
7790       }
7791 
7792       if (!(*Ptr).isRestrictQualified() &&
7793           VisibleTypeConversionsQuals.hasRestrict()) {
7794         // restrict version
7795         ParamTypes[0]
7796           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7797         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7798                               /*IsAssigmentOperator=*/isEqualOp);
7799 
7800         if (NeedVolatile) {
7801           // volatile restrict version
7802           ParamTypes[0]
7803             = S.Context.getLValueReferenceType(
7804                 S.Context.getCVRQualifiedType(*Ptr,
7805                                               (Qualifiers::Volatile |
7806                                                Qualifiers::Restrict)));
7807           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7808                                 /*IsAssigmentOperator=*/isEqualOp);
7809         }
7810       }
7811     }
7812 
7813     if (isEqualOp) {
7814       for (BuiltinCandidateTypeSet::iterator
7815                 Ptr = CandidateTypes[1].pointer_begin(),
7816              PtrEnd = CandidateTypes[1].pointer_end();
7817            Ptr != PtrEnd; ++Ptr) {
7818         // Make sure we don't add the same candidate twice.
7819         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7820           continue;
7821 
7822         QualType ParamTypes[2] = {
7823           S.Context.getLValueReferenceType(*Ptr),
7824           *Ptr,
7825         };
7826 
7827         // non-volatile version
7828         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7829                               /*IsAssigmentOperator=*/true);
7830 
7831         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7832                            VisibleTypeConversionsQuals.hasVolatile();
7833         if (NeedVolatile) {
7834           // volatile version
7835           ParamTypes[0] =
7836             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7837           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7838                                 /*IsAssigmentOperator=*/true);
7839         }
7840 
7841         if (!(*Ptr).isRestrictQualified() &&
7842             VisibleTypeConversionsQuals.hasRestrict()) {
7843           // restrict version
7844           ParamTypes[0]
7845             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7846           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7847                                 /*IsAssigmentOperator=*/true);
7848 
7849           if (NeedVolatile) {
7850             // volatile restrict version
7851             ParamTypes[0]
7852               = S.Context.getLValueReferenceType(
7853                   S.Context.getCVRQualifiedType(*Ptr,
7854                                                 (Qualifiers::Volatile |
7855                                                  Qualifiers::Restrict)));
7856             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7857                                   /*IsAssigmentOperator=*/true);
7858           }
7859         }
7860       }
7861     }
7862   }
7863 
7864   // C++ [over.built]p18:
7865   //
7866   //   For every triple (L, VQ, R), where L is an arithmetic type,
7867   //   VQ is either volatile or empty, and R is a promoted
7868   //   arithmetic type, there exist candidate operator functions of
7869   //   the form
7870   //
7871   //        VQ L&      operator=(VQ L&, R);
7872   //        VQ L&      operator*=(VQ L&, R);
7873   //        VQ L&      operator/=(VQ L&, R);
7874   //        VQ L&      operator+=(VQ L&, R);
7875   //        VQ L&      operator-=(VQ L&, R);
7876   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7877     if (!HasArithmeticOrEnumeralCandidateType)
7878       return;
7879 
7880     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7881       for (unsigned Right = FirstPromotedArithmeticType;
7882            Right < LastPromotedArithmeticType; ++Right) {
7883         QualType ParamTypes[2];
7884         ParamTypes[1] = getArithmeticType(Right);
7885 
7886         // Add this built-in operator as a candidate (VQ is empty).
7887         ParamTypes[0] =
7888           S.Context.getLValueReferenceType(getArithmeticType(Left));
7889         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7890                               /*IsAssigmentOperator=*/isEqualOp);
7891 
7892         // Add this built-in operator as a candidate (VQ is 'volatile').
7893         if (VisibleTypeConversionsQuals.hasVolatile()) {
7894           ParamTypes[0] =
7895             S.Context.getVolatileType(getArithmeticType(Left));
7896           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7897           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7898                                 /*IsAssigmentOperator=*/isEqualOp);
7899         }
7900       }
7901     }
7902 
7903     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7904     for (BuiltinCandidateTypeSet::iterator
7905               Vec1 = CandidateTypes[0].vector_begin(),
7906            Vec1End = CandidateTypes[0].vector_end();
7907          Vec1 != Vec1End; ++Vec1) {
7908       for (BuiltinCandidateTypeSet::iterator
7909                 Vec2 = CandidateTypes[1].vector_begin(),
7910              Vec2End = CandidateTypes[1].vector_end();
7911            Vec2 != Vec2End; ++Vec2) {
7912         QualType ParamTypes[2];
7913         ParamTypes[1] = *Vec2;
7914         // Add this built-in operator as a candidate (VQ is empty).
7915         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7916         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7917                               /*IsAssigmentOperator=*/isEqualOp);
7918 
7919         // Add this built-in operator as a candidate (VQ is 'volatile').
7920         if (VisibleTypeConversionsQuals.hasVolatile()) {
7921           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7922           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7923           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7924                                 /*IsAssigmentOperator=*/isEqualOp);
7925         }
7926       }
7927     }
7928   }
7929 
7930   // C++ [over.built]p22:
7931   //
7932   //   For every triple (L, VQ, R), where L is an integral type, VQ
7933   //   is either volatile or empty, and R is a promoted integral
7934   //   type, there exist candidate operator functions of the form
7935   //
7936   //        VQ L&       operator%=(VQ L&, R);
7937   //        VQ L&       operator<<=(VQ L&, R);
7938   //        VQ L&       operator>>=(VQ L&, R);
7939   //        VQ L&       operator&=(VQ L&, R);
7940   //        VQ L&       operator^=(VQ L&, R);
7941   //        VQ L&       operator|=(VQ L&, R);
7942   void addAssignmentIntegralOverloads() {
7943     if (!HasArithmeticOrEnumeralCandidateType)
7944       return;
7945 
7946     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7947       for (unsigned Right = FirstPromotedIntegralType;
7948            Right < LastPromotedIntegralType; ++Right) {
7949         QualType ParamTypes[2];
7950         ParamTypes[1] = getArithmeticType(Right);
7951 
7952         // Add this built-in operator as a candidate (VQ is empty).
7953         ParamTypes[0] =
7954           S.Context.getLValueReferenceType(getArithmeticType(Left));
7955         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7956         if (VisibleTypeConversionsQuals.hasVolatile()) {
7957           // Add this built-in operator as a candidate (VQ is 'volatile').
7958           ParamTypes[0] = getArithmeticType(Left);
7959           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7960           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7961           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7962         }
7963       }
7964     }
7965   }
7966 
7967   // C++ [over.operator]p23:
7968   //
7969   //   There also exist candidate operator functions of the form
7970   //
7971   //        bool        operator!(bool);
7972   //        bool        operator&&(bool, bool);
7973   //        bool        operator||(bool, bool);
7974   void addExclaimOverload() {
7975     QualType ParamTy = S.Context.BoolTy;
7976     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7977                           /*IsAssignmentOperator=*/false,
7978                           /*NumContextualBoolArguments=*/1);
7979   }
7980   void addAmpAmpOrPipePipeOverload() {
7981     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7982     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7983                           /*IsAssignmentOperator=*/false,
7984                           /*NumContextualBoolArguments=*/2);
7985   }
7986 
7987   // C++ [over.built]p13:
7988   //
7989   //   For every cv-qualified or cv-unqualified object type T there
7990   //   exist candidate operator functions of the form
7991   //
7992   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7993   //        T&         operator[](T*, ptrdiff_t);
7994   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7995   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7996   //        T&         operator[](ptrdiff_t, T*);
7997   void addSubscriptOverloads() {
7998     for (BuiltinCandidateTypeSet::iterator
7999               Ptr = CandidateTypes[0].pointer_begin(),
8000            PtrEnd = CandidateTypes[0].pointer_end();
8001          Ptr != PtrEnd; ++Ptr) {
8002       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8003       QualType PointeeType = (*Ptr)->getPointeeType();
8004       if (!PointeeType->isObjectType())
8005         continue;
8006 
8007       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8008 
8009       // T& operator[](T*, ptrdiff_t)
8010       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8011     }
8012 
8013     for (BuiltinCandidateTypeSet::iterator
8014               Ptr = CandidateTypes[1].pointer_begin(),
8015            PtrEnd = CandidateTypes[1].pointer_end();
8016          Ptr != PtrEnd; ++Ptr) {
8017       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8018       QualType PointeeType = (*Ptr)->getPointeeType();
8019       if (!PointeeType->isObjectType())
8020         continue;
8021 
8022       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8023 
8024       // T& operator[](ptrdiff_t, T*)
8025       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8026     }
8027   }
8028 
8029   // C++ [over.built]p11:
8030   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8031   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8032   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8033   //    there exist candidate operator functions of the form
8034   //
8035   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8036   //
8037   //    where CV12 is the union of CV1 and CV2.
8038   void addArrowStarOverloads() {
8039     for (BuiltinCandidateTypeSet::iterator
8040              Ptr = CandidateTypes[0].pointer_begin(),
8041            PtrEnd = CandidateTypes[0].pointer_end();
8042          Ptr != PtrEnd; ++Ptr) {
8043       QualType C1Ty = (*Ptr);
8044       QualType C1;
8045       QualifierCollector Q1;
8046       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8047       if (!isa<RecordType>(C1))
8048         continue;
8049       // heuristic to reduce number of builtin candidates in the set.
8050       // Add volatile/restrict version only if there are conversions to a
8051       // volatile/restrict type.
8052       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8053         continue;
8054       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8055         continue;
8056       for (BuiltinCandidateTypeSet::iterator
8057                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8058              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8059            MemPtr != MemPtrEnd; ++MemPtr) {
8060         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8061         QualType C2 = QualType(mptr->getClass(), 0);
8062         C2 = C2.getUnqualifiedType();
8063         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8064           break;
8065         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8066         // build CV12 T&
8067         QualType T = mptr->getPointeeType();
8068         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8069             T.isVolatileQualified())
8070           continue;
8071         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8072             T.isRestrictQualified())
8073           continue;
8074         T = Q1.apply(S.Context, T);
8075         QualType ResultTy = S.Context.getLValueReferenceType(T);
8076         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8077       }
8078     }
8079   }
8080 
8081   // Note that we don't consider the first argument, since it has been
8082   // contextually converted to bool long ago. The candidates below are
8083   // therefore added as binary.
8084   //
8085   // C++ [over.built]p25:
8086   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8087   //   enumeration type, there exist candidate operator functions of the form
8088   //
8089   //        T        operator?(bool, T, T);
8090   //
8091   void addConditionalOperatorOverloads() {
8092     /// Set of (canonical) types that we've already handled.
8093     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8094 
8095     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8096       for (BuiltinCandidateTypeSet::iterator
8097                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8098              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8099            Ptr != PtrEnd; ++Ptr) {
8100         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8101           continue;
8102 
8103         QualType ParamTypes[2] = { *Ptr, *Ptr };
8104         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8105       }
8106 
8107       for (BuiltinCandidateTypeSet::iterator
8108                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8109              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8110            MemPtr != MemPtrEnd; ++MemPtr) {
8111         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8112           continue;
8113 
8114         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8115         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8116       }
8117 
8118       if (S.getLangOpts().CPlusPlus11) {
8119         for (BuiltinCandidateTypeSet::iterator
8120                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8121                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8122              Enum != EnumEnd; ++Enum) {
8123           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8124             continue;
8125 
8126           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8127             continue;
8128 
8129           QualType ParamTypes[2] = { *Enum, *Enum };
8130           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8131         }
8132       }
8133     }
8134   }
8135 };
8136 
8137 } // end anonymous namespace
8138 
8139 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8140 /// operator overloads to the candidate set (C++ [over.built]), based
8141 /// on the operator @p Op and the arguments given. For example, if the
8142 /// operator is a binary '+', this routine might add "int
8143 /// operator+(int, int)" to cover integer addition.
8144 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8145                                         SourceLocation OpLoc,
8146                                         ArrayRef<Expr *> Args,
8147                                         OverloadCandidateSet &CandidateSet) {
8148   // Find all of the types that the arguments can convert to, but only
8149   // if the operator we're looking at has built-in operator candidates
8150   // that make use of these types. Also record whether we encounter non-record
8151   // candidate types or either arithmetic or enumeral candidate types.
8152   Qualifiers VisibleTypeConversionsQuals;
8153   VisibleTypeConversionsQuals.addConst();
8154   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8155     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8156 
8157   bool HasNonRecordCandidateType = false;
8158   bool HasArithmeticOrEnumeralCandidateType = false;
8159   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8160   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8161     CandidateTypes.emplace_back(*this);
8162     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8163                                                  OpLoc,
8164                                                  true,
8165                                                  (Op == OO_Exclaim ||
8166                                                   Op == OO_AmpAmp ||
8167                                                   Op == OO_PipePipe),
8168                                                  VisibleTypeConversionsQuals);
8169     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8170         CandidateTypes[ArgIdx].hasNonRecordTypes();
8171     HasArithmeticOrEnumeralCandidateType =
8172         HasArithmeticOrEnumeralCandidateType ||
8173         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8174   }
8175 
8176   // Exit early when no non-record types have been added to the candidate set
8177   // for any of the arguments to the operator.
8178   //
8179   // We can't exit early for !, ||, or &&, since there we have always have
8180   // 'bool' overloads.
8181   if (!HasNonRecordCandidateType &&
8182       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8183     return;
8184 
8185   // Setup an object to manage the common state for building overloads.
8186   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8187                                            VisibleTypeConversionsQuals,
8188                                            HasArithmeticOrEnumeralCandidateType,
8189                                            CandidateTypes, CandidateSet);
8190 
8191   // Dispatch over the operation to add in only those overloads which apply.
8192   switch (Op) {
8193   case OO_None:
8194   case NUM_OVERLOADED_OPERATORS:
8195     llvm_unreachable("Expected an overloaded operator");
8196 
8197   case OO_New:
8198   case OO_Delete:
8199   case OO_Array_New:
8200   case OO_Array_Delete:
8201   case OO_Call:
8202     llvm_unreachable(
8203                     "Special operators don't use AddBuiltinOperatorCandidates");
8204 
8205   case OO_Comma:
8206   case OO_Arrow:
8207     // C++ [over.match.oper]p3:
8208     //   -- For the operator ',', the unary operator '&', or the
8209     //      operator '->', the built-in candidates set is empty.
8210     break;
8211 
8212   case OO_Plus: // '+' is either unary or binary
8213     if (Args.size() == 1)
8214       OpBuilder.addUnaryPlusPointerOverloads();
8215     // Fall through.
8216 
8217   case OO_Minus: // '-' is either unary or binary
8218     if (Args.size() == 1) {
8219       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8220     } else {
8221       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8222       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8223     }
8224     break;
8225 
8226   case OO_Star: // '*' is either unary or binary
8227     if (Args.size() == 1)
8228       OpBuilder.addUnaryStarPointerOverloads();
8229     else
8230       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8231     break;
8232 
8233   case OO_Slash:
8234     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8235     break;
8236 
8237   case OO_PlusPlus:
8238   case OO_MinusMinus:
8239     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8240     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8241     break;
8242 
8243   case OO_EqualEqual:
8244   case OO_ExclaimEqual:
8245     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8246     // Fall through.
8247 
8248   case OO_Less:
8249   case OO_Greater:
8250   case OO_LessEqual:
8251   case OO_GreaterEqual:
8252     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8253     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8254     break;
8255 
8256   case OO_Percent:
8257   case OO_Caret:
8258   case OO_Pipe:
8259   case OO_LessLess:
8260   case OO_GreaterGreater:
8261     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8262     break;
8263 
8264   case OO_Amp: // '&' is either unary or binary
8265     if (Args.size() == 1)
8266       // C++ [over.match.oper]p3:
8267       //   -- For the operator ',', the unary operator '&', or the
8268       //      operator '->', the built-in candidates set is empty.
8269       break;
8270 
8271     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8272     break;
8273 
8274   case OO_Tilde:
8275     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8276     break;
8277 
8278   case OO_Equal:
8279     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8280     // Fall through.
8281 
8282   case OO_PlusEqual:
8283   case OO_MinusEqual:
8284     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8285     // Fall through.
8286 
8287   case OO_StarEqual:
8288   case OO_SlashEqual:
8289     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8290     break;
8291 
8292   case OO_PercentEqual:
8293   case OO_LessLessEqual:
8294   case OO_GreaterGreaterEqual:
8295   case OO_AmpEqual:
8296   case OO_CaretEqual:
8297   case OO_PipeEqual:
8298     OpBuilder.addAssignmentIntegralOverloads();
8299     break;
8300 
8301   case OO_Exclaim:
8302     OpBuilder.addExclaimOverload();
8303     break;
8304 
8305   case OO_AmpAmp:
8306   case OO_PipePipe:
8307     OpBuilder.addAmpAmpOrPipePipeOverload();
8308     break;
8309 
8310   case OO_Subscript:
8311     OpBuilder.addSubscriptOverloads();
8312     break;
8313 
8314   case OO_ArrowStar:
8315     OpBuilder.addArrowStarOverloads();
8316     break;
8317 
8318   case OO_Conditional:
8319     OpBuilder.addConditionalOperatorOverloads();
8320     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8321     break;
8322   }
8323 }
8324 
8325 /// \brief Add function candidates found via argument-dependent lookup
8326 /// to the set of overloading candidates.
8327 ///
8328 /// This routine performs argument-dependent name lookup based on the
8329 /// given function name (which may also be an operator name) and adds
8330 /// all of the overload candidates found by ADL to the overload
8331 /// candidate set (C++ [basic.lookup.argdep]).
8332 void
8333 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8334                                            SourceLocation Loc,
8335                                            ArrayRef<Expr *> Args,
8336                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8337                                            OverloadCandidateSet& CandidateSet,
8338                                            bool PartialOverloading) {
8339   ADLResult Fns;
8340 
8341   // FIXME: This approach for uniquing ADL results (and removing
8342   // redundant candidates from the set) relies on pointer-equality,
8343   // which means we need to key off the canonical decl.  However,
8344   // always going back to the canonical decl might not get us the
8345   // right set of default arguments.  What default arguments are
8346   // we supposed to consider on ADL candidates, anyway?
8347 
8348   // FIXME: Pass in the explicit template arguments?
8349   ArgumentDependentLookup(Name, Loc, Args, Fns);
8350 
8351   // Erase all of the candidates we already knew about.
8352   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8353                                    CandEnd = CandidateSet.end();
8354        Cand != CandEnd; ++Cand)
8355     if (Cand->Function) {
8356       Fns.erase(Cand->Function);
8357       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8358         Fns.erase(FunTmpl);
8359     }
8360 
8361   // For each of the ADL candidates we found, add it to the overload
8362   // set.
8363   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8364     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8365     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8366       if (ExplicitTemplateArgs)
8367         continue;
8368 
8369       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8370                            PartialOverloading);
8371     } else
8372       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8373                                    FoundDecl, ExplicitTemplateArgs,
8374                                    Args, CandidateSet, PartialOverloading);
8375   }
8376 }
8377 
8378 /// isBetterOverloadCandidate - Determines whether the first overload
8379 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8380 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8381                                       const OverloadCandidate &Cand2,
8382                                       SourceLocation Loc,
8383                                       bool UserDefinedConversion) {
8384   // Define viable functions to be better candidates than non-viable
8385   // functions.
8386   if (!Cand2.Viable)
8387     return Cand1.Viable;
8388   else if (!Cand1.Viable)
8389     return false;
8390 
8391   // C++ [over.match.best]p1:
8392   //
8393   //   -- if F is a static member function, ICS1(F) is defined such
8394   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8395   //      any function G, and, symmetrically, ICS1(G) is neither
8396   //      better nor worse than ICS1(F).
8397   unsigned StartArg = 0;
8398   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8399     StartArg = 1;
8400 
8401   // C++ [over.match.best]p1:
8402   //   A viable function F1 is defined to be a better function than another
8403   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8404   //   conversion sequence than ICSi(F2), and then...
8405   unsigned NumArgs = Cand1.NumConversions;
8406   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8407   bool HasBetterConversion = false;
8408   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8409     switch (CompareImplicitConversionSequences(S,
8410                                                Cand1.Conversions[ArgIdx],
8411                                                Cand2.Conversions[ArgIdx])) {
8412     case ImplicitConversionSequence::Better:
8413       // Cand1 has a better conversion sequence.
8414       HasBetterConversion = true;
8415       break;
8416 
8417     case ImplicitConversionSequence::Worse:
8418       // Cand1 can't be better than Cand2.
8419       return false;
8420 
8421     case ImplicitConversionSequence::Indistinguishable:
8422       // Do nothing.
8423       break;
8424     }
8425   }
8426 
8427   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8428   //       ICSj(F2), or, if not that,
8429   if (HasBetterConversion)
8430     return true;
8431 
8432   //   -- the context is an initialization by user-defined conversion
8433   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8434   //      from the return type of F1 to the destination type (i.e.,
8435   //      the type of the entity being initialized) is a better
8436   //      conversion sequence than the standard conversion sequence
8437   //      from the return type of F2 to the destination type.
8438   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8439       isa<CXXConversionDecl>(Cand1.Function) &&
8440       isa<CXXConversionDecl>(Cand2.Function)) {
8441     // First check whether we prefer one of the conversion functions over the
8442     // other. This only distinguishes the results in non-standard, extension
8443     // cases such as the conversion from a lambda closure type to a function
8444     // pointer or block.
8445     ImplicitConversionSequence::CompareKind Result =
8446         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8447     if (Result == ImplicitConversionSequence::Indistinguishable)
8448       Result = CompareStandardConversionSequences(S,
8449                                                   Cand1.FinalConversion,
8450                                                   Cand2.FinalConversion);
8451 
8452     if (Result != ImplicitConversionSequence::Indistinguishable)
8453       return Result == ImplicitConversionSequence::Better;
8454 
8455     // FIXME: Compare kind of reference binding if conversion functions
8456     // convert to a reference type used in direct reference binding, per
8457     // C++14 [over.match.best]p1 section 2 bullet 3.
8458   }
8459 
8460   //    -- F1 is a non-template function and F2 is a function template
8461   //       specialization, or, if not that,
8462   bool Cand1IsSpecialization = Cand1.Function &&
8463                                Cand1.Function->getPrimaryTemplate();
8464   bool Cand2IsSpecialization = Cand2.Function &&
8465                                Cand2.Function->getPrimaryTemplate();
8466   if (Cand1IsSpecialization != Cand2IsSpecialization)
8467     return Cand2IsSpecialization;
8468 
8469   //   -- F1 and F2 are function template specializations, and the function
8470   //      template for F1 is more specialized than the template for F2
8471   //      according to the partial ordering rules described in 14.5.5.2, or,
8472   //      if not that,
8473   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8474     if (FunctionTemplateDecl *BetterTemplate
8475           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8476                                          Cand2.Function->getPrimaryTemplate(),
8477                                          Loc,
8478                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8479                                                              : TPOC_Call,
8480                                          Cand1.ExplicitCallArguments,
8481                                          Cand2.ExplicitCallArguments))
8482       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8483   }
8484 
8485   // Check for enable_if value-based overload resolution.
8486   if (Cand1.Function && Cand2.Function &&
8487       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8488        Cand2.Function->hasAttr<EnableIfAttr>())) {
8489     // FIXME: The next several lines are just
8490     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8491     // instead of reverse order which is how they're stored in the AST.
8492     AttrVec Cand1Attrs;
8493     if (Cand1.Function->hasAttrs()) {
8494       Cand1Attrs = Cand1.Function->getAttrs();
8495       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8496                                       IsNotEnableIfAttr),
8497                        Cand1Attrs.end());
8498       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8499     }
8500 
8501     AttrVec Cand2Attrs;
8502     if (Cand2.Function->hasAttrs()) {
8503       Cand2Attrs = Cand2.Function->getAttrs();
8504       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8505                                       IsNotEnableIfAttr),
8506                        Cand2Attrs.end());
8507       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8508     }
8509 
8510     // Candidate 1 is better if it has strictly more attributes and
8511     // the common sequence is identical.
8512     if (Cand1Attrs.size() <= Cand2Attrs.size())
8513       return false;
8514 
8515     auto Cand1I = Cand1Attrs.begin();
8516     for (auto &Cand2A : Cand2Attrs) {
8517       auto &Cand1A = *Cand1I++;
8518       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8519       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8520                                                      S.getASTContext(), true);
8521       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8522                                                      S.getASTContext(), true);
8523       if (Cand1ID != Cand2ID)
8524         return false;
8525     }
8526 
8527     return true;
8528   }
8529 
8530   if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8531       Cand1.Function && Cand2.Function) {
8532     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8533     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8534            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8535   }
8536 
8537   return false;
8538 }
8539 
8540 /// \brief Computes the best viable function (C++ 13.3.3)
8541 /// within an overload candidate set.
8542 ///
8543 /// \param Loc The location of the function name (or operator symbol) for
8544 /// which overload resolution occurs.
8545 ///
8546 /// \param Best If overload resolution was successful or found a deleted
8547 /// function, \p Best points to the candidate function found.
8548 ///
8549 /// \returns The result of overload resolution.
8550 OverloadingResult
8551 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8552                                          iterator &Best,
8553                                          bool UserDefinedConversion) {
8554   // Find the best viable function.
8555   Best = end();
8556   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8557     if (Cand->Viable)
8558       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8559                                                      UserDefinedConversion))
8560         Best = Cand;
8561   }
8562 
8563   // If we didn't find any viable functions, abort.
8564   if (Best == end())
8565     return OR_No_Viable_Function;
8566 
8567   // Make sure that this function is better than every other viable
8568   // function. If not, we have an ambiguity.
8569   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8570     if (Cand->Viable &&
8571         Cand != Best &&
8572         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8573                                    UserDefinedConversion)) {
8574       Best = end();
8575       return OR_Ambiguous;
8576     }
8577   }
8578 
8579   // Best is the best viable function.
8580   if (Best->Function &&
8581       (Best->Function->isDeleted() ||
8582        S.isFunctionConsideredUnavailable(Best->Function)))
8583     return OR_Deleted;
8584 
8585   return OR_Success;
8586 }
8587 
8588 namespace {
8589 
8590 enum OverloadCandidateKind {
8591   oc_function,
8592   oc_method,
8593   oc_constructor,
8594   oc_function_template,
8595   oc_method_template,
8596   oc_constructor_template,
8597   oc_implicit_default_constructor,
8598   oc_implicit_copy_constructor,
8599   oc_implicit_move_constructor,
8600   oc_implicit_copy_assignment,
8601   oc_implicit_move_assignment,
8602   oc_implicit_inherited_constructor
8603 };
8604 
8605 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8606                                                 FunctionDecl *Fn,
8607                                                 std::string &Description) {
8608   bool isTemplate = false;
8609 
8610   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8611     isTemplate = true;
8612     Description = S.getTemplateArgumentBindingsText(
8613       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8614   }
8615 
8616   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8617     if (!Ctor->isImplicit())
8618       return isTemplate ? oc_constructor_template : oc_constructor;
8619 
8620     if (Ctor->getInheritedConstructor())
8621       return oc_implicit_inherited_constructor;
8622 
8623     if (Ctor->isDefaultConstructor())
8624       return oc_implicit_default_constructor;
8625 
8626     if (Ctor->isMoveConstructor())
8627       return oc_implicit_move_constructor;
8628 
8629     assert(Ctor->isCopyConstructor() &&
8630            "unexpected sort of implicit constructor");
8631     return oc_implicit_copy_constructor;
8632   }
8633 
8634   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8635     // This actually gets spelled 'candidate function' for now, but
8636     // it doesn't hurt to split it out.
8637     if (!Meth->isImplicit())
8638       return isTemplate ? oc_method_template : oc_method;
8639 
8640     if (Meth->isMoveAssignmentOperator())
8641       return oc_implicit_move_assignment;
8642 
8643     if (Meth->isCopyAssignmentOperator())
8644       return oc_implicit_copy_assignment;
8645 
8646     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8647     return oc_method;
8648   }
8649 
8650   return isTemplate ? oc_function_template : oc_function;
8651 }
8652 
8653 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8654   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8655   if (!Ctor) return;
8656 
8657   Ctor = Ctor->getInheritedConstructor();
8658   if (!Ctor) return;
8659 
8660   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8661 }
8662 
8663 } // end anonymous namespace
8664 
8665 // Notes the location of an overload candidate.
8666 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8667   std::string FnDesc;
8668   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8669   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8670                              << (unsigned) K << FnDesc;
8671   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8672   Diag(Fn->getLocation(), PD);
8673   MaybeEmitInheritedConstructorNote(*this, Fn);
8674 }
8675 
8676 // Notes the location of all overload candidates designated through
8677 // OverloadedExpr
8678 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8679   assert(OverloadedExpr->getType() == Context.OverloadTy);
8680 
8681   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8682   OverloadExpr *OvlExpr = Ovl.Expression;
8683 
8684   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8685                             IEnd = OvlExpr->decls_end();
8686        I != IEnd; ++I) {
8687     if (FunctionTemplateDecl *FunTmpl =
8688                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8689       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8690     } else if (FunctionDecl *Fun
8691                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8692       NoteOverloadCandidate(Fun, DestType);
8693     }
8694   }
8695 }
8696 
8697 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8698 /// "lead" diagnostic; it will be given two arguments, the source and
8699 /// target types of the conversion.
8700 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8701                                  Sema &S,
8702                                  SourceLocation CaretLoc,
8703                                  const PartialDiagnostic &PDiag) const {
8704   S.Diag(CaretLoc, PDiag)
8705     << Ambiguous.getFromType() << Ambiguous.getToType();
8706   // FIXME: The note limiting machinery is borrowed from
8707   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8708   // refactoring here.
8709   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8710   unsigned CandsShown = 0;
8711   AmbiguousConversionSequence::const_iterator I, E;
8712   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8713     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8714       break;
8715     ++CandsShown;
8716     S.NoteOverloadCandidate(*I);
8717   }
8718   if (I != E)
8719     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8720 }
8721 
8722 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8723                                   unsigned I) {
8724   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8725   assert(Conv.isBad());
8726   assert(Cand->Function && "for now, candidate must be a function");
8727   FunctionDecl *Fn = Cand->Function;
8728 
8729   // There's a conversion slot for the object argument if this is a
8730   // non-constructor method.  Note that 'I' corresponds the
8731   // conversion-slot index.
8732   bool isObjectArgument = false;
8733   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8734     if (I == 0)
8735       isObjectArgument = true;
8736     else
8737       I--;
8738   }
8739 
8740   std::string FnDesc;
8741   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8742 
8743   Expr *FromExpr = Conv.Bad.FromExpr;
8744   QualType FromTy = Conv.Bad.getFromType();
8745   QualType ToTy = Conv.Bad.getToType();
8746 
8747   if (FromTy == S.Context.OverloadTy) {
8748     assert(FromExpr && "overload set argument came from implicit argument?");
8749     Expr *E = FromExpr->IgnoreParens();
8750     if (isa<UnaryOperator>(E))
8751       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8752     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8753 
8754     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8755       << (unsigned) FnKind << FnDesc
8756       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8757       << ToTy << Name << I+1;
8758     MaybeEmitInheritedConstructorNote(S, Fn);
8759     return;
8760   }
8761 
8762   // Do some hand-waving analysis to see if the non-viability is due
8763   // to a qualifier mismatch.
8764   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8765   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8766   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8767     CToTy = RT->getPointeeType();
8768   else {
8769     // TODO: detect and diagnose the full richness of const mismatches.
8770     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8771       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8772         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8773   }
8774 
8775   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8776       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8777     Qualifiers FromQs = CFromTy.getQualifiers();
8778     Qualifiers ToQs = CToTy.getQualifiers();
8779 
8780     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8781       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8782         << (unsigned) FnKind << FnDesc
8783         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8784         << FromTy
8785         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8786         << (unsigned) isObjectArgument << I+1;
8787       MaybeEmitInheritedConstructorNote(S, Fn);
8788       return;
8789     }
8790 
8791     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8792       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8793         << (unsigned) FnKind << FnDesc
8794         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8795         << FromTy
8796         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8797         << (unsigned) isObjectArgument << I+1;
8798       MaybeEmitInheritedConstructorNote(S, Fn);
8799       return;
8800     }
8801 
8802     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8803       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8804       << (unsigned) FnKind << FnDesc
8805       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8806       << FromTy
8807       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8808       << (unsigned) isObjectArgument << I+1;
8809       MaybeEmitInheritedConstructorNote(S, Fn);
8810       return;
8811     }
8812 
8813     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8814     assert(CVR && "unexpected qualifiers mismatch");
8815 
8816     if (isObjectArgument) {
8817       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8818         << (unsigned) FnKind << FnDesc
8819         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8820         << FromTy << (CVR - 1);
8821     } else {
8822       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8823         << (unsigned) FnKind << FnDesc
8824         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8825         << FromTy << (CVR - 1) << I+1;
8826     }
8827     MaybeEmitInheritedConstructorNote(S, Fn);
8828     return;
8829   }
8830 
8831   // Special diagnostic for failure to convert an initializer list, since
8832   // telling the user that it has type void is not useful.
8833   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8834     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8835       << (unsigned) FnKind << FnDesc
8836       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8837       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8838     MaybeEmitInheritedConstructorNote(S, Fn);
8839     return;
8840   }
8841 
8842   // Diagnose references or pointers to incomplete types differently,
8843   // since it's far from impossible that the incompleteness triggered
8844   // the failure.
8845   QualType TempFromTy = FromTy.getNonReferenceType();
8846   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8847     TempFromTy = PTy->getPointeeType();
8848   if (TempFromTy->isIncompleteType()) {
8849     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8850       << (unsigned) FnKind << FnDesc
8851       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8852       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8853     MaybeEmitInheritedConstructorNote(S, Fn);
8854     return;
8855   }
8856 
8857   // Diagnose base -> derived pointer conversions.
8858   unsigned BaseToDerivedConversion = 0;
8859   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8860     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8861       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8862                                                FromPtrTy->getPointeeType()) &&
8863           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8864           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8865           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8866                           FromPtrTy->getPointeeType()))
8867         BaseToDerivedConversion = 1;
8868     }
8869   } else if (const ObjCObjectPointerType *FromPtrTy
8870                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8871     if (const ObjCObjectPointerType *ToPtrTy
8872                                         = ToTy->getAs<ObjCObjectPointerType>())
8873       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8874         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8875           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8876                                                 FromPtrTy->getPointeeType()) &&
8877               FromIface->isSuperClassOf(ToIface))
8878             BaseToDerivedConversion = 2;
8879   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8880     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8881         !FromTy->isIncompleteType() &&
8882         !ToRefTy->getPointeeType()->isIncompleteType() &&
8883         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8884       BaseToDerivedConversion = 3;
8885     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8886                ToTy.getNonReferenceType().getCanonicalType() ==
8887                FromTy.getNonReferenceType().getCanonicalType()) {
8888       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8889         << (unsigned) FnKind << FnDesc
8890         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8891         << (unsigned) isObjectArgument << I + 1;
8892       MaybeEmitInheritedConstructorNote(S, Fn);
8893       return;
8894     }
8895   }
8896 
8897   if (BaseToDerivedConversion) {
8898     S.Diag(Fn->getLocation(),
8899            diag::note_ovl_candidate_bad_base_to_derived_conv)
8900       << (unsigned) FnKind << FnDesc
8901       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8902       << (BaseToDerivedConversion - 1)
8903       << FromTy << ToTy << I+1;
8904     MaybeEmitInheritedConstructorNote(S, Fn);
8905     return;
8906   }
8907 
8908   if (isa<ObjCObjectPointerType>(CFromTy) &&
8909       isa<PointerType>(CToTy)) {
8910       Qualifiers FromQs = CFromTy.getQualifiers();
8911       Qualifiers ToQs = CToTy.getQualifiers();
8912       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8913         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8914         << (unsigned) FnKind << FnDesc
8915         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8916         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8917         MaybeEmitInheritedConstructorNote(S, Fn);
8918         return;
8919       }
8920   }
8921 
8922   // Emit the generic diagnostic and, optionally, add the hints to it.
8923   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8924   FDiag << (unsigned) FnKind << FnDesc
8925     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8926     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8927     << (unsigned) (Cand->Fix.Kind);
8928 
8929   // If we can fix the conversion, suggest the FixIts.
8930   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8931        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8932     FDiag << *HI;
8933   S.Diag(Fn->getLocation(), FDiag);
8934 
8935   MaybeEmitInheritedConstructorNote(S, Fn);
8936 }
8937 
8938 /// Additional arity mismatch diagnosis specific to a function overload
8939 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8940 /// over a candidate in any candidate set.
8941 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8942                                unsigned NumArgs) {
8943   FunctionDecl *Fn = Cand->Function;
8944   unsigned MinParams = Fn->getMinRequiredArguments();
8945 
8946   // With invalid overloaded operators, it's possible that we think we
8947   // have an arity mismatch when in fact it looks like we have the
8948   // right number of arguments, because only overloaded operators have
8949   // the weird behavior of overloading member and non-member functions.
8950   // Just don't report anything.
8951   if (Fn->isInvalidDecl() &&
8952       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8953     return true;
8954 
8955   if (NumArgs < MinParams) {
8956     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8957            (Cand->FailureKind == ovl_fail_bad_deduction &&
8958             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8959   } else {
8960     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8961            (Cand->FailureKind == ovl_fail_bad_deduction &&
8962             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8963   }
8964 
8965   return false;
8966 }
8967 
8968 /// General arity mismatch diagnosis over a candidate in a candidate set.
8969 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8970   assert(isa<FunctionDecl>(D) &&
8971       "The templated declaration should at least be a function"
8972       " when diagnosing bad template argument deduction due to too many"
8973       " or too few arguments");
8974 
8975   FunctionDecl *Fn = cast<FunctionDecl>(D);
8976 
8977   // TODO: treat calls to a missing default constructor as a special case
8978   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8979   unsigned MinParams = Fn->getMinRequiredArguments();
8980 
8981   // at least / at most / exactly
8982   unsigned mode, modeCount;
8983   if (NumFormalArgs < MinParams) {
8984     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8985         FnTy->isTemplateVariadic())
8986       mode = 0; // "at least"
8987     else
8988       mode = 2; // "exactly"
8989     modeCount = MinParams;
8990   } else {
8991     if (MinParams != FnTy->getNumParams())
8992       mode = 1; // "at most"
8993     else
8994       mode = 2; // "exactly"
8995     modeCount = FnTy->getNumParams();
8996   }
8997 
8998   std::string Description;
8999   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9000 
9001   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9002     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9003       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9004       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9005   else
9006     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9007       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9008       << mode << modeCount << NumFormalArgs;
9009   MaybeEmitInheritedConstructorNote(S, Fn);
9010 }
9011 
9012 /// Arity mismatch diagnosis specific to a function overload candidate.
9013 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9014                                   unsigned NumFormalArgs) {
9015   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9016     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9017 }
9018 
9019 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9020   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9021     return FD->getDescribedFunctionTemplate();
9022   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9023     return RD->getDescribedClassTemplate();
9024 
9025   llvm_unreachable("Unsupported: Getting the described template declaration"
9026                    " for bad deduction diagnosis");
9027 }
9028 
9029 /// Diagnose a failed template-argument deduction.
9030 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9031                                  DeductionFailureInfo &DeductionFailure,
9032                                  unsigned NumArgs) {
9033   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9034   NamedDecl *ParamD;
9035   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9036   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9037   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9038   switch (DeductionFailure.Result) {
9039   case Sema::TDK_Success:
9040     llvm_unreachable("TDK_success while diagnosing bad deduction");
9041 
9042   case Sema::TDK_Incomplete: {
9043     assert(ParamD && "no parameter found for incomplete deduction result");
9044     S.Diag(Templated->getLocation(),
9045            diag::note_ovl_candidate_incomplete_deduction)
9046         << ParamD->getDeclName();
9047     MaybeEmitInheritedConstructorNote(S, Templated);
9048     return;
9049   }
9050 
9051   case Sema::TDK_Underqualified: {
9052     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9053     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9054 
9055     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9056 
9057     // Param will have been canonicalized, but it should just be a
9058     // qualified version of ParamD, so move the qualifiers to that.
9059     QualifierCollector Qs;
9060     Qs.strip(Param);
9061     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9062     assert(S.Context.hasSameType(Param, NonCanonParam));
9063 
9064     // Arg has also been canonicalized, but there's nothing we can do
9065     // about that.  It also doesn't matter as much, because it won't
9066     // have any template parameters in it (because deduction isn't
9067     // done on dependent types).
9068     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9069 
9070     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9071         << ParamD->getDeclName() << Arg << NonCanonParam;
9072     MaybeEmitInheritedConstructorNote(S, Templated);
9073     return;
9074   }
9075 
9076   case Sema::TDK_Inconsistent: {
9077     assert(ParamD && "no parameter found for inconsistent deduction result");
9078     int which = 0;
9079     if (isa<TemplateTypeParmDecl>(ParamD))
9080       which = 0;
9081     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9082       which = 1;
9083     else {
9084       which = 2;
9085     }
9086 
9087     S.Diag(Templated->getLocation(),
9088            diag::note_ovl_candidate_inconsistent_deduction)
9089         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9090         << *DeductionFailure.getSecondArg();
9091     MaybeEmitInheritedConstructorNote(S, Templated);
9092     return;
9093   }
9094 
9095   case Sema::TDK_InvalidExplicitArguments:
9096     assert(ParamD && "no parameter found for invalid explicit arguments");
9097     if (ParamD->getDeclName())
9098       S.Diag(Templated->getLocation(),
9099              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9100           << ParamD->getDeclName();
9101     else {
9102       int index = 0;
9103       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9104         index = TTP->getIndex();
9105       else if (NonTypeTemplateParmDecl *NTTP
9106                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9107         index = NTTP->getIndex();
9108       else
9109         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9110       S.Diag(Templated->getLocation(),
9111              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9112           << (index + 1);
9113     }
9114     MaybeEmitInheritedConstructorNote(S, Templated);
9115     return;
9116 
9117   case Sema::TDK_TooManyArguments:
9118   case Sema::TDK_TooFewArguments:
9119     DiagnoseArityMismatch(S, Templated, NumArgs);
9120     return;
9121 
9122   case Sema::TDK_InstantiationDepth:
9123     S.Diag(Templated->getLocation(),
9124            diag::note_ovl_candidate_instantiation_depth);
9125     MaybeEmitInheritedConstructorNote(S, Templated);
9126     return;
9127 
9128   case Sema::TDK_SubstitutionFailure: {
9129     // Format the template argument list into the argument string.
9130     SmallString<128> TemplateArgString;
9131     if (TemplateArgumentList *Args =
9132             DeductionFailure.getTemplateArgumentList()) {
9133       TemplateArgString = " ";
9134       TemplateArgString += S.getTemplateArgumentBindingsText(
9135           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9136     }
9137 
9138     // If this candidate was disabled by enable_if, say so.
9139     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9140     if (PDiag && PDiag->second.getDiagID() ==
9141           diag::err_typename_nested_not_found_enable_if) {
9142       // FIXME: Use the source range of the condition, and the fully-qualified
9143       //        name of the enable_if template. These are both present in PDiag.
9144       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9145         << "'enable_if'" << TemplateArgString;
9146       return;
9147     }
9148 
9149     // Format the SFINAE diagnostic into the argument string.
9150     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9151     //        formatted message in another diagnostic.
9152     SmallString<128> SFINAEArgString;
9153     SourceRange R;
9154     if (PDiag) {
9155       SFINAEArgString = ": ";
9156       R = SourceRange(PDiag->first, PDiag->first);
9157       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9158     }
9159 
9160     S.Diag(Templated->getLocation(),
9161            diag::note_ovl_candidate_substitution_failure)
9162         << TemplateArgString << SFINAEArgString << R;
9163     MaybeEmitInheritedConstructorNote(S, Templated);
9164     return;
9165   }
9166 
9167   case Sema::TDK_FailedOverloadResolution: {
9168     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9169     S.Diag(Templated->getLocation(),
9170            diag::note_ovl_candidate_failed_overload_resolution)
9171         << R.Expression->getName();
9172     return;
9173   }
9174 
9175   case Sema::TDK_NonDeducedMismatch: {
9176     // FIXME: Provide a source location to indicate what we couldn't match.
9177     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9178     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9179     if (FirstTA.getKind() == TemplateArgument::Template &&
9180         SecondTA.getKind() == TemplateArgument::Template) {
9181       TemplateName FirstTN = FirstTA.getAsTemplate();
9182       TemplateName SecondTN = SecondTA.getAsTemplate();
9183       if (FirstTN.getKind() == TemplateName::Template &&
9184           SecondTN.getKind() == TemplateName::Template) {
9185         if (FirstTN.getAsTemplateDecl()->getName() ==
9186             SecondTN.getAsTemplateDecl()->getName()) {
9187           // FIXME: This fixes a bad diagnostic where both templates are named
9188           // the same.  This particular case is a bit difficult since:
9189           // 1) It is passed as a string to the diagnostic printer.
9190           // 2) The diagnostic printer only attempts to find a better
9191           //    name for types, not decls.
9192           // Ideally, this should folded into the diagnostic printer.
9193           S.Diag(Templated->getLocation(),
9194                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9195               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9196           return;
9197         }
9198       }
9199     }
9200     // FIXME: For generic lambda parameters, check if the function is a lambda
9201     // call operator, and if so, emit a prettier and more informative
9202     // diagnostic that mentions 'auto' and lambda in addition to
9203     // (or instead of?) the canonical template type parameters.
9204     S.Diag(Templated->getLocation(),
9205            diag::note_ovl_candidate_non_deduced_mismatch)
9206         << FirstTA << SecondTA;
9207     return;
9208   }
9209   // TODO: diagnose these individually, then kill off
9210   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9211   case Sema::TDK_MiscellaneousDeductionFailure:
9212     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9213     MaybeEmitInheritedConstructorNote(S, Templated);
9214     return;
9215   }
9216 }
9217 
9218 /// Diagnose a failed template-argument deduction, for function calls.
9219 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9220                                  unsigned NumArgs) {
9221   unsigned TDK = Cand->DeductionFailure.Result;
9222   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9223     if (CheckArityMismatch(S, Cand, NumArgs))
9224       return;
9225   }
9226   DiagnoseBadDeduction(S, Cand->Function, // pattern
9227                        Cand->DeductionFailure, NumArgs);
9228 }
9229 
9230 /// CUDA: diagnose an invalid call across targets.
9231 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9232   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9233   FunctionDecl *Callee = Cand->Function;
9234 
9235   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9236                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9237 
9238   std::string FnDesc;
9239   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9240 
9241   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9242       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9243 
9244   // This could be an implicit constructor for which we could not infer the
9245   // target due to a collsion. Diagnose that case.
9246   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9247   if (Meth != nullptr && Meth->isImplicit()) {
9248     CXXRecordDecl *ParentClass = Meth->getParent();
9249     Sema::CXXSpecialMember CSM;
9250 
9251     switch (FnKind) {
9252     default:
9253       return;
9254     case oc_implicit_default_constructor:
9255       CSM = Sema::CXXDefaultConstructor;
9256       break;
9257     case oc_implicit_copy_constructor:
9258       CSM = Sema::CXXCopyConstructor;
9259       break;
9260     case oc_implicit_move_constructor:
9261       CSM = Sema::CXXMoveConstructor;
9262       break;
9263     case oc_implicit_copy_assignment:
9264       CSM = Sema::CXXCopyAssignment;
9265       break;
9266     case oc_implicit_move_assignment:
9267       CSM = Sema::CXXMoveAssignment;
9268       break;
9269     };
9270 
9271     bool ConstRHS = false;
9272     if (Meth->getNumParams()) {
9273       if (const ReferenceType *RT =
9274               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9275         ConstRHS = RT->getPointeeType().isConstQualified();
9276       }
9277     }
9278 
9279     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9280                                               /* ConstRHS */ ConstRHS,
9281                                               /* Diagnose */ true);
9282   }
9283 }
9284 
9285 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9286   FunctionDecl *Callee = Cand->Function;
9287   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9288 
9289   S.Diag(Callee->getLocation(),
9290          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9291       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9292 }
9293 
9294 /// Generates a 'note' diagnostic for an overload candidate.  We've
9295 /// already generated a primary error at the call site.
9296 ///
9297 /// It really does need to be a single diagnostic with its caret
9298 /// pointed at the candidate declaration.  Yes, this creates some
9299 /// major challenges of technical writing.  Yes, this makes pointing
9300 /// out problems with specific arguments quite awkward.  It's still
9301 /// better than generating twenty screens of text for every failed
9302 /// overload.
9303 ///
9304 /// It would be great to be able to express per-candidate problems
9305 /// more richly for those diagnostic clients that cared, but we'd
9306 /// still have to be just as careful with the default diagnostics.
9307 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9308                                   unsigned NumArgs) {
9309   FunctionDecl *Fn = Cand->Function;
9310 
9311   // Note deleted candidates, but only if they're viable.
9312   if (Cand->Viable && (Fn->isDeleted() ||
9313       S.isFunctionConsideredUnavailable(Fn))) {
9314     std::string FnDesc;
9315     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9316 
9317     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9318       << FnKind << FnDesc
9319       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9320     MaybeEmitInheritedConstructorNote(S, Fn);
9321     return;
9322   }
9323 
9324   // We don't really have anything else to say about viable candidates.
9325   if (Cand->Viable) {
9326     S.NoteOverloadCandidate(Fn);
9327     return;
9328   }
9329 
9330   switch (Cand->FailureKind) {
9331   case ovl_fail_too_many_arguments:
9332   case ovl_fail_too_few_arguments:
9333     return DiagnoseArityMismatch(S, Cand, NumArgs);
9334 
9335   case ovl_fail_bad_deduction:
9336     return DiagnoseBadDeduction(S, Cand, NumArgs);
9337 
9338   case ovl_fail_illegal_constructor: {
9339     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9340       << (Fn->getPrimaryTemplate() ? 1 : 0);
9341     MaybeEmitInheritedConstructorNote(S, Fn);
9342     return;
9343   }
9344 
9345   case ovl_fail_trivial_conversion:
9346   case ovl_fail_bad_final_conversion:
9347   case ovl_fail_final_conversion_not_exact:
9348     return S.NoteOverloadCandidate(Fn);
9349 
9350   case ovl_fail_bad_conversion: {
9351     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9352     for (unsigned N = Cand->NumConversions; I != N; ++I)
9353       if (Cand->Conversions[I].isBad())
9354         return DiagnoseBadConversion(S, Cand, I);
9355 
9356     // FIXME: this currently happens when we're called from SemaInit
9357     // when user-conversion overload fails.  Figure out how to handle
9358     // those conditions and diagnose them well.
9359     return S.NoteOverloadCandidate(Fn);
9360   }
9361 
9362   case ovl_fail_bad_target:
9363     return DiagnoseBadTarget(S, Cand);
9364 
9365   case ovl_fail_enable_if:
9366     return DiagnoseFailedEnableIfAttr(S, Cand);
9367   }
9368 }
9369 
9370 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9371   // Desugar the type of the surrogate down to a function type,
9372   // retaining as many typedefs as possible while still showing
9373   // the function type (and, therefore, its parameter types).
9374   QualType FnType = Cand->Surrogate->getConversionType();
9375   bool isLValueReference = false;
9376   bool isRValueReference = false;
9377   bool isPointer = false;
9378   if (const LValueReferenceType *FnTypeRef =
9379         FnType->getAs<LValueReferenceType>()) {
9380     FnType = FnTypeRef->getPointeeType();
9381     isLValueReference = true;
9382   } else if (const RValueReferenceType *FnTypeRef =
9383                FnType->getAs<RValueReferenceType>()) {
9384     FnType = FnTypeRef->getPointeeType();
9385     isRValueReference = true;
9386   }
9387   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9388     FnType = FnTypePtr->getPointeeType();
9389     isPointer = true;
9390   }
9391   // Desugar down to a function type.
9392   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9393   // Reconstruct the pointer/reference as appropriate.
9394   if (isPointer) FnType = S.Context.getPointerType(FnType);
9395   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9396   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9397 
9398   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9399     << FnType;
9400   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9401 }
9402 
9403 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9404                                          SourceLocation OpLoc,
9405                                          OverloadCandidate *Cand) {
9406   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9407   std::string TypeStr("operator");
9408   TypeStr += Opc;
9409   TypeStr += "(";
9410   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9411   if (Cand->NumConversions == 1) {
9412     TypeStr += ")";
9413     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9414   } else {
9415     TypeStr += ", ";
9416     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9417     TypeStr += ")";
9418     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9419   }
9420 }
9421 
9422 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9423                                          OverloadCandidate *Cand) {
9424   unsigned NoOperands = Cand->NumConversions;
9425   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9426     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9427     if (ICS.isBad()) break; // all meaningless after first invalid
9428     if (!ICS.isAmbiguous()) continue;
9429 
9430     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9431                               S.PDiag(diag::note_ambiguous_type_conversion));
9432   }
9433 }
9434 
9435 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9436   if (Cand->Function)
9437     return Cand->Function->getLocation();
9438   if (Cand->IsSurrogate)
9439     return Cand->Surrogate->getLocation();
9440   return SourceLocation();
9441 }
9442 
9443 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9444   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9445   case Sema::TDK_Success:
9446     llvm_unreachable("TDK_success while diagnosing bad deduction");
9447 
9448   case Sema::TDK_Invalid:
9449   case Sema::TDK_Incomplete:
9450     return 1;
9451 
9452   case Sema::TDK_Underqualified:
9453   case Sema::TDK_Inconsistent:
9454     return 2;
9455 
9456   case Sema::TDK_SubstitutionFailure:
9457   case Sema::TDK_NonDeducedMismatch:
9458   case Sema::TDK_MiscellaneousDeductionFailure:
9459     return 3;
9460 
9461   case Sema::TDK_InstantiationDepth:
9462   case Sema::TDK_FailedOverloadResolution:
9463     return 4;
9464 
9465   case Sema::TDK_InvalidExplicitArguments:
9466     return 5;
9467 
9468   case Sema::TDK_TooManyArguments:
9469   case Sema::TDK_TooFewArguments:
9470     return 6;
9471   }
9472   llvm_unreachable("Unhandled deduction result");
9473 }
9474 
9475 namespace {
9476 struct CompareOverloadCandidatesForDisplay {
9477   Sema &S;
9478   size_t NumArgs;
9479 
9480   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9481       : S(S), NumArgs(nArgs) {}
9482 
9483   bool operator()(const OverloadCandidate *L,
9484                   const OverloadCandidate *R) {
9485     // Fast-path this check.
9486     if (L == R) return false;
9487 
9488     // Order first by viability.
9489     if (L->Viable) {
9490       if (!R->Viable) return true;
9491 
9492       // TODO: introduce a tri-valued comparison for overload
9493       // candidates.  Would be more worthwhile if we had a sort
9494       // that could exploit it.
9495       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9496       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9497     } else if (R->Viable)
9498       return false;
9499 
9500     assert(L->Viable == R->Viable);
9501 
9502     // Criteria by which we can sort non-viable candidates:
9503     if (!L->Viable) {
9504       // 1. Arity mismatches come after other candidates.
9505       if (L->FailureKind == ovl_fail_too_many_arguments ||
9506           L->FailureKind == ovl_fail_too_few_arguments) {
9507         if (R->FailureKind == ovl_fail_too_many_arguments ||
9508             R->FailureKind == ovl_fail_too_few_arguments) {
9509           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9510           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9511           if (LDist == RDist) {
9512             if (L->FailureKind == R->FailureKind)
9513               // Sort non-surrogates before surrogates.
9514               return !L->IsSurrogate && R->IsSurrogate;
9515             // Sort candidates requiring fewer parameters than there were
9516             // arguments given after candidates requiring more parameters
9517             // than there were arguments given.
9518             return L->FailureKind == ovl_fail_too_many_arguments;
9519           }
9520           return LDist < RDist;
9521         }
9522         return false;
9523       }
9524       if (R->FailureKind == ovl_fail_too_many_arguments ||
9525           R->FailureKind == ovl_fail_too_few_arguments)
9526         return true;
9527 
9528       // 2. Bad conversions come first and are ordered by the number
9529       // of bad conversions and quality of good conversions.
9530       if (L->FailureKind == ovl_fail_bad_conversion) {
9531         if (R->FailureKind != ovl_fail_bad_conversion)
9532           return true;
9533 
9534         // The conversion that can be fixed with a smaller number of changes,
9535         // comes first.
9536         unsigned numLFixes = L->Fix.NumConversionsFixed;
9537         unsigned numRFixes = R->Fix.NumConversionsFixed;
9538         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9539         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9540         if (numLFixes != numRFixes) {
9541           return numLFixes < numRFixes;
9542         }
9543 
9544         // If there's any ordering between the defined conversions...
9545         // FIXME: this might not be transitive.
9546         assert(L->NumConversions == R->NumConversions);
9547 
9548         int leftBetter = 0;
9549         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9550         for (unsigned E = L->NumConversions; I != E; ++I) {
9551           switch (CompareImplicitConversionSequences(S,
9552                                                      L->Conversions[I],
9553                                                      R->Conversions[I])) {
9554           case ImplicitConversionSequence::Better:
9555             leftBetter++;
9556             break;
9557 
9558           case ImplicitConversionSequence::Worse:
9559             leftBetter--;
9560             break;
9561 
9562           case ImplicitConversionSequence::Indistinguishable:
9563             break;
9564           }
9565         }
9566         if (leftBetter > 0) return true;
9567         if (leftBetter < 0) return false;
9568 
9569       } else if (R->FailureKind == ovl_fail_bad_conversion)
9570         return false;
9571 
9572       if (L->FailureKind == ovl_fail_bad_deduction) {
9573         if (R->FailureKind != ovl_fail_bad_deduction)
9574           return true;
9575 
9576         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9577           return RankDeductionFailure(L->DeductionFailure)
9578                < RankDeductionFailure(R->DeductionFailure);
9579       } else if (R->FailureKind == ovl_fail_bad_deduction)
9580         return false;
9581 
9582       // TODO: others?
9583     }
9584 
9585     // Sort everything else by location.
9586     SourceLocation LLoc = GetLocationForCandidate(L);
9587     SourceLocation RLoc = GetLocationForCandidate(R);
9588 
9589     // Put candidates without locations (e.g. builtins) at the end.
9590     if (LLoc.isInvalid()) return false;
9591     if (RLoc.isInvalid()) return true;
9592 
9593     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9594   }
9595 };
9596 }
9597 
9598 /// CompleteNonViableCandidate - Normally, overload resolution only
9599 /// computes up to the first. Produces the FixIt set if possible.
9600 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9601                                        ArrayRef<Expr *> Args) {
9602   assert(!Cand->Viable);
9603 
9604   // Don't do anything on failures other than bad conversion.
9605   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9606 
9607   // We only want the FixIts if all the arguments can be corrected.
9608   bool Unfixable = false;
9609   // Use a implicit copy initialization to check conversion fixes.
9610   Cand->Fix.setConversionChecker(TryCopyInitialization);
9611 
9612   // Skip forward to the first bad conversion.
9613   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9614   unsigned ConvCount = Cand->NumConversions;
9615   while (true) {
9616     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9617     ConvIdx++;
9618     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9619       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9620       break;
9621     }
9622   }
9623 
9624   if (ConvIdx == ConvCount)
9625     return;
9626 
9627   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9628          "remaining conversion is initialized?");
9629 
9630   // FIXME: this should probably be preserved from the overload
9631   // operation somehow.
9632   bool SuppressUserConversions = false;
9633 
9634   const FunctionProtoType* Proto;
9635   unsigned ArgIdx = ConvIdx;
9636 
9637   if (Cand->IsSurrogate) {
9638     QualType ConvType
9639       = Cand->Surrogate->getConversionType().getNonReferenceType();
9640     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9641       ConvType = ConvPtrType->getPointeeType();
9642     Proto = ConvType->getAs<FunctionProtoType>();
9643     ArgIdx--;
9644   } else if (Cand->Function) {
9645     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9646     if (isa<CXXMethodDecl>(Cand->Function) &&
9647         !isa<CXXConstructorDecl>(Cand->Function))
9648       ArgIdx--;
9649   } else {
9650     // Builtin binary operator with a bad first conversion.
9651     assert(ConvCount <= 3);
9652     for (; ConvIdx != ConvCount; ++ConvIdx)
9653       Cand->Conversions[ConvIdx]
9654         = TryCopyInitialization(S, Args[ConvIdx],
9655                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9656                                 SuppressUserConversions,
9657                                 /*InOverloadResolution*/ true,
9658                                 /*AllowObjCWritebackConversion=*/
9659                                   S.getLangOpts().ObjCAutoRefCount);
9660     return;
9661   }
9662 
9663   // Fill in the rest of the conversions.
9664   unsigned NumParams = Proto->getNumParams();
9665   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9666     if (ArgIdx < NumParams) {
9667       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9668           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9669           /*InOverloadResolution=*/true,
9670           /*AllowObjCWritebackConversion=*/
9671           S.getLangOpts().ObjCAutoRefCount);
9672       // Store the FixIt in the candidate if it exists.
9673       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9674         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9675     }
9676     else
9677       Cand->Conversions[ConvIdx].setEllipsis();
9678   }
9679 }
9680 
9681 /// PrintOverloadCandidates - When overload resolution fails, prints
9682 /// diagnostic messages containing the candidates in the candidate
9683 /// set.
9684 void OverloadCandidateSet::NoteCandidates(Sema &S,
9685                                           OverloadCandidateDisplayKind OCD,
9686                                           ArrayRef<Expr *> Args,
9687                                           StringRef Opc,
9688                                           SourceLocation OpLoc) {
9689   // Sort the candidates by viability and position.  Sorting directly would
9690   // be prohibitive, so we make a set of pointers and sort those.
9691   SmallVector<OverloadCandidate*, 32> Cands;
9692   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9693   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9694     if (Cand->Viable)
9695       Cands.push_back(Cand);
9696     else if (OCD == OCD_AllCandidates) {
9697       CompleteNonViableCandidate(S, Cand, Args);
9698       if (Cand->Function || Cand->IsSurrogate)
9699         Cands.push_back(Cand);
9700       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9701       // want to list every possible builtin candidate.
9702     }
9703   }
9704 
9705   std::sort(Cands.begin(), Cands.end(),
9706             CompareOverloadCandidatesForDisplay(S, Args.size()));
9707 
9708   bool ReportedAmbiguousConversions = false;
9709 
9710   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9711   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9712   unsigned CandsShown = 0;
9713   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9714     OverloadCandidate *Cand = *I;
9715 
9716     // Set an arbitrary limit on the number of candidate functions we'll spam
9717     // the user with.  FIXME: This limit should depend on details of the
9718     // candidate list.
9719     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9720       break;
9721     }
9722     ++CandsShown;
9723 
9724     if (Cand->Function)
9725       NoteFunctionCandidate(S, Cand, Args.size());
9726     else if (Cand->IsSurrogate)
9727       NoteSurrogateCandidate(S, Cand);
9728     else {
9729       assert(Cand->Viable &&
9730              "Non-viable built-in candidates are not added to Cands.");
9731       // Generally we only see ambiguities including viable builtin
9732       // operators if overload resolution got screwed up by an
9733       // ambiguous user-defined conversion.
9734       //
9735       // FIXME: It's quite possible for different conversions to see
9736       // different ambiguities, though.
9737       if (!ReportedAmbiguousConversions) {
9738         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9739         ReportedAmbiguousConversions = true;
9740       }
9741 
9742       // If this is a viable builtin, print it.
9743       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9744     }
9745   }
9746 
9747   if (I != E)
9748     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9749 }
9750 
9751 static SourceLocation
9752 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9753   return Cand->Specialization ? Cand->Specialization->getLocation()
9754                               : SourceLocation();
9755 }
9756 
9757 namespace {
9758 struct CompareTemplateSpecCandidatesForDisplay {
9759   Sema &S;
9760   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9761 
9762   bool operator()(const TemplateSpecCandidate *L,
9763                   const TemplateSpecCandidate *R) {
9764     // Fast-path this check.
9765     if (L == R)
9766       return false;
9767 
9768     // Assuming that both candidates are not matches...
9769 
9770     // Sort by the ranking of deduction failures.
9771     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9772       return RankDeductionFailure(L->DeductionFailure) <
9773              RankDeductionFailure(R->DeductionFailure);
9774 
9775     // Sort everything else by location.
9776     SourceLocation LLoc = GetLocationForCandidate(L);
9777     SourceLocation RLoc = GetLocationForCandidate(R);
9778 
9779     // Put candidates without locations (e.g. builtins) at the end.
9780     if (LLoc.isInvalid())
9781       return false;
9782     if (RLoc.isInvalid())
9783       return true;
9784 
9785     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9786   }
9787 };
9788 }
9789 
9790 /// Diagnose a template argument deduction failure.
9791 /// We are treating these failures as overload failures due to bad
9792 /// deductions.
9793 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9794   DiagnoseBadDeduction(S, Specialization, // pattern
9795                        DeductionFailure, /*NumArgs=*/0);
9796 }
9797 
9798 void TemplateSpecCandidateSet::destroyCandidates() {
9799   for (iterator i = begin(), e = end(); i != e; ++i) {
9800     i->DeductionFailure.Destroy();
9801   }
9802 }
9803 
9804 void TemplateSpecCandidateSet::clear() {
9805   destroyCandidates();
9806   Candidates.clear();
9807 }
9808 
9809 /// NoteCandidates - When no template specialization match is found, prints
9810 /// diagnostic messages containing the non-matching specializations that form
9811 /// the candidate set.
9812 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9813 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9814 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9815   // Sort the candidates by position (assuming no candidate is a match).
9816   // Sorting directly would be prohibitive, so we make a set of pointers
9817   // and sort those.
9818   SmallVector<TemplateSpecCandidate *, 32> Cands;
9819   Cands.reserve(size());
9820   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9821     if (Cand->Specialization)
9822       Cands.push_back(Cand);
9823     // Otherwise, this is a non-matching builtin candidate.  We do not,
9824     // in general, want to list every possible builtin candidate.
9825   }
9826 
9827   std::sort(Cands.begin(), Cands.end(),
9828             CompareTemplateSpecCandidatesForDisplay(S));
9829 
9830   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9831   // for generalization purposes (?).
9832   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9833 
9834   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9835   unsigned CandsShown = 0;
9836   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9837     TemplateSpecCandidate *Cand = *I;
9838 
9839     // Set an arbitrary limit on the number of candidates we'll spam
9840     // the user with.  FIXME: This limit should depend on details of the
9841     // candidate list.
9842     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9843       break;
9844     ++CandsShown;
9845 
9846     assert(Cand->Specialization &&
9847            "Non-matching built-in candidates are not added to Cands.");
9848     Cand->NoteDeductionFailure(S);
9849   }
9850 
9851   if (I != E)
9852     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9853 }
9854 
9855 // [PossiblyAFunctionType]  -->   [Return]
9856 // NonFunctionType --> NonFunctionType
9857 // R (A) --> R(A)
9858 // R (*)(A) --> R (A)
9859 // R (&)(A) --> R (A)
9860 // R (S::*)(A) --> R (A)
9861 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9862   QualType Ret = PossiblyAFunctionType;
9863   if (const PointerType *ToTypePtr =
9864     PossiblyAFunctionType->getAs<PointerType>())
9865     Ret = ToTypePtr->getPointeeType();
9866   else if (const ReferenceType *ToTypeRef =
9867     PossiblyAFunctionType->getAs<ReferenceType>())
9868     Ret = ToTypeRef->getPointeeType();
9869   else if (const MemberPointerType *MemTypePtr =
9870     PossiblyAFunctionType->getAs<MemberPointerType>())
9871     Ret = MemTypePtr->getPointeeType();
9872   Ret =
9873     Context.getCanonicalType(Ret).getUnqualifiedType();
9874   return Ret;
9875 }
9876 
9877 namespace {
9878 // A helper class to help with address of function resolution
9879 // - allows us to avoid passing around all those ugly parameters
9880 class AddressOfFunctionResolver {
9881   Sema& S;
9882   Expr* SourceExpr;
9883   const QualType& TargetType;
9884   QualType TargetFunctionType; // Extracted function type from target type
9885 
9886   bool Complain;
9887   //DeclAccessPair& ResultFunctionAccessPair;
9888   ASTContext& Context;
9889 
9890   bool TargetTypeIsNonStaticMemberFunction;
9891   bool FoundNonTemplateFunction;
9892   bool StaticMemberFunctionFromBoundPointer;
9893 
9894   OverloadExpr::FindResult OvlExprInfo;
9895   OverloadExpr *OvlExpr;
9896   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9897   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9898   TemplateSpecCandidateSet FailedCandidates;
9899 
9900 public:
9901   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9902                             const QualType &TargetType, bool Complain)
9903       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9904         Complain(Complain), Context(S.getASTContext()),
9905         TargetTypeIsNonStaticMemberFunction(
9906             !!TargetType->getAs<MemberPointerType>()),
9907         FoundNonTemplateFunction(false),
9908         StaticMemberFunctionFromBoundPointer(false),
9909         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9910         OvlExpr(OvlExprInfo.Expression),
9911         FailedCandidates(OvlExpr->getNameLoc()) {
9912     ExtractUnqualifiedFunctionTypeFromTargetType();
9913 
9914     if (TargetFunctionType->isFunctionType()) {
9915       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9916         if (!UME->isImplicitAccess() &&
9917             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9918           StaticMemberFunctionFromBoundPointer = true;
9919     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9920       DeclAccessPair dap;
9921       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9922               OvlExpr, false, &dap)) {
9923         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9924           if (!Method->isStatic()) {
9925             // If the target type is a non-function type and the function found
9926             // is a non-static member function, pretend as if that was the
9927             // target, it's the only possible type to end up with.
9928             TargetTypeIsNonStaticMemberFunction = true;
9929 
9930             // And skip adding the function if its not in the proper form.
9931             // We'll diagnose this due to an empty set of functions.
9932             if (!OvlExprInfo.HasFormOfMemberPointer)
9933               return;
9934           }
9935 
9936         Matches.push_back(std::make_pair(dap, Fn));
9937       }
9938       return;
9939     }
9940 
9941     if (OvlExpr->hasExplicitTemplateArgs())
9942       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9943 
9944     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9945       // C++ [over.over]p4:
9946       //   If more than one function is selected, [...]
9947       if (Matches.size() > 1) {
9948         if (FoundNonTemplateFunction)
9949           EliminateAllTemplateMatches();
9950         else
9951           EliminateAllExceptMostSpecializedTemplate();
9952       }
9953     }
9954 
9955     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
9956         Matches.size() > 1)
9957       EliminateSuboptimalCudaMatches();
9958   }
9959 
9960 private:
9961   bool isTargetTypeAFunction() const {
9962     return TargetFunctionType->isFunctionType();
9963   }
9964 
9965   // [ToType]     [Return]
9966 
9967   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9968   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9969   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9970   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9971     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9972   }
9973 
9974   // return true if any matching specializations were found
9975   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9976                                    const DeclAccessPair& CurAccessFunPair) {
9977     if (CXXMethodDecl *Method
9978               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9979       // Skip non-static function templates when converting to pointer, and
9980       // static when converting to member pointer.
9981       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9982         return false;
9983     }
9984     else if (TargetTypeIsNonStaticMemberFunction)
9985       return false;
9986 
9987     // C++ [over.over]p2:
9988     //   If the name is a function template, template argument deduction is
9989     //   done (14.8.2.2), and if the argument deduction succeeds, the
9990     //   resulting template argument list is used to generate a single
9991     //   function template specialization, which is added to the set of
9992     //   overloaded functions considered.
9993     FunctionDecl *Specialization = nullptr;
9994     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9995     if (Sema::TemplateDeductionResult Result
9996           = S.DeduceTemplateArguments(FunctionTemplate,
9997                                       &OvlExplicitTemplateArgs,
9998                                       TargetFunctionType, Specialization,
9999                                       Info, /*InOverloadResolution=*/true)) {
10000       // Make a note of the failed deduction for diagnostics.
10001       FailedCandidates.addCandidate()
10002           .set(FunctionTemplate->getTemplatedDecl(),
10003                MakeDeductionFailureInfo(Context, Result, Info));
10004       return false;
10005     }
10006 
10007     // Template argument deduction ensures that we have an exact match or
10008     // compatible pointer-to-function arguments that would be adjusted by ICS.
10009     // This function template specicalization works.
10010     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
10011     assert(S.isSameOrCompatibleFunctionType(
10012               Context.getCanonicalType(Specialization->getType()),
10013               Context.getCanonicalType(TargetFunctionType)));
10014     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10015     return true;
10016   }
10017 
10018   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10019                                       const DeclAccessPair& CurAccessFunPair) {
10020     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10021       // Skip non-static functions when converting to pointer, and static
10022       // when converting to member pointer.
10023       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10024         return false;
10025     }
10026     else if (TargetTypeIsNonStaticMemberFunction)
10027       return false;
10028 
10029     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10030       if (S.getLangOpts().CUDA)
10031         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10032           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10033             return false;
10034 
10035       // If any candidate has a placeholder return type, trigger its deduction
10036       // now.
10037       if (S.getLangOpts().CPlusPlus14 &&
10038           FunDecl->getReturnType()->isUndeducedType() &&
10039           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10040         return false;
10041 
10042       QualType ResultTy;
10043       if (Context.hasSameUnqualifiedType(TargetFunctionType,
10044                                          FunDecl->getType()) ||
10045           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10046                                  ResultTy)) {
10047         Matches.push_back(std::make_pair(CurAccessFunPair,
10048           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10049         FoundNonTemplateFunction = true;
10050         return true;
10051       }
10052     }
10053 
10054     return false;
10055   }
10056 
10057   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10058     bool Ret = false;
10059 
10060     // If the overload expression doesn't have the form of a pointer to
10061     // member, don't try to convert it to a pointer-to-member type.
10062     if (IsInvalidFormOfPointerToMemberFunction())
10063       return false;
10064 
10065     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10066                                E = OvlExpr->decls_end();
10067          I != E; ++I) {
10068       // Look through any using declarations to find the underlying function.
10069       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10070 
10071       // C++ [over.over]p3:
10072       //   Non-member functions and static member functions match
10073       //   targets of type "pointer-to-function" or "reference-to-function."
10074       //   Nonstatic member functions match targets of
10075       //   type "pointer-to-member-function."
10076       // Note that according to DR 247, the containing class does not matter.
10077       if (FunctionTemplateDecl *FunctionTemplate
10078                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10079         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10080           Ret = true;
10081       }
10082       // If we have explicit template arguments supplied, skip non-templates.
10083       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10084                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10085         Ret = true;
10086     }
10087     assert(Ret || Matches.empty());
10088     return Ret;
10089   }
10090 
10091   void EliminateAllExceptMostSpecializedTemplate() {
10092     //   [...] and any given function template specialization F1 is
10093     //   eliminated if the set contains a second function template
10094     //   specialization whose function template is more specialized
10095     //   than the function template of F1 according to the partial
10096     //   ordering rules of 14.5.5.2.
10097 
10098     // The algorithm specified above is quadratic. We instead use a
10099     // two-pass algorithm (similar to the one used to identify the
10100     // best viable function in an overload set) that identifies the
10101     // best function template (if it exists).
10102 
10103     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10104     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10105       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10106 
10107     // TODO: It looks like FailedCandidates does not serve much purpose
10108     // here, since the no_viable diagnostic has index 0.
10109     UnresolvedSetIterator Result = S.getMostSpecialized(
10110         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10111         SourceExpr->getLocStart(), S.PDiag(),
10112         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10113                                                      .second->getDeclName(),
10114         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10115         Complain, TargetFunctionType);
10116 
10117     if (Result != MatchesCopy.end()) {
10118       // Make it the first and only element
10119       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10120       Matches[0].second = cast<FunctionDecl>(*Result);
10121       Matches.resize(1);
10122     }
10123   }
10124 
10125   void EliminateAllTemplateMatches() {
10126     //   [...] any function template specializations in the set are
10127     //   eliminated if the set also contains a non-template function, [...]
10128     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10129       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10130         ++I;
10131       else {
10132         Matches[I] = Matches[--N];
10133         Matches.resize(N);
10134       }
10135     }
10136   }
10137 
10138   void EliminateSuboptimalCudaMatches() {
10139     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10140   }
10141 
10142 public:
10143   void ComplainNoMatchesFound() const {
10144     assert(Matches.empty());
10145     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10146         << OvlExpr->getName() << TargetFunctionType
10147         << OvlExpr->getSourceRange();
10148     if (FailedCandidates.empty())
10149       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10150     else {
10151       // We have some deduction failure messages. Use them to diagnose
10152       // the function templates, and diagnose the non-template candidates
10153       // normally.
10154       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10155                                  IEnd = OvlExpr->decls_end();
10156            I != IEnd; ++I)
10157         if (FunctionDecl *Fun =
10158                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10159           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10160       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10161     }
10162   }
10163 
10164   bool IsInvalidFormOfPointerToMemberFunction() const {
10165     return TargetTypeIsNonStaticMemberFunction &&
10166       !OvlExprInfo.HasFormOfMemberPointer;
10167   }
10168 
10169   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10170       // TODO: Should we condition this on whether any functions might
10171       // have matched, or is it more appropriate to do that in callers?
10172       // TODO: a fixit wouldn't hurt.
10173       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10174         << TargetType << OvlExpr->getSourceRange();
10175   }
10176 
10177   bool IsStaticMemberFunctionFromBoundPointer() const {
10178     return StaticMemberFunctionFromBoundPointer;
10179   }
10180 
10181   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10182     S.Diag(OvlExpr->getLocStart(),
10183            diag::err_invalid_form_pointer_member_function)
10184       << OvlExpr->getSourceRange();
10185   }
10186 
10187   void ComplainOfInvalidConversion() const {
10188     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10189       << OvlExpr->getName() << TargetType;
10190   }
10191 
10192   void ComplainMultipleMatchesFound() const {
10193     assert(Matches.size() > 1);
10194     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10195       << OvlExpr->getName()
10196       << OvlExpr->getSourceRange();
10197     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10198   }
10199 
10200   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10201 
10202   int getNumMatches() const { return Matches.size(); }
10203 
10204   FunctionDecl* getMatchingFunctionDecl() const {
10205     if (Matches.size() != 1) return nullptr;
10206     return Matches[0].second;
10207   }
10208 
10209   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10210     if (Matches.size() != 1) return nullptr;
10211     return &Matches[0].first;
10212   }
10213 };
10214 }
10215 
10216 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10217 /// an overloaded function (C++ [over.over]), where @p From is an
10218 /// expression with overloaded function type and @p ToType is the type
10219 /// we're trying to resolve to. For example:
10220 ///
10221 /// @code
10222 /// int f(double);
10223 /// int f(int);
10224 ///
10225 /// int (*pfd)(double) = f; // selects f(double)
10226 /// @endcode
10227 ///
10228 /// This routine returns the resulting FunctionDecl if it could be
10229 /// resolved, and NULL otherwise. When @p Complain is true, this
10230 /// routine will emit diagnostics if there is an error.
10231 FunctionDecl *
10232 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10233                                          QualType TargetType,
10234                                          bool Complain,
10235                                          DeclAccessPair &FoundResult,
10236                                          bool *pHadMultipleCandidates) {
10237   assert(AddressOfExpr->getType() == Context.OverloadTy);
10238 
10239   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10240                                      Complain);
10241   int NumMatches = Resolver.getNumMatches();
10242   FunctionDecl *Fn = nullptr;
10243   if (NumMatches == 0 && Complain) {
10244     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10245       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10246     else
10247       Resolver.ComplainNoMatchesFound();
10248   }
10249   else if (NumMatches > 1 && Complain)
10250     Resolver.ComplainMultipleMatchesFound();
10251   else if (NumMatches == 1) {
10252     Fn = Resolver.getMatchingFunctionDecl();
10253     assert(Fn);
10254     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10255     if (Complain) {
10256       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10257         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10258       else
10259         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10260     }
10261   }
10262 
10263   if (pHadMultipleCandidates)
10264     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10265   return Fn;
10266 }
10267 
10268 /// \brief Given an expression that refers to an overloaded function, try to
10269 /// resolve that overloaded function expression down to a single function.
10270 ///
10271 /// This routine can only resolve template-ids that refer to a single function
10272 /// template, where that template-id refers to a single template whose template
10273 /// arguments are either provided by the template-id or have defaults,
10274 /// as described in C++0x [temp.arg.explicit]p3.
10275 ///
10276 /// If no template-ids are found, no diagnostics are emitted and NULL is
10277 /// returned.
10278 FunctionDecl *
10279 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10280                                                   bool Complain,
10281                                                   DeclAccessPair *FoundResult) {
10282   // C++ [over.over]p1:
10283   //   [...] [Note: any redundant set of parentheses surrounding the
10284   //   overloaded function name is ignored (5.1). ]
10285   // C++ [over.over]p1:
10286   //   [...] The overloaded function name can be preceded by the &
10287   //   operator.
10288 
10289   // If we didn't actually find any template-ids, we're done.
10290   if (!ovl->hasExplicitTemplateArgs())
10291     return nullptr;
10292 
10293   TemplateArgumentListInfo ExplicitTemplateArgs;
10294   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10295   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10296 
10297   // Look through all of the overloaded functions, searching for one
10298   // whose type matches exactly.
10299   FunctionDecl *Matched = nullptr;
10300   for (UnresolvedSetIterator I = ovl->decls_begin(),
10301          E = ovl->decls_end(); I != E; ++I) {
10302     // C++0x [temp.arg.explicit]p3:
10303     //   [...] In contexts where deduction is done and fails, or in contexts
10304     //   where deduction is not done, if a template argument list is
10305     //   specified and it, along with any default template arguments,
10306     //   identifies a single function template specialization, then the
10307     //   template-id is an lvalue for the function template specialization.
10308     FunctionTemplateDecl *FunctionTemplate
10309       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10310 
10311     // C++ [over.over]p2:
10312     //   If the name is a function template, template argument deduction is
10313     //   done (14.8.2.2), and if the argument deduction succeeds, the
10314     //   resulting template argument list is used to generate a single
10315     //   function template specialization, which is added to the set of
10316     //   overloaded functions considered.
10317     FunctionDecl *Specialization = nullptr;
10318     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10319     if (TemplateDeductionResult Result
10320           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10321                                     Specialization, Info,
10322                                     /*InOverloadResolution=*/true)) {
10323       // Make a note of the failed deduction for diagnostics.
10324       // TODO: Actually use the failed-deduction info?
10325       FailedCandidates.addCandidate()
10326           .set(FunctionTemplate->getTemplatedDecl(),
10327                MakeDeductionFailureInfo(Context, Result, Info));
10328       continue;
10329     }
10330 
10331     assert(Specialization && "no specialization and no error?");
10332 
10333     // Multiple matches; we can't resolve to a single declaration.
10334     if (Matched) {
10335       if (Complain) {
10336         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10337           << ovl->getName();
10338         NoteAllOverloadCandidates(ovl);
10339       }
10340       return nullptr;
10341     }
10342 
10343     Matched = Specialization;
10344     if (FoundResult) *FoundResult = I.getPair();
10345   }
10346 
10347   if (Matched && getLangOpts().CPlusPlus14 &&
10348       Matched->getReturnType()->isUndeducedType() &&
10349       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10350     return nullptr;
10351 
10352   return Matched;
10353 }
10354 
10355 
10356 
10357 
10358 // Resolve and fix an overloaded expression that can be resolved
10359 // because it identifies a single function template specialization.
10360 //
10361 // Last three arguments should only be supplied if Complain = true
10362 //
10363 // Return true if it was logically possible to so resolve the
10364 // expression, regardless of whether or not it succeeded.  Always
10365 // returns true if 'complain' is set.
10366 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10367                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10368                    bool complain, const SourceRange& OpRangeForComplaining,
10369                                            QualType DestTypeForComplaining,
10370                                             unsigned DiagIDForComplaining) {
10371   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10372 
10373   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10374 
10375   DeclAccessPair found;
10376   ExprResult SingleFunctionExpression;
10377   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10378                            ovl.Expression, /*complain*/ false, &found)) {
10379     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10380       SrcExpr = ExprError();
10381       return true;
10382     }
10383 
10384     // It is only correct to resolve to an instance method if we're
10385     // resolving a form that's permitted to be a pointer to member.
10386     // Otherwise we'll end up making a bound member expression, which
10387     // is illegal in all the contexts we resolve like this.
10388     if (!ovl.HasFormOfMemberPointer &&
10389         isa<CXXMethodDecl>(fn) &&
10390         cast<CXXMethodDecl>(fn)->isInstance()) {
10391       if (!complain) return false;
10392 
10393       Diag(ovl.Expression->getExprLoc(),
10394            diag::err_bound_member_function)
10395         << 0 << ovl.Expression->getSourceRange();
10396 
10397       // TODO: I believe we only end up here if there's a mix of
10398       // static and non-static candidates (otherwise the expression
10399       // would have 'bound member' type, not 'overload' type).
10400       // Ideally we would note which candidate was chosen and why
10401       // the static candidates were rejected.
10402       SrcExpr = ExprError();
10403       return true;
10404     }
10405 
10406     // Fix the expression to refer to 'fn'.
10407     SingleFunctionExpression =
10408         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10409 
10410     // If desired, do function-to-pointer decay.
10411     if (doFunctionPointerConverion) {
10412       SingleFunctionExpression =
10413         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10414       if (SingleFunctionExpression.isInvalid()) {
10415         SrcExpr = ExprError();
10416         return true;
10417       }
10418     }
10419   }
10420 
10421   if (!SingleFunctionExpression.isUsable()) {
10422     if (complain) {
10423       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10424         << ovl.Expression->getName()
10425         << DestTypeForComplaining
10426         << OpRangeForComplaining
10427         << ovl.Expression->getQualifierLoc().getSourceRange();
10428       NoteAllOverloadCandidates(SrcExpr.get());
10429 
10430       SrcExpr = ExprError();
10431       return true;
10432     }
10433 
10434     return false;
10435   }
10436 
10437   SrcExpr = SingleFunctionExpression;
10438   return true;
10439 }
10440 
10441 /// \brief Add a single candidate to the overload set.
10442 static void AddOverloadedCallCandidate(Sema &S,
10443                                        DeclAccessPair FoundDecl,
10444                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10445                                        ArrayRef<Expr *> Args,
10446                                        OverloadCandidateSet &CandidateSet,
10447                                        bool PartialOverloading,
10448                                        bool KnownValid) {
10449   NamedDecl *Callee = FoundDecl.getDecl();
10450   if (isa<UsingShadowDecl>(Callee))
10451     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10452 
10453   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10454     if (ExplicitTemplateArgs) {
10455       assert(!KnownValid && "Explicit template arguments?");
10456       return;
10457     }
10458     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10459                            /*SuppressUsedConversions=*/false,
10460                            PartialOverloading);
10461     return;
10462   }
10463 
10464   if (FunctionTemplateDecl *FuncTemplate
10465       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10466     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10467                                    ExplicitTemplateArgs, Args, CandidateSet,
10468                                    /*SuppressUsedConversions=*/false,
10469                                    PartialOverloading);
10470     return;
10471   }
10472 
10473   assert(!KnownValid && "unhandled case in overloaded call candidate");
10474 }
10475 
10476 /// \brief Add the overload candidates named by callee and/or found by argument
10477 /// dependent lookup to the given overload set.
10478 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10479                                        ArrayRef<Expr *> Args,
10480                                        OverloadCandidateSet &CandidateSet,
10481                                        bool PartialOverloading) {
10482 
10483 #ifndef NDEBUG
10484   // Verify that ArgumentDependentLookup is consistent with the rules
10485   // in C++0x [basic.lookup.argdep]p3:
10486   //
10487   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10488   //   and let Y be the lookup set produced by argument dependent
10489   //   lookup (defined as follows). If X contains
10490   //
10491   //     -- a declaration of a class member, or
10492   //
10493   //     -- a block-scope function declaration that is not a
10494   //        using-declaration, or
10495   //
10496   //     -- a declaration that is neither a function or a function
10497   //        template
10498   //
10499   //   then Y is empty.
10500 
10501   if (ULE->requiresADL()) {
10502     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10503            E = ULE->decls_end(); I != E; ++I) {
10504       assert(!(*I)->getDeclContext()->isRecord());
10505       assert(isa<UsingShadowDecl>(*I) ||
10506              !(*I)->getDeclContext()->isFunctionOrMethod());
10507       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10508     }
10509   }
10510 #endif
10511 
10512   // It would be nice to avoid this copy.
10513   TemplateArgumentListInfo TABuffer;
10514   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10515   if (ULE->hasExplicitTemplateArgs()) {
10516     ULE->copyTemplateArgumentsInto(TABuffer);
10517     ExplicitTemplateArgs = &TABuffer;
10518   }
10519 
10520   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10521          E = ULE->decls_end(); I != E; ++I)
10522     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10523                                CandidateSet, PartialOverloading,
10524                                /*KnownValid*/ true);
10525 
10526   if (ULE->requiresADL())
10527     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10528                                          Args, ExplicitTemplateArgs,
10529                                          CandidateSet, PartialOverloading);
10530 }
10531 
10532 /// Determine whether a declaration with the specified name could be moved into
10533 /// a different namespace.
10534 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10535   switch (Name.getCXXOverloadedOperator()) {
10536   case OO_New: case OO_Array_New:
10537   case OO_Delete: case OO_Array_Delete:
10538     return false;
10539 
10540   default:
10541     return true;
10542   }
10543 }
10544 
10545 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10546 /// template, where the non-dependent name was declared after the template
10547 /// was defined. This is common in code written for a compilers which do not
10548 /// correctly implement two-stage name lookup.
10549 ///
10550 /// Returns true if a viable candidate was found and a diagnostic was issued.
10551 static bool
10552 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10553                        const CXXScopeSpec &SS, LookupResult &R,
10554                        OverloadCandidateSet::CandidateSetKind CSK,
10555                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10556                        ArrayRef<Expr *> Args,
10557                        bool *DoDiagnoseEmptyLookup = nullptr) {
10558   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10559     return false;
10560 
10561   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10562     if (DC->isTransparentContext())
10563       continue;
10564 
10565     SemaRef.LookupQualifiedName(R, DC);
10566 
10567     if (!R.empty()) {
10568       R.suppressDiagnostics();
10569 
10570       if (isa<CXXRecordDecl>(DC)) {
10571         // Don't diagnose names we find in classes; we get much better
10572         // diagnostics for these from DiagnoseEmptyLookup.
10573         R.clear();
10574         if (DoDiagnoseEmptyLookup)
10575           *DoDiagnoseEmptyLookup = true;
10576         return false;
10577       }
10578 
10579       OverloadCandidateSet Candidates(FnLoc, CSK);
10580       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10581         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10582                                    ExplicitTemplateArgs, Args,
10583                                    Candidates, false, /*KnownValid*/ false);
10584 
10585       OverloadCandidateSet::iterator Best;
10586       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10587         // No viable functions. Don't bother the user with notes for functions
10588         // which don't work and shouldn't be found anyway.
10589         R.clear();
10590         return false;
10591       }
10592 
10593       // Find the namespaces where ADL would have looked, and suggest
10594       // declaring the function there instead.
10595       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10596       Sema::AssociatedClassSet AssociatedClasses;
10597       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10598                                                  AssociatedNamespaces,
10599                                                  AssociatedClasses);
10600       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10601       if (canBeDeclaredInNamespace(R.getLookupName())) {
10602         DeclContext *Std = SemaRef.getStdNamespace();
10603         for (Sema::AssociatedNamespaceSet::iterator
10604                it = AssociatedNamespaces.begin(),
10605                end = AssociatedNamespaces.end(); it != end; ++it) {
10606           // Never suggest declaring a function within namespace 'std'.
10607           if (Std && Std->Encloses(*it))
10608             continue;
10609 
10610           // Never suggest declaring a function within a namespace with a
10611           // reserved name, like __gnu_cxx.
10612           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10613           if (NS &&
10614               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10615             continue;
10616 
10617           SuggestedNamespaces.insert(*it);
10618         }
10619       }
10620 
10621       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10622         << R.getLookupName();
10623       if (SuggestedNamespaces.empty()) {
10624         SemaRef.Diag(Best->Function->getLocation(),
10625                      diag::note_not_found_by_two_phase_lookup)
10626           << R.getLookupName() << 0;
10627       } else if (SuggestedNamespaces.size() == 1) {
10628         SemaRef.Diag(Best->Function->getLocation(),
10629                      diag::note_not_found_by_two_phase_lookup)
10630           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10631       } else {
10632         // FIXME: It would be useful to list the associated namespaces here,
10633         // but the diagnostics infrastructure doesn't provide a way to produce
10634         // a localized representation of a list of items.
10635         SemaRef.Diag(Best->Function->getLocation(),
10636                      diag::note_not_found_by_two_phase_lookup)
10637           << R.getLookupName() << 2;
10638       }
10639 
10640       // Try to recover by calling this function.
10641       return true;
10642     }
10643 
10644     R.clear();
10645   }
10646 
10647   return false;
10648 }
10649 
10650 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10651 /// template, where the non-dependent operator was declared after the template
10652 /// was defined.
10653 ///
10654 /// Returns true if a viable candidate was found and a diagnostic was issued.
10655 static bool
10656 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10657                                SourceLocation OpLoc,
10658                                ArrayRef<Expr *> Args) {
10659   DeclarationName OpName =
10660     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10661   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10662   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10663                                 OverloadCandidateSet::CSK_Operator,
10664                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10665 }
10666 
10667 namespace {
10668 class BuildRecoveryCallExprRAII {
10669   Sema &SemaRef;
10670 public:
10671   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10672     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10673     SemaRef.IsBuildingRecoveryCallExpr = true;
10674   }
10675 
10676   ~BuildRecoveryCallExprRAII() {
10677     SemaRef.IsBuildingRecoveryCallExpr = false;
10678   }
10679 };
10680 
10681 }
10682 
10683 static std::unique_ptr<CorrectionCandidateCallback>
10684 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10685               bool HasTemplateArgs, bool AllowTypoCorrection) {
10686   if (!AllowTypoCorrection)
10687     return llvm::make_unique<NoTypoCorrectionCCC>();
10688   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10689                                                   HasTemplateArgs, ME);
10690 }
10691 
10692 /// Attempts to recover from a call where no functions were found.
10693 ///
10694 /// Returns true if new candidates were found.
10695 static ExprResult
10696 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10697                       UnresolvedLookupExpr *ULE,
10698                       SourceLocation LParenLoc,
10699                       MutableArrayRef<Expr *> Args,
10700                       SourceLocation RParenLoc,
10701                       bool EmptyLookup, bool AllowTypoCorrection) {
10702   // Do not try to recover if it is already building a recovery call.
10703   // This stops infinite loops for template instantiations like
10704   //
10705   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10706   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10707   //
10708   if (SemaRef.IsBuildingRecoveryCallExpr)
10709     return ExprError();
10710   BuildRecoveryCallExprRAII RCE(SemaRef);
10711 
10712   CXXScopeSpec SS;
10713   SS.Adopt(ULE->getQualifierLoc());
10714   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10715 
10716   TemplateArgumentListInfo TABuffer;
10717   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10718   if (ULE->hasExplicitTemplateArgs()) {
10719     ULE->copyTemplateArgumentsInto(TABuffer);
10720     ExplicitTemplateArgs = &TABuffer;
10721   }
10722 
10723   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10724                  Sema::LookupOrdinaryName);
10725   bool DoDiagnoseEmptyLookup = EmptyLookup;
10726   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10727                               OverloadCandidateSet::CSK_Normal,
10728                               ExplicitTemplateArgs, Args,
10729                               &DoDiagnoseEmptyLookup) &&
10730     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10731         S, SS, R,
10732         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10733                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10734         ExplicitTemplateArgs, Args)))
10735     return ExprError();
10736 
10737   assert(!R.empty() && "lookup results empty despite recovery");
10738 
10739   // Build an implicit member call if appropriate.  Just drop the
10740   // casts and such from the call, we don't really care.
10741   ExprResult NewFn = ExprError();
10742   if ((*R.begin())->isCXXClassMember())
10743     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10744                                                     ExplicitTemplateArgs, S);
10745   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10746     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10747                                         ExplicitTemplateArgs);
10748   else
10749     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10750 
10751   if (NewFn.isInvalid())
10752     return ExprError();
10753 
10754   // This shouldn't cause an infinite loop because we're giving it
10755   // an expression with viable lookup results, which should never
10756   // end up here.
10757   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10758                                MultiExprArg(Args.data(), Args.size()),
10759                                RParenLoc);
10760 }
10761 
10762 /// \brief Constructs and populates an OverloadedCandidateSet from
10763 /// the given function.
10764 /// \returns true when an the ExprResult output parameter has been set.
10765 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10766                                   UnresolvedLookupExpr *ULE,
10767                                   MultiExprArg Args,
10768                                   SourceLocation RParenLoc,
10769                                   OverloadCandidateSet *CandidateSet,
10770                                   ExprResult *Result) {
10771 #ifndef NDEBUG
10772   if (ULE->requiresADL()) {
10773     // To do ADL, we must have found an unqualified name.
10774     assert(!ULE->getQualifier() && "qualified name with ADL");
10775 
10776     // We don't perform ADL for implicit declarations of builtins.
10777     // Verify that this was correctly set up.
10778     FunctionDecl *F;
10779     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10780         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10781         F->getBuiltinID() && F->isImplicit())
10782       llvm_unreachable("performing ADL for builtin");
10783 
10784     // We don't perform ADL in C.
10785     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10786   }
10787 #endif
10788 
10789   UnbridgedCastsSet UnbridgedCasts;
10790   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10791     *Result = ExprError();
10792     return true;
10793   }
10794 
10795   // Add the functions denoted by the callee to the set of candidate
10796   // functions, including those from argument-dependent lookup.
10797   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10798 
10799   if (getLangOpts().MSVCCompat &&
10800       CurContext->isDependentContext() && !isSFINAEContext() &&
10801       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10802 
10803     OverloadCandidateSet::iterator Best;
10804     if (CandidateSet->empty() ||
10805         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10806             OR_No_Viable_Function) {
10807       // In Microsoft mode, if we are inside a template class member function then
10808       // create a type dependent CallExpr. The goal is to postpone name lookup
10809       // to instantiation time to be able to search into type dependent base
10810       // classes.
10811       CallExpr *CE = new (Context) CallExpr(
10812           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
10813       CE->setTypeDependent(true);
10814       CE->setValueDependent(true);
10815       CE->setInstantiationDependent(true);
10816       *Result = CE;
10817       return true;
10818     }
10819   }
10820 
10821   if (CandidateSet->empty())
10822     return false;
10823 
10824   UnbridgedCasts.restore();
10825   return false;
10826 }
10827 
10828 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10829 /// the completed call expression. If overload resolution fails, emits
10830 /// diagnostics and returns ExprError()
10831 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10832                                            UnresolvedLookupExpr *ULE,
10833                                            SourceLocation LParenLoc,
10834                                            MultiExprArg Args,
10835                                            SourceLocation RParenLoc,
10836                                            Expr *ExecConfig,
10837                                            OverloadCandidateSet *CandidateSet,
10838                                            OverloadCandidateSet::iterator *Best,
10839                                            OverloadingResult OverloadResult,
10840                                            bool AllowTypoCorrection) {
10841   if (CandidateSet->empty())
10842     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10843                                  RParenLoc, /*EmptyLookup=*/true,
10844                                  AllowTypoCorrection);
10845 
10846   switch (OverloadResult) {
10847   case OR_Success: {
10848     FunctionDecl *FDecl = (*Best)->Function;
10849     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10850     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10851       return ExprError();
10852     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10853     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10854                                          ExecConfig);
10855   }
10856 
10857   case OR_No_Viable_Function: {
10858     // Try to recover by looking for viable functions which the user might
10859     // have meant to call.
10860     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10861                                                 Args, RParenLoc,
10862                                                 /*EmptyLookup=*/false,
10863                                                 AllowTypoCorrection);
10864     if (!Recovery.isInvalid())
10865       return Recovery;
10866 
10867     SemaRef.Diag(Fn->getLocStart(),
10868          diag::err_ovl_no_viable_function_in_call)
10869       << ULE->getName() << Fn->getSourceRange();
10870     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10871     break;
10872   }
10873 
10874   case OR_Ambiguous:
10875     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10876       << ULE->getName() << Fn->getSourceRange();
10877     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10878     break;
10879 
10880   case OR_Deleted: {
10881     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10882       << (*Best)->Function->isDeleted()
10883       << ULE->getName()
10884       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10885       << Fn->getSourceRange();
10886     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10887 
10888     // We emitted an error for the unvailable/deleted function call but keep
10889     // the call in the AST.
10890     FunctionDecl *FDecl = (*Best)->Function;
10891     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10892     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10893                                          ExecConfig);
10894   }
10895   }
10896 
10897   // Overload resolution failed.
10898   return ExprError();
10899 }
10900 
10901 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10902 /// (which eventually refers to the declaration Func) and the call
10903 /// arguments Args/NumArgs, attempt to resolve the function call down
10904 /// to a specific function. If overload resolution succeeds, returns
10905 /// the call expression produced by overload resolution.
10906 /// Otherwise, emits diagnostics and returns ExprError.
10907 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10908                                          UnresolvedLookupExpr *ULE,
10909                                          SourceLocation LParenLoc,
10910                                          MultiExprArg Args,
10911                                          SourceLocation RParenLoc,
10912                                          Expr *ExecConfig,
10913                                          bool AllowTypoCorrection) {
10914   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10915                                     OverloadCandidateSet::CSK_Normal);
10916   ExprResult result;
10917 
10918   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10919                              &result))
10920     return result;
10921 
10922   OverloadCandidateSet::iterator Best;
10923   OverloadingResult OverloadResult =
10924       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10925 
10926   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10927                                   RParenLoc, ExecConfig, &CandidateSet,
10928                                   &Best, OverloadResult,
10929                                   AllowTypoCorrection);
10930 }
10931 
10932 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10933   return Functions.size() > 1 ||
10934     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10935 }
10936 
10937 /// \brief Create a unary operation that may resolve to an overloaded
10938 /// operator.
10939 ///
10940 /// \param OpLoc The location of the operator itself (e.g., '*').
10941 ///
10942 /// \param OpcIn The UnaryOperator::Opcode that describes this
10943 /// operator.
10944 ///
10945 /// \param Fns The set of non-member functions that will be
10946 /// considered by overload resolution. The caller needs to build this
10947 /// set based on the context using, e.g.,
10948 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10949 /// set should not contain any member functions; those will be added
10950 /// by CreateOverloadedUnaryOp().
10951 ///
10952 /// \param Input The input argument.
10953 ExprResult
10954 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10955                               const UnresolvedSetImpl &Fns,
10956                               Expr *Input) {
10957   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10958 
10959   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10960   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10961   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10962   // TODO: provide better source location info.
10963   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10964 
10965   if (checkPlaceholderForOverload(*this, Input))
10966     return ExprError();
10967 
10968   Expr *Args[2] = { Input, nullptr };
10969   unsigned NumArgs = 1;
10970 
10971   // For post-increment and post-decrement, add the implicit '0' as
10972   // the second argument, so that we know this is a post-increment or
10973   // post-decrement.
10974   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10975     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10976     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10977                                      SourceLocation());
10978     NumArgs = 2;
10979   }
10980 
10981   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10982 
10983   if (Input->isTypeDependent()) {
10984     if (Fns.empty())
10985       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10986                                          VK_RValue, OK_Ordinary, OpLoc);
10987 
10988     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10989     UnresolvedLookupExpr *Fn
10990       = UnresolvedLookupExpr::Create(Context, NamingClass,
10991                                      NestedNameSpecifierLoc(), OpNameInfo,
10992                                      /*ADL*/ true, IsOverloaded(Fns),
10993                                      Fns.begin(), Fns.end());
10994     return new (Context)
10995         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10996                             VK_RValue, OpLoc, false);
10997   }
10998 
10999   // Build an empty overload set.
11000   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11001 
11002   // Add the candidates from the given function set.
11003   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11004 
11005   // Add operator candidates that are member functions.
11006   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11007 
11008   // Add candidates from ADL.
11009   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11010                                        /*ExplicitTemplateArgs*/nullptr,
11011                                        CandidateSet);
11012 
11013   // Add builtin operator candidates.
11014   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11015 
11016   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11017 
11018   // Perform overload resolution.
11019   OverloadCandidateSet::iterator Best;
11020   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11021   case OR_Success: {
11022     // We found a built-in operator or an overloaded operator.
11023     FunctionDecl *FnDecl = Best->Function;
11024 
11025     if (FnDecl) {
11026       // We matched an overloaded operator. Build a call to that
11027       // operator.
11028 
11029       // Convert the arguments.
11030       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11031         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11032 
11033         ExprResult InputRes =
11034           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11035                                               Best->FoundDecl, Method);
11036         if (InputRes.isInvalid())
11037           return ExprError();
11038         Input = InputRes.get();
11039       } else {
11040         // Convert the arguments.
11041         ExprResult InputInit
11042           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11043                                                       Context,
11044                                                       FnDecl->getParamDecl(0)),
11045                                       SourceLocation(),
11046                                       Input);
11047         if (InputInit.isInvalid())
11048           return ExprError();
11049         Input = InputInit.get();
11050       }
11051 
11052       // Build the actual expression node.
11053       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11054                                                 HadMultipleCandidates, OpLoc);
11055       if (FnExpr.isInvalid())
11056         return ExprError();
11057 
11058       // Determine the result type.
11059       QualType ResultTy = FnDecl->getReturnType();
11060       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11061       ResultTy = ResultTy.getNonLValueExprType(Context);
11062 
11063       Args[0] = Input;
11064       CallExpr *TheCall =
11065         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11066                                           ResultTy, VK, OpLoc, false);
11067 
11068       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11069         return ExprError();
11070 
11071       return MaybeBindToTemporary(TheCall);
11072     } else {
11073       // We matched a built-in operator. Convert the arguments, then
11074       // break out so that we will build the appropriate built-in
11075       // operator node.
11076       ExprResult InputRes =
11077         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11078                                   Best->Conversions[0], AA_Passing);
11079       if (InputRes.isInvalid())
11080         return ExprError();
11081       Input = InputRes.get();
11082       break;
11083     }
11084   }
11085 
11086   case OR_No_Viable_Function:
11087     // This is an erroneous use of an operator which can be overloaded by
11088     // a non-member function. Check for non-member operators which were
11089     // defined too late to be candidates.
11090     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11091       // FIXME: Recover by calling the found function.
11092       return ExprError();
11093 
11094     // No viable function; fall through to handling this as a
11095     // built-in operator, which will produce an error message for us.
11096     break;
11097 
11098   case OR_Ambiguous:
11099     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11100         << UnaryOperator::getOpcodeStr(Opc)
11101         << Input->getType()
11102         << Input->getSourceRange();
11103     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11104                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11105     return ExprError();
11106 
11107   case OR_Deleted:
11108     Diag(OpLoc, diag::err_ovl_deleted_oper)
11109       << Best->Function->isDeleted()
11110       << UnaryOperator::getOpcodeStr(Opc)
11111       << getDeletedOrUnavailableSuffix(Best->Function)
11112       << Input->getSourceRange();
11113     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11114                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11115     return ExprError();
11116   }
11117 
11118   // Either we found no viable overloaded operator or we matched a
11119   // built-in operator. In either case, fall through to trying to
11120   // build a built-in operation.
11121   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11122 }
11123 
11124 /// \brief Create a binary operation that may resolve to an overloaded
11125 /// operator.
11126 ///
11127 /// \param OpLoc The location of the operator itself (e.g., '+').
11128 ///
11129 /// \param OpcIn The BinaryOperator::Opcode that describes this
11130 /// operator.
11131 ///
11132 /// \param Fns The set of non-member functions that will be
11133 /// considered by overload resolution. The caller needs to build this
11134 /// set based on the context using, e.g.,
11135 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11136 /// set should not contain any member functions; those will be added
11137 /// by CreateOverloadedBinOp().
11138 ///
11139 /// \param LHS Left-hand argument.
11140 /// \param RHS Right-hand argument.
11141 ExprResult
11142 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11143                             unsigned OpcIn,
11144                             const UnresolvedSetImpl &Fns,
11145                             Expr *LHS, Expr *RHS) {
11146   Expr *Args[2] = { LHS, RHS };
11147   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11148 
11149   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11150   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11151   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11152 
11153   // If either side is type-dependent, create an appropriate dependent
11154   // expression.
11155   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11156     if (Fns.empty()) {
11157       // If there are no functions to store, just build a dependent
11158       // BinaryOperator or CompoundAssignment.
11159       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11160         return new (Context) BinaryOperator(
11161             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11162             OpLoc, FPFeatures.fp_contract);
11163 
11164       return new (Context) CompoundAssignOperator(
11165           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11166           Context.DependentTy, Context.DependentTy, OpLoc,
11167           FPFeatures.fp_contract);
11168     }
11169 
11170     // FIXME: save results of ADL from here?
11171     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11172     // TODO: provide better source location info in DNLoc component.
11173     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11174     UnresolvedLookupExpr *Fn
11175       = UnresolvedLookupExpr::Create(Context, NamingClass,
11176                                      NestedNameSpecifierLoc(), OpNameInfo,
11177                                      /*ADL*/ true, IsOverloaded(Fns),
11178                                      Fns.begin(), Fns.end());
11179     return new (Context)
11180         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11181                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11182   }
11183 
11184   // Always do placeholder-like conversions on the RHS.
11185   if (checkPlaceholderForOverload(*this, Args[1]))
11186     return ExprError();
11187 
11188   // Do placeholder-like conversion on the LHS; note that we should
11189   // not get here with a PseudoObject LHS.
11190   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11191   if (checkPlaceholderForOverload(*this, Args[0]))
11192     return ExprError();
11193 
11194   // If this is the assignment operator, we only perform overload resolution
11195   // if the left-hand side is a class or enumeration type. This is actually
11196   // a hack. The standard requires that we do overload resolution between the
11197   // various built-in candidates, but as DR507 points out, this can lead to
11198   // problems. So we do it this way, which pretty much follows what GCC does.
11199   // Note that we go the traditional code path for compound assignment forms.
11200   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11201     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11202 
11203   // If this is the .* operator, which is not overloadable, just
11204   // create a built-in binary operator.
11205   if (Opc == BO_PtrMemD)
11206     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11207 
11208   // Build an empty overload set.
11209   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11210 
11211   // Add the candidates from the given function set.
11212   AddFunctionCandidates(Fns, Args, CandidateSet);
11213 
11214   // Add operator candidates that are member functions.
11215   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11216 
11217   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11218   // performed for an assignment operator (nor for operator[] nor operator->,
11219   // which don't get here).
11220   if (Opc != BO_Assign)
11221     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11222                                          /*ExplicitTemplateArgs*/ nullptr,
11223                                          CandidateSet);
11224 
11225   // Add builtin operator candidates.
11226   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11227 
11228   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11229 
11230   // Perform overload resolution.
11231   OverloadCandidateSet::iterator Best;
11232   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11233     case OR_Success: {
11234       // We found a built-in operator or an overloaded operator.
11235       FunctionDecl *FnDecl = Best->Function;
11236 
11237       if (FnDecl) {
11238         // We matched an overloaded operator. Build a call to that
11239         // operator.
11240 
11241         // Convert the arguments.
11242         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11243           // Best->Access is only meaningful for class members.
11244           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11245 
11246           ExprResult Arg1 =
11247             PerformCopyInitialization(
11248               InitializedEntity::InitializeParameter(Context,
11249                                                      FnDecl->getParamDecl(0)),
11250               SourceLocation(), Args[1]);
11251           if (Arg1.isInvalid())
11252             return ExprError();
11253 
11254           ExprResult Arg0 =
11255             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11256                                                 Best->FoundDecl, Method);
11257           if (Arg0.isInvalid())
11258             return ExprError();
11259           Args[0] = Arg0.getAs<Expr>();
11260           Args[1] = RHS = Arg1.getAs<Expr>();
11261         } else {
11262           // Convert the arguments.
11263           ExprResult Arg0 = PerformCopyInitialization(
11264             InitializedEntity::InitializeParameter(Context,
11265                                                    FnDecl->getParamDecl(0)),
11266             SourceLocation(), Args[0]);
11267           if (Arg0.isInvalid())
11268             return ExprError();
11269 
11270           ExprResult Arg1 =
11271             PerformCopyInitialization(
11272               InitializedEntity::InitializeParameter(Context,
11273                                                      FnDecl->getParamDecl(1)),
11274               SourceLocation(), Args[1]);
11275           if (Arg1.isInvalid())
11276             return ExprError();
11277           Args[0] = LHS = Arg0.getAs<Expr>();
11278           Args[1] = RHS = Arg1.getAs<Expr>();
11279         }
11280 
11281         // Build the actual expression node.
11282         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11283                                                   Best->FoundDecl,
11284                                                   HadMultipleCandidates, OpLoc);
11285         if (FnExpr.isInvalid())
11286           return ExprError();
11287 
11288         // Determine the result type.
11289         QualType ResultTy = FnDecl->getReturnType();
11290         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11291         ResultTy = ResultTy.getNonLValueExprType(Context);
11292 
11293         CXXOperatorCallExpr *TheCall =
11294           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11295                                             Args, ResultTy, VK, OpLoc,
11296                                             FPFeatures.fp_contract);
11297 
11298         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11299                                 FnDecl))
11300           return ExprError();
11301 
11302         ArrayRef<const Expr *> ArgsArray(Args, 2);
11303         // Cut off the implicit 'this'.
11304         if (isa<CXXMethodDecl>(FnDecl))
11305           ArgsArray = ArgsArray.slice(1);
11306 
11307         // Check for a self move.
11308         if (Op == OO_Equal)
11309           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11310 
11311         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11312                   TheCall->getSourceRange(), VariadicDoesNotApply);
11313 
11314         return MaybeBindToTemporary(TheCall);
11315       } else {
11316         // We matched a built-in operator. Convert the arguments, then
11317         // break out so that we will build the appropriate built-in
11318         // operator node.
11319         ExprResult ArgsRes0 =
11320           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11321                                     Best->Conversions[0], AA_Passing);
11322         if (ArgsRes0.isInvalid())
11323           return ExprError();
11324         Args[0] = ArgsRes0.get();
11325 
11326         ExprResult ArgsRes1 =
11327           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11328                                     Best->Conversions[1], AA_Passing);
11329         if (ArgsRes1.isInvalid())
11330           return ExprError();
11331         Args[1] = ArgsRes1.get();
11332         break;
11333       }
11334     }
11335 
11336     case OR_No_Viable_Function: {
11337       // C++ [over.match.oper]p9:
11338       //   If the operator is the operator , [...] and there are no
11339       //   viable functions, then the operator is assumed to be the
11340       //   built-in operator and interpreted according to clause 5.
11341       if (Opc == BO_Comma)
11342         break;
11343 
11344       // For class as left operand for assignment or compound assigment
11345       // operator do not fall through to handling in built-in, but report that
11346       // no overloaded assignment operator found
11347       ExprResult Result = ExprError();
11348       if (Args[0]->getType()->isRecordType() &&
11349           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11350         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11351              << BinaryOperator::getOpcodeStr(Opc)
11352              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11353         if (Args[0]->getType()->isIncompleteType()) {
11354           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11355             << Args[0]->getType()
11356             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11357         }
11358       } else {
11359         // This is an erroneous use of an operator which can be overloaded by
11360         // a non-member function. Check for non-member operators which were
11361         // defined too late to be candidates.
11362         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11363           // FIXME: Recover by calling the found function.
11364           return ExprError();
11365 
11366         // No viable function; try to create a built-in operation, which will
11367         // produce an error. Then, show the non-viable candidates.
11368         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11369       }
11370       assert(Result.isInvalid() &&
11371              "C++ binary operator overloading is missing candidates!");
11372       if (Result.isInvalid())
11373         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11374                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11375       return Result;
11376     }
11377 
11378     case OR_Ambiguous:
11379       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11380           << BinaryOperator::getOpcodeStr(Opc)
11381           << Args[0]->getType() << Args[1]->getType()
11382           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11383       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11384                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11385       return ExprError();
11386 
11387     case OR_Deleted:
11388       if (isImplicitlyDeleted(Best->Function)) {
11389         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11390         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11391           << Context.getRecordType(Method->getParent())
11392           << getSpecialMember(Method);
11393 
11394         // The user probably meant to call this special member. Just
11395         // explain why it's deleted.
11396         NoteDeletedFunction(Method);
11397         return ExprError();
11398       } else {
11399         Diag(OpLoc, diag::err_ovl_deleted_oper)
11400           << Best->Function->isDeleted()
11401           << BinaryOperator::getOpcodeStr(Opc)
11402           << getDeletedOrUnavailableSuffix(Best->Function)
11403           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11404       }
11405       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11406                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11407       return ExprError();
11408   }
11409 
11410   // We matched a built-in operator; build it.
11411   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11412 }
11413 
11414 ExprResult
11415 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11416                                          SourceLocation RLoc,
11417                                          Expr *Base, Expr *Idx) {
11418   Expr *Args[2] = { Base, Idx };
11419   DeclarationName OpName =
11420       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11421 
11422   // If either side is type-dependent, create an appropriate dependent
11423   // expression.
11424   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11425 
11426     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11427     // CHECKME: no 'operator' keyword?
11428     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11429     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11430     UnresolvedLookupExpr *Fn
11431       = UnresolvedLookupExpr::Create(Context, NamingClass,
11432                                      NestedNameSpecifierLoc(), OpNameInfo,
11433                                      /*ADL*/ true, /*Overloaded*/ false,
11434                                      UnresolvedSetIterator(),
11435                                      UnresolvedSetIterator());
11436     // Can't add any actual overloads yet
11437 
11438     return new (Context)
11439         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11440                             Context.DependentTy, VK_RValue, RLoc, false);
11441   }
11442 
11443   // Handle placeholders on both operands.
11444   if (checkPlaceholderForOverload(*this, Args[0]))
11445     return ExprError();
11446   if (checkPlaceholderForOverload(*this, Args[1]))
11447     return ExprError();
11448 
11449   // Build an empty overload set.
11450   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11451 
11452   // Subscript can only be overloaded as a member function.
11453 
11454   // Add operator candidates that are member functions.
11455   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11456 
11457   // Add builtin operator candidates.
11458   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11459 
11460   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11461 
11462   // Perform overload resolution.
11463   OverloadCandidateSet::iterator Best;
11464   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11465     case OR_Success: {
11466       // We found a built-in operator or an overloaded operator.
11467       FunctionDecl *FnDecl = Best->Function;
11468 
11469       if (FnDecl) {
11470         // We matched an overloaded operator. Build a call to that
11471         // operator.
11472 
11473         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11474 
11475         // Convert the arguments.
11476         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11477         ExprResult Arg0 =
11478           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11479                                               Best->FoundDecl, Method);
11480         if (Arg0.isInvalid())
11481           return ExprError();
11482         Args[0] = Arg0.get();
11483 
11484         // Convert the arguments.
11485         ExprResult InputInit
11486           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11487                                                       Context,
11488                                                       FnDecl->getParamDecl(0)),
11489                                       SourceLocation(),
11490                                       Args[1]);
11491         if (InputInit.isInvalid())
11492           return ExprError();
11493 
11494         Args[1] = InputInit.getAs<Expr>();
11495 
11496         // Build the actual expression node.
11497         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11498         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11499         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11500                                                   Best->FoundDecl,
11501                                                   HadMultipleCandidates,
11502                                                   OpLocInfo.getLoc(),
11503                                                   OpLocInfo.getInfo());
11504         if (FnExpr.isInvalid())
11505           return ExprError();
11506 
11507         // Determine the result type
11508         QualType ResultTy = FnDecl->getReturnType();
11509         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11510         ResultTy = ResultTy.getNonLValueExprType(Context);
11511 
11512         CXXOperatorCallExpr *TheCall =
11513           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11514                                             FnExpr.get(), Args,
11515                                             ResultTy, VK, RLoc,
11516                                             false);
11517 
11518         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11519           return ExprError();
11520 
11521         return MaybeBindToTemporary(TheCall);
11522       } else {
11523         // We matched a built-in operator. Convert the arguments, then
11524         // break out so that we will build the appropriate built-in
11525         // operator node.
11526         ExprResult ArgsRes0 =
11527           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11528                                     Best->Conversions[0], AA_Passing);
11529         if (ArgsRes0.isInvalid())
11530           return ExprError();
11531         Args[0] = ArgsRes0.get();
11532 
11533         ExprResult ArgsRes1 =
11534           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11535                                     Best->Conversions[1], AA_Passing);
11536         if (ArgsRes1.isInvalid())
11537           return ExprError();
11538         Args[1] = ArgsRes1.get();
11539 
11540         break;
11541       }
11542     }
11543 
11544     case OR_No_Viable_Function: {
11545       if (CandidateSet.empty())
11546         Diag(LLoc, diag::err_ovl_no_oper)
11547           << Args[0]->getType() << /*subscript*/ 0
11548           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11549       else
11550         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11551           << Args[0]->getType()
11552           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11553       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11554                                   "[]", LLoc);
11555       return ExprError();
11556     }
11557 
11558     case OR_Ambiguous:
11559       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11560           << "[]"
11561           << Args[0]->getType() << Args[1]->getType()
11562           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11563       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11564                                   "[]", LLoc);
11565       return ExprError();
11566 
11567     case OR_Deleted:
11568       Diag(LLoc, diag::err_ovl_deleted_oper)
11569         << Best->Function->isDeleted() << "[]"
11570         << getDeletedOrUnavailableSuffix(Best->Function)
11571         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11572       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11573                                   "[]", LLoc);
11574       return ExprError();
11575     }
11576 
11577   // We matched a built-in operator; build it.
11578   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11579 }
11580 
11581 /// BuildCallToMemberFunction - Build a call to a member
11582 /// function. MemExpr is the expression that refers to the member
11583 /// function (and includes the object parameter), Args/NumArgs are the
11584 /// arguments to the function call (not including the object
11585 /// parameter). The caller needs to validate that the member
11586 /// expression refers to a non-static member function or an overloaded
11587 /// member function.
11588 ExprResult
11589 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11590                                 SourceLocation LParenLoc,
11591                                 MultiExprArg Args,
11592                                 SourceLocation RParenLoc) {
11593   assert(MemExprE->getType() == Context.BoundMemberTy ||
11594          MemExprE->getType() == Context.OverloadTy);
11595 
11596   // Dig out the member expression. This holds both the object
11597   // argument and the member function we're referring to.
11598   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11599 
11600   // Determine whether this is a call to a pointer-to-member function.
11601   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11602     assert(op->getType() == Context.BoundMemberTy);
11603     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11604 
11605     QualType fnType =
11606       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11607 
11608     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11609     QualType resultType = proto->getCallResultType(Context);
11610     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11611 
11612     // Check that the object type isn't more qualified than the
11613     // member function we're calling.
11614     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11615 
11616     QualType objectType = op->getLHS()->getType();
11617     if (op->getOpcode() == BO_PtrMemI)
11618       objectType = objectType->castAs<PointerType>()->getPointeeType();
11619     Qualifiers objectQuals = objectType.getQualifiers();
11620 
11621     Qualifiers difference = objectQuals - funcQuals;
11622     difference.removeObjCGCAttr();
11623     difference.removeAddressSpace();
11624     if (difference) {
11625       std::string qualsString = difference.getAsString();
11626       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11627         << fnType.getUnqualifiedType()
11628         << qualsString
11629         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11630     }
11631 
11632     CXXMemberCallExpr *call
11633       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11634                                         resultType, valueKind, RParenLoc);
11635 
11636     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11637                             call, nullptr))
11638       return ExprError();
11639 
11640     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11641       return ExprError();
11642 
11643     if (CheckOtherCall(call, proto))
11644       return ExprError();
11645 
11646     return MaybeBindToTemporary(call);
11647   }
11648 
11649   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11650     return new (Context)
11651         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11652 
11653   UnbridgedCastsSet UnbridgedCasts;
11654   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11655     return ExprError();
11656 
11657   MemberExpr *MemExpr;
11658   CXXMethodDecl *Method = nullptr;
11659   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11660   NestedNameSpecifier *Qualifier = nullptr;
11661   if (isa<MemberExpr>(NakedMemExpr)) {
11662     MemExpr = cast<MemberExpr>(NakedMemExpr);
11663     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11664     FoundDecl = MemExpr->getFoundDecl();
11665     Qualifier = MemExpr->getQualifier();
11666     UnbridgedCasts.restore();
11667 
11668     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11669       Diag(MemExprE->getLocStart(),
11670            diag::err_ovl_no_viable_member_function_in_call)
11671           << Method << Method->getSourceRange();
11672       Diag(Method->getLocation(),
11673            diag::note_ovl_candidate_disabled_by_enable_if_attr)
11674           << Attr->getCond()->getSourceRange() << Attr->getMessage();
11675       return ExprError();
11676     }
11677   } else {
11678     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11679     Qualifier = UnresExpr->getQualifier();
11680 
11681     QualType ObjectType = UnresExpr->getBaseType();
11682     Expr::Classification ObjectClassification
11683       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11684                             : UnresExpr->getBase()->Classify(Context);
11685 
11686     // Add overload candidates
11687     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11688                                       OverloadCandidateSet::CSK_Normal);
11689 
11690     // FIXME: avoid copy.
11691     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11692     if (UnresExpr->hasExplicitTemplateArgs()) {
11693       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11694       TemplateArgs = &TemplateArgsBuffer;
11695     }
11696 
11697     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11698            E = UnresExpr->decls_end(); I != E; ++I) {
11699 
11700       NamedDecl *Func = *I;
11701       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11702       if (isa<UsingShadowDecl>(Func))
11703         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11704 
11705 
11706       // Microsoft supports direct constructor calls.
11707       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11708         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11709                              Args, CandidateSet);
11710       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11711         // If explicit template arguments were provided, we can't call a
11712         // non-template member function.
11713         if (TemplateArgs)
11714           continue;
11715 
11716         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11717                            ObjectClassification, Args, CandidateSet,
11718                            /*SuppressUserConversions=*/false);
11719       } else {
11720         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11721                                    I.getPair(), ActingDC, TemplateArgs,
11722                                    ObjectType,  ObjectClassification,
11723                                    Args, CandidateSet,
11724                                    /*SuppressUsedConversions=*/false);
11725       }
11726     }
11727 
11728     DeclarationName DeclName = UnresExpr->getMemberName();
11729 
11730     UnbridgedCasts.restore();
11731 
11732     OverloadCandidateSet::iterator Best;
11733     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11734                                             Best)) {
11735     case OR_Success:
11736       Method = cast<CXXMethodDecl>(Best->Function);
11737       FoundDecl = Best->FoundDecl;
11738       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11739       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11740         return ExprError();
11741       // If FoundDecl is different from Method (such as if one is a template
11742       // and the other a specialization), make sure DiagnoseUseOfDecl is
11743       // called on both.
11744       // FIXME: This would be more comprehensively addressed by modifying
11745       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11746       // being used.
11747       if (Method != FoundDecl.getDecl() &&
11748                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11749         return ExprError();
11750       break;
11751 
11752     case OR_No_Viable_Function:
11753       Diag(UnresExpr->getMemberLoc(),
11754            diag::err_ovl_no_viable_member_function_in_call)
11755         << DeclName << MemExprE->getSourceRange();
11756       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11757       // FIXME: Leaking incoming expressions!
11758       return ExprError();
11759 
11760     case OR_Ambiguous:
11761       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11762         << DeclName << MemExprE->getSourceRange();
11763       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11764       // FIXME: Leaking incoming expressions!
11765       return ExprError();
11766 
11767     case OR_Deleted:
11768       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11769         << Best->Function->isDeleted()
11770         << DeclName
11771         << getDeletedOrUnavailableSuffix(Best->Function)
11772         << MemExprE->getSourceRange();
11773       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11774       // FIXME: Leaking incoming expressions!
11775       return ExprError();
11776     }
11777 
11778     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11779 
11780     // If overload resolution picked a static member, build a
11781     // non-member call based on that function.
11782     if (Method->isStatic()) {
11783       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11784                                    RParenLoc);
11785     }
11786 
11787     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11788   }
11789 
11790   QualType ResultType = Method->getReturnType();
11791   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11792   ResultType = ResultType.getNonLValueExprType(Context);
11793 
11794   assert(Method && "Member call to something that isn't a method?");
11795   CXXMemberCallExpr *TheCall =
11796     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11797                                     ResultType, VK, RParenLoc);
11798 
11799   // (CUDA B.1): Check for invalid calls between targets.
11800   if (getLangOpts().CUDA) {
11801     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11802       if (CheckCUDATarget(Caller, Method)) {
11803         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11804             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11805             << IdentifyCUDATarget(Caller);
11806         return ExprError();
11807       }
11808     }
11809   }
11810 
11811   // Check for a valid return type.
11812   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11813                           TheCall, Method))
11814     return ExprError();
11815 
11816   // Convert the object argument (for a non-static member function call).
11817   // We only need to do this if there was actually an overload; otherwise
11818   // it was done at lookup.
11819   if (!Method->isStatic()) {
11820     ExprResult ObjectArg =
11821       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11822                                           FoundDecl, Method);
11823     if (ObjectArg.isInvalid())
11824       return ExprError();
11825     MemExpr->setBase(ObjectArg.get());
11826   }
11827 
11828   // Convert the rest of the arguments
11829   const FunctionProtoType *Proto =
11830     Method->getType()->getAs<FunctionProtoType>();
11831   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11832                               RParenLoc))
11833     return ExprError();
11834 
11835   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11836 
11837   if (CheckFunctionCall(Method, TheCall, Proto))
11838     return ExprError();
11839 
11840   if ((isa<CXXConstructorDecl>(CurContext) ||
11841        isa<CXXDestructorDecl>(CurContext)) &&
11842       TheCall->getMethodDecl()->isPure()) {
11843     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11844 
11845     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11846         MemExpr->performsVirtualDispatch(getLangOpts())) {
11847       Diag(MemExpr->getLocStart(),
11848            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11849         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11850         << MD->getParent()->getDeclName();
11851 
11852       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11853       if (getLangOpts().AppleKext)
11854         Diag(MemExpr->getLocStart(),
11855              diag::note_pure_qualified_call_kext)
11856              << MD->getParent()->getDeclName()
11857              << MD->getDeclName();
11858     }
11859   }
11860   return MaybeBindToTemporary(TheCall);
11861 }
11862 
11863 /// BuildCallToObjectOfClassType - Build a call to an object of class
11864 /// type (C++ [over.call.object]), which can end up invoking an
11865 /// overloaded function call operator (@c operator()) or performing a
11866 /// user-defined conversion on the object argument.
11867 ExprResult
11868 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11869                                    SourceLocation LParenLoc,
11870                                    MultiExprArg Args,
11871                                    SourceLocation RParenLoc) {
11872   if (checkPlaceholderForOverload(*this, Obj))
11873     return ExprError();
11874   ExprResult Object = Obj;
11875 
11876   UnbridgedCastsSet UnbridgedCasts;
11877   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11878     return ExprError();
11879 
11880   assert(Object.get()->getType()->isRecordType() &&
11881          "Requires object type argument");
11882   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11883 
11884   // C++ [over.call.object]p1:
11885   //  If the primary-expression E in the function call syntax
11886   //  evaluates to a class object of type "cv T", then the set of
11887   //  candidate functions includes at least the function call
11888   //  operators of T. The function call operators of T are obtained by
11889   //  ordinary lookup of the name operator() in the context of
11890   //  (E).operator().
11891   OverloadCandidateSet CandidateSet(LParenLoc,
11892                                     OverloadCandidateSet::CSK_Operator);
11893   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11894 
11895   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11896                           diag::err_incomplete_object_call, Object.get()))
11897     return true;
11898 
11899   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11900   LookupQualifiedName(R, Record->getDecl());
11901   R.suppressDiagnostics();
11902 
11903   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11904        Oper != OperEnd; ++Oper) {
11905     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11906                        Object.get()->Classify(Context),
11907                        Args, CandidateSet,
11908                        /*SuppressUserConversions=*/ false);
11909   }
11910 
11911   // C++ [over.call.object]p2:
11912   //   In addition, for each (non-explicit in C++0x) conversion function
11913   //   declared in T of the form
11914   //
11915   //        operator conversion-type-id () cv-qualifier;
11916   //
11917   //   where cv-qualifier is the same cv-qualification as, or a
11918   //   greater cv-qualification than, cv, and where conversion-type-id
11919   //   denotes the type "pointer to function of (P1,...,Pn) returning
11920   //   R", or the type "reference to pointer to function of
11921   //   (P1,...,Pn) returning R", or the type "reference to function
11922   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11923   //   is also considered as a candidate function. Similarly,
11924   //   surrogate call functions are added to the set of candidate
11925   //   functions for each conversion function declared in an
11926   //   accessible base class provided the function is not hidden
11927   //   within T by another intervening declaration.
11928   const auto &Conversions =
11929       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11930   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11931     NamedDecl *D = *I;
11932     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11933     if (isa<UsingShadowDecl>(D))
11934       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11935 
11936     // Skip over templated conversion functions; they aren't
11937     // surrogates.
11938     if (isa<FunctionTemplateDecl>(D))
11939       continue;
11940 
11941     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11942     if (!Conv->isExplicit()) {
11943       // Strip the reference type (if any) and then the pointer type (if
11944       // any) to get down to what might be a function type.
11945       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11946       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11947         ConvType = ConvPtrType->getPointeeType();
11948 
11949       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11950       {
11951         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11952                               Object.get(), Args, CandidateSet);
11953       }
11954     }
11955   }
11956 
11957   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11958 
11959   // Perform overload resolution.
11960   OverloadCandidateSet::iterator Best;
11961   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11962                              Best)) {
11963   case OR_Success:
11964     // Overload resolution succeeded; we'll build the appropriate call
11965     // below.
11966     break;
11967 
11968   case OR_No_Viable_Function:
11969     if (CandidateSet.empty())
11970       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11971         << Object.get()->getType() << /*call*/ 1
11972         << Object.get()->getSourceRange();
11973     else
11974       Diag(Object.get()->getLocStart(),
11975            diag::err_ovl_no_viable_object_call)
11976         << Object.get()->getType() << Object.get()->getSourceRange();
11977     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11978     break;
11979 
11980   case OR_Ambiguous:
11981     Diag(Object.get()->getLocStart(),
11982          diag::err_ovl_ambiguous_object_call)
11983       << Object.get()->getType() << Object.get()->getSourceRange();
11984     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11985     break;
11986 
11987   case OR_Deleted:
11988     Diag(Object.get()->getLocStart(),
11989          diag::err_ovl_deleted_object_call)
11990       << Best->Function->isDeleted()
11991       << Object.get()->getType()
11992       << getDeletedOrUnavailableSuffix(Best->Function)
11993       << Object.get()->getSourceRange();
11994     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11995     break;
11996   }
11997 
11998   if (Best == CandidateSet.end())
11999     return true;
12000 
12001   UnbridgedCasts.restore();
12002 
12003   if (Best->Function == nullptr) {
12004     // Since there is no function declaration, this is one of the
12005     // surrogate candidates. Dig out the conversion function.
12006     CXXConversionDecl *Conv
12007       = cast<CXXConversionDecl>(
12008                          Best->Conversions[0].UserDefined.ConversionFunction);
12009 
12010     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12011                               Best->FoundDecl);
12012     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12013       return ExprError();
12014     assert(Conv == Best->FoundDecl.getDecl() &&
12015              "Found Decl & conversion-to-functionptr should be same, right?!");
12016     // We selected one of the surrogate functions that converts the
12017     // object parameter to a function pointer. Perform the conversion
12018     // on the object argument, then let ActOnCallExpr finish the job.
12019 
12020     // Create an implicit member expr to refer to the conversion operator.
12021     // and then call it.
12022     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12023                                              Conv, HadMultipleCandidates);
12024     if (Call.isInvalid())
12025       return ExprError();
12026     // Record usage of conversion in an implicit cast.
12027     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12028                                     CK_UserDefinedConversion, Call.get(),
12029                                     nullptr, VK_RValue);
12030 
12031     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12032   }
12033 
12034   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12035 
12036   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12037   // that calls this method, using Object for the implicit object
12038   // parameter and passing along the remaining arguments.
12039   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12040 
12041   // An error diagnostic has already been printed when parsing the declaration.
12042   if (Method->isInvalidDecl())
12043     return ExprError();
12044 
12045   const FunctionProtoType *Proto =
12046     Method->getType()->getAs<FunctionProtoType>();
12047 
12048   unsigned NumParams = Proto->getNumParams();
12049 
12050   DeclarationNameInfo OpLocInfo(
12051                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12052   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12053   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12054                                            HadMultipleCandidates,
12055                                            OpLocInfo.getLoc(),
12056                                            OpLocInfo.getInfo());
12057   if (NewFn.isInvalid())
12058     return true;
12059 
12060   // Build the full argument list for the method call (the implicit object
12061   // parameter is placed at the beginning of the list).
12062   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12063   MethodArgs[0] = Object.get();
12064   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12065 
12066   // Once we've built TheCall, all of the expressions are properly
12067   // owned.
12068   QualType ResultTy = Method->getReturnType();
12069   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12070   ResultTy = ResultTy.getNonLValueExprType(Context);
12071 
12072   CXXOperatorCallExpr *TheCall = new (Context)
12073       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12074                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12075                           ResultTy, VK, RParenLoc, false);
12076   MethodArgs.reset();
12077 
12078   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12079     return true;
12080 
12081   // We may have default arguments. If so, we need to allocate more
12082   // slots in the call for them.
12083   if (Args.size() < NumParams)
12084     TheCall->setNumArgs(Context, NumParams + 1);
12085 
12086   bool IsError = false;
12087 
12088   // Initialize the implicit object parameter.
12089   ExprResult ObjRes =
12090     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12091                                         Best->FoundDecl, Method);
12092   if (ObjRes.isInvalid())
12093     IsError = true;
12094   else
12095     Object = ObjRes;
12096   TheCall->setArg(0, Object.get());
12097 
12098   // Check the argument types.
12099   for (unsigned i = 0; i != NumParams; i++) {
12100     Expr *Arg;
12101     if (i < Args.size()) {
12102       Arg = Args[i];
12103 
12104       // Pass the argument.
12105 
12106       ExprResult InputInit
12107         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12108                                                     Context,
12109                                                     Method->getParamDecl(i)),
12110                                     SourceLocation(), Arg);
12111 
12112       IsError |= InputInit.isInvalid();
12113       Arg = InputInit.getAs<Expr>();
12114     } else {
12115       ExprResult DefArg
12116         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12117       if (DefArg.isInvalid()) {
12118         IsError = true;
12119         break;
12120       }
12121 
12122       Arg = DefArg.getAs<Expr>();
12123     }
12124 
12125     TheCall->setArg(i + 1, Arg);
12126   }
12127 
12128   // If this is a variadic call, handle args passed through "...".
12129   if (Proto->isVariadic()) {
12130     // Promote the arguments (C99 6.5.2.2p7).
12131     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12132       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12133                                                         nullptr);
12134       IsError |= Arg.isInvalid();
12135       TheCall->setArg(i + 1, Arg.get());
12136     }
12137   }
12138 
12139   if (IsError) return true;
12140 
12141   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12142 
12143   if (CheckFunctionCall(Method, TheCall, Proto))
12144     return true;
12145 
12146   return MaybeBindToTemporary(TheCall);
12147 }
12148 
12149 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12150 ///  (if one exists), where @c Base is an expression of class type and
12151 /// @c Member is the name of the member we're trying to find.
12152 ExprResult
12153 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12154                                bool *NoArrowOperatorFound) {
12155   assert(Base->getType()->isRecordType() &&
12156          "left-hand side must have class type");
12157 
12158   if (checkPlaceholderForOverload(*this, Base))
12159     return ExprError();
12160 
12161   SourceLocation Loc = Base->getExprLoc();
12162 
12163   // C++ [over.ref]p1:
12164   //
12165   //   [...] An expression x->m is interpreted as (x.operator->())->m
12166   //   for a class object x of type T if T::operator->() exists and if
12167   //   the operator is selected as the best match function by the
12168   //   overload resolution mechanism (13.3).
12169   DeclarationName OpName =
12170     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12171   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12172   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12173 
12174   if (RequireCompleteType(Loc, Base->getType(),
12175                           diag::err_typecheck_incomplete_tag, Base))
12176     return ExprError();
12177 
12178   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12179   LookupQualifiedName(R, BaseRecord->getDecl());
12180   R.suppressDiagnostics();
12181 
12182   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12183        Oper != OperEnd; ++Oper) {
12184     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12185                        None, CandidateSet, /*SuppressUserConversions=*/false);
12186   }
12187 
12188   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12189 
12190   // Perform overload resolution.
12191   OverloadCandidateSet::iterator Best;
12192   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12193   case OR_Success:
12194     // Overload resolution succeeded; we'll build the call below.
12195     break;
12196 
12197   case OR_No_Viable_Function:
12198     if (CandidateSet.empty()) {
12199       QualType BaseType = Base->getType();
12200       if (NoArrowOperatorFound) {
12201         // Report this specific error to the caller instead of emitting a
12202         // diagnostic, as requested.
12203         *NoArrowOperatorFound = true;
12204         return ExprError();
12205       }
12206       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12207         << BaseType << Base->getSourceRange();
12208       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12209         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12210           << FixItHint::CreateReplacement(OpLoc, ".");
12211       }
12212     } else
12213       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12214         << "operator->" << Base->getSourceRange();
12215     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12216     return ExprError();
12217 
12218   case OR_Ambiguous:
12219     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12220       << "->" << Base->getType() << Base->getSourceRange();
12221     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12222     return ExprError();
12223 
12224   case OR_Deleted:
12225     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12226       << Best->Function->isDeleted()
12227       << "->"
12228       << getDeletedOrUnavailableSuffix(Best->Function)
12229       << Base->getSourceRange();
12230     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12231     return ExprError();
12232   }
12233 
12234   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12235 
12236   // Convert the object parameter.
12237   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12238   ExprResult BaseResult =
12239     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12240                                         Best->FoundDecl, Method);
12241   if (BaseResult.isInvalid())
12242     return ExprError();
12243   Base = BaseResult.get();
12244 
12245   // Build the operator call.
12246   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12247                                             HadMultipleCandidates, OpLoc);
12248   if (FnExpr.isInvalid())
12249     return ExprError();
12250 
12251   QualType ResultTy = Method->getReturnType();
12252   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12253   ResultTy = ResultTy.getNonLValueExprType(Context);
12254   CXXOperatorCallExpr *TheCall =
12255     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12256                                       Base, ResultTy, VK, OpLoc, false);
12257 
12258   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12259           return ExprError();
12260 
12261   return MaybeBindToTemporary(TheCall);
12262 }
12263 
12264 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12265 /// a literal operator described by the provided lookup results.
12266 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12267                                           DeclarationNameInfo &SuffixInfo,
12268                                           ArrayRef<Expr*> Args,
12269                                           SourceLocation LitEndLoc,
12270                                        TemplateArgumentListInfo *TemplateArgs) {
12271   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12272 
12273   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12274                                     OverloadCandidateSet::CSK_Normal);
12275   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12276                         /*SuppressUserConversions=*/true);
12277 
12278   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12279 
12280   // Perform overload resolution. This will usually be trivial, but might need
12281   // to perform substitutions for a literal operator template.
12282   OverloadCandidateSet::iterator Best;
12283   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12284   case OR_Success:
12285   case OR_Deleted:
12286     break;
12287 
12288   case OR_No_Viable_Function:
12289     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12290       << R.getLookupName();
12291     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12292     return ExprError();
12293 
12294   case OR_Ambiguous:
12295     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12296     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12297     return ExprError();
12298   }
12299 
12300   FunctionDecl *FD = Best->Function;
12301   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12302                                         HadMultipleCandidates,
12303                                         SuffixInfo.getLoc(),
12304                                         SuffixInfo.getInfo());
12305   if (Fn.isInvalid())
12306     return true;
12307 
12308   // Check the argument types. This should almost always be a no-op, except
12309   // that array-to-pointer decay is applied to string literals.
12310   Expr *ConvArgs[2];
12311   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12312     ExprResult InputInit = PerformCopyInitialization(
12313       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12314       SourceLocation(), Args[ArgIdx]);
12315     if (InputInit.isInvalid())
12316       return true;
12317     ConvArgs[ArgIdx] = InputInit.get();
12318   }
12319 
12320   QualType ResultTy = FD->getReturnType();
12321   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12322   ResultTy = ResultTy.getNonLValueExprType(Context);
12323 
12324   UserDefinedLiteral *UDL =
12325     new (Context) UserDefinedLiteral(Context, Fn.get(),
12326                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12327                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12328 
12329   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12330     return ExprError();
12331 
12332   if (CheckFunctionCall(FD, UDL, nullptr))
12333     return ExprError();
12334 
12335   return MaybeBindToTemporary(UDL);
12336 }
12337 
12338 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12339 /// given LookupResult is non-empty, it is assumed to describe a member which
12340 /// will be invoked. Otherwise, the function will be found via argument
12341 /// dependent lookup.
12342 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12343 /// otherwise CallExpr is set to ExprError() and some non-success value
12344 /// is returned.
12345 Sema::ForRangeStatus
12346 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12347                                 SourceLocation RangeLoc, VarDecl *Decl,
12348                                 BeginEndFunction BEF,
12349                                 const DeclarationNameInfo &NameInfo,
12350                                 LookupResult &MemberLookup,
12351                                 OverloadCandidateSet *CandidateSet,
12352                                 Expr *Range, ExprResult *CallExpr) {
12353   CandidateSet->clear();
12354   if (!MemberLookup.empty()) {
12355     ExprResult MemberRef =
12356         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12357                                  /*IsPtr=*/false, CXXScopeSpec(),
12358                                  /*TemplateKWLoc=*/SourceLocation(),
12359                                  /*FirstQualifierInScope=*/nullptr,
12360                                  MemberLookup,
12361                                  /*TemplateArgs=*/nullptr, S);
12362     if (MemberRef.isInvalid()) {
12363       *CallExpr = ExprError();
12364       Diag(Range->getLocStart(), diag::note_in_for_range)
12365           << RangeLoc << BEF << Range->getType();
12366       return FRS_DiagnosticIssued;
12367     }
12368     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12369     if (CallExpr->isInvalid()) {
12370       *CallExpr = ExprError();
12371       Diag(Range->getLocStart(), diag::note_in_for_range)
12372           << RangeLoc << BEF << Range->getType();
12373       return FRS_DiagnosticIssued;
12374     }
12375   } else {
12376     UnresolvedSet<0> FoundNames;
12377     UnresolvedLookupExpr *Fn =
12378       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12379                                    NestedNameSpecifierLoc(), NameInfo,
12380                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12381                                    FoundNames.begin(), FoundNames.end());
12382 
12383     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12384                                                     CandidateSet, CallExpr);
12385     if (CandidateSet->empty() || CandidateSetError) {
12386       *CallExpr = ExprError();
12387       return FRS_NoViableFunction;
12388     }
12389     OverloadCandidateSet::iterator Best;
12390     OverloadingResult OverloadResult =
12391         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12392 
12393     if (OverloadResult == OR_No_Viable_Function) {
12394       *CallExpr = ExprError();
12395       return FRS_NoViableFunction;
12396     }
12397     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12398                                          Loc, nullptr, CandidateSet, &Best,
12399                                          OverloadResult,
12400                                          /*AllowTypoCorrection=*/false);
12401     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12402       *CallExpr = ExprError();
12403       Diag(Range->getLocStart(), diag::note_in_for_range)
12404           << RangeLoc << BEF << Range->getType();
12405       return FRS_DiagnosticIssued;
12406     }
12407   }
12408   return FRS_Success;
12409 }
12410 
12411 
12412 /// FixOverloadedFunctionReference - E is an expression that refers to
12413 /// a C++ overloaded function (possibly with some parentheses and
12414 /// perhaps a '&' around it). We have resolved the overloaded function
12415 /// to the function declaration Fn, so patch up the expression E to
12416 /// refer (possibly indirectly) to Fn. Returns the new expr.
12417 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12418                                            FunctionDecl *Fn) {
12419   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12420     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12421                                                    Found, Fn);
12422     if (SubExpr == PE->getSubExpr())
12423       return PE;
12424 
12425     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12426   }
12427 
12428   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12429     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12430                                                    Found, Fn);
12431     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12432                                SubExpr->getType()) &&
12433            "Implicit cast type cannot be determined from overload");
12434     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12435     if (SubExpr == ICE->getSubExpr())
12436       return ICE;
12437 
12438     return ImplicitCastExpr::Create(Context, ICE->getType(),
12439                                     ICE->getCastKind(),
12440                                     SubExpr, nullptr,
12441                                     ICE->getValueKind());
12442   }
12443 
12444   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12445     assert(UnOp->getOpcode() == UO_AddrOf &&
12446            "Can only take the address of an overloaded function");
12447     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12448       if (Method->isStatic()) {
12449         // Do nothing: static member functions aren't any different
12450         // from non-member functions.
12451       } else {
12452         // Fix the subexpression, which really has to be an
12453         // UnresolvedLookupExpr holding an overloaded member function
12454         // or template.
12455         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12456                                                        Found, Fn);
12457         if (SubExpr == UnOp->getSubExpr())
12458           return UnOp;
12459 
12460         assert(isa<DeclRefExpr>(SubExpr)
12461                && "fixed to something other than a decl ref");
12462         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12463                && "fixed to a member ref with no nested name qualifier");
12464 
12465         // We have taken the address of a pointer to member
12466         // function. Perform the computation here so that we get the
12467         // appropriate pointer to member type.
12468         QualType ClassType
12469           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12470         QualType MemPtrType
12471           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12472 
12473         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12474                                            VK_RValue, OK_Ordinary,
12475                                            UnOp->getOperatorLoc());
12476       }
12477     }
12478     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12479                                                    Found, Fn);
12480     if (SubExpr == UnOp->getSubExpr())
12481       return UnOp;
12482 
12483     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12484                                      Context.getPointerType(SubExpr->getType()),
12485                                        VK_RValue, OK_Ordinary,
12486                                        UnOp->getOperatorLoc());
12487   }
12488 
12489   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12490     // FIXME: avoid copy.
12491     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12492     if (ULE->hasExplicitTemplateArgs()) {
12493       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12494       TemplateArgs = &TemplateArgsBuffer;
12495     }
12496 
12497     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12498                                            ULE->getQualifierLoc(),
12499                                            ULE->getTemplateKeywordLoc(),
12500                                            Fn,
12501                                            /*enclosing*/ false, // FIXME?
12502                                            ULE->getNameLoc(),
12503                                            Fn->getType(),
12504                                            VK_LValue,
12505                                            Found.getDecl(),
12506                                            TemplateArgs);
12507     MarkDeclRefReferenced(DRE);
12508     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12509     return DRE;
12510   }
12511 
12512   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12513     // FIXME: avoid copy.
12514     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12515     if (MemExpr->hasExplicitTemplateArgs()) {
12516       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12517       TemplateArgs = &TemplateArgsBuffer;
12518     }
12519 
12520     Expr *Base;
12521 
12522     // If we're filling in a static method where we used to have an
12523     // implicit member access, rewrite to a simple decl ref.
12524     if (MemExpr->isImplicitAccess()) {
12525       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12526         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12527                                                MemExpr->getQualifierLoc(),
12528                                                MemExpr->getTemplateKeywordLoc(),
12529                                                Fn,
12530                                                /*enclosing*/ false,
12531                                                MemExpr->getMemberLoc(),
12532                                                Fn->getType(),
12533                                                VK_LValue,
12534                                                Found.getDecl(),
12535                                                TemplateArgs);
12536         MarkDeclRefReferenced(DRE);
12537         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12538         return DRE;
12539       } else {
12540         SourceLocation Loc = MemExpr->getMemberLoc();
12541         if (MemExpr->getQualifier())
12542           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12543         CheckCXXThisCapture(Loc);
12544         Base = new (Context) CXXThisExpr(Loc,
12545                                          MemExpr->getBaseType(),
12546                                          /*isImplicit=*/true);
12547       }
12548     } else
12549       Base = MemExpr->getBase();
12550 
12551     ExprValueKind valueKind;
12552     QualType type;
12553     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12554       valueKind = VK_LValue;
12555       type = Fn->getType();
12556     } else {
12557       valueKind = VK_RValue;
12558       type = Context.BoundMemberTy;
12559     }
12560 
12561     MemberExpr *ME = MemberExpr::Create(
12562         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12563         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12564         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12565         OK_Ordinary);
12566     ME->setHadMultipleCandidates(true);
12567     MarkMemberReferenced(ME);
12568     return ME;
12569   }
12570 
12571   llvm_unreachable("Invalid reference to overloaded function");
12572 }
12573 
12574 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12575                                                 DeclAccessPair Found,
12576                                                 FunctionDecl *Fn) {
12577   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12578 }
12579