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/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47 
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 NarrowingKind
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                              const Expr *Converted,
294                                              APValue &ConstantValue,
295                                              QualType &ConstantType) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331       llvm::APSInt IntConstantValue;
332       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333 
334       // If it's value-dependent, we can't tell whether it's narrowing.
335       if (Initializer->isValueDependent())
336         return NK_Dependent_Narrowing;
337 
338       if (Initializer &&
339           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340         // Convert the integer to the floating type.
341         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343                                 llvm::APFloat::rmNearestTiesToEven);
344         // And back.
345         llvm::APSInt ConvertedValue = IntConstantValue;
346         bool ignored;
347         Result.convertToInteger(ConvertedValue,
348                                 llvm::APFloat::rmTowardZero, &ignored);
349         // If the resulting value is different, this was a narrowing conversion.
350         if (IntConstantValue != ConvertedValue) {
351           ConstantValue = APValue(IntConstantValue);
352           ConstantType = Initializer->getType();
353           return NK_Constant_Narrowing;
354         }
355       } else {
356         // Variables are always narrowings.
357         return NK_Variable_Narrowing;
358       }
359     }
360     return NK_Not_Narrowing;
361 
362   // -- from long double to double or float, or from double to float, except
363   //    where the source is a constant expression and the actual value after
364   //    conversion is within the range of values that can be represented (even
365   //    if it cannot be represented exactly), or
366   case ICK_Floating_Conversion:
367     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369       // FromType is larger than ToType.
370       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371 
372       // If it's value-dependent, we can't tell whether it's narrowing.
373       if (Initializer->isValueDependent())
374         return NK_Dependent_Narrowing;
375 
376       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377         // Constant!
378         assert(ConstantValue.isFloat());
379         llvm::APFloat FloatVal = ConstantValue.getFloat();
380         // Convert the source value into the target type.
381         bool ignored;
382         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383           Ctx.getFloatTypeSemantics(ToType),
384           llvm::APFloat::rmNearestTiesToEven, &ignored);
385         // If there was no overflow, the source value is within the range of
386         // values that can be represented.
387         if (ConvertStatus & llvm::APFloat::opOverflow) {
388           ConstantType = Initializer->getType();
389           return NK_Constant_Narrowing;
390         }
391       } else {
392         return NK_Variable_Narrowing;
393       }
394     }
395     return NK_Not_Narrowing;
396 
397   // -- from an integer type or unscoped enumeration type to an integer type
398   //    that cannot represent all the values of the original type, except where
399   //    the source is a constant expression and the actual value after
400   //    conversion will fit into the target type and will produce the original
401   //    value when converted back to the original type.
402   case ICK_Integral_Conversion:
403   IntegralConversion: {
404     assert(FromType->isIntegralOrUnscopedEnumerationType());
405     assert(ToType->isIntegralOrUnscopedEnumerationType());
406     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407     const unsigned FromWidth = Ctx.getIntWidth(FromType);
408     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409     const unsigned ToWidth = Ctx.getIntWidth(ToType);
410 
411     if (FromWidth > ToWidth ||
412         (FromWidth == ToWidth && FromSigned != ToSigned) ||
413         (FromSigned && !ToSigned)) {
414       // Not all values of FromType can be represented in ToType.
415       llvm::APSInt InitializerValue;
416       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417 
418       // If it's value-dependent, we can't tell whether it's narrowing.
419       if (Initializer->isValueDependent())
420         return NK_Dependent_Narrowing;
421 
422       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423         // Such conversions on variables are always narrowing.
424         return NK_Variable_Narrowing;
425       }
426       bool Narrowing = false;
427       if (FromWidth < ToWidth) {
428         // Negative -> unsigned is narrowing. Otherwise, more bits is never
429         // narrowing.
430         if (InitializerValue.isSigned() && InitializerValue.isNegative())
431           Narrowing = true;
432       } else {
433         // Add a bit to the InitializerValue so we don't have to worry about
434         // signed vs. unsigned comparisons.
435         InitializerValue = InitializerValue.extend(
436           InitializerValue.getBitWidth() + 1);
437         // Convert the initializer to and from the target width and signed-ness.
438         llvm::APSInt ConvertedValue = InitializerValue;
439         ConvertedValue = ConvertedValue.trunc(ToWidth);
440         ConvertedValue.setIsSigned(ToSigned);
441         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442         ConvertedValue.setIsSigned(InitializerValue.isSigned());
443         // If the result is different, this was a narrowing conversion.
444         if (ConvertedValue != InitializerValue)
445           Narrowing = true;
446       }
447       if (Narrowing) {
448         ConstantType = Initializer->getType();
449         ConstantValue = APValue(InitializerValue);
450         return NK_Constant_Narrowing;
451       }
452     }
453     return NK_Not_Narrowing;
454   }
455 
456   default:
457     // Other kinds of conversions are not narrowings.
458     return NK_Not_Narrowing;
459   }
460 }
461 
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465   raw_ostream &OS = llvm::errs();
466   bool PrintedSomething = false;
467   if (First != ICK_Identity) {
468     OS << GetImplicitConversionName(First);
469     PrintedSomething = true;
470   }
471 
472   if (Second != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Second);
477 
478     if (CopyConstructor) {
479       OS << " (by copy constructor)";
480     } else if (DirectBinding) {
481       OS << " (direct reference binding)";
482     } else if (ReferenceBinding) {
483       OS << " (reference binding)";
484     }
485     PrintedSomething = true;
486   }
487 
488   if (Third != ICK_Identity) {
489     if (PrintedSomething) {
490       OS << " -> ";
491     }
492     OS << GetImplicitConversionName(Third);
493     PrintedSomething = true;
494   }
495 
496   if (!PrintedSomething) {
497     OS << "No conversions required";
498   }
499 }
500 
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504   raw_ostream &OS = llvm::errs();
505   if (Before.First || Before.Second || Before.Third) {
506     Before.dump();
507     OS << " -> ";
508   }
509   if (ConversionFunction)
510     OS << '\'' << *ConversionFunction << '\'';
511   else
512     OS << "aggregate initialization";
513   if (After.First || After.Second || After.Third) {
514     OS << " -> ";
515     After.dump();
516   }
517 }
518 
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (isStdInitializerListElement())
524     OS << "Worst std::initializer_list element conversion: ";
525   switch (ConversionKind) {
526   case StandardConversion:
527     OS << "Standard conversion: ";
528     Standard.dump();
529     break;
530   case UserDefinedConversion:
531     OS << "User-defined conversion: ";
532     UserDefined.dump();
533     break;
534   case EllipsisConversion:
535     OS << "Ellipsis conversion";
536     break;
537   case AmbiguousConversion:
538     OS << "Ambiguous conversion";
539     break;
540   case BadConversion:
541     OS << "Bad conversion";
542     break;
543   }
544 
545   OS << "\n";
546 }
547 
548 void AmbiguousConversionSequence::construct() {
549   new (&conversions()) ConversionSet();
550 }
551 
552 void AmbiguousConversionSequence::destruct() {
553   conversions().~ConversionSet();
554 }
555 
556 void
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558   FromTypePtr = O.FromTypePtr;
559   ToTypePtr = O.ToTypePtr;
560   new (&conversions()) ConversionSet(O.conversions());
561 }
562 
563 namespace {
564   // Structure used by DeductionFailureInfo to store
565   // template argument information.
566   struct DFIArguments {
567     TemplateArgument FirstArg;
568     TemplateArgument SecondArg;
569   };
570   // Structure used by DeductionFailureInfo to store
571   // template parameter and template argument information.
572   struct DFIParamWithArguments : DFIArguments {
573     TemplateParameter Param;
574   };
575   // Structure used by DeductionFailureInfo to store template argument
576   // information and the index of the problematic call argument.
577   struct DFIDeducedMismatchArgs : DFIArguments {
578     TemplateArgumentList *TemplateArgs;
579     unsigned CallArgIndex;
580   };
581 }
582 
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
585 DeductionFailureInfo
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587                                 Sema::TemplateDeductionResult TDK,
588                                 TemplateDeductionInfo &Info) {
589   DeductionFailureInfo Result;
590   Result.Result = static_cast<unsigned>(TDK);
591   Result.HasDiagnostic = false;
592   switch (TDK) {
593   case Sema::TDK_Invalid:
594   case Sema::TDK_InstantiationDepth:
595   case Sema::TDK_TooManyArguments:
596   case Sema::TDK_TooFewArguments:
597   case Sema::TDK_MiscellaneousDeductionFailure:
598   case Sema::TDK_CUDATargetMismatch:
599     Result.Data = nullptr;
600     break;
601 
602   case Sema::TDK_Incomplete:
603   case Sema::TDK_InvalidExplicitArguments:
604     Result.Data = Info.Param.getOpaqueValue();
605     break;
606 
607   case Sema::TDK_DeducedMismatch:
608   case Sema::TDK_DeducedMismatchNested: {
609     // FIXME: Should allocate from normal heap so that we can free this later.
610     auto *Saved = new (Context) DFIDeducedMismatchArgs;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Saved->TemplateArgs = Info.take();
614     Saved->CallArgIndex = Info.CallArgIndex;
615     Result.Data = Saved;
616     break;
617   }
618 
619   case Sema::TDK_NonDeducedMismatch: {
620     // FIXME: Should allocate from normal heap so that we can free this later.
621     DFIArguments *Saved = new (Context) DFIArguments;
622     Saved->FirstArg = Info.FirstArg;
623     Saved->SecondArg = Info.SecondArg;
624     Result.Data = Saved;
625     break;
626   }
627 
628   case Sema::TDK_Inconsistent:
629   case Sema::TDK_Underqualified: {
630     // FIXME: Should allocate from normal heap so that we can free this later.
631     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632     Saved->Param = Info.Param;
633     Saved->FirstArg = Info.FirstArg;
634     Saved->SecondArg = Info.SecondArg;
635     Result.Data = Saved;
636     break;
637   }
638 
639   case Sema::TDK_SubstitutionFailure:
640     Result.Data = Info.take();
641     if (Info.hasSFINAEDiagnostic()) {
642       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643           SourceLocation(), PartialDiagnostic::NullDiagnostic());
644       Info.takeSFINAEDiagnostic(*Diag);
645       Result.HasDiagnostic = true;
646     }
647     break;
648 
649   case Sema::TDK_Success:
650   case Sema::TDK_NonDependentConversionFailure:
651     llvm_unreachable("not a deduction failure");
652   }
653 
654   return Result;
655 }
656 
657 void DeductionFailureInfo::Destroy() {
658   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659   case Sema::TDK_Success:
660   case Sema::TDK_Invalid:
661   case Sema::TDK_InstantiationDepth:
662   case Sema::TDK_Incomplete:
663   case Sema::TDK_TooManyArguments:
664   case Sema::TDK_TooFewArguments:
665   case Sema::TDK_InvalidExplicitArguments:
666   case Sema::TDK_CUDATargetMismatch:
667   case Sema::TDK_NonDependentConversionFailure:
668     break;
669 
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified:
672   case Sema::TDK_DeducedMismatch:
673   case Sema::TDK_DeducedMismatchNested:
674   case Sema::TDK_NonDeducedMismatch:
675     // FIXME: Destroy the data?
676     Data = nullptr;
677     break;
678 
679   case Sema::TDK_SubstitutionFailure:
680     // FIXME: Destroy the template argument list?
681     Data = nullptr;
682     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683       Diag->~PartialDiagnosticAt();
684       HasDiagnostic = false;
685     }
686     break;
687 
688   // Unhandled
689   case Sema::TDK_MiscellaneousDeductionFailure:
690     break;
691   }
692 }
693 
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695   if (HasDiagnostic)
696     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697   return nullptr;
698 }
699 
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_SubstitutionFailure:
708   case Sema::TDK_DeducedMismatch:
709   case Sema::TDK_DeducedMismatchNested:
710   case Sema::TDK_NonDeducedMismatch:
711   case Sema::TDK_CUDATargetMismatch:
712   case Sema::TDK_NonDependentConversionFailure:
713     return TemplateParameter();
714 
715   case Sema::TDK_Incomplete:
716   case Sema::TDK_InvalidExplicitArguments:
717     return TemplateParameter::getFromOpaqueValue(Data);
718 
719   case Sema::TDK_Inconsistent:
720   case Sema::TDK_Underqualified:
721     return static_cast<DFIParamWithArguments*>(Data)->Param;
722 
723   // Unhandled
724   case Sema::TDK_MiscellaneousDeductionFailure:
725     break;
726   }
727 
728   return TemplateParameter();
729 }
730 
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733   case Sema::TDK_Success:
734   case Sema::TDK_Invalid:
735   case Sema::TDK_InstantiationDepth:
736   case Sema::TDK_TooManyArguments:
737   case Sema::TDK_TooFewArguments:
738   case Sema::TDK_Incomplete:
739   case Sema::TDK_InvalidExplicitArguments:
740   case Sema::TDK_Inconsistent:
741   case Sema::TDK_Underqualified:
742   case Sema::TDK_NonDeducedMismatch:
743   case Sema::TDK_CUDATargetMismatch:
744   case Sema::TDK_NonDependentConversionFailure:
745     return nullptr;
746 
747   case Sema::TDK_DeducedMismatch:
748   case Sema::TDK_DeducedMismatchNested:
749     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750 
751   case Sema::TDK_SubstitutionFailure:
752     return static_cast<TemplateArgumentList*>(Data);
753 
754   // Unhandled
755   case Sema::TDK_MiscellaneousDeductionFailure:
756     break;
757   }
758 
759   return nullptr;
760 }
761 
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_Incomplete:
768   case Sema::TDK_TooManyArguments:
769   case Sema::TDK_TooFewArguments:
770   case Sema::TDK_InvalidExplicitArguments:
771   case Sema::TDK_SubstitutionFailure:
772   case Sema::TDK_CUDATargetMismatch:
773   case Sema::TDK_NonDependentConversionFailure:
774     return nullptr;
775 
776   case Sema::TDK_Inconsistent:
777   case Sema::TDK_Underqualified:
778   case Sema::TDK_DeducedMismatch:
779   case Sema::TDK_DeducedMismatchNested:
780   case Sema::TDK_NonDeducedMismatch:
781     return &static_cast<DFIArguments*>(Data)->FirstArg;
782 
783   // Unhandled
784   case Sema::TDK_MiscellaneousDeductionFailure:
785     break;
786   }
787 
788   return nullptr;
789 }
790 
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793   case Sema::TDK_Success:
794   case Sema::TDK_Invalid:
795   case Sema::TDK_InstantiationDepth:
796   case Sema::TDK_Incomplete:
797   case Sema::TDK_TooManyArguments:
798   case Sema::TDK_TooFewArguments:
799   case Sema::TDK_InvalidExplicitArguments:
800   case Sema::TDK_SubstitutionFailure:
801   case Sema::TDK_CUDATargetMismatch:
802   case Sema::TDK_NonDependentConversionFailure:
803     return nullptr;
804 
805   case Sema::TDK_Inconsistent:
806   case Sema::TDK_Underqualified:
807   case Sema::TDK_DeducedMismatch:
808   case Sema::TDK_DeducedMismatchNested:
809   case Sema::TDK_NonDeducedMismatch:
810     return &static_cast<DFIArguments*>(Data)->SecondArg;
811 
812   // Unhandled
813   case Sema::TDK_MiscellaneousDeductionFailure:
814     break;
815   }
816 
817   return nullptr;
818 }
819 
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822   case Sema::TDK_DeducedMismatch:
823   case Sema::TDK_DeducedMismatchNested:
824     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825 
826   default:
827     return llvm::None;
828   }
829 }
830 
831 void OverloadCandidateSet::destroyCandidates() {
832   for (iterator i = begin(), e = end(); i != e; ++i) {
833     for (auto &C : i->Conversions)
834       C.~ImplicitConversionSequence();
835     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836       i->DeductionFailure.Destroy();
837   }
838 }
839 
840 void OverloadCandidateSet::clear() {
841   destroyCandidates();
842   // DiagnoseIfAttrs are just pointers, so we don't need to destroy them.
843   SlabAllocator.Reset();
844   NumInlineBytesUsed = 0;
845   Candidates.clear();
846   Functions.clear();
847 }
848 
849 DiagnoseIfAttr **
850 OverloadCandidateSet::addDiagnoseIfComplaints(ArrayRef<DiagnoseIfAttr *> CA) {
851   auto *DIA = slabAllocate<DiagnoseIfAttr *>(CA.size());
852   std::uninitialized_copy(CA.begin(), CA.end(), DIA);
853   return DIA;
854 }
855 
856 namespace {
857   class UnbridgedCastsSet {
858     struct Entry {
859       Expr **Addr;
860       Expr *Saved;
861     };
862     SmallVector<Entry, 2> Entries;
863 
864   public:
865     void save(Sema &S, Expr *&E) {
866       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
867       Entry entry = { &E, E };
868       Entries.push_back(entry);
869       E = S.stripARCUnbridgedCast(E);
870     }
871 
872     void restore() {
873       for (SmallVectorImpl<Entry>::iterator
874              i = Entries.begin(), e = Entries.end(); i != e; ++i)
875         *i->Addr = i->Saved;
876     }
877   };
878 }
879 
880 /// checkPlaceholderForOverload - Do any interesting placeholder-like
881 /// preprocessing on the given expression.
882 ///
883 /// \param unbridgedCasts a collection to which to add unbridged casts;
884 ///   without this, they will be immediately diagnosed as errors
885 ///
886 /// Return true on unrecoverable error.
887 static bool
888 checkPlaceholderForOverload(Sema &S, Expr *&E,
889                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
890   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
891     // We can't handle overloaded expressions here because overload
892     // resolution might reasonably tweak them.
893     if (placeholder->getKind() == BuiltinType::Overload) return false;
894 
895     // If the context potentially accepts unbridged ARC casts, strip
896     // the unbridged cast and add it to the collection for later restoration.
897     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
898         unbridgedCasts) {
899       unbridgedCasts->save(S, E);
900       return false;
901     }
902 
903     // Go ahead and check everything else.
904     ExprResult result = S.CheckPlaceholderExpr(E);
905     if (result.isInvalid())
906       return true;
907 
908     E = result.get();
909     return false;
910   }
911 
912   // Nothing to do.
913   return false;
914 }
915 
916 /// checkArgPlaceholdersForOverload - Check a set of call operands for
917 /// placeholders.
918 static bool checkArgPlaceholdersForOverload(Sema &S,
919                                             MultiExprArg Args,
920                                             UnbridgedCastsSet &unbridged) {
921   for (unsigned i = 0, e = Args.size(); i != e; ++i)
922     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
923       return true;
924 
925   return false;
926 }
927 
928 // IsOverload - Determine whether the given New declaration is an
929 // overload of the declarations in Old. This routine returns false if
930 // New and Old cannot be overloaded, e.g., if New has the same
931 // signature as some function in Old (C++ 1.3.10) or if the Old
932 // declarations aren't functions (or function templates) at all. When
933 // it does return false, MatchedDecl will point to the decl that New
934 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
935 // top of the underlying declaration.
936 //
937 // Example: Given the following input:
938 //
939 //   void f(int, float); // #1
940 //   void f(int, int); // #2
941 //   int f(int, int); // #3
942 //
943 // When we process #1, there is no previous declaration of "f",
944 // so IsOverload will not be used.
945 //
946 // When we process #2, Old contains only the FunctionDecl for #1.  By
947 // comparing the parameter types, we see that #1 and #2 are overloaded
948 // (since they have different signatures), so this routine returns
949 // false; MatchedDecl is unchanged.
950 //
951 // When we process #3, Old is an overload set containing #1 and #2. We
952 // compare the signatures of #3 to #1 (they're overloaded, so we do
953 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
954 // identical (return types of functions are not part of the
955 // signature), IsOverload returns false and MatchedDecl will be set to
956 // point to the FunctionDecl for #2.
957 //
958 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
959 // into a class by a using declaration.  The rules for whether to hide
960 // shadow declarations ignore some properties which otherwise figure
961 // into a function template's signature.
962 Sema::OverloadKind
963 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
964                     NamedDecl *&Match, bool NewIsUsingDecl) {
965   for (LookupResult::iterator I = Old.begin(), E = Old.end();
966          I != E; ++I) {
967     NamedDecl *OldD = *I;
968 
969     bool OldIsUsingDecl = false;
970     if (isa<UsingShadowDecl>(OldD)) {
971       OldIsUsingDecl = true;
972 
973       // We can always introduce two using declarations into the same
974       // context, even if they have identical signatures.
975       if (NewIsUsingDecl) continue;
976 
977       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
978     }
979 
980     // A using-declaration does not conflict with another declaration
981     // if one of them is hidden.
982     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
983       continue;
984 
985     // If either declaration was introduced by a using declaration,
986     // we'll need to use slightly different rules for matching.
987     // Essentially, these rules are the normal rules, except that
988     // function templates hide function templates with different
989     // return types or template parameter lists.
990     bool UseMemberUsingDeclRules =
991       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
992       !New->getFriendObjectKind();
993 
994     if (FunctionDecl *OldF = OldD->getAsFunction()) {
995       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
996         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
997           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
998           continue;
999         }
1000 
1001         if (!isa<FunctionTemplateDecl>(OldD) &&
1002             !shouldLinkPossiblyHiddenDecl(*I, New))
1003           continue;
1004 
1005         Match = *I;
1006         return Ovl_Match;
1007       }
1008     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1009       // We can overload with these, which can show up when doing
1010       // redeclaration checks for UsingDecls.
1011       assert(Old.getLookupKind() == LookupUsingDeclName);
1012     } else if (isa<TagDecl>(OldD)) {
1013       // We can always overload with tags by hiding them.
1014     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1015       // Optimistically assume that an unresolved using decl will
1016       // overload; if it doesn't, we'll have to diagnose during
1017       // template instantiation.
1018       //
1019       // Exception: if the scope is dependent and this is not a class
1020       // member, the using declaration can only introduce an enumerator.
1021       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1022         Match = *I;
1023         return Ovl_NonFunction;
1024       }
1025     } else {
1026       // (C++ 13p1):
1027       //   Only function declarations can be overloaded; object and type
1028       //   declarations cannot be overloaded.
1029       Match = *I;
1030       return Ovl_NonFunction;
1031     }
1032   }
1033 
1034   return Ovl_Overload;
1035 }
1036 
1037 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1038                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1039   // C++ [basic.start.main]p2: This function shall not be overloaded.
1040   if (New->isMain())
1041     return false;
1042 
1043   // MSVCRT user defined entry points cannot be overloaded.
1044   if (New->isMSVCRTEntryPoint())
1045     return false;
1046 
1047   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1048   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1049 
1050   // C++ [temp.fct]p2:
1051   //   A function template can be overloaded with other function templates
1052   //   and with normal (non-template) functions.
1053   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1054     return true;
1055 
1056   // Is the function New an overload of the function Old?
1057   QualType OldQType = Context.getCanonicalType(Old->getType());
1058   QualType NewQType = Context.getCanonicalType(New->getType());
1059 
1060   // Compare the signatures (C++ 1.3.10) of the two functions to
1061   // determine whether they are overloads. If we find any mismatch
1062   // in the signature, they are overloads.
1063 
1064   // If either of these functions is a K&R-style function (no
1065   // prototype), then we consider them to have matching signatures.
1066   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1067       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1068     return false;
1069 
1070   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1071   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1072 
1073   // The signature of a function includes the types of its
1074   // parameters (C++ 1.3.10), which includes the presence or absence
1075   // of the ellipsis; see C++ DR 357).
1076   if (OldQType != NewQType &&
1077       (OldType->getNumParams() != NewType->getNumParams() ||
1078        OldType->isVariadic() != NewType->isVariadic() ||
1079        !FunctionParamTypesAreEqual(OldType, NewType)))
1080     return true;
1081 
1082   // C++ [temp.over.link]p4:
1083   //   The signature of a function template consists of its function
1084   //   signature, its return type and its template parameter list. The names
1085   //   of the template parameters are significant only for establishing the
1086   //   relationship between the template parameters and the rest of the
1087   //   signature.
1088   //
1089   // We check the return type and template parameter lists for function
1090   // templates first; the remaining checks follow.
1091   //
1092   // However, we don't consider either of these when deciding whether
1093   // a member introduced by a shadow declaration is hidden.
1094   if (!UseMemberUsingDeclRules && NewTemplate &&
1095       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1096                                        OldTemplate->getTemplateParameters(),
1097                                        false, TPL_TemplateMatch) ||
1098        OldType->getReturnType() != NewType->getReturnType()))
1099     return true;
1100 
1101   // If the function is a class member, its signature includes the
1102   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1103   //
1104   // As part of this, also check whether one of the member functions
1105   // is static, in which case they are not overloads (C++
1106   // 13.1p2). While not part of the definition of the signature,
1107   // this check is important to determine whether these functions
1108   // can be overloaded.
1109   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1110   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1111   if (OldMethod && NewMethod &&
1112       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1113     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1114       if (!UseMemberUsingDeclRules &&
1115           (OldMethod->getRefQualifier() == RQ_None ||
1116            NewMethod->getRefQualifier() == RQ_None)) {
1117         // C++0x [over.load]p2:
1118         //   - Member function declarations with the same name and the same
1119         //     parameter-type-list as well as member function template
1120         //     declarations with the same name, the same parameter-type-list, and
1121         //     the same template parameter lists cannot be overloaded if any of
1122         //     them, but not all, have a ref-qualifier (8.3.5).
1123         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1124           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1125         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1126       }
1127       return true;
1128     }
1129 
1130     // We may not have applied the implicit const for a constexpr member
1131     // function yet (because we haven't yet resolved whether this is a static
1132     // or non-static member function). Add it now, on the assumption that this
1133     // is a redeclaration of OldMethod.
1134     unsigned OldQuals = OldMethod->getTypeQualifiers();
1135     unsigned NewQuals = NewMethod->getTypeQualifiers();
1136     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1137         !isa<CXXConstructorDecl>(NewMethod))
1138       NewQuals |= Qualifiers::Const;
1139 
1140     // We do not allow overloading based off of '__restrict'.
1141     OldQuals &= ~Qualifiers::Restrict;
1142     NewQuals &= ~Qualifiers::Restrict;
1143     if (OldQuals != NewQuals)
1144       return true;
1145   }
1146 
1147   // Though pass_object_size is placed on parameters and takes an argument, we
1148   // consider it to be a function-level modifier for the sake of function
1149   // identity. Either the function has one or more parameters with
1150   // pass_object_size or it doesn't.
1151   if (functionHasPassObjectSizeParams(New) !=
1152       functionHasPassObjectSizeParams(Old))
1153     return true;
1154 
1155   // enable_if attributes are an order-sensitive part of the signature.
1156   for (specific_attr_iterator<EnableIfAttr>
1157          NewI = New->specific_attr_begin<EnableIfAttr>(),
1158          NewE = New->specific_attr_end<EnableIfAttr>(),
1159          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1160          OldE = Old->specific_attr_end<EnableIfAttr>();
1161        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1162     if (NewI == NewE || OldI == OldE)
1163       return true;
1164     llvm::FoldingSetNodeID NewID, OldID;
1165     NewI->getCond()->Profile(NewID, Context, true);
1166     OldI->getCond()->Profile(OldID, Context, true);
1167     if (NewID != OldID)
1168       return true;
1169   }
1170 
1171   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1172     // Don't allow overloading of destructors.  (In theory we could, but it
1173     // would be a giant change to clang.)
1174     if (isa<CXXDestructorDecl>(New))
1175       return false;
1176 
1177     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1178                        OldTarget = IdentifyCUDATarget(Old);
1179     if (NewTarget == CFT_InvalidTarget)
1180       return false;
1181 
1182     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1183 
1184     // Allow overloading of functions with same signature and different CUDA
1185     // target attributes.
1186     return NewTarget != OldTarget;
1187   }
1188 
1189   // The signatures match; this is not an overload.
1190   return false;
1191 }
1192 
1193 /// \brief Checks availability of the function depending on the current
1194 /// function context. Inside an unavailable function, unavailability is ignored.
1195 ///
1196 /// \returns true if \arg FD is unavailable and current context is inside
1197 /// an available function, false otherwise.
1198 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1199   if (!FD->isUnavailable())
1200     return false;
1201 
1202   // Walk up the context of the caller.
1203   Decl *C = cast<Decl>(CurContext);
1204   do {
1205     if (C->isUnavailable())
1206       return false;
1207   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1208   return true;
1209 }
1210 
1211 /// \brief Tries a user-defined conversion from From to ToType.
1212 ///
1213 /// Produces an implicit conversion sequence for when a standard conversion
1214 /// is not an option. See TryImplicitConversion for more information.
1215 static ImplicitConversionSequence
1216 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1217                          bool SuppressUserConversions,
1218                          bool AllowExplicit,
1219                          bool InOverloadResolution,
1220                          bool CStyle,
1221                          bool AllowObjCWritebackConversion,
1222                          bool AllowObjCConversionOnExplicit) {
1223   ImplicitConversionSequence ICS;
1224 
1225   if (SuppressUserConversions) {
1226     // We're not in the case above, so there is no conversion that
1227     // we can perform.
1228     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1229     return ICS;
1230   }
1231 
1232   // Attempt user-defined conversion.
1233   OverloadCandidateSet Conversions(From->getExprLoc(),
1234                                    OverloadCandidateSet::CSK_Normal);
1235   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1236                                   Conversions, AllowExplicit,
1237                                   AllowObjCConversionOnExplicit)) {
1238   case OR_Success:
1239   case OR_Deleted:
1240     ICS.setUserDefined();
1241     // C++ [over.ics.user]p4:
1242     //   A conversion of an expression of class type to the same class
1243     //   type is given Exact Match rank, and a conversion of an
1244     //   expression of class type to a base class of that type is
1245     //   given Conversion rank, in spite of the fact that a copy
1246     //   constructor (i.e., a user-defined conversion function) is
1247     //   called for those cases.
1248     if (CXXConstructorDecl *Constructor
1249           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1250       QualType FromCanon
1251         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1252       QualType ToCanon
1253         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1254       if (Constructor->isCopyConstructor() &&
1255           (FromCanon == ToCanon ||
1256            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1257         // Turn this into a "standard" conversion sequence, so that it
1258         // gets ranked with standard conversion sequences.
1259         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1260         ICS.setStandard();
1261         ICS.Standard.setAsIdentityConversion();
1262         ICS.Standard.setFromType(From->getType());
1263         ICS.Standard.setAllToTypes(ToType);
1264         ICS.Standard.CopyConstructor = Constructor;
1265         ICS.Standard.FoundCopyConstructor = Found;
1266         if (ToCanon != FromCanon)
1267           ICS.Standard.Second = ICK_Derived_To_Base;
1268       }
1269     }
1270     break;
1271 
1272   case OR_Ambiguous:
1273     ICS.setAmbiguous();
1274     ICS.Ambiguous.setFromType(From->getType());
1275     ICS.Ambiguous.setToType(ToType);
1276     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1277          Cand != Conversions.end(); ++Cand)
1278       if (Cand->Viable)
1279         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1280     break;
1281 
1282     // Fall through.
1283   case OR_No_Viable_Function:
1284     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1285     break;
1286   }
1287 
1288   return ICS;
1289 }
1290 
1291 /// TryImplicitConversion - Attempt to perform an implicit conversion
1292 /// from the given expression (Expr) to the given type (ToType). This
1293 /// function returns an implicit conversion sequence that can be used
1294 /// to perform the initialization. Given
1295 ///
1296 ///   void f(float f);
1297 ///   void g(int i) { f(i); }
1298 ///
1299 /// this routine would produce an implicit conversion sequence to
1300 /// describe the initialization of f from i, which will be a standard
1301 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1302 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1303 //
1304 /// Note that this routine only determines how the conversion can be
1305 /// performed; it does not actually perform the conversion. As such,
1306 /// it will not produce any diagnostics if no conversion is available,
1307 /// but will instead return an implicit conversion sequence of kind
1308 /// "BadConversion".
1309 ///
1310 /// If @p SuppressUserConversions, then user-defined conversions are
1311 /// not permitted.
1312 /// If @p AllowExplicit, then explicit user-defined conversions are
1313 /// permitted.
1314 ///
1315 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1316 /// writeback conversion, which allows __autoreleasing id* parameters to
1317 /// be initialized with __strong id* or __weak id* arguments.
1318 static ImplicitConversionSequence
1319 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1320                       bool SuppressUserConversions,
1321                       bool AllowExplicit,
1322                       bool InOverloadResolution,
1323                       bool CStyle,
1324                       bool AllowObjCWritebackConversion,
1325                       bool AllowObjCConversionOnExplicit) {
1326   ImplicitConversionSequence ICS;
1327   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1328                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1329     ICS.setStandard();
1330     return ICS;
1331   }
1332 
1333   if (!S.getLangOpts().CPlusPlus) {
1334     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335     return ICS;
1336   }
1337 
1338   // C++ [over.ics.user]p4:
1339   //   A conversion of an expression of class type to the same class
1340   //   type is given Exact Match rank, and a conversion of an
1341   //   expression of class type to a base class of that type is
1342   //   given Conversion rank, in spite of the fact that a copy/move
1343   //   constructor (i.e., a user-defined conversion function) is
1344   //   called for those cases.
1345   QualType FromType = From->getType();
1346   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1347       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1348        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1349     ICS.setStandard();
1350     ICS.Standard.setAsIdentityConversion();
1351     ICS.Standard.setFromType(FromType);
1352     ICS.Standard.setAllToTypes(ToType);
1353 
1354     // We don't actually check at this point whether there is a valid
1355     // copy/move constructor, since overloading just assumes that it
1356     // exists. When we actually perform initialization, we'll find the
1357     // appropriate constructor to copy the returned object, if needed.
1358     ICS.Standard.CopyConstructor = nullptr;
1359 
1360     // Determine whether this is considered a derived-to-base conversion.
1361     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1362       ICS.Standard.Second = ICK_Derived_To_Base;
1363 
1364     return ICS;
1365   }
1366 
1367   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1368                                   AllowExplicit, InOverloadResolution, CStyle,
1369                                   AllowObjCWritebackConversion,
1370                                   AllowObjCConversionOnExplicit);
1371 }
1372 
1373 ImplicitConversionSequence
1374 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1375                             bool SuppressUserConversions,
1376                             bool AllowExplicit,
1377                             bool InOverloadResolution,
1378                             bool CStyle,
1379                             bool AllowObjCWritebackConversion) {
1380   return ::TryImplicitConversion(*this, From, ToType,
1381                                  SuppressUserConversions, AllowExplicit,
1382                                  InOverloadResolution, CStyle,
1383                                  AllowObjCWritebackConversion,
1384                                  /*AllowObjCConversionOnExplicit=*/false);
1385 }
1386 
1387 /// PerformImplicitConversion - Perform an implicit conversion of the
1388 /// expression From to the type ToType. Returns the
1389 /// converted expression. Flavor is the kind of conversion we're
1390 /// performing, used in the error message. If @p AllowExplicit,
1391 /// explicit user-defined conversions are permitted.
1392 ExprResult
1393 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1394                                 AssignmentAction Action, bool AllowExplicit) {
1395   ImplicitConversionSequence ICS;
1396   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1397 }
1398 
1399 ExprResult
1400 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1401                                 AssignmentAction Action, bool AllowExplicit,
1402                                 ImplicitConversionSequence& ICS) {
1403   if (checkPlaceholderForOverload(*this, From))
1404     return ExprError();
1405 
1406   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1407   bool AllowObjCWritebackConversion
1408     = getLangOpts().ObjCAutoRefCount &&
1409       (Action == AA_Passing || Action == AA_Sending);
1410   if (getLangOpts().ObjC1)
1411     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1412                                       ToType, From->getType(), From);
1413   ICS = ::TryImplicitConversion(*this, From, ToType,
1414                                 /*SuppressUserConversions=*/false,
1415                                 AllowExplicit,
1416                                 /*InOverloadResolution=*/false,
1417                                 /*CStyle=*/false,
1418                                 AllowObjCWritebackConversion,
1419                                 /*AllowObjCConversionOnExplicit=*/false);
1420   return PerformImplicitConversion(From, ToType, ICS, Action);
1421 }
1422 
1423 /// \brief Determine whether the conversion from FromType to ToType is a valid
1424 /// conversion that strips "noexcept" or "noreturn" off the nested function
1425 /// type.
1426 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1427                                 QualType &ResultTy) {
1428   if (Context.hasSameUnqualifiedType(FromType, ToType))
1429     return false;
1430 
1431   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1432   //                    or F(t noexcept) -> F(t)
1433   // where F adds one of the following at most once:
1434   //   - a pointer
1435   //   - a member pointer
1436   //   - a block pointer
1437   // Changes here need matching changes in FindCompositePointerType.
1438   CanQualType CanTo = Context.getCanonicalType(ToType);
1439   CanQualType CanFrom = Context.getCanonicalType(FromType);
1440   Type::TypeClass TyClass = CanTo->getTypeClass();
1441   if (TyClass != CanFrom->getTypeClass()) return false;
1442   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1443     if (TyClass == Type::Pointer) {
1444       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1445       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1446     } else if (TyClass == Type::BlockPointer) {
1447       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1448       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1449     } else if (TyClass == Type::MemberPointer) {
1450       auto ToMPT = CanTo.getAs<MemberPointerType>();
1451       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1452       // A function pointer conversion cannot change the class of the function.
1453       if (ToMPT->getClass() != FromMPT->getClass())
1454         return false;
1455       CanTo = ToMPT->getPointeeType();
1456       CanFrom = FromMPT->getPointeeType();
1457     } else {
1458       return false;
1459     }
1460 
1461     TyClass = CanTo->getTypeClass();
1462     if (TyClass != CanFrom->getTypeClass()) return false;
1463     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1464       return false;
1465   }
1466 
1467   const auto *FromFn = cast<FunctionType>(CanFrom);
1468   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1469 
1470   const auto *ToFn = cast<FunctionType>(CanTo);
1471   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1472 
1473   bool Changed = false;
1474 
1475   // Drop 'noreturn' if not present in target type.
1476   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1477     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1478     Changed = true;
1479   }
1480 
1481   // Drop 'noexcept' if not present in target type.
1482   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1483     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1484     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1485       FromFn = cast<FunctionType>(
1486           Context.getFunctionType(FromFPT->getReturnType(),
1487                                   FromFPT->getParamTypes(),
1488                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1489                                       FunctionProtoType::ExceptionSpecInfo()))
1490                  .getTypePtr());
1491       Changed = true;
1492     }
1493   }
1494 
1495   if (!Changed)
1496     return false;
1497 
1498   assert(QualType(FromFn, 0).isCanonical());
1499   if (QualType(FromFn, 0) != CanTo) return false;
1500 
1501   ResultTy = ToType;
1502   return true;
1503 }
1504 
1505 /// \brief Determine whether the conversion from FromType to ToType is a valid
1506 /// vector conversion.
1507 ///
1508 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1509 /// conversion.
1510 static bool IsVectorConversion(Sema &S, QualType FromType,
1511                                QualType ToType, ImplicitConversionKind &ICK) {
1512   // We need at least one of these types to be a vector type to have a vector
1513   // conversion.
1514   if (!ToType->isVectorType() && !FromType->isVectorType())
1515     return false;
1516 
1517   // Identical types require no conversions.
1518   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1519     return false;
1520 
1521   // There are no conversions between extended vector types, only identity.
1522   if (ToType->isExtVectorType()) {
1523     // There are no conversions between extended vector types other than the
1524     // identity conversion.
1525     if (FromType->isExtVectorType())
1526       return false;
1527 
1528     // Vector splat from any arithmetic type to a vector.
1529     if (FromType->isArithmeticType()) {
1530       ICK = ICK_Vector_Splat;
1531       return true;
1532     }
1533   }
1534 
1535   // We can perform the conversion between vector types in the following cases:
1536   // 1)vector types are equivalent AltiVec and GCC vector types
1537   // 2)lax vector conversions are permitted and the vector types are of the
1538   //   same size
1539   if (ToType->isVectorType() && FromType->isVectorType()) {
1540     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1541         S.isLaxVectorConversion(FromType, ToType)) {
1542       ICK = ICK_Vector_Conversion;
1543       return true;
1544     }
1545   }
1546 
1547   return false;
1548 }
1549 
1550 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1551                                 bool InOverloadResolution,
1552                                 StandardConversionSequence &SCS,
1553                                 bool CStyle);
1554 
1555 /// IsStandardConversion - Determines whether there is a standard
1556 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1557 /// expression From to the type ToType. Standard conversion sequences
1558 /// only consider non-class types; for conversions that involve class
1559 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1560 /// contain the standard conversion sequence required to perform this
1561 /// conversion and this routine will return true. Otherwise, this
1562 /// routine will return false and the value of SCS is unspecified.
1563 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1564                                  bool InOverloadResolution,
1565                                  StandardConversionSequence &SCS,
1566                                  bool CStyle,
1567                                  bool AllowObjCWritebackConversion) {
1568   QualType FromType = From->getType();
1569 
1570   // Standard conversions (C++ [conv])
1571   SCS.setAsIdentityConversion();
1572   SCS.IncompatibleObjC = false;
1573   SCS.setFromType(FromType);
1574   SCS.CopyConstructor = nullptr;
1575 
1576   // There are no standard conversions for class types in C++, so
1577   // abort early. When overloading in C, however, we do permit them.
1578   if (S.getLangOpts().CPlusPlus &&
1579       (FromType->isRecordType() || ToType->isRecordType()))
1580     return false;
1581 
1582   // The first conversion can be an lvalue-to-rvalue conversion,
1583   // array-to-pointer conversion, or function-to-pointer conversion
1584   // (C++ 4p1).
1585 
1586   if (FromType == S.Context.OverloadTy) {
1587     DeclAccessPair AccessPair;
1588     if (FunctionDecl *Fn
1589           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1590                                                  AccessPair)) {
1591       // We were able to resolve the address of the overloaded function,
1592       // so we can convert to the type of that function.
1593       FromType = Fn->getType();
1594       SCS.setFromType(FromType);
1595 
1596       // we can sometimes resolve &foo<int> regardless of ToType, so check
1597       // if the type matches (identity) or we are converting to bool
1598       if (!S.Context.hasSameUnqualifiedType(
1599                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1600         QualType resultTy;
1601         // if the function type matches except for [[noreturn]], it's ok
1602         if (!S.IsFunctionConversion(FromType,
1603               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1604           // otherwise, only a boolean conversion is standard
1605           if (!ToType->isBooleanType())
1606             return false;
1607       }
1608 
1609       // Check if the "from" expression is taking the address of an overloaded
1610       // function and recompute the FromType accordingly. Take advantage of the
1611       // fact that non-static member functions *must* have such an address-of
1612       // expression.
1613       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1614       if (Method && !Method->isStatic()) {
1615         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1616                "Non-unary operator on non-static member address");
1617         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1618                == UO_AddrOf &&
1619                "Non-address-of operator on non-static member address");
1620         const Type *ClassType
1621           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1622         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1623       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1624         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1625                UO_AddrOf &&
1626                "Non-address-of operator for overloaded function expression");
1627         FromType = S.Context.getPointerType(FromType);
1628       }
1629 
1630       // Check that we've computed the proper type after overload resolution.
1631       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1632       // be calling it from within an NDEBUG block.
1633       assert(S.Context.hasSameType(
1634         FromType,
1635         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1636     } else {
1637       return false;
1638     }
1639   }
1640   // Lvalue-to-rvalue conversion (C++11 4.1):
1641   //   A glvalue (3.10) of a non-function, non-array type T can
1642   //   be converted to a prvalue.
1643   bool argIsLValue = From->isGLValue();
1644   if (argIsLValue &&
1645       !FromType->isFunctionType() && !FromType->isArrayType() &&
1646       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1647     SCS.First = ICK_Lvalue_To_Rvalue;
1648 
1649     // C11 6.3.2.1p2:
1650     //   ... if the lvalue has atomic type, the value has the non-atomic version
1651     //   of the type of the lvalue ...
1652     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1653       FromType = Atomic->getValueType();
1654 
1655     // If T is a non-class type, the type of the rvalue is the
1656     // cv-unqualified version of T. Otherwise, the type of the rvalue
1657     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1658     // just strip the qualifiers because they don't matter.
1659     FromType = FromType.getUnqualifiedType();
1660   } else if (FromType->isArrayType()) {
1661     // Array-to-pointer conversion (C++ 4.2)
1662     SCS.First = ICK_Array_To_Pointer;
1663 
1664     // An lvalue or rvalue of type "array of N T" or "array of unknown
1665     // bound of T" can be converted to an rvalue of type "pointer to
1666     // T" (C++ 4.2p1).
1667     FromType = S.Context.getArrayDecayedType(FromType);
1668 
1669     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1670       // This conversion is deprecated in C++03 (D.4)
1671       SCS.DeprecatedStringLiteralToCharPtr = true;
1672 
1673       // For the purpose of ranking in overload resolution
1674       // (13.3.3.1.1), this conversion is considered an
1675       // array-to-pointer conversion followed by a qualification
1676       // conversion (4.4). (C++ 4.2p2)
1677       SCS.Second = ICK_Identity;
1678       SCS.Third = ICK_Qualification;
1679       SCS.QualificationIncludesObjCLifetime = false;
1680       SCS.setAllToTypes(FromType);
1681       return true;
1682     }
1683   } else if (FromType->isFunctionType() && argIsLValue) {
1684     // Function-to-pointer conversion (C++ 4.3).
1685     SCS.First = ICK_Function_To_Pointer;
1686 
1687     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1688       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1689         if (!S.checkAddressOfFunctionIsAvailable(FD))
1690           return false;
1691 
1692     // An lvalue of function type T can be converted to an rvalue of
1693     // type "pointer to T." The result is a pointer to the
1694     // function. (C++ 4.3p1).
1695     FromType = S.Context.getPointerType(FromType);
1696   } else {
1697     // We don't require any conversions for the first step.
1698     SCS.First = ICK_Identity;
1699   }
1700   SCS.setToType(0, FromType);
1701 
1702   // The second conversion can be an integral promotion, floating
1703   // point promotion, integral conversion, floating point conversion,
1704   // floating-integral conversion, pointer conversion,
1705   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1706   // For overloading in C, this can also be a "compatible-type"
1707   // conversion.
1708   bool IncompatibleObjC = false;
1709   ImplicitConversionKind SecondICK = ICK_Identity;
1710   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1711     // The unqualified versions of the types are the same: there's no
1712     // conversion to do.
1713     SCS.Second = ICK_Identity;
1714   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1715     // Integral promotion (C++ 4.5).
1716     SCS.Second = ICK_Integral_Promotion;
1717     FromType = ToType.getUnqualifiedType();
1718   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1719     // Floating point promotion (C++ 4.6).
1720     SCS.Second = ICK_Floating_Promotion;
1721     FromType = ToType.getUnqualifiedType();
1722   } else if (S.IsComplexPromotion(FromType, ToType)) {
1723     // Complex promotion (Clang extension)
1724     SCS.Second = ICK_Complex_Promotion;
1725     FromType = ToType.getUnqualifiedType();
1726   } else if (ToType->isBooleanType() &&
1727              (FromType->isArithmeticType() ||
1728               FromType->isAnyPointerType() ||
1729               FromType->isBlockPointerType() ||
1730               FromType->isMemberPointerType() ||
1731               FromType->isNullPtrType())) {
1732     // Boolean conversions (C++ 4.12).
1733     SCS.Second = ICK_Boolean_Conversion;
1734     FromType = S.Context.BoolTy;
1735   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1736              ToType->isIntegralType(S.Context)) {
1737     // Integral conversions (C++ 4.7).
1738     SCS.Second = ICK_Integral_Conversion;
1739     FromType = ToType.getUnqualifiedType();
1740   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1741     // Complex conversions (C99 6.3.1.6)
1742     SCS.Second = ICK_Complex_Conversion;
1743     FromType = ToType.getUnqualifiedType();
1744   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1745              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1746     // Complex-real conversions (C99 6.3.1.7)
1747     SCS.Second = ICK_Complex_Real;
1748     FromType = ToType.getUnqualifiedType();
1749   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1750     // FIXME: disable conversions between long double and __float128 if
1751     // their representation is different until there is back end support
1752     // We of course allow this conversion if long double is really double.
1753     if (&S.Context.getFloatTypeSemantics(FromType) !=
1754         &S.Context.getFloatTypeSemantics(ToType)) {
1755       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1756                                     ToType == S.Context.LongDoubleTy) ||
1757                                    (FromType == S.Context.LongDoubleTy &&
1758                                     ToType == S.Context.Float128Ty));
1759       if (Float128AndLongDouble &&
1760           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1761            &llvm::APFloat::IEEEdouble()))
1762         return false;
1763     }
1764     // Floating point conversions (C++ 4.8).
1765     SCS.Second = ICK_Floating_Conversion;
1766     FromType = ToType.getUnqualifiedType();
1767   } else if ((FromType->isRealFloatingType() &&
1768               ToType->isIntegralType(S.Context)) ||
1769              (FromType->isIntegralOrUnscopedEnumerationType() &&
1770               ToType->isRealFloatingType())) {
1771     // Floating-integral conversions (C++ 4.9).
1772     SCS.Second = ICK_Floating_Integral;
1773     FromType = ToType.getUnqualifiedType();
1774   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1775     SCS.Second = ICK_Block_Pointer_Conversion;
1776   } else if (AllowObjCWritebackConversion &&
1777              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1778     SCS.Second = ICK_Writeback_Conversion;
1779   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1780                                    FromType, IncompatibleObjC)) {
1781     // Pointer conversions (C++ 4.10).
1782     SCS.Second = ICK_Pointer_Conversion;
1783     SCS.IncompatibleObjC = IncompatibleObjC;
1784     FromType = FromType.getUnqualifiedType();
1785   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1786                                          InOverloadResolution, FromType)) {
1787     // Pointer to member conversions (4.11).
1788     SCS.Second = ICK_Pointer_Member;
1789   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1790     SCS.Second = SecondICK;
1791     FromType = ToType.getUnqualifiedType();
1792   } else if (!S.getLangOpts().CPlusPlus &&
1793              S.Context.typesAreCompatible(ToType, FromType)) {
1794     // Compatible conversions (Clang extension for C function overloading)
1795     SCS.Second = ICK_Compatible_Conversion;
1796     FromType = ToType.getUnqualifiedType();
1797   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1798                                              InOverloadResolution,
1799                                              SCS, CStyle)) {
1800     SCS.Second = ICK_TransparentUnionConversion;
1801     FromType = ToType;
1802   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1803                                  CStyle)) {
1804     // tryAtomicConversion has updated the standard conversion sequence
1805     // appropriately.
1806     return true;
1807   } else if (ToType->isEventT() &&
1808              From->isIntegerConstantExpr(S.getASTContext()) &&
1809              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1810     SCS.Second = ICK_Zero_Event_Conversion;
1811     FromType = ToType;
1812   } else if (ToType->isQueueT() &&
1813              From->isIntegerConstantExpr(S.getASTContext()) &&
1814              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1815     SCS.Second = ICK_Zero_Queue_Conversion;
1816     FromType = ToType;
1817   } else {
1818     // No second conversion required.
1819     SCS.Second = ICK_Identity;
1820   }
1821   SCS.setToType(1, FromType);
1822 
1823   // The third conversion can be a function pointer conversion or a
1824   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1825   bool ObjCLifetimeConversion;
1826   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1827     // Function pointer conversions (removing 'noexcept') including removal of
1828     // 'noreturn' (Clang extension).
1829     SCS.Third = ICK_Function_Conversion;
1830   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1831                                          ObjCLifetimeConversion)) {
1832     SCS.Third = ICK_Qualification;
1833     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1834     FromType = ToType;
1835   } else {
1836     // No conversion required
1837     SCS.Third = ICK_Identity;
1838   }
1839 
1840   // C++ [over.best.ics]p6:
1841   //   [...] Any difference in top-level cv-qualification is
1842   //   subsumed by the initialization itself and does not constitute
1843   //   a conversion. [...]
1844   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1845   QualType CanonTo = S.Context.getCanonicalType(ToType);
1846   if (CanonFrom.getLocalUnqualifiedType()
1847                                      == CanonTo.getLocalUnqualifiedType() &&
1848       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1849     FromType = ToType;
1850     CanonFrom = CanonTo;
1851   }
1852 
1853   SCS.setToType(2, FromType);
1854 
1855   if (CanonFrom == CanonTo)
1856     return true;
1857 
1858   // If we have not converted the argument type to the parameter type,
1859   // this is a bad conversion sequence, unless we're resolving an overload in C.
1860   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1861     return false;
1862 
1863   ExprResult ER = ExprResult{From};
1864   Sema::AssignConvertType Conv =
1865       S.CheckSingleAssignmentConstraints(ToType, ER,
1866                                          /*Diagnose=*/false,
1867                                          /*DiagnoseCFAudited=*/false,
1868                                          /*ConvertRHS=*/false);
1869   ImplicitConversionKind SecondConv;
1870   switch (Conv) {
1871   case Sema::Compatible:
1872     SecondConv = ICK_C_Only_Conversion;
1873     break;
1874   // For our purposes, discarding qualifiers is just as bad as using an
1875   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1876   // qualifiers, as well.
1877   case Sema::CompatiblePointerDiscardsQualifiers:
1878   case Sema::IncompatiblePointer:
1879   case Sema::IncompatiblePointerSign:
1880     SecondConv = ICK_Incompatible_Pointer_Conversion;
1881     break;
1882   default:
1883     return false;
1884   }
1885 
1886   // First can only be an lvalue conversion, so we pretend that this was the
1887   // second conversion. First should already be valid from earlier in the
1888   // function.
1889   SCS.Second = SecondConv;
1890   SCS.setToType(1, ToType);
1891 
1892   // Third is Identity, because Second should rank us worse than any other
1893   // conversion. This could also be ICK_Qualification, but it's simpler to just
1894   // lump everything in with the second conversion, and we don't gain anything
1895   // from making this ICK_Qualification.
1896   SCS.Third = ICK_Identity;
1897   SCS.setToType(2, ToType);
1898   return true;
1899 }
1900 
1901 static bool
1902 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1903                                      QualType &ToType,
1904                                      bool InOverloadResolution,
1905                                      StandardConversionSequence &SCS,
1906                                      bool CStyle) {
1907 
1908   const RecordType *UT = ToType->getAsUnionType();
1909   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1910     return false;
1911   // The field to initialize within the transparent union.
1912   RecordDecl *UD = UT->getDecl();
1913   // It's compatible if the expression matches any of the fields.
1914   for (const auto *it : UD->fields()) {
1915     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1916                              CStyle, /*ObjCWritebackConversion=*/false)) {
1917       ToType = it->getType();
1918       return true;
1919     }
1920   }
1921   return false;
1922 }
1923 
1924 /// IsIntegralPromotion - Determines whether the conversion from the
1925 /// expression From (whose potentially-adjusted type is FromType) to
1926 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1927 /// sets PromotedType to the promoted type.
1928 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1929   const BuiltinType *To = ToType->getAs<BuiltinType>();
1930   // All integers are built-in.
1931   if (!To) {
1932     return false;
1933   }
1934 
1935   // An rvalue of type char, signed char, unsigned char, short int, or
1936   // unsigned short int can be converted to an rvalue of type int if
1937   // int can represent all the values of the source type; otherwise,
1938   // the source rvalue can be converted to an rvalue of type unsigned
1939   // int (C++ 4.5p1).
1940   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1941       !FromType->isEnumeralType()) {
1942     if (// We can promote any signed, promotable integer type to an int
1943         (FromType->isSignedIntegerType() ||
1944          // We can promote any unsigned integer type whose size is
1945          // less than int to an int.
1946          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1947       return To->getKind() == BuiltinType::Int;
1948     }
1949 
1950     return To->getKind() == BuiltinType::UInt;
1951   }
1952 
1953   // C++11 [conv.prom]p3:
1954   //   A prvalue of an unscoped enumeration type whose underlying type is not
1955   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1956   //   following types that can represent all the values of the enumeration
1957   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1958   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1959   //   long long int. If none of the types in that list can represent all the
1960   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1961   //   type can be converted to an rvalue a prvalue of the extended integer type
1962   //   with lowest integer conversion rank (4.13) greater than the rank of long
1963   //   long in which all the values of the enumeration can be represented. If
1964   //   there are two such extended types, the signed one is chosen.
1965   // C++11 [conv.prom]p4:
1966   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1967   //   can be converted to a prvalue of its underlying type. Moreover, if
1968   //   integral promotion can be applied to its underlying type, a prvalue of an
1969   //   unscoped enumeration type whose underlying type is fixed can also be
1970   //   converted to a prvalue of the promoted underlying type.
1971   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1972     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1973     // provided for a scoped enumeration.
1974     if (FromEnumType->getDecl()->isScoped())
1975       return false;
1976 
1977     // We can perform an integral promotion to the underlying type of the enum,
1978     // even if that's not the promoted type. Note that the check for promoting
1979     // the underlying type is based on the type alone, and does not consider
1980     // the bitfield-ness of the actual source expression.
1981     if (FromEnumType->getDecl()->isFixed()) {
1982       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1983       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1984              IsIntegralPromotion(nullptr, Underlying, ToType);
1985     }
1986 
1987     // We have already pre-calculated the promotion type, so this is trivial.
1988     if (ToType->isIntegerType() &&
1989         isCompleteType(From->getLocStart(), FromType))
1990       return Context.hasSameUnqualifiedType(
1991           ToType, FromEnumType->getDecl()->getPromotionType());
1992   }
1993 
1994   // C++0x [conv.prom]p2:
1995   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1996   //   to an rvalue a prvalue of the first of the following types that can
1997   //   represent all the values of its underlying type: int, unsigned int,
1998   //   long int, unsigned long int, long long int, or unsigned long long int.
1999   //   If none of the types in that list can represent all the values of its
2000   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2001   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2002   //   type.
2003   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2004       ToType->isIntegerType()) {
2005     // Determine whether the type we're converting from is signed or
2006     // unsigned.
2007     bool FromIsSigned = FromType->isSignedIntegerType();
2008     uint64_t FromSize = Context.getTypeSize(FromType);
2009 
2010     // The types we'll try to promote to, in the appropriate
2011     // order. Try each of these types.
2012     QualType PromoteTypes[6] = {
2013       Context.IntTy, Context.UnsignedIntTy,
2014       Context.LongTy, Context.UnsignedLongTy ,
2015       Context.LongLongTy, Context.UnsignedLongLongTy
2016     };
2017     for (int Idx = 0; Idx < 6; ++Idx) {
2018       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2019       if (FromSize < ToSize ||
2020           (FromSize == ToSize &&
2021            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2022         // We found the type that we can promote to. If this is the
2023         // type we wanted, we have a promotion. Otherwise, no
2024         // promotion.
2025         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2026       }
2027     }
2028   }
2029 
2030   // An rvalue for an integral bit-field (9.6) can be converted to an
2031   // rvalue of type int if int can represent all the values of the
2032   // bit-field; otherwise, it can be converted to unsigned int if
2033   // unsigned int can represent all the values of the bit-field. If
2034   // the bit-field is larger yet, no integral promotion applies to
2035   // it. If the bit-field has an enumerated type, it is treated as any
2036   // other value of that type for promotion purposes (C++ 4.5p3).
2037   // FIXME: We should delay checking of bit-fields until we actually perform the
2038   // conversion.
2039   if (From) {
2040     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2041       llvm::APSInt BitWidth;
2042       if (FromType->isIntegralType(Context) &&
2043           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2044         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2045         ToSize = Context.getTypeSize(ToType);
2046 
2047         // Are we promoting to an int from a bitfield that fits in an int?
2048         if (BitWidth < ToSize ||
2049             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2050           return To->getKind() == BuiltinType::Int;
2051         }
2052 
2053         // Are we promoting to an unsigned int from an unsigned bitfield
2054         // that fits into an unsigned int?
2055         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2056           return To->getKind() == BuiltinType::UInt;
2057         }
2058 
2059         return false;
2060       }
2061     }
2062   }
2063 
2064   // An rvalue of type bool can be converted to an rvalue of type int,
2065   // with false becoming zero and true becoming one (C++ 4.5p4).
2066   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2067     return true;
2068   }
2069 
2070   return false;
2071 }
2072 
2073 /// IsFloatingPointPromotion - Determines whether the conversion from
2074 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2075 /// returns true and sets PromotedType to the promoted type.
2076 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2077   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2078     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2079       /// An rvalue of type float can be converted to an rvalue of type
2080       /// double. (C++ 4.6p1).
2081       if (FromBuiltin->getKind() == BuiltinType::Float &&
2082           ToBuiltin->getKind() == BuiltinType::Double)
2083         return true;
2084 
2085       // C99 6.3.1.5p1:
2086       //   When a float is promoted to double or long double, or a
2087       //   double is promoted to long double [...].
2088       if (!getLangOpts().CPlusPlus &&
2089           (FromBuiltin->getKind() == BuiltinType::Float ||
2090            FromBuiltin->getKind() == BuiltinType::Double) &&
2091           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2092            ToBuiltin->getKind() == BuiltinType::Float128))
2093         return true;
2094 
2095       // Half can be promoted to float.
2096       if (!getLangOpts().NativeHalfType &&
2097            FromBuiltin->getKind() == BuiltinType::Half &&
2098           ToBuiltin->getKind() == BuiltinType::Float)
2099         return true;
2100     }
2101 
2102   return false;
2103 }
2104 
2105 /// \brief Determine if a conversion is a complex promotion.
2106 ///
2107 /// A complex promotion is defined as a complex -> complex conversion
2108 /// where the conversion between the underlying real types is a
2109 /// floating-point or integral promotion.
2110 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2111   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2112   if (!FromComplex)
2113     return false;
2114 
2115   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2116   if (!ToComplex)
2117     return false;
2118 
2119   return IsFloatingPointPromotion(FromComplex->getElementType(),
2120                                   ToComplex->getElementType()) ||
2121     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2122                         ToComplex->getElementType());
2123 }
2124 
2125 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2126 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2127 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2128 /// if non-empty, will be a pointer to ToType that may or may not have
2129 /// the right set of qualifiers on its pointee.
2130 ///
2131 static QualType
2132 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2133                                    QualType ToPointee, QualType ToType,
2134                                    ASTContext &Context,
2135                                    bool StripObjCLifetime = false) {
2136   assert((FromPtr->getTypeClass() == Type::Pointer ||
2137           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2138          "Invalid similarly-qualified pointer type");
2139 
2140   /// Conversions to 'id' subsume cv-qualifier conversions.
2141   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2142     return ToType.getUnqualifiedType();
2143 
2144   QualType CanonFromPointee
2145     = Context.getCanonicalType(FromPtr->getPointeeType());
2146   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2147   Qualifiers Quals = CanonFromPointee.getQualifiers();
2148 
2149   if (StripObjCLifetime)
2150     Quals.removeObjCLifetime();
2151 
2152   // Exact qualifier match -> return the pointer type we're converting to.
2153   if (CanonToPointee.getLocalQualifiers() == Quals) {
2154     // ToType is exactly what we need. Return it.
2155     if (!ToType.isNull())
2156       return ToType.getUnqualifiedType();
2157 
2158     // Build a pointer to ToPointee. It has the right qualifiers
2159     // already.
2160     if (isa<ObjCObjectPointerType>(ToType))
2161       return Context.getObjCObjectPointerType(ToPointee);
2162     return Context.getPointerType(ToPointee);
2163   }
2164 
2165   // Just build a canonical type that has the right qualifiers.
2166   QualType QualifiedCanonToPointee
2167     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2168 
2169   if (isa<ObjCObjectPointerType>(ToType))
2170     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2171   return Context.getPointerType(QualifiedCanonToPointee);
2172 }
2173 
2174 static bool isNullPointerConstantForConversion(Expr *Expr,
2175                                                bool InOverloadResolution,
2176                                                ASTContext &Context) {
2177   // Handle value-dependent integral null pointer constants correctly.
2178   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2179   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2180       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2181     return !InOverloadResolution;
2182 
2183   return Expr->isNullPointerConstant(Context,
2184                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2185                                         : Expr::NPC_ValueDependentIsNull);
2186 }
2187 
2188 /// IsPointerConversion - Determines whether the conversion of the
2189 /// expression From, which has the (possibly adjusted) type FromType,
2190 /// can be converted to the type ToType via a pointer conversion (C++
2191 /// 4.10). If so, returns true and places the converted type (that
2192 /// might differ from ToType in its cv-qualifiers at some level) into
2193 /// ConvertedType.
2194 ///
2195 /// This routine also supports conversions to and from block pointers
2196 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2197 /// pointers to interfaces. FIXME: Once we've determined the
2198 /// appropriate overloading rules for Objective-C, we may want to
2199 /// split the Objective-C checks into a different routine; however,
2200 /// GCC seems to consider all of these conversions to be pointer
2201 /// conversions, so for now they live here. IncompatibleObjC will be
2202 /// set if the conversion is an allowed Objective-C conversion that
2203 /// should result in a warning.
2204 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2205                                bool InOverloadResolution,
2206                                QualType& ConvertedType,
2207                                bool &IncompatibleObjC) {
2208   IncompatibleObjC = false;
2209   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2210                               IncompatibleObjC))
2211     return true;
2212 
2213   // Conversion from a null pointer constant to any Objective-C pointer type.
2214   if (ToType->isObjCObjectPointerType() &&
2215       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2216     ConvertedType = ToType;
2217     return true;
2218   }
2219 
2220   // Blocks: Block pointers can be converted to void*.
2221   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2222       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2223     ConvertedType = ToType;
2224     return true;
2225   }
2226   // Blocks: A null pointer constant can be converted to a block
2227   // pointer type.
2228   if (ToType->isBlockPointerType() &&
2229       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2230     ConvertedType = ToType;
2231     return true;
2232   }
2233 
2234   // If the left-hand-side is nullptr_t, the right side can be a null
2235   // pointer constant.
2236   if (ToType->isNullPtrType() &&
2237       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2238     ConvertedType = ToType;
2239     return true;
2240   }
2241 
2242   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2243   if (!ToTypePtr)
2244     return false;
2245 
2246   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2247   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2248     ConvertedType = ToType;
2249     return true;
2250   }
2251 
2252   // Beyond this point, both types need to be pointers
2253   // , including objective-c pointers.
2254   QualType ToPointeeType = ToTypePtr->getPointeeType();
2255   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2256       !getLangOpts().ObjCAutoRefCount) {
2257     ConvertedType = BuildSimilarlyQualifiedPointerType(
2258                                       FromType->getAs<ObjCObjectPointerType>(),
2259                                                        ToPointeeType,
2260                                                        ToType, Context);
2261     return true;
2262   }
2263   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2264   if (!FromTypePtr)
2265     return false;
2266 
2267   QualType FromPointeeType = FromTypePtr->getPointeeType();
2268 
2269   // If the unqualified pointee types are the same, this can't be a
2270   // pointer conversion, so don't do all of the work below.
2271   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2272     return false;
2273 
2274   // An rvalue of type "pointer to cv T," where T is an object type,
2275   // can be converted to an rvalue of type "pointer to cv void" (C++
2276   // 4.10p2).
2277   if (FromPointeeType->isIncompleteOrObjectType() &&
2278       ToPointeeType->isVoidType()) {
2279     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2280                                                        ToPointeeType,
2281                                                        ToType, Context,
2282                                                    /*StripObjCLifetime=*/true);
2283     return true;
2284   }
2285 
2286   // MSVC allows implicit function to void* type conversion.
2287   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2288       ToPointeeType->isVoidType()) {
2289     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2290                                                        ToPointeeType,
2291                                                        ToType, Context);
2292     return true;
2293   }
2294 
2295   // When we're overloading in C, we allow a special kind of pointer
2296   // conversion for compatible-but-not-identical pointee types.
2297   if (!getLangOpts().CPlusPlus &&
2298       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2299     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2300                                                        ToPointeeType,
2301                                                        ToType, Context);
2302     return true;
2303   }
2304 
2305   // C++ [conv.ptr]p3:
2306   //
2307   //   An rvalue of type "pointer to cv D," where D is a class type,
2308   //   can be converted to an rvalue of type "pointer to cv B," where
2309   //   B is a base class (clause 10) of D. If B is an inaccessible
2310   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2311   //   necessitates this conversion is ill-formed. The result of the
2312   //   conversion is a pointer to the base class sub-object of the
2313   //   derived class object. The null pointer value is converted to
2314   //   the null pointer value of the destination type.
2315   //
2316   // Note that we do not check for ambiguity or inaccessibility
2317   // here. That is handled by CheckPointerConversion.
2318   if (getLangOpts().CPlusPlus &&
2319       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2320       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2321       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2322     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2323                                                        ToPointeeType,
2324                                                        ToType, Context);
2325     return true;
2326   }
2327 
2328   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2329       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2330     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331                                                        ToPointeeType,
2332                                                        ToType, Context);
2333     return true;
2334   }
2335 
2336   return false;
2337 }
2338 
2339 /// \brief Adopt the given qualifiers for the given type.
2340 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2341   Qualifiers TQs = T.getQualifiers();
2342 
2343   // Check whether qualifiers already match.
2344   if (TQs == Qs)
2345     return T;
2346 
2347   if (Qs.compatiblyIncludes(TQs))
2348     return Context.getQualifiedType(T, Qs);
2349 
2350   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2351 }
2352 
2353 /// isObjCPointerConversion - Determines whether this is an
2354 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2355 /// with the same arguments and return values.
2356 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2357                                    QualType& ConvertedType,
2358                                    bool &IncompatibleObjC) {
2359   if (!getLangOpts().ObjC1)
2360     return false;
2361 
2362   // The set of qualifiers on the type we're converting from.
2363   Qualifiers FromQualifiers = FromType.getQualifiers();
2364 
2365   // First, we handle all conversions on ObjC object pointer types.
2366   const ObjCObjectPointerType* ToObjCPtr =
2367     ToType->getAs<ObjCObjectPointerType>();
2368   const ObjCObjectPointerType *FromObjCPtr =
2369     FromType->getAs<ObjCObjectPointerType>();
2370 
2371   if (ToObjCPtr && FromObjCPtr) {
2372     // If the pointee types are the same (ignoring qualifications),
2373     // then this is not a pointer conversion.
2374     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2375                                        FromObjCPtr->getPointeeType()))
2376       return false;
2377 
2378     // Conversion between Objective-C pointers.
2379     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2380       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2381       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2382       if (getLangOpts().CPlusPlus && LHS && RHS &&
2383           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2384                                                 FromObjCPtr->getPointeeType()))
2385         return false;
2386       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2387                                                    ToObjCPtr->getPointeeType(),
2388                                                          ToType, Context);
2389       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2390       return true;
2391     }
2392 
2393     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2394       // Okay: this is some kind of implicit downcast of Objective-C
2395       // interfaces, which is permitted. However, we're going to
2396       // complain about it.
2397       IncompatibleObjC = true;
2398       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2399                                                    ToObjCPtr->getPointeeType(),
2400                                                          ToType, Context);
2401       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2402       return true;
2403     }
2404   }
2405   // Beyond this point, both types need to be C pointers or block pointers.
2406   QualType ToPointeeType;
2407   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2408     ToPointeeType = ToCPtr->getPointeeType();
2409   else if (const BlockPointerType *ToBlockPtr =
2410             ToType->getAs<BlockPointerType>()) {
2411     // Objective C++: We're able to convert from a pointer to any object
2412     // to a block pointer type.
2413     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2414       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2415       return true;
2416     }
2417     ToPointeeType = ToBlockPtr->getPointeeType();
2418   }
2419   else if (FromType->getAs<BlockPointerType>() &&
2420            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2421     // Objective C++: We're able to convert from a block pointer type to a
2422     // pointer to any object.
2423     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2424     return true;
2425   }
2426   else
2427     return false;
2428 
2429   QualType FromPointeeType;
2430   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2431     FromPointeeType = FromCPtr->getPointeeType();
2432   else if (const BlockPointerType *FromBlockPtr =
2433            FromType->getAs<BlockPointerType>())
2434     FromPointeeType = FromBlockPtr->getPointeeType();
2435   else
2436     return false;
2437 
2438   // If we have pointers to pointers, recursively check whether this
2439   // is an Objective-C conversion.
2440   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2441       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2442                               IncompatibleObjC)) {
2443     // We always complain about this conversion.
2444     IncompatibleObjC = true;
2445     ConvertedType = Context.getPointerType(ConvertedType);
2446     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2447     return true;
2448   }
2449   // Allow conversion of pointee being objective-c pointer to another one;
2450   // as in I* to id.
2451   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2452       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2453       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2454                               IncompatibleObjC)) {
2455 
2456     ConvertedType = Context.getPointerType(ConvertedType);
2457     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2458     return true;
2459   }
2460 
2461   // If we have pointers to functions or blocks, check whether the only
2462   // differences in the argument and result types are in Objective-C
2463   // pointer conversions. If so, we permit the conversion (but
2464   // complain about it).
2465   const FunctionProtoType *FromFunctionType
2466     = FromPointeeType->getAs<FunctionProtoType>();
2467   const FunctionProtoType *ToFunctionType
2468     = ToPointeeType->getAs<FunctionProtoType>();
2469   if (FromFunctionType && ToFunctionType) {
2470     // If the function types are exactly the same, this isn't an
2471     // Objective-C pointer conversion.
2472     if (Context.getCanonicalType(FromPointeeType)
2473           == Context.getCanonicalType(ToPointeeType))
2474       return false;
2475 
2476     // Perform the quick checks that will tell us whether these
2477     // function types are obviously different.
2478     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2479         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2480         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2481       return false;
2482 
2483     bool HasObjCConversion = false;
2484     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2485         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2486       // Okay, the types match exactly. Nothing to do.
2487     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2488                                        ToFunctionType->getReturnType(),
2489                                        ConvertedType, IncompatibleObjC)) {
2490       // Okay, we have an Objective-C pointer conversion.
2491       HasObjCConversion = true;
2492     } else {
2493       // Function types are too different. Abort.
2494       return false;
2495     }
2496 
2497     // Check argument types.
2498     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2499          ArgIdx != NumArgs; ++ArgIdx) {
2500       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2501       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2502       if (Context.getCanonicalType(FromArgType)
2503             == Context.getCanonicalType(ToArgType)) {
2504         // Okay, the types match exactly. Nothing to do.
2505       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2506                                          ConvertedType, IncompatibleObjC)) {
2507         // Okay, we have an Objective-C pointer conversion.
2508         HasObjCConversion = true;
2509       } else {
2510         // Argument types are too different. Abort.
2511         return false;
2512       }
2513     }
2514 
2515     if (HasObjCConversion) {
2516       // We had an Objective-C conversion. Allow this pointer
2517       // conversion, but complain about it.
2518       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2519       IncompatibleObjC = true;
2520       return true;
2521     }
2522   }
2523 
2524   return false;
2525 }
2526 
2527 /// \brief Determine whether this is an Objective-C writeback conversion,
2528 /// used for parameter passing when performing automatic reference counting.
2529 ///
2530 /// \param FromType The type we're converting form.
2531 ///
2532 /// \param ToType The type we're converting to.
2533 ///
2534 /// \param ConvertedType The type that will be produced after applying
2535 /// this conversion.
2536 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2537                                      QualType &ConvertedType) {
2538   if (!getLangOpts().ObjCAutoRefCount ||
2539       Context.hasSameUnqualifiedType(FromType, ToType))
2540     return false;
2541 
2542   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2543   QualType ToPointee;
2544   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2545     ToPointee = ToPointer->getPointeeType();
2546   else
2547     return false;
2548 
2549   Qualifiers ToQuals = ToPointee.getQualifiers();
2550   if (!ToPointee->isObjCLifetimeType() ||
2551       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2552       !ToQuals.withoutObjCLifetime().empty())
2553     return false;
2554 
2555   // Argument must be a pointer to __strong to __weak.
2556   QualType FromPointee;
2557   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2558     FromPointee = FromPointer->getPointeeType();
2559   else
2560     return false;
2561 
2562   Qualifiers FromQuals = FromPointee.getQualifiers();
2563   if (!FromPointee->isObjCLifetimeType() ||
2564       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2565        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2566     return false;
2567 
2568   // Make sure that we have compatible qualifiers.
2569   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2570   if (!ToQuals.compatiblyIncludes(FromQuals))
2571     return false;
2572 
2573   // Remove qualifiers from the pointee type we're converting from; they
2574   // aren't used in the compatibility check belong, and we'll be adding back
2575   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2576   FromPointee = FromPointee.getUnqualifiedType();
2577 
2578   // The unqualified form of the pointee types must be compatible.
2579   ToPointee = ToPointee.getUnqualifiedType();
2580   bool IncompatibleObjC;
2581   if (Context.typesAreCompatible(FromPointee, ToPointee))
2582     FromPointee = ToPointee;
2583   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2584                                     IncompatibleObjC))
2585     return false;
2586 
2587   /// \brief Construct the type we're converting to, which is a pointer to
2588   /// __autoreleasing pointee.
2589   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2590   ConvertedType = Context.getPointerType(FromPointee);
2591   return true;
2592 }
2593 
2594 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2595                                     QualType& ConvertedType) {
2596   QualType ToPointeeType;
2597   if (const BlockPointerType *ToBlockPtr =
2598         ToType->getAs<BlockPointerType>())
2599     ToPointeeType = ToBlockPtr->getPointeeType();
2600   else
2601     return false;
2602 
2603   QualType FromPointeeType;
2604   if (const BlockPointerType *FromBlockPtr =
2605       FromType->getAs<BlockPointerType>())
2606     FromPointeeType = FromBlockPtr->getPointeeType();
2607   else
2608     return false;
2609   // We have pointer to blocks, check whether the only
2610   // differences in the argument and result types are in Objective-C
2611   // pointer conversions. If so, we permit the conversion.
2612 
2613   const FunctionProtoType *FromFunctionType
2614     = FromPointeeType->getAs<FunctionProtoType>();
2615   const FunctionProtoType *ToFunctionType
2616     = ToPointeeType->getAs<FunctionProtoType>();
2617 
2618   if (!FromFunctionType || !ToFunctionType)
2619     return false;
2620 
2621   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2622     return true;
2623 
2624   // Perform the quick checks that will tell us whether these
2625   // function types are obviously different.
2626   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2627       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2628     return false;
2629 
2630   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2631   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2632   if (FromEInfo != ToEInfo)
2633     return false;
2634 
2635   bool IncompatibleObjC = false;
2636   if (Context.hasSameType(FromFunctionType->getReturnType(),
2637                           ToFunctionType->getReturnType())) {
2638     // Okay, the types match exactly. Nothing to do.
2639   } else {
2640     QualType RHS = FromFunctionType->getReturnType();
2641     QualType LHS = ToFunctionType->getReturnType();
2642     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2643         !RHS.hasQualifiers() && LHS.hasQualifiers())
2644        LHS = LHS.getUnqualifiedType();
2645 
2646      if (Context.hasSameType(RHS,LHS)) {
2647        // OK exact match.
2648      } else if (isObjCPointerConversion(RHS, LHS,
2649                                         ConvertedType, IncompatibleObjC)) {
2650      if (IncompatibleObjC)
2651        return false;
2652      // Okay, we have an Objective-C pointer conversion.
2653      }
2654      else
2655        return false;
2656    }
2657 
2658    // Check argument types.
2659    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2660         ArgIdx != NumArgs; ++ArgIdx) {
2661      IncompatibleObjC = false;
2662      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2663      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2664      if (Context.hasSameType(FromArgType, ToArgType)) {
2665        // Okay, the types match exactly. Nothing to do.
2666      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2667                                         ConvertedType, IncompatibleObjC)) {
2668        if (IncompatibleObjC)
2669          return false;
2670        // Okay, we have an Objective-C pointer conversion.
2671      } else
2672        // Argument types are too different. Abort.
2673        return false;
2674    }
2675    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2676                                                         ToFunctionType))
2677      return false;
2678 
2679    ConvertedType = ToType;
2680    return true;
2681 }
2682 
2683 enum {
2684   ft_default,
2685   ft_different_class,
2686   ft_parameter_arity,
2687   ft_parameter_mismatch,
2688   ft_return_type,
2689   ft_qualifer_mismatch,
2690   ft_noexcept
2691 };
2692 
2693 /// Attempts to get the FunctionProtoType from a Type. Handles
2694 /// MemberFunctionPointers properly.
2695 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2696   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2697     return FPT;
2698 
2699   if (auto *MPT = FromType->getAs<MemberPointerType>())
2700     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2701 
2702   return nullptr;
2703 }
2704 
2705 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2706 /// function types.  Catches different number of parameter, mismatch in
2707 /// parameter types, and different return types.
2708 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2709                                       QualType FromType, QualType ToType) {
2710   // If either type is not valid, include no extra info.
2711   if (FromType.isNull() || ToType.isNull()) {
2712     PDiag << ft_default;
2713     return;
2714   }
2715 
2716   // Get the function type from the pointers.
2717   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2718     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2719                             *ToMember = ToType->getAs<MemberPointerType>();
2720     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2721       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2722             << QualType(FromMember->getClass(), 0);
2723       return;
2724     }
2725     FromType = FromMember->getPointeeType();
2726     ToType = ToMember->getPointeeType();
2727   }
2728 
2729   if (FromType->isPointerType())
2730     FromType = FromType->getPointeeType();
2731   if (ToType->isPointerType())
2732     ToType = ToType->getPointeeType();
2733 
2734   // Remove references.
2735   FromType = FromType.getNonReferenceType();
2736   ToType = ToType.getNonReferenceType();
2737 
2738   // Don't print extra info for non-specialized template functions.
2739   if (FromType->isInstantiationDependentType() &&
2740       !FromType->getAs<TemplateSpecializationType>()) {
2741     PDiag << ft_default;
2742     return;
2743   }
2744 
2745   // No extra info for same types.
2746   if (Context.hasSameType(FromType, ToType)) {
2747     PDiag << ft_default;
2748     return;
2749   }
2750 
2751   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2752                           *ToFunction = tryGetFunctionProtoType(ToType);
2753 
2754   // Both types need to be function types.
2755   if (!FromFunction || !ToFunction) {
2756     PDiag << ft_default;
2757     return;
2758   }
2759 
2760   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2761     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2762           << FromFunction->getNumParams();
2763     return;
2764   }
2765 
2766   // Handle different parameter types.
2767   unsigned ArgPos;
2768   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2769     PDiag << ft_parameter_mismatch << ArgPos + 1
2770           << ToFunction->getParamType(ArgPos)
2771           << FromFunction->getParamType(ArgPos);
2772     return;
2773   }
2774 
2775   // Handle different return type.
2776   if (!Context.hasSameType(FromFunction->getReturnType(),
2777                            ToFunction->getReturnType())) {
2778     PDiag << ft_return_type << ToFunction->getReturnType()
2779           << FromFunction->getReturnType();
2780     return;
2781   }
2782 
2783   unsigned FromQuals = FromFunction->getTypeQuals(),
2784            ToQuals = ToFunction->getTypeQuals();
2785   if (FromQuals != ToQuals) {
2786     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2787     return;
2788   }
2789 
2790   // Handle exception specification differences on canonical type (in C++17
2791   // onwards).
2792   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2793           ->isNothrow(Context) !=
2794       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2795           ->isNothrow(Context)) {
2796     PDiag << ft_noexcept;
2797     return;
2798   }
2799 
2800   // Unable to find a difference, so add no extra info.
2801   PDiag << ft_default;
2802 }
2803 
2804 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2805 /// for equality of their argument types. Caller has already checked that
2806 /// they have same number of arguments.  If the parameters are different,
2807 /// ArgPos will have the parameter index of the first different parameter.
2808 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2809                                       const FunctionProtoType *NewType,
2810                                       unsigned *ArgPos) {
2811   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2812                                               N = NewType->param_type_begin(),
2813                                               E = OldType->param_type_end();
2814        O && (O != E); ++O, ++N) {
2815     if (!Context.hasSameType(O->getUnqualifiedType(),
2816                              N->getUnqualifiedType())) {
2817       if (ArgPos)
2818         *ArgPos = O - OldType->param_type_begin();
2819       return false;
2820     }
2821   }
2822   return true;
2823 }
2824 
2825 /// CheckPointerConversion - Check the pointer conversion from the
2826 /// expression From to the type ToType. This routine checks for
2827 /// ambiguous or inaccessible derived-to-base pointer
2828 /// conversions for which IsPointerConversion has already returned
2829 /// true. It returns true and produces a diagnostic if there was an
2830 /// error, or returns false otherwise.
2831 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2832                                   CastKind &Kind,
2833                                   CXXCastPath& BasePath,
2834                                   bool IgnoreBaseAccess,
2835                                   bool Diagnose) {
2836   QualType FromType = From->getType();
2837   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2838 
2839   Kind = CK_BitCast;
2840 
2841   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2842       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2843           Expr::NPCK_ZeroExpression) {
2844     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2845       DiagRuntimeBehavior(From->getExprLoc(), From,
2846                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2847                             << ToType << From->getSourceRange());
2848     else if (!isUnevaluatedContext())
2849       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2850         << ToType << From->getSourceRange();
2851   }
2852   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2853     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2854       QualType FromPointeeType = FromPtrType->getPointeeType(),
2855                ToPointeeType   = ToPtrType->getPointeeType();
2856 
2857       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2858           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2859         // We must have a derived-to-base conversion. Check an
2860         // ambiguous or inaccessible conversion.
2861         unsigned InaccessibleID = 0;
2862         unsigned AmbigiousID = 0;
2863         if (Diagnose) {
2864           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2865           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2866         }
2867         if (CheckDerivedToBaseConversion(
2868                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2869                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2870                 &BasePath, IgnoreBaseAccess))
2871           return true;
2872 
2873         // The conversion was successful.
2874         Kind = CK_DerivedToBase;
2875       }
2876 
2877       if (Diagnose && !IsCStyleOrFunctionalCast &&
2878           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2879         assert(getLangOpts().MSVCCompat &&
2880                "this should only be possible with MSVCCompat!");
2881         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2882             << From->getSourceRange();
2883       }
2884     }
2885   } else if (const ObjCObjectPointerType *ToPtrType =
2886                ToType->getAs<ObjCObjectPointerType>()) {
2887     if (const ObjCObjectPointerType *FromPtrType =
2888           FromType->getAs<ObjCObjectPointerType>()) {
2889       // Objective-C++ conversions are always okay.
2890       // FIXME: We should have a different class of conversions for the
2891       // Objective-C++ implicit conversions.
2892       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2893         return false;
2894     } else if (FromType->isBlockPointerType()) {
2895       Kind = CK_BlockPointerToObjCPointerCast;
2896     } else {
2897       Kind = CK_CPointerToObjCPointerCast;
2898     }
2899   } else if (ToType->isBlockPointerType()) {
2900     if (!FromType->isBlockPointerType())
2901       Kind = CK_AnyPointerToBlockPointerCast;
2902   }
2903 
2904   // We shouldn't fall into this case unless it's valid for other
2905   // reasons.
2906   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2907     Kind = CK_NullToPointer;
2908 
2909   return false;
2910 }
2911 
2912 /// IsMemberPointerConversion - Determines whether the conversion of the
2913 /// expression From, which has the (possibly adjusted) type FromType, can be
2914 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2915 /// If so, returns true and places the converted type (that might differ from
2916 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2917 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2918                                      QualType ToType,
2919                                      bool InOverloadResolution,
2920                                      QualType &ConvertedType) {
2921   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2922   if (!ToTypePtr)
2923     return false;
2924 
2925   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2926   if (From->isNullPointerConstant(Context,
2927                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2928                                         : Expr::NPC_ValueDependentIsNull)) {
2929     ConvertedType = ToType;
2930     return true;
2931   }
2932 
2933   // Otherwise, both types have to be member pointers.
2934   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2935   if (!FromTypePtr)
2936     return false;
2937 
2938   // A pointer to member of B can be converted to a pointer to member of D,
2939   // where D is derived from B (C++ 4.11p2).
2940   QualType FromClass(FromTypePtr->getClass(), 0);
2941   QualType ToClass(ToTypePtr->getClass(), 0);
2942 
2943   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2944       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2945     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2946                                                  ToClass.getTypePtr());
2947     return true;
2948   }
2949 
2950   return false;
2951 }
2952 
2953 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2954 /// expression From to the type ToType. This routine checks for ambiguous or
2955 /// virtual or inaccessible base-to-derived member pointer conversions
2956 /// for which IsMemberPointerConversion has already returned true. It returns
2957 /// true and produces a diagnostic if there was an error, or returns false
2958 /// otherwise.
2959 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2960                                         CastKind &Kind,
2961                                         CXXCastPath &BasePath,
2962                                         bool IgnoreBaseAccess) {
2963   QualType FromType = From->getType();
2964   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2965   if (!FromPtrType) {
2966     // This must be a null pointer to member pointer conversion
2967     assert(From->isNullPointerConstant(Context,
2968                                        Expr::NPC_ValueDependentIsNull) &&
2969            "Expr must be null pointer constant!");
2970     Kind = CK_NullToMemberPointer;
2971     return false;
2972   }
2973 
2974   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2975   assert(ToPtrType && "No member pointer cast has a target type "
2976                       "that is not a member pointer.");
2977 
2978   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2979   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2980 
2981   // FIXME: What about dependent types?
2982   assert(FromClass->isRecordType() && "Pointer into non-class.");
2983   assert(ToClass->isRecordType() && "Pointer into non-class.");
2984 
2985   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2986                      /*DetectVirtual=*/true);
2987   bool DerivationOkay =
2988       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2989   assert(DerivationOkay &&
2990          "Should not have been called if derivation isn't OK.");
2991   (void)DerivationOkay;
2992 
2993   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2994                                   getUnqualifiedType())) {
2995     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2996     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2997       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2998     return true;
2999   }
3000 
3001   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3002     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3003       << FromClass << ToClass << QualType(VBase, 0)
3004       << From->getSourceRange();
3005     return true;
3006   }
3007 
3008   if (!IgnoreBaseAccess)
3009     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3010                          Paths.front(),
3011                          diag::err_downcast_from_inaccessible_base);
3012 
3013   // Must be a base to derived member conversion.
3014   BuildBasePathArray(Paths, BasePath);
3015   Kind = CK_BaseToDerivedMemberPointer;
3016   return false;
3017 }
3018 
3019 /// Determine whether the lifetime conversion between the two given
3020 /// qualifiers sets is nontrivial.
3021 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3022                                                Qualifiers ToQuals) {
3023   // Converting anything to const __unsafe_unretained is trivial.
3024   if (ToQuals.hasConst() &&
3025       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3026     return false;
3027 
3028   return true;
3029 }
3030 
3031 /// IsQualificationConversion - Determines whether the conversion from
3032 /// an rvalue of type FromType to ToType is a qualification conversion
3033 /// (C++ 4.4).
3034 ///
3035 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3036 /// when the qualification conversion involves a change in the Objective-C
3037 /// object lifetime.
3038 bool
3039 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3040                                 bool CStyle, bool &ObjCLifetimeConversion) {
3041   FromType = Context.getCanonicalType(FromType);
3042   ToType = Context.getCanonicalType(ToType);
3043   ObjCLifetimeConversion = false;
3044 
3045   // If FromType and ToType are the same type, this is not a
3046   // qualification conversion.
3047   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3048     return false;
3049 
3050   // (C++ 4.4p4):
3051   //   A conversion can add cv-qualifiers at levels other than the first
3052   //   in multi-level pointers, subject to the following rules: [...]
3053   bool PreviousToQualsIncludeConst = true;
3054   bool UnwrappedAnyPointer = false;
3055   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3056     // Within each iteration of the loop, we check the qualifiers to
3057     // determine if this still looks like a qualification
3058     // conversion. Then, if all is well, we unwrap one more level of
3059     // pointers or pointers-to-members and do it all again
3060     // until there are no more pointers or pointers-to-members left to
3061     // unwrap.
3062     UnwrappedAnyPointer = true;
3063 
3064     Qualifiers FromQuals = FromType.getQualifiers();
3065     Qualifiers ToQuals = ToType.getQualifiers();
3066 
3067     // Ignore __unaligned qualifier if this type is void.
3068     if (ToType.getUnqualifiedType()->isVoidType())
3069       FromQuals.removeUnaligned();
3070 
3071     // Objective-C ARC:
3072     //   Check Objective-C lifetime conversions.
3073     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3074         UnwrappedAnyPointer) {
3075       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3076         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3077           ObjCLifetimeConversion = true;
3078         FromQuals.removeObjCLifetime();
3079         ToQuals.removeObjCLifetime();
3080       } else {
3081         // Qualification conversions cannot cast between different
3082         // Objective-C lifetime qualifiers.
3083         return false;
3084       }
3085     }
3086 
3087     // Allow addition/removal of GC attributes but not changing GC attributes.
3088     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3089         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3090       FromQuals.removeObjCGCAttr();
3091       ToQuals.removeObjCGCAttr();
3092     }
3093 
3094     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3095     //      2,j, and similarly for volatile.
3096     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3097       return false;
3098 
3099     //   -- if the cv 1,j and cv 2,j are different, then const is in
3100     //      every cv for 0 < k < j.
3101     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3102         && !PreviousToQualsIncludeConst)
3103       return false;
3104 
3105     // Keep track of whether all prior cv-qualifiers in the "to" type
3106     // include const.
3107     PreviousToQualsIncludeConst
3108       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3109   }
3110 
3111   // We are left with FromType and ToType being the pointee types
3112   // after unwrapping the original FromType and ToType the same number
3113   // of types. If we unwrapped any pointers, and if FromType and
3114   // ToType have the same unqualified type (since we checked
3115   // qualifiers above), then this is a qualification conversion.
3116   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3117 }
3118 
3119 /// \brief - Determine whether this is a conversion from a scalar type to an
3120 /// atomic type.
3121 ///
3122 /// If successful, updates \c SCS's second and third steps in the conversion
3123 /// sequence to finish the conversion.
3124 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3125                                 bool InOverloadResolution,
3126                                 StandardConversionSequence &SCS,
3127                                 bool CStyle) {
3128   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3129   if (!ToAtomic)
3130     return false;
3131 
3132   StandardConversionSequence InnerSCS;
3133   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3134                             InOverloadResolution, InnerSCS,
3135                             CStyle, /*AllowObjCWritebackConversion=*/false))
3136     return false;
3137 
3138   SCS.Second = InnerSCS.Second;
3139   SCS.setToType(1, InnerSCS.getToType(1));
3140   SCS.Third = InnerSCS.Third;
3141   SCS.QualificationIncludesObjCLifetime
3142     = InnerSCS.QualificationIncludesObjCLifetime;
3143   SCS.setToType(2, InnerSCS.getToType(2));
3144   return true;
3145 }
3146 
3147 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3148                                               CXXConstructorDecl *Constructor,
3149                                               QualType Type) {
3150   const FunctionProtoType *CtorType =
3151       Constructor->getType()->getAs<FunctionProtoType>();
3152   if (CtorType->getNumParams() > 0) {
3153     QualType FirstArg = CtorType->getParamType(0);
3154     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3155       return true;
3156   }
3157   return false;
3158 }
3159 
3160 static OverloadingResult
3161 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3162                                        CXXRecordDecl *To,
3163                                        UserDefinedConversionSequence &User,
3164                                        OverloadCandidateSet &CandidateSet,
3165                                        bool AllowExplicit) {
3166   for (auto *D : S.LookupConstructors(To)) {
3167     auto Info = getConstructorInfo(D);
3168     if (!Info)
3169       continue;
3170 
3171     bool Usable = !Info.Constructor->isInvalidDecl() &&
3172                   S.isInitListConstructor(Info.Constructor) &&
3173                   (AllowExplicit || !Info.Constructor->isExplicit());
3174     if (Usable) {
3175       // If the first argument is (a reference to) the target type,
3176       // suppress conversions.
3177       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3178           S.Context, Info.Constructor, ToType);
3179       if (Info.ConstructorTmpl)
3180         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3181                                        /*ExplicitArgs*/ nullptr, From,
3182                                        CandidateSet, SuppressUserConversions);
3183       else
3184         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3185                                CandidateSet, SuppressUserConversions);
3186     }
3187   }
3188 
3189   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3190 
3191   OverloadCandidateSet::iterator Best;
3192   switch (auto Result =
3193             CandidateSet.BestViableFunction(S, From->getLocStart(),
3194                                             Best, true)) {
3195   case OR_Deleted:
3196   case OR_Success: {
3197     // Record the standard conversion we used and the conversion function.
3198     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3199     QualType ThisType = Constructor->getThisType(S.Context);
3200     // Initializer lists don't have conversions as such.
3201     User.Before.setAsIdentityConversion();
3202     User.HadMultipleCandidates = HadMultipleCandidates;
3203     User.ConversionFunction = Constructor;
3204     User.FoundConversionFunction = Best->FoundDecl;
3205     User.After.setAsIdentityConversion();
3206     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3207     User.After.setAllToTypes(ToType);
3208     return Result;
3209   }
3210 
3211   case OR_No_Viable_Function:
3212     return OR_No_Viable_Function;
3213   case OR_Ambiguous:
3214     return OR_Ambiguous;
3215   }
3216 
3217   llvm_unreachable("Invalid OverloadResult!");
3218 }
3219 
3220 /// Determines whether there is a user-defined conversion sequence
3221 /// (C++ [over.ics.user]) that converts expression From to the type
3222 /// ToType. If such a conversion exists, User will contain the
3223 /// user-defined conversion sequence that performs such a conversion
3224 /// and this routine will return true. Otherwise, this routine returns
3225 /// false and User is unspecified.
3226 ///
3227 /// \param AllowExplicit  true if the conversion should consider C++0x
3228 /// "explicit" conversion functions as well as non-explicit conversion
3229 /// functions (C++0x [class.conv.fct]p2).
3230 ///
3231 /// \param AllowObjCConversionOnExplicit true if the conversion should
3232 /// allow an extra Objective-C pointer conversion on uses of explicit
3233 /// constructors. Requires \c AllowExplicit to also be set.
3234 static OverloadingResult
3235 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3236                         UserDefinedConversionSequence &User,
3237                         OverloadCandidateSet &CandidateSet,
3238                         bool AllowExplicit,
3239                         bool AllowObjCConversionOnExplicit) {
3240   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3241 
3242   // Whether we will only visit constructors.
3243   bool ConstructorsOnly = false;
3244 
3245   // If the type we are conversion to is a class type, enumerate its
3246   // constructors.
3247   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3248     // C++ [over.match.ctor]p1:
3249     //   When objects of class type are direct-initialized (8.5), or
3250     //   copy-initialized from an expression of the same or a
3251     //   derived class type (8.5), overload resolution selects the
3252     //   constructor. [...] For copy-initialization, the candidate
3253     //   functions are all the converting constructors (12.3.1) of
3254     //   that class. The argument list is the expression-list within
3255     //   the parentheses of the initializer.
3256     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3257         (From->getType()->getAs<RecordType>() &&
3258          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3259       ConstructorsOnly = true;
3260 
3261     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3262       // We're not going to find any constructors.
3263     } else if (CXXRecordDecl *ToRecordDecl
3264                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3265 
3266       Expr **Args = &From;
3267       unsigned NumArgs = 1;
3268       bool ListInitializing = false;
3269       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3270         // But first, see if there is an init-list-constructor that will work.
3271         OverloadingResult Result = IsInitializerListConstructorConversion(
3272             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3273         if (Result != OR_No_Viable_Function)
3274           return Result;
3275         // Never mind.
3276         CandidateSet.clear();
3277 
3278         // If we're list-initializing, we pass the individual elements as
3279         // arguments, not the entire list.
3280         Args = InitList->getInits();
3281         NumArgs = InitList->getNumInits();
3282         ListInitializing = true;
3283       }
3284 
3285       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3286         auto Info = getConstructorInfo(D);
3287         if (!Info)
3288           continue;
3289 
3290         bool Usable = !Info.Constructor->isInvalidDecl();
3291         if (ListInitializing)
3292           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3293         else
3294           Usable = Usable &&
3295                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3296         if (Usable) {
3297           bool SuppressUserConversions = !ConstructorsOnly;
3298           if (SuppressUserConversions && ListInitializing) {
3299             SuppressUserConversions = false;
3300             if (NumArgs == 1) {
3301               // If the first argument is (a reference to) the target type,
3302               // suppress conversions.
3303               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3304                   S.Context, Info.Constructor, ToType);
3305             }
3306           }
3307           if (Info.ConstructorTmpl)
3308             S.AddTemplateOverloadCandidate(
3309                 Info.ConstructorTmpl, Info.FoundDecl,
3310                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3311                 CandidateSet, SuppressUserConversions);
3312           else
3313             // Allow one user-defined conversion when user specifies a
3314             // From->ToType conversion via an static cast (c-style, etc).
3315             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3316                                    llvm::makeArrayRef(Args, NumArgs),
3317                                    CandidateSet, SuppressUserConversions);
3318         }
3319       }
3320     }
3321   }
3322 
3323   // Enumerate conversion functions, if we're allowed to.
3324   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3325   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3326     // No conversion functions from incomplete types.
3327   } else if (const RecordType *FromRecordType
3328                                    = From->getType()->getAs<RecordType>()) {
3329     if (CXXRecordDecl *FromRecordDecl
3330          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3331       // Add all of the conversion functions as candidates.
3332       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3333       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3334         DeclAccessPair FoundDecl = I.getPair();
3335         NamedDecl *D = FoundDecl.getDecl();
3336         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3337         if (isa<UsingShadowDecl>(D))
3338           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3339 
3340         CXXConversionDecl *Conv;
3341         FunctionTemplateDecl *ConvTemplate;
3342         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3343           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3344         else
3345           Conv = cast<CXXConversionDecl>(D);
3346 
3347         if (AllowExplicit || !Conv->isExplicit()) {
3348           if (ConvTemplate)
3349             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3350                                              ActingContext, From, ToType,
3351                                              CandidateSet,
3352                                              AllowObjCConversionOnExplicit);
3353           else
3354             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3355                                      From, ToType, CandidateSet,
3356                                      AllowObjCConversionOnExplicit);
3357         }
3358       }
3359     }
3360   }
3361 
3362   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3363 
3364   OverloadCandidateSet::iterator Best;
3365   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3366                                                         Best, true)) {
3367   case OR_Success:
3368   case OR_Deleted:
3369     // Record the standard conversion we used and the conversion function.
3370     if (CXXConstructorDecl *Constructor
3371           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3372       // C++ [over.ics.user]p1:
3373       //   If the user-defined conversion is specified by a
3374       //   constructor (12.3.1), the initial standard conversion
3375       //   sequence converts the source type to the type required by
3376       //   the argument of the constructor.
3377       //
3378       QualType ThisType = Constructor->getThisType(S.Context);
3379       if (isa<InitListExpr>(From)) {
3380         // Initializer lists don't have conversions as such.
3381         User.Before.setAsIdentityConversion();
3382       } else {
3383         if (Best->Conversions[0].isEllipsis())
3384           User.EllipsisConversion = true;
3385         else {
3386           User.Before = Best->Conversions[0].Standard;
3387           User.EllipsisConversion = false;
3388         }
3389       }
3390       User.HadMultipleCandidates = HadMultipleCandidates;
3391       User.ConversionFunction = Constructor;
3392       User.FoundConversionFunction = Best->FoundDecl;
3393       User.After.setAsIdentityConversion();
3394       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3395       User.After.setAllToTypes(ToType);
3396       return Result;
3397     }
3398     if (CXXConversionDecl *Conversion
3399                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3400       // C++ [over.ics.user]p1:
3401       //
3402       //   [...] If the user-defined conversion is specified by a
3403       //   conversion function (12.3.2), the initial standard
3404       //   conversion sequence converts the source type to the
3405       //   implicit object parameter of the conversion function.
3406       User.Before = Best->Conversions[0].Standard;
3407       User.HadMultipleCandidates = HadMultipleCandidates;
3408       User.ConversionFunction = Conversion;
3409       User.FoundConversionFunction = Best->FoundDecl;
3410       User.EllipsisConversion = false;
3411 
3412       // C++ [over.ics.user]p2:
3413       //   The second standard conversion sequence converts the
3414       //   result of the user-defined conversion to the target type
3415       //   for the sequence. Since an implicit conversion sequence
3416       //   is an initialization, the special rules for
3417       //   initialization by user-defined conversion apply when
3418       //   selecting the best user-defined conversion for a
3419       //   user-defined conversion sequence (see 13.3.3 and
3420       //   13.3.3.1).
3421       User.After = Best->FinalConversion;
3422       return Result;
3423     }
3424     llvm_unreachable("Not a constructor or conversion function?");
3425 
3426   case OR_No_Viable_Function:
3427     return OR_No_Viable_Function;
3428 
3429   case OR_Ambiguous:
3430     return OR_Ambiguous;
3431   }
3432 
3433   llvm_unreachable("Invalid OverloadResult!");
3434 }
3435 
3436 bool
3437 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3438   ImplicitConversionSequence ICS;
3439   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3440                                     OverloadCandidateSet::CSK_Normal);
3441   OverloadingResult OvResult =
3442     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3443                             CandidateSet, false, false);
3444   if (OvResult == OR_Ambiguous)
3445     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3446         << From->getType() << ToType << From->getSourceRange();
3447   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3448     if (!RequireCompleteType(From->getLocStart(), ToType,
3449                              diag::err_typecheck_nonviable_condition_incomplete,
3450                              From->getType(), From->getSourceRange()))
3451       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3452           << false << From->getType() << From->getSourceRange() << ToType;
3453   } else
3454     return false;
3455   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3456   return true;
3457 }
3458 
3459 /// \brief Compare the user-defined conversion functions or constructors
3460 /// of two user-defined conversion sequences to determine whether any ordering
3461 /// is possible.
3462 static ImplicitConversionSequence::CompareKind
3463 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3464                            FunctionDecl *Function2) {
3465   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3466     return ImplicitConversionSequence::Indistinguishable;
3467 
3468   // Objective-C++:
3469   //   If both conversion functions are implicitly-declared conversions from
3470   //   a lambda closure type to a function pointer and a block pointer,
3471   //   respectively, always prefer the conversion to a function pointer,
3472   //   because the function pointer is more lightweight and is more likely
3473   //   to keep code working.
3474   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3475   if (!Conv1)
3476     return ImplicitConversionSequence::Indistinguishable;
3477 
3478   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3479   if (!Conv2)
3480     return ImplicitConversionSequence::Indistinguishable;
3481 
3482   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3483     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3484     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3485     if (Block1 != Block2)
3486       return Block1 ? ImplicitConversionSequence::Worse
3487                     : ImplicitConversionSequence::Better;
3488   }
3489 
3490   return ImplicitConversionSequence::Indistinguishable;
3491 }
3492 
3493 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3494     const ImplicitConversionSequence &ICS) {
3495   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3496          (ICS.isUserDefined() &&
3497           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3498 }
3499 
3500 /// CompareImplicitConversionSequences - Compare two implicit
3501 /// conversion sequences to determine whether one is better than the
3502 /// other or if they are indistinguishable (C++ 13.3.3.2).
3503 static ImplicitConversionSequence::CompareKind
3504 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3505                                    const ImplicitConversionSequence& ICS1,
3506                                    const ImplicitConversionSequence& ICS2)
3507 {
3508   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3509   // conversion sequences (as defined in 13.3.3.1)
3510   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3511   //      conversion sequence than a user-defined conversion sequence or
3512   //      an ellipsis conversion sequence, and
3513   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3514   //      conversion sequence than an ellipsis conversion sequence
3515   //      (13.3.3.1.3).
3516   //
3517   // C++0x [over.best.ics]p10:
3518   //   For the purpose of ranking implicit conversion sequences as
3519   //   described in 13.3.3.2, the ambiguous conversion sequence is
3520   //   treated as a user-defined sequence that is indistinguishable
3521   //   from any other user-defined conversion sequence.
3522 
3523   // String literal to 'char *' conversion has been deprecated in C++03. It has
3524   // been removed from C++11. We still accept this conversion, if it happens at
3525   // the best viable function. Otherwise, this conversion is considered worse
3526   // than ellipsis conversion. Consider this as an extension; this is not in the
3527   // standard. For example:
3528   //
3529   // int &f(...);    // #1
3530   // void f(char*);  // #2
3531   // void g() { int &r = f("foo"); }
3532   //
3533   // In C++03, we pick #2 as the best viable function.
3534   // In C++11, we pick #1 as the best viable function, because ellipsis
3535   // conversion is better than string-literal to char* conversion (since there
3536   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3537   // convert arguments, #2 would be the best viable function in C++11.
3538   // If the best viable function has this conversion, a warning will be issued
3539   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3540 
3541   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3542       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3543       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3544     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3545                ? ImplicitConversionSequence::Worse
3546                : ImplicitConversionSequence::Better;
3547 
3548   if (ICS1.getKindRank() < ICS2.getKindRank())
3549     return ImplicitConversionSequence::Better;
3550   if (ICS2.getKindRank() < ICS1.getKindRank())
3551     return ImplicitConversionSequence::Worse;
3552 
3553   // The following checks require both conversion sequences to be of
3554   // the same kind.
3555   if (ICS1.getKind() != ICS2.getKind())
3556     return ImplicitConversionSequence::Indistinguishable;
3557 
3558   ImplicitConversionSequence::CompareKind Result =
3559       ImplicitConversionSequence::Indistinguishable;
3560 
3561   // Two implicit conversion sequences of the same form are
3562   // indistinguishable conversion sequences unless one of the
3563   // following rules apply: (C++ 13.3.3.2p3):
3564 
3565   // List-initialization sequence L1 is a better conversion sequence than
3566   // list-initialization sequence L2 if:
3567   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3568   //   if not that,
3569   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3570   //   and N1 is smaller than N2.,
3571   // even if one of the other rules in this paragraph would otherwise apply.
3572   if (!ICS1.isBad()) {
3573     if (ICS1.isStdInitializerListElement() &&
3574         !ICS2.isStdInitializerListElement())
3575       return ImplicitConversionSequence::Better;
3576     if (!ICS1.isStdInitializerListElement() &&
3577         ICS2.isStdInitializerListElement())
3578       return ImplicitConversionSequence::Worse;
3579   }
3580 
3581   if (ICS1.isStandard())
3582     // Standard conversion sequence S1 is a better conversion sequence than
3583     // standard conversion sequence S2 if [...]
3584     Result = CompareStandardConversionSequences(S, Loc,
3585                                                 ICS1.Standard, ICS2.Standard);
3586   else if (ICS1.isUserDefined()) {
3587     // User-defined conversion sequence U1 is a better conversion
3588     // sequence than another user-defined conversion sequence U2 if
3589     // they contain the same user-defined conversion function or
3590     // constructor and if the second standard conversion sequence of
3591     // U1 is better than the second standard conversion sequence of
3592     // U2 (C++ 13.3.3.2p3).
3593     if (ICS1.UserDefined.ConversionFunction ==
3594           ICS2.UserDefined.ConversionFunction)
3595       Result = CompareStandardConversionSequences(S, Loc,
3596                                                   ICS1.UserDefined.After,
3597                                                   ICS2.UserDefined.After);
3598     else
3599       Result = compareConversionFunctions(S,
3600                                           ICS1.UserDefined.ConversionFunction,
3601                                           ICS2.UserDefined.ConversionFunction);
3602   }
3603 
3604   return Result;
3605 }
3606 
3607 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3608   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3609     Qualifiers Quals;
3610     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3611     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3612   }
3613 
3614   return Context.hasSameUnqualifiedType(T1, T2);
3615 }
3616 
3617 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3618 // determine if one is a proper subset of the other.
3619 static ImplicitConversionSequence::CompareKind
3620 compareStandardConversionSubsets(ASTContext &Context,
3621                                  const StandardConversionSequence& SCS1,
3622                                  const StandardConversionSequence& SCS2) {
3623   ImplicitConversionSequence::CompareKind Result
3624     = ImplicitConversionSequence::Indistinguishable;
3625 
3626   // the identity conversion sequence is considered to be a subsequence of
3627   // any non-identity conversion sequence
3628   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3629     return ImplicitConversionSequence::Better;
3630   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3631     return ImplicitConversionSequence::Worse;
3632 
3633   if (SCS1.Second != SCS2.Second) {
3634     if (SCS1.Second == ICK_Identity)
3635       Result = ImplicitConversionSequence::Better;
3636     else if (SCS2.Second == ICK_Identity)
3637       Result = ImplicitConversionSequence::Worse;
3638     else
3639       return ImplicitConversionSequence::Indistinguishable;
3640   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3641     return ImplicitConversionSequence::Indistinguishable;
3642 
3643   if (SCS1.Third == SCS2.Third) {
3644     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3645                              : ImplicitConversionSequence::Indistinguishable;
3646   }
3647 
3648   if (SCS1.Third == ICK_Identity)
3649     return Result == ImplicitConversionSequence::Worse
3650              ? ImplicitConversionSequence::Indistinguishable
3651              : ImplicitConversionSequence::Better;
3652 
3653   if (SCS2.Third == ICK_Identity)
3654     return Result == ImplicitConversionSequence::Better
3655              ? ImplicitConversionSequence::Indistinguishable
3656              : ImplicitConversionSequence::Worse;
3657 
3658   return ImplicitConversionSequence::Indistinguishable;
3659 }
3660 
3661 /// \brief Determine whether one of the given reference bindings is better
3662 /// than the other based on what kind of bindings they are.
3663 static bool
3664 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3665                              const StandardConversionSequence &SCS2) {
3666   // C++0x [over.ics.rank]p3b4:
3667   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3668   //      implicit object parameter of a non-static member function declared
3669   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3670   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3671   //      lvalue reference to a function lvalue and S2 binds an rvalue
3672   //      reference*.
3673   //
3674   // FIXME: Rvalue references. We're going rogue with the above edits,
3675   // because the semantics in the current C++0x working paper (N3225 at the
3676   // time of this writing) break the standard definition of std::forward
3677   // and std::reference_wrapper when dealing with references to functions.
3678   // Proposed wording changes submitted to CWG for consideration.
3679   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3680       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3681     return false;
3682 
3683   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3684           SCS2.IsLvalueReference) ||
3685          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3686           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3687 }
3688 
3689 /// CompareStandardConversionSequences - Compare two standard
3690 /// conversion sequences to determine whether one is better than the
3691 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3692 static ImplicitConversionSequence::CompareKind
3693 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3694                                    const StandardConversionSequence& SCS1,
3695                                    const StandardConversionSequence& SCS2)
3696 {
3697   // Standard conversion sequence S1 is a better conversion sequence
3698   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3699 
3700   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3701   //     sequences in the canonical form defined by 13.3.3.1.1,
3702   //     excluding any Lvalue Transformation; the identity conversion
3703   //     sequence is considered to be a subsequence of any
3704   //     non-identity conversion sequence) or, if not that,
3705   if (ImplicitConversionSequence::CompareKind CK
3706         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3707     return CK;
3708 
3709   //  -- the rank of S1 is better than the rank of S2 (by the rules
3710   //     defined below), or, if not that,
3711   ImplicitConversionRank Rank1 = SCS1.getRank();
3712   ImplicitConversionRank Rank2 = SCS2.getRank();
3713   if (Rank1 < Rank2)
3714     return ImplicitConversionSequence::Better;
3715   else if (Rank2 < Rank1)
3716     return ImplicitConversionSequence::Worse;
3717 
3718   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3719   // are indistinguishable unless one of the following rules
3720   // applies:
3721 
3722   //   A conversion that is not a conversion of a pointer, or
3723   //   pointer to member, to bool is better than another conversion
3724   //   that is such a conversion.
3725   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3726     return SCS2.isPointerConversionToBool()
3727              ? ImplicitConversionSequence::Better
3728              : ImplicitConversionSequence::Worse;
3729 
3730   // C++ [over.ics.rank]p4b2:
3731   //
3732   //   If class B is derived directly or indirectly from class A,
3733   //   conversion of B* to A* is better than conversion of B* to
3734   //   void*, and conversion of A* to void* is better than conversion
3735   //   of B* to void*.
3736   bool SCS1ConvertsToVoid
3737     = SCS1.isPointerConversionToVoidPointer(S.Context);
3738   bool SCS2ConvertsToVoid
3739     = SCS2.isPointerConversionToVoidPointer(S.Context);
3740   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3741     // Exactly one of the conversion sequences is a conversion to
3742     // a void pointer; it's the worse conversion.
3743     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3744                               : ImplicitConversionSequence::Worse;
3745   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3746     // Neither conversion sequence converts to a void pointer; compare
3747     // their derived-to-base conversions.
3748     if (ImplicitConversionSequence::CompareKind DerivedCK
3749           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3750       return DerivedCK;
3751   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3752              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3753     // Both conversion sequences are conversions to void
3754     // pointers. Compare the source types to determine if there's an
3755     // inheritance relationship in their sources.
3756     QualType FromType1 = SCS1.getFromType();
3757     QualType FromType2 = SCS2.getFromType();
3758 
3759     // Adjust the types we're converting from via the array-to-pointer
3760     // conversion, if we need to.
3761     if (SCS1.First == ICK_Array_To_Pointer)
3762       FromType1 = S.Context.getArrayDecayedType(FromType1);
3763     if (SCS2.First == ICK_Array_To_Pointer)
3764       FromType2 = S.Context.getArrayDecayedType(FromType2);
3765 
3766     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3767     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3768 
3769     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3770       return ImplicitConversionSequence::Better;
3771     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3772       return ImplicitConversionSequence::Worse;
3773 
3774     // Objective-C++: If one interface is more specific than the
3775     // other, it is the better one.
3776     const ObjCObjectPointerType* FromObjCPtr1
3777       = FromType1->getAs<ObjCObjectPointerType>();
3778     const ObjCObjectPointerType* FromObjCPtr2
3779       = FromType2->getAs<ObjCObjectPointerType>();
3780     if (FromObjCPtr1 && FromObjCPtr2) {
3781       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3782                                                           FromObjCPtr2);
3783       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3784                                                            FromObjCPtr1);
3785       if (AssignLeft != AssignRight) {
3786         return AssignLeft? ImplicitConversionSequence::Better
3787                          : ImplicitConversionSequence::Worse;
3788       }
3789     }
3790   }
3791 
3792   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3793   // bullet 3).
3794   if (ImplicitConversionSequence::CompareKind QualCK
3795         = CompareQualificationConversions(S, SCS1, SCS2))
3796     return QualCK;
3797 
3798   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3799     // Check for a better reference binding based on the kind of bindings.
3800     if (isBetterReferenceBindingKind(SCS1, SCS2))
3801       return ImplicitConversionSequence::Better;
3802     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3803       return ImplicitConversionSequence::Worse;
3804 
3805     // C++ [over.ics.rank]p3b4:
3806     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3807     //      which the references refer are the same type except for
3808     //      top-level cv-qualifiers, and the type to which the reference
3809     //      initialized by S2 refers is more cv-qualified than the type
3810     //      to which the reference initialized by S1 refers.
3811     QualType T1 = SCS1.getToType(2);
3812     QualType T2 = SCS2.getToType(2);
3813     T1 = S.Context.getCanonicalType(T1);
3814     T2 = S.Context.getCanonicalType(T2);
3815     Qualifiers T1Quals, T2Quals;
3816     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3817     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3818     if (UnqualT1 == UnqualT2) {
3819       // Objective-C++ ARC: If the references refer to objects with different
3820       // lifetimes, prefer bindings that don't change lifetime.
3821       if (SCS1.ObjCLifetimeConversionBinding !=
3822                                           SCS2.ObjCLifetimeConversionBinding) {
3823         return SCS1.ObjCLifetimeConversionBinding
3824                                            ? ImplicitConversionSequence::Worse
3825                                            : ImplicitConversionSequence::Better;
3826       }
3827 
3828       // If the type is an array type, promote the element qualifiers to the
3829       // type for comparison.
3830       if (isa<ArrayType>(T1) && T1Quals)
3831         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3832       if (isa<ArrayType>(T2) && T2Quals)
3833         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3834       if (T2.isMoreQualifiedThan(T1))
3835         return ImplicitConversionSequence::Better;
3836       else if (T1.isMoreQualifiedThan(T2))
3837         return ImplicitConversionSequence::Worse;
3838     }
3839   }
3840 
3841   // In Microsoft mode, prefer an integral conversion to a
3842   // floating-to-integral conversion if the integral conversion
3843   // is between types of the same size.
3844   // For example:
3845   // void f(float);
3846   // void f(int);
3847   // int main {
3848   //    long a;
3849   //    f(a);
3850   // }
3851   // Here, MSVC will call f(int) instead of generating a compile error
3852   // as clang will do in standard mode.
3853   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3854       SCS2.Second == ICK_Floating_Integral &&
3855       S.Context.getTypeSize(SCS1.getFromType()) ==
3856           S.Context.getTypeSize(SCS1.getToType(2)))
3857     return ImplicitConversionSequence::Better;
3858 
3859   return ImplicitConversionSequence::Indistinguishable;
3860 }
3861 
3862 /// CompareQualificationConversions - Compares two standard conversion
3863 /// sequences to determine whether they can be ranked based on their
3864 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3865 static ImplicitConversionSequence::CompareKind
3866 CompareQualificationConversions(Sema &S,
3867                                 const StandardConversionSequence& SCS1,
3868                                 const StandardConversionSequence& SCS2) {
3869   // C++ 13.3.3.2p3:
3870   //  -- S1 and S2 differ only in their qualification conversion and
3871   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3872   //     cv-qualification signature of type T1 is a proper subset of
3873   //     the cv-qualification signature of type T2, and S1 is not the
3874   //     deprecated string literal array-to-pointer conversion (4.2).
3875   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3876       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3877     return ImplicitConversionSequence::Indistinguishable;
3878 
3879   // FIXME: the example in the standard doesn't use a qualification
3880   // conversion (!)
3881   QualType T1 = SCS1.getToType(2);
3882   QualType T2 = SCS2.getToType(2);
3883   T1 = S.Context.getCanonicalType(T1);
3884   T2 = S.Context.getCanonicalType(T2);
3885   Qualifiers T1Quals, T2Quals;
3886   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3887   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3888 
3889   // If the types are the same, we won't learn anything by unwrapped
3890   // them.
3891   if (UnqualT1 == UnqualT2)
3892     return ImplicitConversionSequence::Indistinguishable;
3893 
3894   // If the type is an array type, promote the element qualifiers to the type
3895   // for comparison.
3896   if (isa<ArrayType>(T1) && T1Quals)
3897     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3898   if (isa<ArrayType>(T2) && T2Quals)
3899     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3900 
3901   ImplicitConversionSequence::CompareKind Result
3902     = ImplicitConversionSequence::Indistinguishable;
3903 
3904   // Objective-C++ ARC:
3905   //   Prefer qualification conversions not involving a change in lifetime
3906   //   to qualification conversions that do not change lifetime.
3907   if (SCS1.QualificationIncludesObjCLifetime !=
3908                                       SCS2.QualificationIncludesObjCLifetime) {
3909     Result = SCS1.QualificationIncludesObjCLifetime
3910                ? ImplicitConversionSequence::Worse
3911                : ImplicitConversionSequence::Better;
3912   }
3913 
3914   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3915     // Within each iteration of the loop, we check the qualifiers to
3916     // determine if this still looks like a qualification
3917     // conversion. Then, if all is well, we unwrap one more level of
3918     // pointers or pointers-to-members and do it all again
3919     // until there are no more pointers or pointers-to-members left
3920     // to unwrap. This essentially mimics what
3921     // IsQualificationConversion does, but here we're checking for a
3922     // strict subset of qualifiers.
3923     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3924       // The qualifiers are the same, so this doesn't tell us anything
3925       // about how the sequences rank.
3926       ;
3927     else if (T2.isMoreQualifiedThan(T1)) {
3928       // T1 has fewer qualifiers, so it could be the better sequence.
3929       if (Result == ImplicitConversionSequence::Worse)
3930         // Neither has qualifiers that are a subset of the other's
3931         // qualifiers.
3932         return ImplicitConversionSequence::Indistinguishable;
3933 
3934       Result = ImplicitConversionSequence::Better;
3935     } else if (T1.isMoreQualifiedThan(T2)) {
3936       // T2 has fewer qualifiers, so it could be the better sequence.
3937       if (Result == ImplicitConversionSequence::Better)
3938         // Neither has qualifiers that are a subset of the other's
3939         // qualifiers.
3940         return ImplicitConversionSequence::Indistinguishable;
3941 
3942       Result = ImplicitConversionSequence::Worse;
3943     } else {
3944       // Qualifiers are disjoint.
3945       return ImplicitConversionSequence::Indistinguishable;
3946     }
3947 
3948     // If the types after this point are equivalent, we're done.
3949     if (S.Context.hasSameUnqualifiedType(T1, T2))
3950       break;
3951   }
3952 
3953   // Check that the winning standard conversion sequence isn't using
3954   // the deprecated string literal array to pointer conversion.
3955   switch (Result) {
3956   case ImplicitConversionSequence::Better:
3957     if (SCS1.DeprecatedStringLiteralToCharPtr)
3958       Result = ImplicitConversionSequence::Indistinguishable;
3959     break;
3960 
3961   case ImplicitConversionSequence::Indistinguishable:
3962     break;
3963 
3964   case ImplicitConversionSequence::Worse:
3965     if (SCS2.DeprecatedStringLiteralToCharPtr)
3966       Result = ImplicitConversionSequence::Indistinguishable;
3967     break;
3968   }
3969 
3970   return Result;
3971 }
3972 
3973 /// CompareDerivedToBaseConversions - Compares two standard conversion
3974 /// sequences to determine whether they can be ranked based on their
3975 /// various kinds of derived-to-base conversions (C++
3976 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3977 /// conversions between Objective-C interface types.
3978 static ImplicitConversionSequence::CompareKind
3979 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3980                                 const StandardConversionSequence& SCS1,
3981                                 const StandardConversionSequence& SCS2) {
3982   QualType FromType1 = SCS1.getFromType();
3983   QualType ToType1 = SCS1.getToType(1);
3984   QualType FromType2 = SCS2.getFromType();
3985   QualType ToType2 = SCS2.getToType(1);
3986 
3987   // Adjust the types we're converting from via the array-to-pointer
3988   // conversion, if we need to.
3989   if (SCS1.First == ICK_Array_To_Pointer)
3990     FromType1 = S.Context.getArrayDecayedType(FromType1);
3991   if (SCS2.First == ICK_Array_To_Pointer)
3992     FromType2 = S.Context.getArrayDecayedType(FromType2);
3993 
3994   // Canonicalize all of the types.
3995   FromType1 = S.Context.getCanonicalType(FromType1);
3996   ToType1 = S.Context.getCanonicalType(ToType1);
3997   FromType2 = S.Context.getCanonicalType(FromType2);
3998   ToType2 = S.Context.getCanonicalType(ToType2);
3999 
4000   // C++ [over.ics.rank]p4b3:
4001   //
4002   //   If class B is derived directly or indirectly from class A and
4003   //   class C is derived directly or indirectly from B,
4004   //
4005   // Compare based on pointer conversions.
4006   if (SCS1.Second == ICK_Pointer_Conversion &&
4007       SCS2.Second == ICK_Pointer_Conversion &&
4008       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4009       FromType1->isPointerType() && FromType2->isPointerType() &&
4010       ToType1->isPointerType() && ToType2->isPointerType()) {
4011     QualType FromPointee1
4012       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4013     QualType ToPointee1
4014       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4015     QualType FromPointee2
4016       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4017     QualType ToPointee2
4018       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4019 
4020     //   -- conversion of C* to B* is better than conversion of C* to A*,
4021     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4022       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4023         return ImplicitConversionSequence::Better;
4024       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4025         return ImplicitConversionSequence::Worse;
4026     }
4027 
4028     //   -- conversion of B* to A* is better than conversion of C* to A*,
4029     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4030       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4031         return ImplicitConversionSequence::Better;
4032       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4033         return ImplicitConversionSequence::Worse;
4034     }
4035   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4036              SCS2.Second == ICK_Pointer_Conversion) {
4037     const ObjCObjectPointerType *FromPtr1
4038       = FromType1->getAs<ObjCObjectPointerType>();
4039     const ObjCObjectPointerType *FromPtr2
4040       = FromType2->getAs<ObjCObjectPointerType>();
4041     const ObjCObjectPointerType *ToPtr1
4042       = ToType1->getAs<ObjCObjectPointerType>();
4043     const ObjCObjectPointerType *ToPtr2
4044       = ToType2->getAs<ObjCObjectPointerType>();
4045 
4046     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4047       // Apply the same conversion ranking rules for Objective-C pointer types
4048       // that we do for C++ pointers to class types. However, we employ the
4049       // Objective-C pseudo-subtyping relationship used for assignment of
4050       // Objective-C pointer types.
4051       bool FromAssignLeft
4052         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4053       bool FromAssignRight
4054         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4055       bool ToAssignLeft
4056         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4057       bool ToAssignRight
4058         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4059 
4060       // A conversion to an a non-id object pointer type or qualified 'id'
4061       // type is better than a conversion to 'id'.
4062       if (ToPtr1->isObjCIdType() &&
4063           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4064         return ImplicitConversionSequence::Worse;
4065       if (ToPtr2->isObjCIdType() &&
4066           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4067         return ImplicitConversionSequence::Better;
4068 
4069       // A conversion to a non-id object pointer type is better than a
4070       // conversion to a qualified 'id' type
4071       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4072         return ImplicitConversionSequence::Worse;
4073       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4074         return ImplicitConversionSequence::Better;
4075 
4076       // A conversion to an a non-Class object pointer type or qualified 'Class'
4077       // type is better than a conversion to 'Class'.
4078       if (ToPtr1->isObjCClassType() &&
4079           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4080         return ImplicitConversionSequence::Worse;
4081       if (ToPtr2->isObjCClassType() &&
4082           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4083         return ImplicitConversionSequence::Better;
4084 
4085       // A conversion to a non-Class object pointer type is better than a
4086       // conversion to a qualified 'Class' type.
4087       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4088         return ImplicitConversionSequence::Worse;
4089       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4090         return ImplicitConversionSequence::Better;
4091 
4092       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4093       if (S.Context.hasSameType(FromType1, FromType2) &&
4094           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4095           (ToAssignLeft != ToAssignRight))
4096         return ToAssignLeft? ImplicitConversionSequence::Worse
4097                            : ImplicitConversionSequence::Better;
4098 
4099       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4100       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4101           (FromAssignLeft != FromAssignRight))
4102         return FromAssignLeft? ImplicitConversionSequence::Better
4103         : ImplicitConversionSequence::Worse;
4104     }
4105   }
4106 
4107   // Ranking of member-pointer types.
4108   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4109       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4110       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4111     const MemberPointerType * FromMemPointer1 =
4112                                         FromType1->getAs<MemberPointerType>();
4113     const MemberPointerType * ToMemPointer1 =
4114                                           ToType1->getAs<MemberPointerType>();
4115     const MemberPointerType * FromMemPointer2 =
4116                                           FromType2->getAs<MemberPointerType>();
4117     const MemberPointerType * ToMemPointer2 =
4118                                           ToType2->getAs<MemberPointerType>();
4119     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4120     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4121     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4122     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4123     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4124     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4125     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4126     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4127     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4128     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4129       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4130         return ImplicitConversionSequence::Worse;
4131       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4132         return ImplicitConversionSequence::Better;
4133     }
4134     // conversion of B::* to C::* is better than conversion of A::* to C::*
4135     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4136       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4137         return ImplicitConversionSequence::Better;
4138       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4139         return ImplicitConversionSequence::Worse;
4140     }
4141   }
4142 
4143   if (SCS1.Second == ICK_Derived_To_Base) {
4144     //   -- conversion of C to B is better than conversion of C to A,
4145     //   -- binding of an expression of type C to a reference of type
4146     //      B& is better than binding an expression of type C to a
4147     //      reference of type A&,
4148     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4149         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4150       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4151         return ImplicitConversionSequence::Better;
4152       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4153         return ImplicitConversionSequence::Worse;
4154     }
4155 
4156     //   -- conversion of B to A is better than conversion of C to A.
4157     //   -- binding of an expression of type B to a reference of type
4158     //      A& is better than binding an expression of type C to a
4159     //      reference of type A&,
4160     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4161         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4162       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4163         return ImplicitConversionSequence::Better;
4164       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4165         return ImplicitConversionSequence::Worse;
4166     }
4167   }
4168 
4169   return ImplicitConversionSequence::Indistinguishable;
4170 }
4171 
4172 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4173 /// C++ class.
4174 static bool isTypeValid(QualType T) {
4175   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4176     return !Record->isInvalidDecl();
4177 
4178   return true;
4179 }
4180 
4181 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4182 /// determine whether they are reference-related,
4183 /// reference-compatible, reference-compatible with added
4184 /// qualification, or incompatible, for use in C++ initialization by
4185 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4186 /// type, and the first type (T1) is the pointee type of the reference
4187 /// type being initialized.
4188 Sema::ReferenceCompareResult
4189 Sema::CompareReferenceRelationship(SourceLocation Loc,
4190                                    QualType OrigT1, QualType OrigT2,
4191                                    bool &DerivedToBase,
4192                                    bool &ObjCConversion,
4193                                    bool &ObjCLifetimeConversion) {
4194   assert(!OrigT1->isReferenceType() &&
4195     "T1 must be the pointee type of the reference type");
4196   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4197 
4198   QualType T1 = Context.getCanonicalType(OrigT1);
4199   QualType T2 = Context.getCanonicalType(OrigT2);
4200   Qualifiers T1Quals, T2Quals;
4201   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4202   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4203 
4204   // C++ [dcl.init.ref]p4:
4205   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4206   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4207   //   T1 is a base class of T2.
4208   DerivedToBase = false;
4209   ObjCConversion = false;
4210   ObjCLifetimeConversion = false;
4211   QualType ConvertedT2;
4212   if (UnqualT1 == UnqualT2) {
4213     // Nothing to do.
4214   } else if (isCompleteType(Loc, OrigT2) &&
4215              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4216              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4217     DerivedToBase = true;
4218   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4219            UnqualT2->isObjCObjectOrInterfaceType() &&
4220            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4221     ObjCConversion = true;
4222   else if (UnqualT2->isFunctionType() &&
4223            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4224     // C++1z [dcl.init.ref]p4:
4225     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4226     //   function" and T1 is "function"
4227     //
4228     // We extend this to also apply to 'noreturn', so allow any function
4229     // conversion between function types.
4230     return Ref_Compatible;
4231   else
4232     return Ref_Incompatible;
4233 
4234   // At this point, we know that T1 and T2 are reference-related (at
4235   // least).
4236 
4237   // If the type is an array type, promote the element qualifiers to the type
4238   // for comparison.
4239   if (isa<ArrayType>(T1) && T1Quals)
4240     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4241   if (isa<ArrayType>(T2) && T2Quals)
4242     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4243 
4244   // C++ [dcl.init.ref]p4:
4245   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4246   //   reference-related to T2 and cv1 is the same cv-qualification
4247   //   as, or greater cv-qualification than, cv2. For purposes of
4248   //   overload resolution, cases for which cv1 is greater
4249   //   cv-qualification than cv2 are identified as
4250   //   reference-compatible with added qualification (see 13.3.3.2).
4251   //
4252   // Note that we also require equivalence of Objective-C GC and address-space
4253   // qualifiers when performing these computations, so that e.g., an int in
4254   // address space 1 is not reference-compatible with an int in address
4255   // space 2.
4256   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4257       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4258     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4259       ObjCLifetimeConversion = true;
4260 
4261     T1Quals.removeObjCLifetime();
4262     T2Quals.removeObjCLifetime();
4263   }
4264 
4265   // MS compiler ignores __unaligned qualifier for references; do the same.
4266   T1Quals.removeUnaligned();
4267   T2Quals.removeUnaligned();
4268 
4269   if (T1Quals.compatiblyIncludes(T2Quals))
4270     return Ref_Compatible;
4271   else
4272     return Ref_Related;
4273 }
4274 
4275 /// \brief Look for a user-defined conversion to a value reference-compatible
4276 ///        with DeclType. Return true if something definite is found.
4277 static bool
4278 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4279                          QualType DeclType, SourceLocation DeclLoc,
4280                          Expr *Init, QualType T2, bool AllowRvalues,
4281                          bool AllowExplicit) {
4282   assert(T2->isRecordType() && "Can only find conversions of record types.");
4283   CXXRecordDecl *T2RecordDecl
4284     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4285 
4286   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4287   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4288   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4289     NamedDecl *D = *I;
4290     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4291     if (isa<UsingShadowDecl>(D))
4292       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4293 
4294     FunctionTemplateDecl *ConvTemplate
4295       = dyn_cast<FunctionTemplateDecl>(D);
4296     CXXConversionDecl *Conv;
4297     if (ConvTemplate)
4298       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4299     else
4300       Conv = cast<CXXConversionDecl>(D);
4301 
4302     // If this is an explicit conversion, and we're not allowed to consider
4303     // explicit conversions, skip it.
4304     if (!AllowExplicit && Conv->isExplicit())
4305       continue;
4306 
4307     if (AllowRvalues) {
4308       bool DerivedToBase = false;
4309       bool ObjCConversion = false;
4310       bool ObjCLifetimeConversion = false;
4311 
4312       // If we are initializing an rvalue reference, don't permit conversion
4313       // functions that return lvalues.
4314       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4315         const ReferenceType *RefType
4316           = Conv->getConversionType()->getAs<LValueReferenceType>();
4317         if (RefType && !RefType->getPointeeType()->isFunctionType())
4318           continue;
4319       }
4320 
4321       if (!ConvTemplate &&
4322           S.CompareReferenceRelationship(
4323             DeclLoc,
4324             Conv->getConversionType().getNonReferenceType()
4325               .getUnqualifiedType(),
4326             DeclType.getNonReferenceType().getUnqualifiedType(),
4327             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4328           Sema::Ref_Incompatible)
4329         continue;
4330     } else {
4331       // If the conversion function doesn't return a reference type,
4332       // it can't be considered for this conversion. An rvalue reference
4333       // is only acceptable if its referencee is a function type.
4334 
4335       const ReferenceType *RefType =
4336         Conv->getConversionType()->getAs<ReferenceType>();
4337       if (!RefType ||
4338           (!RefType->isLValueReferenceType() &&
4339            !RefType->getPointeeType()->isFunctionType()))
4340         continue;
4341     }
4342 
4343     if (ConvTemplate)
4344       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4345                                        Init, DeclType, CandidateSet,
4346                                        /*AllowObjCConversionOnExplicit=*/false);
4347     else
4348       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4349                                DeclType, CandidateSet,
4350                                /*AllowObjCConversionOnExplicit=*/false);
4351   }
4352 
4353   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4354 
4355   OverloadCandidateSet::iterator Best;
4356   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4357   case OR_Success:
4358     // C++ [over.ics.ref]p1:
4359     //
4360     //   [...] If the parameter binds directly to the result of
4361     //   applying a conversion function to the argument
4362     //   expression, the implicit conversion sequence is a
4363     //   user-defined conversion sequence (13.3.3.1.2), with the
4364     //   second standard conversion sequence either an identity
4365     //   conversion or, if the conversion function returns an
4366     //   entity of a type that is a derived class of the parameter
4367     //   type, a derived-to-base Conversion.
4368     if (!Best->FinalConversion.DirectBinding)
4369       return false;
4370 
4371     ICS.setUserDefined();
4372     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4373     ICS.UserDefined.After = Best->FinalConversion;
4374     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4375     ICS.UserDefined.ConversionFunction = Best->Function;
4376     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4377     ICS.UserDefined.EllipsisConversion = false;
4378     assert(ICS.UserDefined.After.ReferenceBinding &&
4379            ICS.UserDefined.After.DirectBinding &&
4380            "Expected a direct reference binding!");
4381     return true;
4382 
4383   case OR_Ambiguous:
4384     ICS.setAmbiguous();
4385     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4386          Cand != CandidateSet.end(); ++Cand)
4387       if (Cand->Viable)
4388         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4389     return true;
4390 
4391   case OR_No_Viable_Function:
4392   case OR_Deleted:
4393     // There was no suitable conversion, or we found a deleted
4394     // conversion; continue with other checks.
4395     return false;
4396   }
4397 
4398   llvm_unreachable("Invalid OverloadResult!");
4399 }
4400 
4401 /// \brief Compute an implicit conversion sequence for reference
4402 /// initialization.
4403 static ImplicitConversionSequence
4404 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4405                  SourceLocation DeclLoc,
4406                  bool SuppressUserConversions,
4407                  bool AllowExplicit) {
4408   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4409 
4410   // Most paths end in a failed conversion.
4411   ImplicitConversionSequence ICS;
4412   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4413 
4414   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4415   QualType T2 = Init->getType();
4416 
4417   // If the initializer is the address of an overloaded function, try
4418   // to resolve the overloaded function. If all goes well, T2 is the
4419   // type of the resulting function.
4420   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4421     DeclAccessPair Found;
4422     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4423                                                                 false, Found))
4424       T2 = Fn->getType();
4425   }
4426 
4427   // Compute some basic properties of the types and the initializer.
4428   bool isRValRef = DeclType->isRValueReferenceType();
4429   bool DerivedToBase = false;
4430   bool ObjCConversion = false;
4431   bool ObjCLifetimeConversion = false;
4432   Expr::Classification InitCategory = Init->Classify(S.Context);
4433   Sema::ReferenceCompareResult RefRelationship
4434     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4435                                      ObjCConversion, ObjCLifetimeConversion);
4436 
4437 
4438   // C++0x [dcl.init.ref]p5:
4439   //   A reference to type "cv1 T1" is initialized by an expression
4440   //   of type "cv2 T2" as follows:
4441 
4442   //     -- If reference is an lvalue reference and the initializer expression
4443   if (!isRValRef) {
4444     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4445     //        reference-compatible with "cv2 T2," or
4446     //
4447     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4448     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4449       // C++ [over.ics.ref]p1:
4450       //   When a parameter of reference type binds directly (8.5.3)
4451       //   to an argument expression, the implicit conversion sequence
4452       //   is the identity conversion, unless the argument expression
4453       //   has a type that is a derived class of the parameter type,
4454       //   in which case the implicit conversion sequence is a
4455       //   derived-to-base Conversion (13.3.3.1).
4456       ICS.setStandard();
4457       ICS.Standard.First = ICK_Identity;
4458       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4459                          : ObjCConversion? ICK_Compatible_Conversion
4460                          : ICK_Identity;
4461       ICS.Standard.Third = ICK_Identity;
4462       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4463       ICS.Standard.setToType(0, T2);
4464       ICS.Standard.setToType(1, T1);
4465       ICS.Standard.setToType(2, T1);
4466       ICS.Standard.ReferenceBinding = true;
4467       ICS.Standard.DirectBinding = true;
4468       ICS.Standard.IsLvalueReference = !isRValRef;
4469       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4470       ICS.Standard.BindsToRvalue = false;
4471       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4472       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4473       ICS.Standard.CopyConstructor = nullptr;
4474       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4475 
4476       // Nothing more to do: the inaccessibility/ambiguity check for
4477       // derived-to-base conversions is suppressed when we're
4478       // computing the implicit conversion sequence (C++
4479       // [over.best.ics]p2).
4480       return ICS;
4481     }
4482 
4483     //       -- has a class type (i.e., T2 is a class type), where T1 is
4484     //          not reference-related to T2, and can be implicitly
4485     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4486     //          is reference-compatible with "cv3 T3" 92) (this
4487     //          conversion is selected by enumerating the applicable
4488     //          conversion functions (13.3.1.6) and choosing the best
4489     //          one through overload resolution (13.3)),
4490     if (!SuppressUserConversions && T2->isRecordType() &&
4491         S.isCompleteType(DeclLoc, T2) &&
4492         RefRelationship == Sema::Ref_Incompatible) {
4493       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4494                                    Init, T2, /*AllowRvalues=*/false,
4495                                    AllowExplicit))
4496         return ICS;
4497     }
4498   }
4499 
4500   //     -- Otherwise, the reference shall be an lvalue reference to a
4501   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4502   //        shall be an rvalue reference.
4503   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4504     return ICS;
4505 
4506   //       -- If the initializer expression
4507   //
4508   //            -- is an xvalue, class prvalue, array prvalue or function
4509   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4510   if (RefRelationship == Sema::Ref_Compatible &&
4511       (InitCategory.isXValue() ||
4512        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4513        (InitCategory.isLValue() && T2->isFunctionType()))) {
4514     ICS.setStandard();
4515     ICS.Standard.First = ICK_Identity;
4516     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4517                       : ObjCConversion? ICK_Compatible_Conversion
4518                       : ICK_Identity;
4519     ICS.Standard.Third = ICK_Identity;
4520     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4521     ICS.Standard.setToType(0, T2);
4522     ICS.Standard.setToType(1, T1);
4523     ICS.Standard.setToType(2, T1);
4524     ICS.Standard.ReferenceBinding = true;
4525     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4526     // binding unless we're binding to a class prvalue.
4527     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4528     // allow the use of rvalue references in C++98/03 for the benefit of
4529     // standard library implementors; therefore, we need the xvalue check here.
4530     ICS.Standard.DirectBinding =
4531       S.getLangOpts().CPlusPlus11 ||
4532       !(InitCategory.isPRValue() || T2->isRecordType());
4533     ICS.Standard.IsLvalueReference = !isRValRef;
4534     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4535     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4536     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4537     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4538     ICS.Standard.CopyConstructor = nullptr;
4539     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4540     return ICS;
4541   }
4542 
4543   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4544   //               reference-related to T2, and can be implicitly converted to
4545   //               an xvalue, class prvalue, or function lvalue of type
4546   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4547   //               "cv3 T3",
4548   //
4549   //          then the reference is bound to the value of the initializer
4550   //          expression in the first case and to the result of the conversion
4551   //          in the second case (or, in either case, to an appropriate base
4552   //          class subobject).
4553   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4554       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4555       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4556                                Init, T2, /*AllowRvalues=*/true,
4557                                AllowExplicit)) {
4558     // In the second case, if the reference is an rvalue reference
4559     // and the second standard conversion sequence of the
4560     // user-defined conversion sequence includes an lvalue-to-rvalue
4561     // conversion, the program is ill-formed.
4562     if (ICS.isUserDefined() && isRValRef &&
4563         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4564       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4565 
4566     return ICS;
4567   }
4568 
4569   // A temporary of function type cannot be created; don't even try.
4570   if (T1->isFunctionType())
4571     return ICS;
4572 
4573   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4574   //          initialized from the initializer expression using the
4575   //          rules for a non-reference copy initialization (8.5). The
4576   //          reference is then bound to the temporary. If T1 is
4577   //          reference-related to T2, cv1 must be the same
4578   //          cv-qualification as, or greater cv-qualification than,
4579   //          cv2; otherwise, the program is ill-formed.
4580   if (RefRelationship == Sema::Ref_Related) {
4581     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4582     // we would be reference-compatible or reference-compatible with
4583     // added qualification. But that wasn't the case, so the reference
4584     // initialization fails.
4585     //
4586     // Note that we only want to check address spaces and cvr-qualifiers here.
4587     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4588     Qualifiers T1Quals = T1.getQualifiers();
4589     Qualifiers T2Quals = T2.getQualifiers();
4590     T1Quals.removeObjCGCAttr();
4591     T1Quals.removeObjCLifetime();
4592     T2Quals.removeObjCGCAttr();
4593     T2Quals.removeObjCLifetime();
4594     // MS compiler ignores __unaligned qualifier for references; do the same.
4595     T1Quals.removeUnaligned();
4596     T2Quals.removeUnaligned();
4597     if (!T1Quals.compatiblyIncludes(T2Quals))
4598       return ICS;
4599   }
4600 
4601   // If at least one of the types is a class type, the types are not
4602   // related, and we aren't allowed any user conversions, the
4603   // reference binding fails. This case is important for breaking
4604   // recursion, since TryImplicitConversion below will attempt to
4605   // create a temporary through the use of a copy constructor.
4606   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4607       (T1->isRecordType() || T2->isRecordType()))
4608     return ICS;
4609 
4610   // If T1 is reference-related to T2 and the reference is an rvalue
4611   // reference, the initializer expression shall not be an lvalue.
4612   if (RefRelationship >= Sema::Ref_Related &&
4613       isRValRef && Init->Classify(S.Context).isLValue())
4614     return ICS;
4615 
4616   // C++ [over.ics.ref]p2:
4617   //   When a parameter of reference type is not bound directly to
4618   //   an argument expression, the conversion sequence is the one
4619   //   required to convert the argument expression to the
4620   //   underlying type of the reference according to
4621   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4622   //   to copy-initializing a temporary of the underlying type with
4623   //   the argument expression. Any difference in top-level
4624   //   cv-qualification is subsumed by the initialization itself
4625   //   and does not constitute a conversion.
4626   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4627                               /*AllowExplicit=*/false,
4628                               /*InOverloadResolution=*/false,
4629                               /*CStyle=*/false,
4630                               /*AllowObjCWritebackConversion=*/false,
4631                               /*AllowObjCConversionOnExplicit=*/false);
4632 
4633   // Of course, that's still a reference binding.
4634   if (ICS.isStandard()) {
4635     ICS.Standard.ReferenceBinding = true;
4636     ICS.Standard.IsLvalueReference = !isRValRef;
4637     ICS.Standard.BindsToFunctionLvalue = false;
4638     ICS.Standard.BindsToRvalue = true;
4639     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4640     ICS.Standard.ObjCLifetimeConversionBinding = false;
4641   } else if (ICS.isUserDefined()) {
4642     const ReferenceType *LValRefType =
4643         ICS.UserDefined.ConversionFunction->getReturnType()
4644             ->getAs<LValueReferenceType>();
4645 
4646     // C++ [over.ics.ref]p3:
4647     //   Except for an implicit object parameter, for which see 13.3.1, a
4648     //   standard conversion sequence cannot be formed if it requires [...]
4649     //   binding an rvalue reference to an lvalue other than a function
4650     //   lvalue.
4651     // Note that the function case is not possible here.
4652     if (DeclType->isRValueReferenceType() && LValRefType) {
4653       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4654       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4655       // reference to an rvalue!
4656       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4657       return ICS;
4658     }
4659 
4660     ICS.UserDefined.After.ReferenceBinding = true;
4661     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4662     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4663     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4664     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4665     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4666   }
4667 
4668   return ICS;
4669 }
4670 
4671 static ImplicitConversionSequence
4672 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4673                       bool SuppressUserConversions,
4674                       bool InOverloadResolution,
4675                       bool AllowObjCWritebackConversion,
4676                       bool AllowExplicit = false);
4677 
4678 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4679 /// initializer list From.
4680 static ImplicitConversionSequence
4681 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4682                   bool SuppressUserConversions,
4683                   bool InOverloadResolution,
4684                   bool AllowObjCWritebackConversion) {
4685   // C++11 [over.ics.list]p1:
4686   //   When an argument is an initializer list, it is not an expression and
4687   //   special rules apply for converting it to a parameter type.
4688 
4689   ImplicitConversionSequence Result;
4690   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4691 
4692   // We need a complete type for what follows. Incomplete types can never be
4693   // initialized from init lists.
4694   if (!S.isCompleteType(From->getLocStart(), ToType))
4695     return Result;
4696 
4697   // Per DR1467:
4698   //   If the parameter type is a class X and the initializer list has a single
4699   //   element of type cv U, where U is X or a class derived from X, the
4700   //   implicit conversion sequence is the one required to convert the element
4701   //   to the parameter type.
4702   //
4703   //   Otherwise, if the parameter type is a character array [... ]
4704   //   and the initializer list has a single element that is an
4705   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4706   //   implicit conversion sequence is the identity conversion.
4707   if (From->getNumInits() == 1) {
4708     if (ToType->isRecordType()) {
4709       QualType InitType = From->getInit(0)->getType();
4710       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4711           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4712         return TryCopyInitialization(S, From->getInit(0), ToType,
4713                                      SuppressUserConversions,
4714                                      InOverloadResolution,
4715                                      AllowObjCWritebackConversion);
4716     }
4717     // FIXME: Check the other conditions here: array of character type,
4718     // initializer is a string literal.
4719     if (ToType->isArrayType()) {
4720       InitializedEntity Entity =
4721         InitializedEntity::InitializeParameter(S.Context, ToType,
4722                                                /*Consumed=*/false);
4723       if (S.CanPerformCopyInitialization(Entity, From)) {
4724         Result.setStandard();
4725         Result.Standard.setAsIdentityConversion();
4726         Result.Standard.setFromType(ToType);
4727         Result.Standard.setAllToTypes(ToType);
4728         return Result;
4729       }
4730     }
4731   }
4732 
4733   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4734   // C++11 [over.ics.list]p2:
4735   //   If the parameter type is std::initializer_list<X> or "array of X" and
4736   //   all the elements can be implicitly converted to X, the implicit
4737   //   conversion sequence is the worst conversion necessary to convert an
4738   //   element of the list to X.
4739   //
4740   // C++14 [over.ics.list]p3:
4741   //   Otherwise, if the parameter type is "array of N X", if the initializer
4742   //   list has exactly N elements or if it has fewer than N elements and X is
4743   //   default-constructible, and if all the elements of the initializer list
4744   //   can be implicitly converted to X, the implicit conversion sequence is
4745   //   the worst conversion necessary to convert an element of the list to X.
4746   //
4747   // FIXME: We're missing a lot of these checks.
4748   bool toStdInitializerList = false;
4749   QualType X;
4750   if (ToType->isArrayType())
4751     X = S.Context.getAsArrayType(ToType)->getElementType();
4752   else
4753     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4754   if (!X.isNull()) {
4755     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4756       Expr *Init = From->getInit(i);
4757       ImplicitConversionSequence ICS =
4758           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4759                                 InOverloadResolution,
4760                                 AllowObjCWritebackConversion);
4761       // If a single element isn't convertible, fail.
4762       if (ICS.isBad()) {
4763         Result = ICS;
4764         break;
4765       }
4766       // Otherwise, look for the worst conversion.
4767       if (Result.isBad() ||
4768           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4769                                              Result) ==
4770               ImplicitConversionSequence::Worse)
4771         Result = ICS;
4772     }
4773 
4774     // For an empty list, we won't have computed any conversion sequence.
4775     // Introduce the identity conversion sequence.
4776     if (From->getNumInits() == 0) {
4777       Result.setStandard();
4778       Result.Standard.setAsIdentityConversion();
4779       Result.Standard.setFromType(ToType);
4780       Result.Standard.setAllToTypes(ToType);
4781     }
4782 
4783     Result.setStdInitializerListElement(toStdInitializerList);
4784     return Result;
4785   }
4786 
4787   // C++14 [over.ics.list]p4:
4788   // C++11 [over.ics.list]p3:
4789   //   Otherwise, if the parameter is a non-aggregate class X and overload
4790   //   resolution chooses a single best constructor [...] the implicit
4791   //   conversion sequence is a user-defined conversion sequence. If multiple
4792   //   constructors are viable but none is better than the others, the
4793   //   implicit conversion sequence is a user-defined conversion sequence.
4794   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4795     // This function can deal with initializer lists.
4796     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4797                                     /*AllowExplicit=*/false,
4798                                     InOverloadResolution, /*CStyle=*/false,
4799                                     AllowObjCWritebackConversion,
4800                                     /*AllowObjCConversionOnExplicit=*/false);
4801   }
4802 
4803   // C++14 [over.ics.list]p5:
4804   // C++11 [over.ics.list]p4:
4805   //   Otherwise, if the parameter has an aggregate type which can be
4806   //   initialized from the initializer list [...] the implicit conversion
4807   //   sequence is a user-defined conversion sequence.
4808   if (ToType->isAggregateType()) {
4809     // Type is an aggregate, argument is an init list. At this point it comes
4810     // down to checking whether the initialization works.
4811     // FIXME: Find out whether this parameter is consumed or not.
4812     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4813     // need to call into the initialization code here; overload resolution
4814     // should not be doing that.
4815     InitializedEntity Entity =
4816         InitializedEntity::InitializeParameter(S.Context, ToType,
4817                                                /*Consumed=*/false);
4818     if (S.CanPerformCopyInitialization(Entity, From)) {
4819       Result.setUserDefined();
4820       Result.UserDefined.Before.setAsIdentityConversion();
4821       // Initializer lists don't have a type.
4822       Result.UserDefined.Before.setFromType(QualType());
4823       Result.UserDefined.Before.setAllToTypes(QualType());
4824 
4825       Result.UserDefined.After.setAsIdentityConversion();
4826       Result.UserDefined.After.setFromType(ToType);
4827       Result.UserDefined.After.setAllToTypes(ToType);
4828       Result.UserDefined.ConversionFunction = nullptr;
4829     }
4830     return Result;
4831   }
4832 
4833   // C++14 [over.ics.list]p6:
4834   // C++11 [over.ics.list]p5:
4835   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4836   if (ToType->isReferenceType()) {
4837     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4838     // mention initializer lists in any way. So we go by what list-
4839     // initialization would do and try to extrapolate from that.
4840 
4841     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4842 
4843     // If the initializer list has a single element that is reference-related
4844     // to the parameter type, we initialize the reference from that.
4845     if (From->getNumInits() == 1) {
4846       Expr *Init = From->getInit(0);
4847 
4848       QualType T2 = Init->getType();
4849 
4850       // If the initializer is the address of an overloaded function, try
4851       // to resolve the overloaded function. If all goes well, T2 is the
4852       // type of the resulting function.
4853       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4854         DeclAccessPair Found;
4855         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4856                                    Init, ToType, false, Found))
4857           T2 = Fn->getType();
4858       }
4859 
4860       // Compute some basic properties of the types and the initializer.
4861       bool dummy1 = false;
4862       bool dummy2 = false;
4863       bool dummy3 = false;
4864       Sema::ReferenceCompareResult RefRelationship
4865         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4866                                          dummy2, dummy3);
4867 
4868       if (RefRelationship >= Sema::Ref_Related) {
4869         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4870                                 SuppressUserConversions,
4871                                 /*AllowExplicit=*/false);
4872       }
4873     }
4874 
4875     // Otherwise, we bind the reference to a temporary created from the
4876     // initializer list.
4877     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4878                                InOverloadResolution,
4879                                AllowObjCWritebackConversion);
4880     if (Result.isFailure())
4881       return Result;
4882     assert(!Result.isEllipsis() &&
4883            "Sub-initialization cannot result in ellipsis conversion.");
4884 
4885     // Can we even bind to a temporary?
4886     if (ToType->isRValueReferenceType() ||
4887         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4888       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4889                                             Result.UserDefined.After;
4890       SCS.ReferenceBinding = true;
4891       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4892       SCS.BindsToRvalue = true;
4893       SCS.BindsToFunctionLvalue = false;
4894       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4895       SCS.ObjCLifetimeConversionBinding = false;
4896     } else
4897       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4898                     From, ToType);
4899     return Result;
4900   }
4901 
4902   // C++14 [over.ics.list]p7:
4903   // C++11 [over.ics.list]p6:
4904   //   Otherwise, if the parameter type is not a class:
4905   if (!ToType->isRecordType()) {
4906     //    - if the initializer list has one element that is not itself an
4907     //      initializer list, the implicit conversion sequence is the one
4908     //      required to convert the element to the parameter type.
4909     unsigned NumInits = From->getNumInits();
4910     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4911       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4912                                      SuppressUserConversions,
4913                                      InOverloadResolution,
4914                                      AllowObjCWritebackConversion);
4915     //    - if the initializer list has no elements, the implicit conversion
4916     //      sequence is the identity conversion.
4917     else if (NumInits == 0) {
4918       Result.setStandard();
4919       Result.Standard.setAsIdentityConversion();
4920       Result.Standard.setFromType(ToType);
4921       Result.Standard.setAllToTypes(ToType);
4922     }
4923     return Result;
4924   }
4925 
4926   // C++14 [over.ics.list]p8:
4927   // C++11 [over.ics.list]p7:
4928   //   In all cases other than those enumerated above, no conversion is possible
4929   return Result;
4930 }
4931 
4932 /// TryCopyInitialization - Try to copy-initialize a value of type
4933 /// ToType from the expression From. Return the implicit conversion
4934 /// sequence required to pass this argument, which may be a bad
4935 /// conversion sequence (meaning that the argument cannot be passed to
4936 /// a parameter of this type). If @p SuppressUserConversions, then we
4937 /// do not permit any user-defined conversion sequences.
4938 static ImplicitConversionSequence
4939 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4940                       bool SuppressUserConversions,
4941                       bool InOverloadResolution,
4942                       bool AllowObjCWritebackConversion,
4943                       bool AllowExplicit) {
4944   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4945     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4946                              InOverloadResolution,AllowObjCWritebackConversion);
4947 
4948   if (ToType->isReferenceType())
4949     return TryReferenceInit(S, From, ToType,
4950                             /*FIXME:*/From->getLocStart(),
4951                             SuppressUserConversions,
4952                             AllowExplicit);
4953 
4954   return TryImplicitConversion(S, From, ToType,
4955                                SuppressUserConversions,
4956                                /*AllowExplicit=*/false,
4957                                InOverloadResolution,
4958                                /*CStyle=*/false,
4959                                AllowObjCWritebackConversion,
4960                                /*AllowObjCConversionOnExplicit=*/false);
4961 }
4962 
4963 static bool TryCopyInitialization(const CanQualType FromQTy,
4964                                   const CanQualType ToQTy,
4965                                   Sema &S,
4966                                   SourceLocation Loc,
4967                                   ExprValueKind FromVK) {
4968   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4969   ImplicitConversionSequence ICS =
4970     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4971 
4972   return !ICS.isBad();
4973 }
4974 
4975 /// TryObjectArgumentInitialization - Try to initialize the object
4976 /// parameter of the given member function (@c Method) from the
4977 /// expression @p From.
4978 static ImplicitConversionSequence
4979 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4980                                 Expr::Classification FromClassification,
4981                                 CXXMethodDecl *Method,
4982                                 CXXRecordDecl *ActingContext) {
4983   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4984   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4985   //                 const volatile object.
4986   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4987     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4988   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4989 
4990   // Set up the conversion sequence as a "bad" conversion, to allow us
4991   // to exit early.
4992   ImplicitConversionSequence ICS;
4993 
4994   // We need to have an object of class type.
4995   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4996     FromType = PT->getPointeeType();
4997 
4998     // When we had a pointer, it's implicitly dereferenced, so we
4999     // better have an lvalue.
5000     assert(FromClassification.isLValue());
5001   }
5002 
5003   assert(FromType->isRecordType());
5004 
5005   // C++0x [over.match.funcs]p4:
5006   //   For non-static member functions, the type of the implicit object
5007   //   parameter is
5008   //
5009   //     - "lvalue reference to cv X" for functions declared without a
5010   //        ref-qualifier or with the & ref-qualifier
5011   //     - "rvalue reference to cv X" for functions declared with the &&
5012   //        ref-qualifier
5013   //
5014   // where X is the class of which the function is a member and cv is the
5015   // cv-qualification on the member function declaration.
5016   //
5017   // However, when finding an implicit conversion sequence for the argument, we
5018   // are not allowed to perform user-defined conversions
5019   // (C++ [over.match.funcs]p5). We perform a simplified version of
5020   // reference binding here, that allows class rvalues to bind to
5021   // non-constant references.
5022 
5023   // First check the qualifiers.
5024   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5025   if (ImplicitParamType.getCVRQualifiers()
5026                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5027       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5028     ICS.setBad(BadConversionSequence::bad_qualifiers,
5029                FromType, ImplicitParamType);
5030     return ICS;
5031   }
5032 
5033   // Check that we have either the same type or a derived type. It
5034   // affects the conversion rank.
5035   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5036   ImplicitConversionKind SecondKind;
5037   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5038     SecondKind = ICK_Identity;
5039   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5040     SecondKind = ICK_Derived_To_Base;
5041   else {
5042     ICS.setBad(BadConversionSequence::unrelated_class,
5043                FromType, ImplicitParamType);
5044     return ICS;
5045   }
5046 
5047   // Check the ref-qualifier.
5048   switch (Method->getRefQualifier()) {
5049   case RQ_None:
5050     // Do nothing; we don't care about lvalueness or rvalueness.
5051     break;
5052 
5053   case RQ_LValue:
5054     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5055       // non-const lvalue reference cannot bind to an rvalue
5056       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5057                  ImplicitParamType);
5058       return ICS;
5059     }
5060     break;
5061 
5062   case RQ_RValue:
5063     if (!FromClassification.isRValue()) {
5064       // rvalue reference cannot bind to an lvalue
5065       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5066                  ImplicitParamType);
5067       return ICS;
5068     }
5069     break;
5070   }
5071 
5072   // Success. Mark this as a reference binding.
5073   ICS.setStandard();
5074   ICS.Standard.setAsIdentityConversion();
5075   ICS.Standard.Second = SecondKind;
5076   ICS.Standard.setFromType(FromType);
5077   ICS.Standard.setAllToTypes(ImplicitParamType);
5078   ICS.Standard.ReferenceBinding = true;
5079   ICS.Standard.DirectBinding = true;
5080   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5081   ICS.Standard.BindsToFunctionLvalue = false;
5082   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5083   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5084     = (Method->getRefQualifier() == RQ_None);
5085   return ICS;
5086 }
5087 
5088 /// PerformObjectArgumentInitialization - Perform initialization of
5089 /// the implicit object parameter for the given Method with the given
5090 /// expression.
5091 ExprResult
5092 Sema::PerformObjectArgumentInitialization(Expr *From,
5093                                           NestedNameSpecifier *Qualifier,
5094                                           NamedDecl *FoundDecl,
5095                                           CXXMethodDecl *Method) {
5096   QualType FromRecordType, DestType;
5097   QualType ImplicitParamRecordType  =
5098     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5099 
5100   Expr::Classification FromClassification;
5101   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5102     FromRecordType = PT->getPointeeType();
5103     DestType = Method->getThisType(Context);
5104     FromClassification = Expr::Classification::makeSimpleLValue();
5105   } else {
5106     FromRecordType = From->getType();
5107     DestType = ImplicitParamRecordType;
5108     FromClassification = From->Classify(Context);
5109   }
5110 
5111   // Note that we always use the true parent context when performing
5112   // the actual argument initialization.
5113   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5114       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5115       Method->getParent());
5116   if (ICS.isBad()) {
5117     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5118       Qualifiers FromQs = FromRecordType.getQualifiers();
5119       Qualifiers ToQs = DestType.getQualifiers();
5120       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5121       if (CVR) {
5122         Diag(From->getLocStart(),
5123              diag::err_member_function_call_bad_cvr)
5124           << Method->getDeclName() << FromRecordType << (CVR - 1)
5125           << From->getSourceRange();
5126         Diag(Method->getLocation(), diag::note_previous_decl)
5127           << Method->getDeclName();
5128         return ExprError();
5129       }
5130     }
5131 
5132     return Diag(From->getLocStart(),
5133                 diag::err_implicit_object_parameter_init)
5134        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5135   }
5136 
5137   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5138     ExprResult FromRes =
5139       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5140     if (FromRes.isInvalid())
5141       return ExprError();
5142     From = FromRes.get();
5143   }
5144 
5145   if (!Context.hasSameType(From->getType(), DestType))
5146     From = ImpCastExprToType(From, DestType, CK_NoOp,
5147                              From->getValueKind()).get();
5148   return From;
5149 }
5150 
5151 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5152 /// expression From to bool (C++0x [conv]p3).
5153 static ImplicitConversionSequence
5154 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5155   return TryImplicitConversion(S, From, S.Context.BoolTy,
5156                                /*SuppressUserConversions=*/false,
5157                                /*AllowExplicit=*/true,
5158                                /*InOverloadResolution=*/false,
5159                                /*CStyle=*/false,
5160                                /*AllowObjCWritebackConversion=*/false,
5161                                /*AllowObjCConversionOnExplicit=*/false);
5162 }
5163 
5164 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5165 /// of the expression From to bool (C++0x [conv]p3).
5166 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5167   if (checkPlaceholderForOverload(*this, From))
5168     return ExprError();
5169 
5170   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5171   if (!ICS.isBad())
5172     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5173 
5174   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5175     return Diag(From->getLocStart(),
5176                 diag::err_typecheck_bool_condition)
5177                   << From->getType() << From->getSourceRange();
5178   return ExprError();
5179 }
5180 
5181 /// Check that the specified conversion is permitted in a converted constant
5182 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5183 /// is acceptable.
5184 static bool CheckConvertedConstantConversions(Sema &S,
5185                                               StandardConversionSequence &SCS) {
5186   // Since we know that the target type is an integral or unscoped enumeration
5187   // type, most conversion kinds are impossible. All possible First and Third
5188   // conversions are fine.
5189   switch (SCS.Second) {
5190   case ICK_Identity:
5191   case ICK_Function_Conversion:
5192   case ICK_Integral_Promotion:
5193   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5194   case ICK_Zero_Queue_Conversion:
5195     return true;
5196 
5197   case ICK_Boolean_Conversion:
5198     // Conversion from an integral or unscoped enumeration type to bool is
5199     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5200     // conversion, so we allow it in a converted constant expression.
5201     //
5202     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5203     // a lot of popular code. We should at least add a warning for this
5204     // (non-conforming) extension.
5205     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5206            SCS.getToType(2)->isBooleanType();
5207 
5208   case ICK_Pointer_Conversion:
5209   case ICK_Pointer_Member:
5210     // C++1z: null pointer conversions and null member pointer conversions are
5211     // only permitted if the source type is std::nullptr_t.
5212     return SCS.getFromType()->isNullPtrType();
5213 
5214   case ICK_Floating_Promotion:
5215   case ICK_Complex_Promotion:
5216   case ICK_Floating_Conversion:
5217   case ICK_Complex_Conversion:
5218   case ICK_Floating_Integral:
5219   case ICK_Compatible_Conversion:
5220   case ICK_Derived_To_Base:
5221   case ICK_Vector_Conversion:
5222   case ICK_Vector_Splat:
5223   case ICK_Complex_Real:
5224   case ICK_Block_Pointer_Conversion:
5225   case ICK_TransparentUnionConversion:
5226   case ICK_Writeback_Conversion:
5227   case ICK_Zero_Event_Conversion:
5228   case ICK_C_Only_Conversion:
5229   case ICK_Incompatible_Pointer_Conversion:
5230     return false;
5231 
5232   case ICK_Lvalue_To_Rvalue:
5233   case ICK_Array_To_Pointer:
5234   case ICK_Function_To_Pointer:
5235     llvm_unreachable("found a first conversion kind in Second");
5236 
5237   case ICK_Qualification:
5238     llvm_unreachable("found a third conversion kind in Second");
5239 
5240   case ICK_Num_Conversion_Kinds:
5241     break;
5242   }
5243 
5244   llvm_unreachable("unknown conversion kind");
5245 }
5246 
5247 /// CheckConvertedConstantExpression - Check that the expression From is a
5248 /// converted constant expression of type T, perform the conversion and produce
5249 /// the converted expression, per C++11 [expr.const]p3.
5250 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5251                                                    QualType T, APValue &Value,
5252                                                    Sema::CCEKind CCE,
5253                                                    bool RequireInt) {
5254   assert(S.getLangOpts().CPlusPlus11 &&
5255          "converted constant expression outside C++11");
5256 
5257   if (checkPlaceholderForOverload(S, From))
5258     return ExprError();
5259 
5260   // C++1z [expr.const]p3:
5261   //  A converted constant expression of type T is an expression,
5262   //  implicitly converted to type T, where the converted
5263   //  expression is a constant expression and the implicit conversion
5264   //  sequence contains only [... list of conversions ...].
5265   // C++1z [stmt.if]p2:
5266   //  If the if statement is of the form if constexpr, the value of the
5267   //  condition shall be a contextually converted constant expression of type
5268   //  bool.
5269   ImplicitConversionSequence ICS =
5270       CCE == Sema::CCEK_ConstexprIf
5271           ? TryContextuallyConvertToBool(S, From)
5272           : TryCopyInitialization(S, From, T,
5273                                   /*SuppressUserConversions=*/false,
5274                                   /*InOverloadResolution=*/false,
5275                                   /*AllowObjcWritebackConversion=*/false,
5276                                   /*AllowExplicit=*/false);
5277   StandardConversionSequence *SCS = nullptr;
5278   switch (ICS.getKind()) {
5279   case ImplicitConversionSequence::StandardConversion:
5280     SCS = &ICS.Standard;
5281     break;
5282   case ImplicitConversionSequence::UserDefinedConversion:
5283     // We are converting to a non-class type, so the Before sequence
5284     // must be trivial.
5285     SCS = &ICS.UserDefined.After;
5286     break;
5287   case ImplicitConversionSequence::AmbiguousConversion:
5288   case ImplicitConversionSequence::BadConversion:
5289     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5290       return S.Diag(From->getLocStart(),
5291                     diag::err_typecheck_converted_constant_expression)
5292                 << From->getType() << From->getSourceRange() << T;
5293     return ExprError();
5294 
5295   case ImplicitConversionSequence::EllipsisConversion:
5296     llvm_unreachable("ellipsis conversion in converted constant expression");
5297   }
5298 
5299   // Check that we would only use permitted conversions.
5300   if (!CheckConvertedConstantConversions(S, *SCS)) {
5301     return S.Diag(From->getLocStart(),
5302                   diag::err_typecheck_converted_constant_expression_disallowed)
5303              << From->getType() << From->getSourceRange() << T;
5304   }
5305   // [...] and where the reference binding (if any) binds directly.
5306   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5307     return S.Diag(From->getLocStart(),
5308                   diag::err_typecheck_converted_constant_expression_indirect)
5309              << From->getType() << From->getSourceRange() << T;
5310   }
5311 
5312   ExprResult Result =
5313       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5314   if (Result.isInvalid())
5315     return Result;
5316 
5317   // Check for a narrowing implicit conversion.
5318   APValue PreNarrowingValue;
5319   QualType PreNarrowingType;
5320   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5321                                 PreNarrowingType)) {
5322   case NK_Dependent_Narrowing:
5323     // Implicit conversion to a narrower type, but the expression is
5324     // value-dependent so we can't tell whether it's actually narrowing.
5325   case NK_Variable_Narrowing:
5326     // Implicit conversion to a narrower type, and the value is not a constant
5327     // expression. We'll diagnose this in a moment.
5328   case NK_Not_Narrowing:
5329     break;
5330 
5331   case NK_Constant_Narrowing:
5332     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5333       << CCE << /*Constant*/1
5334       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5335     break;
5336 
5337   case NK_Type_Narrowing:
5338     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5339       << CCE << /*Constant*/0 << From->getType() << T;
5340     break;
5341   }
5342 
5343   if (Result.get()->isValueDependent()) {
5344     Value = APValue();
5345     return Result;
5346   }
5347 
5348   // Check the expression is a constant expression.
5349   SmallVector<PartialDiagnosticAt, 8> Notes;
5350   Expr::EvalResult Eval;
5351   Eval.Diag = &Notes;
5352 
5353   if ((T->isReferenceType()
5354            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5355            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5356       (RequireInt && !Eval.Val.isInt())) {
5357     // The expression can't be folded, so we can't keep it at this position in
5358     // the AST.
5359     Result = ExprError();
5360   } else {
5361     Value = Eval.Val;
5362 
5363     if (Notes.empty()) {
5364       // It's a constant expression.
5365       return Result;
5366     }
5367   }
5368 
5369   // It's not a constant expression. Produce an appropriate diagnostic.
5370   if (Notes.size() == 1 &&
5371       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5372     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5373   else {
5374     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5375       << CCE << From->getSourceRange();
5376     for (unsigned I = 0; I < Notes.size(); ++I)
5377       S.Diag(Notes[I].first, Notes[I].second);
5378   }
5379   return ExprError();
5380 }
5381 
5382 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5383                                                   APValue &Value, CCEKind CCE) {
5384   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5385 }
5386 
5387 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5388                                                   llvm::APSInt &Value,
5389                                                   CCEKind CCE) {
5390   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5391 
5392   APValue V;
5393   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5394   if (!R.isInvalid() && !R.get()->isValueDependent())
5395     Value = V.getInt();
5396   return R;
5397 }
5398 
5399 
5400 /// dropPointerConversions - If the given standard conversion sequence
5401 /// involves any pointer conversions, remove them.  This may change
5402 /// the result type of the conversion sequence.
5403 static void dropPointerConversion(StandardConversionSequence &SCS) {
5404   if (SCS.Second == ICK_Pointer_Conversion) {
5405     SCS.Second = ICK_Identity;
5406     SCS.Third = ICK_Identity;
5407     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5408   }
5409 }
5410 
5411 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5412 /// convert the expression From to an Objective-C pointer type.
5413 static ImplicitConversionSequence
5414 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5415   // Do an implicit conversion to 'id'.
5416   QualType Ty = S.Context.getObjCIdType();
5417   ImplicitConversionSequence ICS
5418     = TryImplicitConversion(S, From, Ty,
5419                             // FIXME: Are these flags correct?
5420                             /*SuppressUserConversions=*/false,
5421                             /*AllowExplicit=*/true,
5422                             /*InOverloadResolution=*/false,
5423                             /*CStyle=*/false,
5424                             /*AllowObjCWritebackConversion=*/false,
5425                             /*AllowObjCConversionOnExplicit=*/true);
5426 
5427   // Strip off any final conversions to 'id'.
5428   switch (ICS.getKind()) {
5429   case ImplicitConversionSequence::BadConversion:
5430   case ImplicitConversionSequence::AmbiguousConversion:
5431   case ImplicitConversionSequence::EllipsisConversion:
5432     break;
5433 
5434   case ImplicitConversionSequence::UserDefinedConversion:
5435     dropPointerConversion(ICS.UserDefined.After);
5436     break;
5437 
5438   case ImplicitConversionSequence::StandardConversion:
5439     dropPointerConversion(ICS.Standard);
5440     break;
5441   }
5442 
5443   return ICS;
5444 }
5445 
5446 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5447 /// conversion of the expression From to an Objective-C pointer type.
5448 /// Returns a valid but null ExprResult if no conversion sequence exists.
5449 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5450   if (checkPlaceholderForOverload(*this, From))
5451     return ExprError();
5452 
5453   QualType Ty = Context.getObjCIdType();
5454   ImplicitConversionSequence ICS =
5455     TryContextuallyConvertToObjCPointer(*this, From);
5456   if (!ICS.isBad())
5457     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5458   return ExprResult();
5459 }
5460 
5461 /// Determine whether the provided type is an integral type, or an enumeration
5462 /// type of a permitted flavor.
5463 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5464   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5465                                  : T->isIntegralOrUnscopedEnumerationType();
5466 }
5467 
5468 static ExprResult
5469 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5470                             Sema::ContextualImplicitConverter &Converter,
5471                             QualType T, UnresolvedSetImpl &ViableConversions) {
5472 
5473   if (Converter.Suppress)
5474     return ExprError();
5475 
5476   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5477   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5478     CXXConversionDecl *Conv =
5479         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5480     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5481     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5482   }
5483   return From;
5484 }
5485 
5486 static bool
5487 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5488                            Sema::ContextualImplicitConverter &Converter,
5489                            QualType T, bool HadMultipleCandidates,
5490                            UnresolvedSetImpl &ExplicitConversions) {
5491   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5492     DeclAccessPair Found = ExplicitConversions[0];
5493     CXXConversionDecl *Conversion =
5494         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5495 
5496     // The user probably meant to invoke the given explicit
5497     // conversion; use it.
5498     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5499     std::string TypeStr;
5500     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5501 
5502     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5503         << FixItHint::CreateInsertion(From->getLocStart(),
5504                                       "static_cast<" + TypeStr + ">(")
5505         << FixItHint::CreateInsertion(
5506                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5507     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5508 
5509     // If we aren't in a SFINAE context, build a call to the
5510     // explicit conversion function.
5511     if (SemaRef.isSFINAEContext())
5512       return true;
5513 
5514     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5515     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5516                                                        HadMultipleCandidates);
5517     if (Result.isInvalid())
5518       return true;
5519     // Record usage of conversion in an implicit cast.
5520     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5521                                     CK_UserDefinedConversion, Result.get(),
5522                                     nullptr, Result.get()->getValueKind());
5523   }
5524   return false;
5525 }
5526 
5527 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5528                              Sema::ContextualImplicitConverter &Converter,
5529                              QualType T, bool HadMultipleCandidates,
5530                              DeclAccessPair &Found) {
5531   CXXConversionDecl *Conversion =
5532       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5533   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5534 
5535   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5536   if (!Converter.SuppressConversion) {
5537     if (SemaRef.isSFINAEContext())
5538       return true;
5539 
5540     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5541         << From->getSourceRange();
5542   }
5543 
5544   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5545                                                      HadMultipleCandidates);
5546   if (Result.isInvalid())
5547     return true;
5548   // Record usage of conversion in an implicit cast.
5549   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5550                                   CK_UserDefinedConversion, Result.get(),
5551                                   nullptr, Result.get()->getValueKind());
5552   return false;
5553 }
5554 
5555 static ExprResult finishContextualImplicitConversion(
5556     Sema &SemaRef, SourceLocation Loc, Expr *From,
5557     Sema::ContextualImplicitConverter &Converter) {
5558   if (!Converter.match(From->getType()) && !Converter.Suppress)
5559     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5560         << From->getSourceRange();
5561 
5562   return SemaRef.DefaultLvalueConversion(From);
5563 }
5564 
5565 static void
5566 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5567                                   UnresolvedSetImpl &ViableConversions,
5568                                   OverloadCandidateSet &CandidateSet) {
5569   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5570     DeclAccessPair FoundDecl = ViableConversions[I];
5571     NamedDecl *D = FoundDecl.getDecl();
5572     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5573     if (isa<UsingShadowDecl>(D))
5574       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5575 
5576     CXXConversionDecl *Conv;
5577     FunctionTemplateDecl *ConvTemplate;
5578     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5579       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5580     else
5581       Conv = cast<CXXConversionDecl>(D);
5582 
5583     if (ConvTemplate)
5584       SemaRef.AddTemplateConversionCandidate(
5585         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5586         /*AllowObjCConversionOnExplicit=*/false);
5587     else
5588       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5589                                      ToType, CandidateSet,
5590                                      /*AllowObjCConversionOnExplicit=*/false);
5591   }
5592 }
5593 
5594 /// \brief Attempt to convert the given expression to a type which is accepted
5595 /// by the given converter.
5596 ///
5597 /// This routine will attempt to convert an expression of class type to a
5598 /// type accepted by the specified converter. In C++11 and before, the class
5599 /// must have a single non-explicit conversion function converting to a matching
5600 /// type. In C++1y, there can be multiple such conversion functions, but only
5601 /// one target type.
5602 ///
5603 /// \param Loc The source location of the construct that requires the
5604 /// conversion.
5605 ///
5606 /// \param From The expression we're converting from.
5607 ///
5608 /// \param Converter Used to control and diagnose the conversion process.
5609 ///
5610 /// \returns The expression, converted to an integral or enumeration type if
5611 /// successful.
5612 ExprResult Sema::PerformContextualImplicitConversion(
5613     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5614   // We can't perform any more checking for type-dependent expressions.
5615   if (From->isTypeDependent())
5616     return From;
5617 
5618   // Process placeholders immediately.
5619   if (From->hasPlaceholderType()) {
5620     ExprResult result = CheckPlaceholderExpr(From);
5621     if (result.isInvalid())
5622       return result;
5623     From = result.get();
5624   }
5625 
5626   // If the expression already has a matching type, we're golden.
5627   QualType T = From->getType();
5628   if (Converter.match(T))
5629     return DefaultLvalueConversion(From);
5630 
5631   // FIXME: Check for missing '()' if T is a function type?
5632 
5633   // We can only perform contextual implicit conversions on objects of class
5634   // type.
5635   const RecordType *RecordTy = T->getAs<RecordType>();
5636   if (!RecordTy || !getLangOpts().CPlusPlus) {
5637     if (!Converter.Suppress)
5638       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5639     return From;
5640   }
5641 
5642   // We must have a complete class type.
5643   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5644     ContextualImplicitConverter &Converter;
5645     Expr *From;
5646 
5647     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5648         : Converter(Converter), From(From) {}
5649 
5650     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5651       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5652     }
5653   } IncompleteDiagnoser(Converter, From);
5654 
5655   if (Converter.Suppress ? !isCompleteType(Loc, T)
5656                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5657     return From;
5658 
5659   // Look for a conversion to an integral or enumeration type.
5660   UnresolvedSet<4>
5661       ViableConversions; // These are *potentially* viable in C++1y.
5662   UnresolvedSet<4> ExplicitConversions;
5663   const auto &Conversions =
5664       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5665 
5666   bool HadMultipleCandidates =
5667       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5668 
5669   // To check that there is only one target type, in C++1y:
5670   QualType ToType;
5671   bool HasUniqueTargetType = true;
5672 
5673   // Collect explicit or viable (potentially in C++1y) conversions.
5674   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5675     NamedDecl *D = (*I)->getUnderlyingDecl();
5676     CXXConversionDecl *Conversion;
5677     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5678     if (ConvTemplate) {
5679       if (getLangOpts().CPlusPlus14)
5680         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5681       else
5682         continue; // C++11 does not consider conversion operator templates(?).
5683     } else
5684       Conversion = cast<CXXConversionDecl>(D);
5685 
5686     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5687            "Conversion operator templates are considered potentially "
5688            "viable in C++1y");
5689 
5690     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5691     if (Converter.match(CurToType) || ConvTemplate) {
5692 
5693       if (Conversion->isExplicit()) {
5694         // FIXME: For C++1y, do we need this restriction?
5695         // cf. diagnoseNoViableConversion()
5696         if (!ConvTemplate)
5697           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5698       } else {
5699         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5700           if (ToType.isNull())
5701             ToType = CurToType.getUnqualifiedType();
5702           else if (HasUniqueTargetType &&
5703                    (CurToType.getUnqualifiedType() != ToType))
5704             HasUniqueTargetType = false;
5705         }
5706         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5707       }
5708     }
5709   }
5710 
5711   if (getLangOpts().CPlusPlus14) {
5712     // C++1y [conv]p6:
5713     // ... An expression e of class type E appearing in such a context
5714     // is said to be contextually implicitly converted to a specified
5715     // type T and is well-formed if and only if e can be implicitly
5716     // converted to a type T that is determined as follows: E is searched
5717     // for conversion functions whose return type is cv T or reference to
5718     // cv T such that T is allowed by the context. There shall be
5719     // exactly one such T.
5720 
5721     // If no unique T is found:
5722     if (ToType.isNull()) {
5723       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5724                                      HadMultipleCandidates,
5725                                      ExplicitConversions))
5726         return ExprError();
5727       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5728     }
5729 
5730     // If more than one unique Ts are found:
5731     if (!HasUniqueTargetType)
5732       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5733                                          ViableConversions);
5734 
5735     // If one unique T is found:
5736     // First, build a candidate set from the previously recorded
5737     // potentially viable conversions.
5738     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5739     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5740                                       CandidateSet);
5741 
5742     // Then, perform overload resolution over the candidate set.
5743     OverloadCandidateSet::iterator Best;
5744     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5745     case OR_Success: {
5746       // Apply this conversion.
5747       DeclAccessPair Found =
5748           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5749       if (recordConversion(*this, Loc, From, Converter, T,
5750                            HadMultipleCandidates, Found))
5751         return ExprError();
5752       break;
5753     }
5754     case OR_Ambiguous:
5755       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5756                                          ViableConversions);
5757     case OR_No_Viable_Function:
5758       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5759                                      HadMultipleCandidates,
5760                                      ExplicitConversions))
5761         return ExprError();
5762     // fall through 'OR_Deleted' case.
5763     case OR_Deleted:
5764       // We'll complain below about a non-integral condition type.
5765       break;
5766     }
5767   } else {
5768     switch (ViableConversions.size()) {
5769     case 0: {
5770       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5771                                      HadMultipleCandidates,
5772                                      ExplicitConversions))
5773         return ExprError();
5774 
5775       // We'll complain below about a non-integral condition type.
5776       break;
5777     }
5778     case 1: {
5779       // Apply this conversion.
5780       DeclAccessPair Found = ViableConversions[0];
5781       if (recordConversion(*this, Loc, From, Converter, T,
5782                            HadMultipleCandidates, Found))
5783         return ExprError();
5784       break;
5785     }
5786     default:
5787       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5788                                          ViableConversions);
5789     }
5790   }
5791 
5792   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5793 }
5794 
5795 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5796 /// an acceptable non-member overloaded operator for a call whose
5797 /// arguments have types T1 (and, if non-empty, T2). This routine
5798 /// implements the check in C++ [over.match.oper]p3b2 concerning
5799 /// enumeration types.
5800 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5801                                                    FunctionDecl *Fn,
5802                                                    ArrayRef<Expr *> Args) {
5803   QualType T1 = Args[0]->getType();
5804   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5805 
5806   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5807     return true;
5808 
5809   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5810     return true;
5811 
5812   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5813   if (Proto->getNumParams() < 1)
5814     return false;
5815 
5816   if (T1->isEnumeralType()) {
5817     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5818     if (Context.hasSameUnqualifiedType(T1, ArgType))
5819       return true;
5820   }
5821 
5822   if (Proto->getNumParams() < 2)
5823     return false;
5824 
5825   if (!T2.isNull() && T2->isEnumeralType()) {
5826     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5827     if (Context.hasSameUnqualifiedType(T2, ArgType))
5828       return true;
5829   }
5830 
5831   return false;
5832 }
5833 
5834 static void initDiagnoseIfComplaint(Sema &S, OverloadCandidateSet &CandidateSet,
5835                                     OverloadCandidate &Candidate,
5836                                     FunctionDecl *Function,
5837                                     ArrayRef<Expr *> Args,
5838                                     bool MissingImplicitThis = false,
5839                                     Expr *ExplicitThis = nullptr) {
5840   SmallVector<DiagnoseIfAttr *, 8> Results;
5841   if (DiagnoseIfAttr *DIA = S.checkArgDependentDiagnoseIf(
5842           Function, Args, Results, MissingImplicitThis, ExplicitThis)) {
5843     Results.clear();
5844     Results.push_back(DIA);
5845   }
5846 
5847   Candidate.NumTriggeredDiagnoseIfs = Results.size();
5848   if (Results.empty())
5849     Candidate.DiagnoseIfInfo = nullptr;
5850   else if (Results.size() == 1)
5851     Candidate.DiagnoseIfInfo = Results[0];
5852   else
5853     Candidate.DiagnoseIfInfo = CandidateSet.addDiagnoseIfComplaints(Results);
5854 }
5855 
5856 /// AddOverloadCandidate - Adds the given function to the set of
5857 /// candidate functions, using the given function call arguments.  If
5858 /// @p SuppressUserConversions, then don't allow user-defined
5859 /// conversions via constructors or conversion operators.
5860 ///
5861 /// \param PartialOverloading true if we are performing "partial" overloading
5862 /// based on an incomplete set of function arguments. This feature is used by
5863 /// code completion.
5864 void
5865 Sema::AddOverloadCandidate(FunctionDecl *Function,
5866                            DeclAccessPair FoundDecl,
5867                            ArrayRef<Expr *> Args,
5868                            OverloadCandidateSet &CandidateSet,
5869                            bool SuppressUserConversions,
5870                            bool PartialOverloading,
5871                            bool AllowExplicit,
5872                            ConversionSequenceList EarlyConversions) {
5873   const FunctionProtoType *Proto
5874     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5875   assert(Proto && "Functions without a prototype cannot be overloaded");
5876   assert(!Function->getDescribedFunctionTemplate() &&
5877          "Use AddTemplateOverloadCandidate for function templates");
5878 
5879   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5880     if (!isa<CXXConstructorDecl>(Method)) {
5881       // If we get here, it's because we're calling a member function
5882       // that is named without a member access expression (e.g.,
5883       // "this->f") that was either written explicitly or created
5884       // implicitly. This can happen with a qualified call to a member
5885       // function, e.g., X::f(). We use an empty type for the implied
5886       // object argument (C++ [over.call.func]p3), and the acting context
5887       // is irrelevant.
5888       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5889                          Expr::Classification::makeSimpleLValue(),
5890                          /*ThisArg=*/nullptr, Args, CandidateSet,
5891                          SuppressUserConversions, PartialOverloading,
5892                          EarlyConversions);
5893       return;
5894     }
5895     // We treat a constructor like a non-member function, since its object
5896     // argument doesn't participate in overload resolution.
5897   }
5898 
5899   if (!CandidateSet.isNewCandidate(Function))
5900     return;
5901 
5902   // C++ [over.match.oper]p3:
5903   //   if no operand has a class type, only those non-member functions in the
5904   //   lookup set that have a first parameter of type T1 or "reference to
5905   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5906   //   is a right operand) a second parameter of type T2 or "reference to
5907   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5908   //   candidate functions.
5909   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5910       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5911     return;
5912 
5913   // C++11 [class.copy]p11: [DR1402]
5914   //   A defaulted move constructor that is defined as deleted is ignored by
5915   //   overload resolution.
5916   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5917   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5918       Constructor->isMoveConstructor())
5919     return;
5920 
5921   // Overload resolution is always an unevaluated context.
5922   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5923 
5924   // Add this candidate
5925   OverloadCandidate &Candidate =
5926       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5927   Candidate.FoundDecl = FoundDecl;
5928   Candidate.Function = Function;
5929   Candidate.Viable = true;
5930   Candidate.IsSurrogate = false;
5931   Candidate.IgnoreObjectArgument = false;
5932   Candidate.ExplicitCallArguments = Args.size();
5933 
5934   if (Constructor) {
5935     // C++ [class.copy]p3:
5936     //   A member function template is never instantiated to perform the copy
5937     //   of a class object to an object of its class type.
5938     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5939     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5940         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5941          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5942                        ClassType))) {
5943       Candidate.Viable = false;
5944       Candidate.FailureKind = ovl_fail_illegal_constructor;
5945       return;
5946     }
5947 
5948     // C++ [over.match.funcs]p8: (proposed DR resolution)
5949     //   A constructor inherited from class type C that has a first parameter
5950     //   of type "reference to P" (including such a constructor instantiated
5951     //   from a template) is excluded from the set of candidate functions when
5952     //   constructing an object of type cv D if the argument list has exactly
5953     //   one argument and D is reference-related to P and P is reference-related
5954     //   to C.
5955     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5956     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5957         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5958       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5959       QualType C = Context.getRecordType(Constructor->getParent());
5960       QualType D = Context.getRecordType(Shadow->getParent());
5961       SourceLocation Loc = Args.front()->getExprLoc();
5962       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5963           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5964         Candidate.Viable = false;
5965         Candidate.FailureKind = ovl_fail_inhctor_slice;
5966         return;
5967       }
5968     }
5969   }
5970 
5971   unsigned NumParams = Proto->getNumParams();
5972 
5973   // (C++ 13.3.2p2): A candidate function having fewer than m
5974   // parameters is viable only if it has an ellipsis in its parameter
5975   // list (8.3.5).
5976   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5977       !Proto->isVariadic()) {
5978     Candidate.Viable = false;
5979     Candidate.FailureKind = ovl_fail_too_many_arguments;
5980     return;
5981   }
5982 
5983   // (C++ 13.3.2p2): A candidate function having more than m parameters
5984   // is viable only if the (m+1)st parameter has a default argument
5985   // (8.3.6). For the purposes of overload resolution, the
5986   // parameter list is truncated on the right, so that there are
5987   // exactly m parameters.
5988   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5989   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5990     // Not enough arguments.
5991     Candidate.Viable = false;
5992     Candidate.FailureKind = ovl_fail_too_few_arguments;
5993     return;
5994   }
5995 
5996   // (CUDA B.1): Check for invalid calls between targets.
5997   if (getLangOpts().CUDA)
5998     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5999       // Skip the check for callers that are implicit members, because in this
6000       // case we may not yet know what the member's target is; the target is
6001       // inferred for the member automatically, based on the bases and fields of
6002       // the class.
6003       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6004         Candidate.Viable = false;
6005         Candidate.FailureKind = ovl_fail_bad_target;
6006         return;
6007       }
6008 
6009   // Determine the implicit conversion sequences for each of the
6010   // arguments.
6011   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6012     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6013       // We already formed a conversion sequence for this parameter during
6014       // template argument deduction.
6015     } else if (ArgIdx < NumParams) {
6016       // (C++ 13.3.2p3): for F to be a viable function, there shall
6017       // exist for each argument an implicit conversion sequence
6018       // (13.3.3.1) that converts that argument to the corresponding
6019       // parameter of F.
6020       QualType ParamType = Proto->getParamType(ArgIdx);
6021       Candidate.Conversions[ArgIdx]
6022         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6023                                 SuppressUserConversions,
6024                                 /*InOverloadResolution=*/true,
6025                                 /*AllowObjCWritebackConversion=*/
6026                                   getLangOpts().ObjCAutoRefCount,
6027                                 AllowExplicit);
6028       if (Candidate.Conversions[ArgIdx].isBad()) {
6029         Candidate.Viable = false;
6030         Candidate.FailureKind = ovl_fail_bad_conversion;
6031         return;
6032       }
6033     } else {
6034       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6035       // argument for which there is no corresponding parameter is
6036       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6037       Candidate.Conversions[ArgIdx].setEllipsis();
6038     }
6039   }
6040 
6041   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6042     Candidate.Viable = false;
6043     Candidate.FailureKind = ovl_fail_enable_if;
6044     Candidate.DeductionFailure.Data = FailedAttr;
6045     return;
6046   }
6047 
6048   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6049     Candidate.Viable = false;
6050     Candidate.FailureKind = ovl_fail_ext_disabled;
6051     return;
6052   }
6053 
6054   initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Function, Args);
6055 }
6056 
6057 ObjCMethodDecl *
6058 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6059                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6060   if (Methods.size() <= 1)
6061     return nullptr;
6062 
6063   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6064     bool Match = true;
6065     ObjCMethodDecl *Method = Methods[b];
6066     unsigned NumNamedArgs = Sel.getNumArgs();
6067     // Method might have more arguments than selector indicates. This is due
6068     // to addition of c-style arguments in method.
6069     if (Method->param_size() > NumNamedArgs)
6070       NumNamedArgs = Method->param_size();
6071     if (Args.size() < NumNamedArgs)
6072       continue;
6073 
6074     for (unsigned i = 0; i < NumNamedArgs; i++) {
6075       // We can't do any type-checking on a type-dependent argument.
6076       if (Args[i]->isTypeDependent()) {
6077         Match = false;
6078         break;
6079       }
6080 
6081       ParmVarDecl *param = Method->parameters()[i];
6082       Expr *argExpr = Args[i];
6083       assert(argExpr && "SelectBestMethod(): missing expression");
6084 
6085       // Strip the unbridged-cast placeholder expression off unless it's
6086       // a consumed argument.
6087       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6088           !param->hasAttr<CFConsumedAttr>())
6089         argExpr = stripARCUnbridgedCast(argExpr);
6090 
6091       // If the parameter is __unknown_anytype, move on to the next method.
6092       if (param->getType() == Context.UnknownAnyTy) {
6093         Match = false;
6094         break;
6095       }
6096 
6097       ImplicitConversionSequence ConversionState
6098         = TryCopyInitialization(*this, argExpr, param->getType(),
6099                                 /*SuppressUserConversions*/false,
6100                                 /*InOverloadResolution=*/true,
6101                                 /*AllowObjCWritebackConversion=*/
6102                                 getLangOpts().ObjCAutoRefCount,
6103                                 /*AllowExplicit*/false);
6104       // This function looks for a reasonably-exact match, so we consider
6105       // incompatible pointer conversions to be a failure here.
6106       if (ConversionState.isBad() ||
6107           (ConversionState.isStandard() &&
6108            ConversionState.Standard.Second ==
6109                ICK_Incompatible_Pointer_Conversion)) {
6110         Match = false;
6111         break;
6112       }
6113     }
6114     // Promote additional arguments to variadic methods.
6115     if (Match && Method->isVariadic()) {
6116       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6117         if (Args[i]->isTypeDependent()) {
6118           Match = false;
6119           break;
6120         }
6121         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6122                                                           nullptr);
6123         if (Arg.isInvalid()) {
6124           Match = false;
6125           break;
6126         }
6127       }
6128     } else {
6129       // Check for extra arguments to non-variadic methods.
6130       if (Args.size() != NumNamedArgs)
6131         Match = false;
6132       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6133         // Special case when selectors have no argument. In this case, select
6134         // one with the most general result type of 'id'.
6135         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6136           QualType ReturnT = Methods[b]->getReturnType();
6137           if (ReturnT->isObjCIdType())
6138             return Methods[b];
6139         }
6140       }
6141     }
6142 
6143     if (Match)
6144       return Method;
6145   }
6146   return nullptr;
6147 }
6148 
6149 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6150 // enable_if is order-sensitive. As a result, we need to reverse things
6151 // sometimes. Size of 4 elements is arbitrary.
6152 static SmallVector<EnableIfAttr *, 4>
6153 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6154   SmallVector<EnableIfAttr *, 4> Result;
6155   if (!Function->hasAttrs())
6156     return Result;
6157 
6158   const auto &FuncAttrs = Function->getAttrs();
6159   for (Attr *Attr : FuncAttrs)
6160     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6161       Result.push_back(EnableIf);
6162 
6163   std::reverse(Result.begin(), Result.end());
6164   return Result;
6165 }
6166 
6167 static bool
6168 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6169                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6170                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6171                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6172   if (ThisArg) {
6173     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6174     assert(!isa<CXXConstructorDecl>(Method) &&
6175            "Shouldn't have `this` for ctors!");
6176     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6177     ExprResult R = S.PerformObjectArgumentInitialization(
6178         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6179     if (R.isInvalid())
6180       return false;
6181     ConvertedThis = R.get();
6182   } else {
6183     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6184       (void)MD;
6185       assert((MissingImplicitThis || MD->isStatic() ||
6186               isa<CXXConstructorDecl>(MD)) &&
6187              "Expected `this` for non-ctor instance methods");
6188     }
6189     ConvertedThis = nullptr;
6190   }
6191 
6192   // Ignore any variadic arguments. Converting them is pointless, since the
6193   // user can't refer to them in the function condition.
6194   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6195 
6196   // Convert the arguments.
6197   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6198     ExprResult R;
6199     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6200                                         S.Context, Function->getParamDecl(I)),
6201                                     SourceLocation(), Args[I]);
6202 
6203     if (R.isInvalid())
6204       return false;
6205 
6206     ConvertedArgs.push_back(R.get());
6207   }
6208 
6209   if (Trap.hasErrorOccurred())
6210     return false;
6211 
6212   // Push default arguments if needed.
6213   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6214     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6215       ParmVarDecl *P = Function->getParamDecl(i);
6216       ExprResult R = S.PerformCopyInitialization(
6217           InitializedEntity::InitializeParameter(S.Context,
6218                                                  Function->getParamDecl(i)),
6219           SourceLocation(),
6220           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6221                                            : P->getDefaultArg());
6222       if (R.isInvalid())
6223         return false;
6224       ConvertedArgs.push_back(R.get());
6225     }
6226 
6227     if (Trap.hasErrorOccurred())
6228       return false;
6229   }
6230   return true;
6231 }
6232 
6233 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6234                                   bool MissingImplicitThis) {
6235   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6236       getOrderedEnableIfAttrs(Function);
6237   if (EnableIfAttrs.empty())
6238     return nullptr;
6239 
6240   SFINAETrap Trap(*this);
6241   SmallVector<Expr *, 16> ConvertedArgs;
6242   // FIXME: We should look into making enable_if late-parsed.
6243   Expr *DiscardedThis;
6244   if (!convertArgsForAvailabilityChecks(
6245           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6246           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6247     return EnableIfAttrs[0];
6248 
6249   for (auto *EIA : EnableIfAttrs) {
6250     APValue Result;
6251     // FIXME: This doesn't consider value-dependent cases, because doing so is
6252     // very difficult. Ideally, we should handle them more gracefully.
6253     if (!EIA->getCond()->EvaluateWithSubstitution(
6254             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6255       return EIA;
6256 
6257     if (!Result.isInt() || !Result.getInt().getBoolValue())
6258       return EIA;
6259   }
6260   return nullptr;
6261 }
6262 
6263 static bool gatherDiagnoseIfAttrs(FunctionDecl *Function, bool ArgDependent,
6264                                   SmallVectorImpl<DiagnoseIfAttr *> &Errors,
6265                                   SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) {
6266   for (auto *DIA : Function->specific_attrs<DiagnoseIfAttr>())
6267     if (ArgDependent == DIA->getArgDependent()) {
6268       if (DIA->isError())
6269         Errors.push_back(DIA);
6270       else
6271         Nonfatal.push_back(DIA);
6272     }
6273 
6274   return !Errors.empty() || !Nonfatal.empty();
6275 }
6276 
6277 template <typename CheckFn>
6278 static DiagnoseIfAttr *
6279 checkDiagnoseIfAttrsWith(const SmallVectorImpl<DiagnoseIfAttr *> &Errors,
6280                          SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal,
6281                          CheckFn &&IsSuccessful) {
6282   // Note that diagnose_if attributes are late-parsed, so they appear in the
6283   // correct order (unlike enable_if attributes).
6284   auto ErrAttr = llvm::find_if(Errors, IsSuccessful);
6285   if (ErrAttr != Errors.end())
6286     return *ErrAttr;
6287 
6288   llvm::erase_if(Nonfatal, [&](DiagnoseIfAttr *A) { return !IsSuccessful(A); });
6289   return nullptr;
6290 }
6291 
6292 DiagnoseIfAttr *
6293 Sema::checkArgDependentDiagnoseIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6294                                   SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal,
6295                                   bool MissingImplicitThis,
6296                                   Expr *ThisArg) {
6297   SmallVector<DiagnoseIfAttr *, 4> Errors;
6298   if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/true, Errors, Nonfatal))
6299     return nullptr;
6300 
6301   SFINAETrap Trap(*this);
6302   SmallVector<Expr *, 16> ConvertedArgs;
6303   Expr *ConvertedThis;
6304   if (!convertArgsForAvailabilityChecks(*this, Function, ThisArg, Args, Trap,
6305                                         MissingImplicitThis, ConvertedThis,
6306                                         ConvertedArgs))
6307     return nullptr;
6308 
6309   return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) {
6310     APValue Result;
6311     // It's sane to use the same ConvertedArgs for any redecl of this function,
6312     // since EvaluateWithSubstitution only cares about the position of each
6313     // argument in the arg list, not the ParmVarDecl* it maps to.
6314     if (!DIA->getCond()->EvaluateWithSubstitution(
6315             Result, Context, DIA->getParent(), ConvertedArgs, ConvertedThis))
6316       return false;
6317     return Result.isInt() && Result.getInt().getBoolValue();
6318   });
6319 }
6320 
6321 DiagnoseIfAttr *Sema::checkArgIndependentDiagnoseIf(
6322     FunctionDecl *Function, SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) {
6323   SmallVector<DiagnoseIfAttr *, 4> Errors;
6324   if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/false, Errors,
6325                              Nonfatal))
6326     return nullptr;
6327 
6328   return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) {
6329     bool Result;
6330     return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6331            Result;
6332   });
6333 }
6334 
6335 void Sema::emitDiagnoseIfDiagnostic(SourceLocation Loc,
6336                                     const DiagnoseIfAttr *DIA) {
6337   auto Code = DIA->isError() ? diag::err_diagnose_if_succeeded
6338                              : diag::warn_diagnose_if_succeeded;
6339   Diag(Loc, Code) << DIA->getMessage();
6340   Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6341       << DIA->getParent() << DIA->getCond()->getSourceRange();
6342 }
6343 
6344 /// \brief Add all of the function declarations in the given function set to
6345 /// the overload candidate set.
6346 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6347                                  ArrayRef<Expr *> Args,
6348                                  OverloadCandidateSet& CandidateSet,
6349                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6350                                  bool SuppressUserConversions,
6351                                  bool PartialOverloading) {
6352   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6353     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6354     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6355       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6356         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6357                            cast<CXXMethodDecl>(FD)->getParent(),
6358                            Args[0]->getType(), Args[0]->Classify(Context),
6359                            Args[0], Args.slice(1), CandidateSet,
6360                            SuppressUserConversions, PartialOverloading);
6361       else
6362         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6363                              SuppressUserConversions, PartialOverloading);
6364     } else {
6365       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6366       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6367           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6368         AddMethodTemplateCandidate(
6369             FunTmpl, F.getPair(),
6370             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6371             ExplicitTemplateArgs, Args[0]->getType(),
6372             Args[0]->Classify(Context), Args[0], Args.slice(1), CandidateSet,
6373             SuppressUserConversions, PartialOverloading);
6374       else
6375         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6376                                      ExplicitTemplateArgs, Args,
6377                                      CandidateSet, SuppressUserConversions,
6378                                      PartialOverloading);
6379     }
6380   }
6381 }
6382 
6383 /// AddMethodCandidate - Adds a named decl (which is some kind of
6384 /// method) as a method candidate to the given overload set.
6385 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6386                               QualType ObjectType,
6387                               Expr::Classification ObjectClassification,
6388                               Expr *ThisArg,
6389                               ArrayRef<Expr *> Args,
6390                               OverloadCandidateSet& CandidateSet,
6391                               bool SuppressUserConversions) {
6392   NamedDecl *Decl = FoundDecl.getDecl();
6393   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6394 
6395   if (isa<UsingShadowDecl>(Decl))
6396     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6397 
6398   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6399     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6400            "Expected a member function template");
6401     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6402                                /*ExplicitArgs*/ nullptr,
6403                                ObjectType, ObjectClassification,
6404                                ThisArg, Args, CandidateSet,
6405                                SuppressUserConversions);
6406   } else {
6407     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6408                        ObjectType, ObjectClassification,
6409                        ThisArg, Args,
6410                        CandidateSet, SuppressUserConversions);
6411   }
6412 }
6413 
6414 /// AddMethodCandidate - Adds the given C++ member function to the set
6415 /// of candidate functions, using the given function call arguments
6416 /// and the object argument (@c Object). For example, in a call
6417 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6418 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6419 /// allow user-defined conversions via constructors or conversion
6420 /// operators.
6421 void
6422 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6423                          CXXRecordDecl *ActingContext, QualType ObjectType,
6424                          Expr::Classification ObjectClassification,
6425                          Expr *ThisArg, ArrayRef<Expr *> Args,
6426                          OverloadCandidateSet &CandidateSet,
6427                          bool SuppressUserConversions,
6428                          bool PartialOverloading,
6429                          ConversionSequenceList EarlyConversions) {
6430   const FunctionProtoType *Proto
6431     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6432   assert(Proto && "Methods without a prototype cannot be overloaded");
6433   assert(!isa<CXXConstructorDecl>(Method) &&
6434          "Use AddOverloadCandidate for constructors");
6435 
6436   if (!CandidateSet.isNewCandidate(Method))
6437     return;
6438 
6439   // C++11 [class.copy]p23: [DR1402]
6440   //   A defaulted move assignment operator that is defined as deleted is
6441   //   ignored by overload resolution.
6442   if (Method->isDefaulted() && Method->isDeleted() &&
6443       Method->isMoveAssignmentOperator())
6444     return;
6445 
6446   // Overload resolution is always an unevaluated context.
6447   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6448 
6449   // Add this candidate
6450   OverloadCandidate &Candidate =
6451       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6452   Candidate.FoundDecl = FoundDecl;
6453   Candidate.Function = Method;
6454   Candidate.IsSurrogate = false;
6455   Candidate.IgnoreObjectArgument = false;
6456   Candidate.ExplicitCallArguments = Args.size();
6457 
6458   unsigned NumParams = Proto->getNumParams();
6459 
6460   // (C++ 13.3.2p2): A candidate function having fewer than m
6461   // parameters is viable only if it has an ellipsis in its parameter
6462   // list (8.3.5).
6463   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6464       !Proto->isVariadic()) {
6465     Candidate.Viable = false;
6466     Candidate.FailureKind = ovl_fail_too_many_arguments;
6467     return;
6468   }
6469 
6470   // (C++ 13.3.2p2): A candidate function having more than m parameters
6471   // is viable only if the (m+1)st parameter has a default argument
6472   // (8.3.6). For the purposes of overload resolution, the
6473   // parameter list is truncated on the right, so that there are
6474   // exactly m parameters.
6475   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6476   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6477     // Not enough arguments.
6478     Candidate.Viable = false;
6479     Candidate.FailureKind = ovl_fail_too_few_arguments;
6480     return;
6481   }
6482 
6483   Candidate.Viable = true;
6484 
6485   if (Method->isStatic() || ObjectType.isNull())
6486     // The implicit object argument is ignored.
6487     Candidate.IgnoreObjectArgument = true;
6488   else {
6489     // Determine the implicit conversion sequence for the object
6490     // parameter.
6491     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6492         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6493         Method, ActingContext);
6494     if (Candidate.Conversions[0].isBad()) {
6495       Candidate.Viable = false;
6496       Candidate.FailureKind = ovl_fail_bad_conversion;
6497       return;
6498     }
6499   }
6500 
6501   // (CUDA B.1): Check for invalid calls between targets.
6502   if (getLangOpts().CUDA)
6503     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6504       if (!IsAllowedCUDACall(Caller, Method)) {
6505         Candidate.Viable = false;
6506         Candidate.FailureKind = ovl_fail_bad_target;
6507         return;
6508       }
6509 
6510   // Determine the implicit conversion sequences for each of the
6511   // arguments.
6512   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6513     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6514       // We already formed a conversion sequence for this parameter during
6515       // template argument deduction.
6516     } else if (ArgIdx < NumParams) {
6517       // (C++ 13.3.2p3): for F to be a viable function, there shall
6518       // exist for each argument an implicit conversion sequence
6519       // (13.3.3.1) that converts that argument to the corresponding
6520       // parameter of F.
6521       QualType ParamType = Proto->getParamType(ArgIdx);
6522       Candidate.Conversions[ArgIdx + 1]
6523         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6524                                 SuppressUserConversions,
6525                                 /*InOverloadResolution=*/true,
6526                                 /*AllowObjCWritebackConversion=*/
6527                                   getLangOpts().ObjCAutoRefCount);
6528       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6529         Candidate.Viable = false;
6530         Candidate.FailureKind = ovl_fail_bad_conversion;
6531         return;
6532       }
6533     } else {
6534       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6535       // argument for which there is no corresponding parameter is
6536       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6537       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6538     }
6539   }
6540 
6541   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6542     Candidate.Viable = false;
6543     Candidate.FailureKind = ovl_fail_enable_if;
6544     Candidate.DeductionFailure.Data = FailedAttr;
6545     return;
6546   }
6547 
6548   initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Method, Args,
6549                           /*MissingImplicitThis=*/!ThisArg, ThisArg);
6550 }
6551 
6552 /// \brief Add a C++ member function template as a candidate to the candidate
6553 /// set, using template argument deduction to produce an appropriate member
6554 /// function template specialization.
6555 void
6556 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6557                                  DeclAccessPair FoundDecl,
6558                                  CXXRecordDecl *ActingContext,
6559                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6560                                  QualType ObjectType,
6561                                  Expr::Classification ObjectClassification,
6562                                  Expr *ThisArg,
6563                                  ArrayRef<Expr *> Args,
6564                                  OverloadCandidateSet& CandidateSet,
6565                                  bool SuppressUserConversions,
6566                                  bool PartialOverloading) {
6567   if (!CandidateSet.isNewCandidate(MethodTmpl))
6568     return;
6569 
6570   // C++ [over.match.funcs]p7:
6571   //   In each case where a candidate is a function template, candidate
6572   //   function template specializations are generated using template argument
6573   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6574   //   candidate functions in the usual way.113) A given name can refer to one
6575   //   or more function templates and also to a set of overloaded non-template
6576   //   functions. In such a case, the candidate functions generated from each
6577   //   function template are combined with the set of non-template candidate
6578   //   functions.
6579   TemplateDeductionInfo Info(CandidateSet.getLocation());
6580   FunctionDecl *Specialization = nullptr;
6581   ConversionSequenceList Conversions;
6582   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6583           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6584           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6585             return CheckNonDependentConversions(
6586                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6587                 SuppressUserConversions, ActingContext, ObjectType,
6588                 ObjectClassification);
6589           })) {
6590     OverloadCandidate &Candidate =
6591         CandidateSet.addCandidate(Conversions.size(), Conversions);
6592     Candidate.FoundDecl = FoundDecl;
6593     Candidate.Function = MethodTmpl->getTemplatedDecl();
6594     Candidate.Viable = false;
6595     Candidate.IsSurrogate = false;
6596     Candidate.IgnoreObjectArgument =
6597         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6598         ObjectType.isNull();
6599     Candidate.ExplicitCallArguments = Args.size();
6600     if (Result == TDK_NonDependentConversionFailure)
6601       Candidate.FailureKind = ovl_fail_bad_conversion;
6602     else {
6603       Candidate.FailureKind = ovl_fail_bad_deduction;
6604       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6605                                                             Info);
6606     }
6607     return;
6608   }
6609 
6610   // Add the function template specialization produced by template argument
6611   // deduction as a candidate.
6612   assert(Specialization && "Missing member function template specialization?");
6613   assert(isa<CXXMethodDecl>(Specialization) &&
6614          "Specialization is not a member function?");
6615   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6616                      ActingContext, ObjectType, ObjectClassification,
6617                      /*ThisArg=*/ThisArg, Args, CandidateSet,
6618                      SuppressUserConversions, PartialOverloading, Conversions);
6619 }
6620 
6621 /// \brief Add a C++ function template specialization as a candidate
6622 /// in the candidate set, using template argument deduction to produce
6623 /// an appropriate function template specialization.
6624 void
6625 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6626                                    DeclAccessPair FoundDecl,
6627                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6628                                    ArrayRef<Expr *> Args,
6629                                    OverloadCandidateSet& CandidateSet,
6630                                    bool SuppressUserConversions,
6631                                    bool PartialOverloading) {
6632   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6633     return;
6634 
6635   // C++ [over.match.funcs]p7:
6636   //   In each case where a candidate is a function template, candidate
6637   //   function template specializations are generated using template argument
6638   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6639   //   candidate functions in the usual way.113) A given name can refer to one
6640   //   or more function templates and also to a set of overloaded non-template
6641   //   functions. In such a case, the candidate functions generated from each
6642   //   function template are combined with the set of non-template candidate
6643   //   functions.
6644   TemplateDeductionInfo Info(CandidateSet.getLocation());
6645   FunctionDecl *Specialization = nullptr;
6646   ConversionSequenceList Conversions;
6647   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6648           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6649           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6650             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6651                                                 Args, CandidateSet, Conversions,
6652                                                 SuppressUserConversions);
6653           })) {
6654     OverloadCandidate &Candidate =
6655         CandidateSet.addCandidate(Conversions.size(), Conversions);
6656     Candidate.FoundDecl = FoundDecl;
6657     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6658     Candidate.Viable = false;
6659     Candidate.IsSurrogate = false;
6660     // Ignore the object argument if there is one, since we don't have an object
6661     // type.
6662     Candidate.IgnoreObjectArgument =
6663         isa<CXXMethodDecl>(Candidate.Function) &&
6664         !isa<CXXConstructorDecl>(Candidate.Function);
6665     Candidate.ExplicitCallArguments = Args.size();
6666     if (Result == TDK_NonDependentConversionFailure)
6667       Candidate.FailureKind = ovl_fail_bad_conversion;
6668     else {
6669       Candidate.FailureKind = ovl_fail_bad_deduction;
6670       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6671                                                             Info);
6672     }
6673     return;
6674   }
6675 
6676   // Add the function template specialization produced by template argument
6677   // deduction as a candidate.
6678   assert(Specialization && "Missing function template specialization?");
6679   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6680                        SuppressUserConversions, PartialOverloading,
6681                        /*AllowExplicit*/false, Conversions);
6682 }
6683 
6684 /// Check that implicit conversion sequences can be formed for each argument
6685 /// whose corresponding parameter has a non-dependent type, per DR1391's
6686 /// [temp.deduct.call]p10.
6687 bool Sema::CheckNonDependentConversions(
6688     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6689     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6690     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6691     CXXRecordDecl *ActingContext, QualType ObjectType,
6692     Expr::Classification ObjectClassification) {
6693   // FIXME: The cases in which we allow explicit conversions for constructor
6694   // arguments never consider calling a constructor template. It's not clear
6695   // that is correct.
6696   const bool AllowExplicit = false;
6697 
6698   auto *FD = FunctionTemplate->getTemplatedDecl();
6699   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6700   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6701   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6702 
6703   Conversions =
6704       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6705 
6706   // Overload resolution is always an unevaluated context.
6707   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6708 
6709   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6710   // require that, but this check should never result in a hard error, and
6711   // overload resolution is permitted to sidestep instantiations.
6712   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6713       !ObjectType.isNull()) {
6714     Conversions[0] = TryObjectArgumentInitialization(
6715         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6716         Method, ActingContext);
6717     if (Conversions[0].isBad())
6718       return true;
6719   }
6720 
6721   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6722        ++I) {
6723     QualType ParamType = ParamTypes[I];
6724     if (!ParamType->isDependentType()) {
6725       Conversions[ThisConversions + I]
6726         = TryCopyInitialization(*this, Args[I], ParamType,
6727                                 SuppressUserConversions,
6728                                 /*InOverloadResolution=*/true,
6729                                 /*AllowObjCWritebackConversion=*/
6730                                   getLangOpts().ObjCAutoRefCount,
6731                                 AllowExplicit);
6732       if (Conversions[ThisConversions + I].isBad())
6733         return true;
6734     }
6735   }
6736 
6737   return false;
6738 }
6739 
6740 /// Determine whether this is an allowable conversion from the result
6741 /// of an explicit conversion operator to the expected type, per C++
6742 /// [over.match.conv]p1 and [over.match.ref]p1.
6743 ///
6744 /// \param ConvType The return type of the conversion function.
6745 ///
6746 /// \param ToType The type we are converting to.
6747 ///
6748 /// \param AllowObjCPointerConversion Allow a conversion from one
6749 /// Objective-C pointer to another.
6750 ///
6751 /// \returns true if the conversion is allowable, false otherwise.
6752 static bool isAllowableExplicitConversion(Sema &S,
6753                                           QualType ConvType, QualType ToType,
6754                                           bool AllowObjCPointerConversion) {
6755   QualType ToNonRefType = ToType.getNonReferenceType();
6756 
6757   // Easy case: the types are the same.
6758   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6759     return true;
6760 
6761   // Allow qualification conversions.
6762   bool ObjCLifetimeConversion;
6763   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6764                                   ObjCLifetimeConversion))
6765     return true;
6766 
6767   // If we're not allowed to consider Objective-C pointer conversions,
6768   // we're done.
6769   if (!AllowObjCPointerConversion)
6770     return false;
6771 
6772   // Is this an Objective-C pointer conversion?
6773   bool IncompatibleObjC = false;
6774   QualType ConvertedType;
6775   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6776                                    IncompatibleObjC);
6777 }
6778 
6779 /// AddConversionCandidate - Add a C++ conversion function as a
6780 /// candidate in the candidate set (C++ [over.match.conv],
6781 /// C++ [over.match.copy]). From is the expression we're converting from,
6782 /// and ToType is the type that we're eventually trying to convert to
6783 /// (which may or may not be the same type as the type that the
6784 /// conversion function produces).
6785 void
6786 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6787                              DeclAccessPair FoundDecl,
6788                              CXXRecordDecl *ActingContext,
6789                              Expr *From, QualType ToType,
6790                              OverloadCandidateSet& CandidateSet,
6791                              bool AllowObjCConversionOnExplicit) {
6792   assert(!Conversion->getDescribedFunctionTemplate() &&
6793          "Conversion function templates use AddTemplateConversionCandidate");
6794   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6795   if (!CandidateSet.isNewCandidate(Conversion))
6796     return;
6797 
6798   // If the conversion function has an undeduced return type, trigger its
6799   // deduction now.
6800   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6801     if (DeduceReturnType(Conversion, From->getExprLoc()))
6802       return;
6803     ConvType = Conversion->getConversionType().getNonReferenceType();
6804   }
6805 
6806   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6807   // operator is only a candidate if its return type is the target type or
6808   // can be converted to the target type with a qualification conversion.
6809   if (Conversion->isExplicit() &&
6810       !isAllowableExplicitConversion(*this, ConvType, ToType,
6811                                      AllowObjCConversionOnExplicit))
6812     return;
6813 
6814   // Overload resolution is always an unevaluated context.
6815   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6816 
6817   // Add this candidate
6818   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6819   Candidate.FoundDecl = FoundDecl;
6820   Candidate.Function = Conversion;
6821   Candidate.IsSurrogate = false;
6822   Candidate.IgnoreObjectArgument = false;
6823   Candidate.FinalConversion.setAsIdentityConversion();
6824   Candidate.FinalConversion.setFromType(ConvType);
6825   Candidate.FinalConversion.setAllToTypes(ToType);
6826   Candidate.Viable = true;
6827   Candidate.ExplicitCallArguments = 1;
6828 
6829   // C++ [over.match.funcs]p4:
6830   //   For conversion functions, the function is considered to be a member of
6831   //   the class of the implicit implied object argument for the purpose of
6832   //   defining the type of the implicit object parameter.
6833   //
6834   // Determine the implicit conversion sequence for the implicit
6835   // object parameter.
6836   QualType ImplicitParamType = From->getType();
6837   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6838     ImplicitParamType = FromPtrType->getPointeeType();
6839   CXXRecordDecl *ConversionContext
6840     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6841 
6842   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6843       *this, CandidateSet.getLocation(), From->getType(),
6844       From->Classify(Context), Conversion, ConversionContext);
6845 
6846   if (Candidate.Conversions[0].isBad()) {
6847     Candidate.Viable = false;
6848     Candidate.FailureKind = ovl_fail_bad_conversion;
6849     return;
6850   }
6851 
6852   // We won't go through a user-defined type conversion function to convert a
6853   // derived to base as such conversions are given Conversion Rank. They only
6854   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6855   QualType FromCanon
6856     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6857   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6858   if (FromCanon == ToCanon ||
6859       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6860     Candidate.Viable = false;
6861     Candidate.FailureKind = ovl_fail_trivial_conversion;
6862     return;
6863   }
6864 
6865   // To determine what the conversion from the result of calling the
6866   // conversion function to the type we're eventually trying to
6867   // convert to (ToType), we need to synthesize a call to the
6868   // conversion function and attempt copy initialization from it. This
6869   // makes sure that we get the right semantics with respect to
6870   // lvalues/rvalues and the type. Fortunately, we can allocate this
6871   // call on the stack and we don't need its arguments to be
6872   // well-formed.
6873   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6874                             VK_LValue, From->getLocStart());
6875   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6876                                 Context.getPointerType(Conversion->getType()),
6877                                 CK_FunctionToPointerDecay,
6878                                 &ConversionRef, VK_RValue);
6879 
6880   QualType ConversionType = Conversion->getConversionType();
6881   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6882     Candidate.Viable = false;
6883     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6884     return;
6885   }
6886 
6887   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6888 
6889   // Note that it is safe to allocate CallExpr on the stack here because
6890   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6891   // allocator).
6892   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6893   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6894                 From->getLocStart());
6895   ImplicitConversionSequence ICS =
6896     TryCopyInitialization(*this, &Call, ToType,
6897                           /*SuppressUserConversions=*/true,
6898                           /*InOverloadResolution=*/false,
6899                           /*AllowObjCWritebackConversion=*/false);
6900 
6901   switch (ICS.getKind()) {
6902   case ImplicitConversionSequence::StandardConversion:
6903     Candidate.FinalConversion = ICS.Standard;
6904 
6905     // C++ [over.ics.user]p3:
6906     //   If the user-defined conversion is specified by a specialization of a
6907     //   conversion function template, the second standard conversion sequence
6908     //   shall have exact match rank.
6909     if (Conversion->getPrimaryTemplate() &&
6910         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6911       Candidate.Viable = false;
6912       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6913       return;
6914     }
6915 
6916     // C++0x [dcl.init.ref]p5:
6917     //    In the second case, if the reference is an rvalue reference and
6918     //    the second standard conversion sequence of the user-defined
6919     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6920     //    program is ill-formed.
6921     if (ToType->isRValueReferenceType() &&
6922         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6923       Candidate.Viable = false;
6924       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6925       return;
6926     }
6927     break;
6928 
6929   case ImplicitConversionSequence::BadConversion:
6930     Candidate.Viable = false;
6931     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6932     return;
6933 
6934   default:
6935     llvm_unreachable(
6936            "Can only end up with a standard conversion sequence or failure");
6937   }
6938 
6939   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6940     Candidate.Viable = false;
6941     Candidate.FailureKind = ovl_fail_enable_if;
6942     Candidate.DeductionFailure.Data = FailedAttr;
6943     return;
6944   }
6945 
6946   initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None, false, From);
6947 }
6948 
6949 /// \brief Adds a conversion function template specialization
6950 /// candidate to the overload set, using template argument deduction
6951 /// to deduce the template arguments of the conversion function
6952 /// template from the type that we are converting to (C++
6953 /// [temp.deduct.conv]).
6954 void
6955 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6956                                      DeclAccessPair FoundDecl,
6957                                      CXXRecordDecl *ActingDC,
6958                                      Expr *From, QualType ToType,
6959                                      OverloadCandidateSet &CandidateSet,
6960                                      bool AllowObjCConversionOnExplicit) {
6961   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6962          "Only conversion function templates permitted here");
6963 
6964   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6965     return;
6966 
6967   TemplateDeductionInfo Info(CandidateSet.getLocation());
6968   CXXConversionDecl *Specialization = nullptr;
6969   if (TemplateDeductionResult Result
6970         = DeduceTemplateArguments(FunctionTemplate, ToType,
6971                                   Specialization, Info)) {
6972     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6973     Candidate.FoundDecl = FoundDecl;
6974     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6975     Candidate.Viable = false;
6976     Candidate.FailureKind = ovl_fail_bad_deduction;
6977     Candidate.IsSurrogate = false;
6978     Candidate.IgnoreObjectArgument = false;
6979     Candidate.ExplicitCallArguments = 1;
6980     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6981                                                           Info);
6982     return;
6983   }
6984 
6985   // Add the conversion function template specialization produced by
6986   // template argument deduction as a candidate.
6987   assert(Specialization && "Missing function template specialization?");
6988   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6989                          CandidateSet, AllowObjCConversionOnExplicit);
6990 }
6991 
6992 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6993 /// converts the given @c Object to a function pointer via the
6994 /// conversion function @c Conversion, and then attempts to call it
6995 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6996 /// the type of function that we'll eventually be calling.
6997 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6998                                  DeclAccessPair FoundDecl,
6999                                  CXXRecordDecl *ActingContext,
7000                                  const FunctionProtoType *Proto,
7001                                  Expr *Object,
7002                                  ArrayRef<Expr *> Args,
7003                                  OverloadCandidateSet& CandidateSet) {
7004   if (!CandidateSet.isNewCandidate(Conversion))
7005     return;
7006 
7007   // Overload resolution is always an unevaluated context.
7008   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
7009 
7010   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7011   Candidate.FoundDecl = FoundDecl;
7012   Candidate.Function = nullptr;
7013   Candidate.Surrogate = Conversion;
7014   Candidate.Viable = true;
7015   Candidate.IsSurrogate = true;
7016   Candidate.IgnoreObjectArgument = false;
7017   Candidate.ExplicitCallArguments = Args.size();
7018 
7019   // Determine the implicit conversion sequence for the implicit
7020   // object parameter.
7021   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7022       *this, CandidateSet.getLocation(), Object->getType(),
7023       Object->Classify(Context), Conversion, ActingContext);
7024   if (ObjectInit.isBad()) {
7025     Candidate.Viable = false;
7026     Candidate.FailureKind = ovl_fail_bad_conversion;
7027     Candidate.Conversions[0] = ObjectInit;
7028     return;
7029   }
7030 
7031   // The first conversion is actually a user-defined conversion whose
7032   // first conversion is ObjectInit's standard conversion (which is
7033   // effectively a reference binding). Record it as such.
7034   Candidate.Conversions[0].setUserDefined();
7035   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7036   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7037   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7038   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7039   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7040   Candidate.Conversions[0].UserDefined.After
7041     = Candidate.Conversions[0].UserDefined.Before;
7042   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7043 
7044   // Find the
7045   unsigned NumParams = Proto->getNumParams();
7046 
7047   // (C++ 13.3.2p2): A candidate function having fewer than m
7048   // parameters is viable only if it has an ellipsis in its parameter
7049   // list (8.3.5).
7050   if (Args.size() > NumParams && !Proto->isVariadic()) {
7051     Candidate.Viable = false;
7052     Candidate.FailureKind = ovl_fail_too_many_arguments;
7053     return;
7054   }
7055 
7056   // Function types don't have any default arguments, so just check if
7057   // we have enough arguments.
7058   if (Args.size() < NumParams) {
7059     // Not enough arguments.
7060     Candidate.Viable = false;
7061     Candidate.FailureKind = ovl_fail_too_few_arguments;
7062     return;
7063   }
7064 
7065   // Determine the implicit conversion sequences for each of the
7066   // arguments.
7067   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7068     if (ArgIdx < NumParams) {
7069       // (C++ 13.3.2p3): for F to be a viable function, there shall
7070       // exist for each argument an implicit conversion sequence
7071       // (13.3.3.1) that converts that argument to the corresponding
7072       // parameter of F.
7073       QualType ParamType = Proto->getParamType(ArgIdx);
7074       Candidate.Conversions[ArgIdx + 1]
7075         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7076                                 /*SuppressUserConversions=*/false,
7077                                 /*InOverloadResolution=*/false,
7078                                 /*AllowObjCWritebackConversion=*/
7079                                   getLangOpts().ObjCAutoRefCount);
7080       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7081         Candidate.Viable = false;
7082         Candidate.FailureKind = ovl_fail_bad_conversion;
7083         return;
7084       }
7085     } else {
7086       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7087       // argument for which there is no corresponding parameter is
7088       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7089       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7090     }
7091   }
7092 
7093   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7094     Candidate.Viable = false;
7095     Candidate.FailureKind = ovl_fail_enable_if;
7096     Candidate.DeductionFailure.Data = FailedAttr;
7097     return;
7098   }
7099 
7100   initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None);
7101 }
7102 
7103 /// \brief Add overload candidates for overloaded operators that are
7104 /// member functions.
7105 ///
7106 /// Add the overloaded operator candidates that are member functions
7107 /// for the operator Op that was used in an operator expression such
7108 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7109 /// CandidateSet will store the added overload candidates. (C++
7110 /// [over.match.oper]).
7111 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7112                                        SourceLocation OpLoc,
7113                                        ArrayRef<Expr *> Args,
7114                                        OverloadCandidateSet& CandidateSet,
7115                                        SourceRange OpRange) {
7116   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7117 
7118   // C++ [over.match.oper]p3:
7119   //   For a unary operator @ with an operand of a type whose
7120   //   cv-unqualified version is T1, and for a binary operator @ with
7121   //   a left operand of a type whose cv-unqualified version is T1 and
7122   //   a right operand of a type whose cv-unqualified version is T2,
7123   //   three sets of candidate functions, designated member
7124   //   candidates, non-member candidates and built-in candidates, are
7125   //   constructed as follows:
7126   QualType T1 = Args[0]->getType();
7127 
7128   //     -- If T1 is a complete class type or a class currently being
7129   //        defined, the set of member candidates is the result of the
7130   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7131   //        the set of member candidates is empty.
7132   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7133     // Complete the type if it can be completed.
7134     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7135       return;
7136     // If the type is neither complete nor being defined, bail out now.
7137     if (!T1Rec->getDecl()->getDefinition())
7138       return;
7139 
7140     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7141     LookupQualifiedName(Operators, T1Rec->getDecl());
7142     Operators.suppressDiagnostics();
7143 
7144     for (LookupResult::iterator Oper = Operators.begin(),
7145                              OperEnd = Operators.end();
7146          Oper != OperEnd;
7147          ++Oper)
7148       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7149                          Args[0]->Classify(Context), Args[0], Args.slice(1),
7150                          CandidateSet, /*SuppressUserConversions=*/false);
7151   }
7152 }
7153 
7154 /// AddBuiltinCandidate - Add a candidate for a built-in
7155 /// operator. ResultTy and ParamTys are the result and parameter types
7156 /// of the built-in candidate, respectively. Args and NumArgs are the
7157 /// arguments being passed to the candidate. IsAssignmentOperator
7158 /// should be true when this built-in candidate is an assignment
7159 /// operator. NumContextualBoolArguments is the number of arguments
7160 /// (at the beginning of the argument list) that will be contextually
7161 /// converted to bool.
7162 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
7163                                ArrayRef<Expr *> Args,
7164                                OverloadCandidateSet& CandidateSet,
7165                                bool IsAssignmentOperator,
7166                                unsigned NumContextualBoolArguments) {
7167   // Overload resolution is always an unevaluated context.
7168   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
7169 
7170   // Add this candidate
7171   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7172   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7173   Candidate.Function = nullptr;
7174   Candidate.IsSurrogate = false;
7175   Candidate.IgnoreObjectArgument = false;
7176   Candidate.BuiltinTypes.ResultTy = ResultTy;
7177   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7178     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7179 
7180   // Determine the implicit conversion sequences for each of the
7181   // arguments.
7182   Candidate.Viable = true;
7183   Candidate.ExplicitCallArguments = Args.size();
7184   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7185     // C++ [over.match.oper]p4:
7186     //   For the built-in assignment operators, conversions of the
7187     //   left operand are restricted as follows:
7188     //     -- no temporaries are introduced to hold the left operand, and
7189     //     -- no user-defined conversions are applied to the left
7190     //        operand to achieve a type match with the left-most
7191     //        parameter of a built-in candidate.
7192     //
7193     // We block these conversions by turning off user-defined
7194     // conversions, since that is the only way that initialization of
7195     // a reference to a non-class type can occur from something that
7196     // is not of the same type.
7197     if (ArgIdx < NumContextualBoolArguments) {
7198       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7199              "Contextual conversion to bool requires bool type");
7200       Candidate.Conversions[ArgIdx]
7201         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7202     } else {
7203       Candidate.Conversions[ArgIdx]
7204         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7205                                 ArgIdx == 0 && IsAssignmentOperator,
7206                                 /*InOverloadResolution=*/false,
7207                                 /*AllowObjCWritebackConversion=*/
7208                                   getLangOpts().ObjCAutoRefCount);
7209     }
7210     if (Candidate.Conversions[ArgIdx].isBad()) {
7211       Candidate.Viable = false;
7212       Candidate.FailureKind = ovl_fail_bad_conversion;
7213       break;
7214     }
7215   }
7216 }
7217 
7218 namespace {
7219 
7220 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7221 /// candidate operator functions for built-in operators (C++
7222 /// [over.built]). The types are separated into pointer types and
7223 /// enumeration types.
7224 class BuiltinCandidateTypeSet  {
7225   /// TypeSet - A set of types.
7226   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7227                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7228 
7229   /// PointerTypes - The set of pointer types that will be used in the
7230   /// built-in candidates.
7231   TypeSet PointerTypes;
7232 
7233   /// MemberPointerTypes - The set of member pointer types that will be
7234   /// used in the built-in candidates.
7235   TypeSet MemberPointerTypes;
7236 
7237   /// EnumerationTypes - The set of enumeration types that will be
7238   /// used in the built-in candidates.
7239   TypeSet EnumerationTypes;
7240 
7241   /// \brief The set of vector types that will be used in the built-in
7242   /// candidates.
7243   TypeSet VectorTypes;
7244 
7245   /// \brief A flag indicating non-record types are viable candidates
7246   bool HasNonRecordTypes;
7247 
7248   /// \brief A flag indicating whether either arithmetic or enumeration types
7249   /// were present in the candidate set.
7250   bool HasArithmeticOrEnumeralTypes;
7251 
7252   /// \brief A flag indicating whether the nullptr type was present in the
7253   /// candidate set.
7254   bool HasNullPtrType;
7255 
7256   /// Sema - The semantic analysis instance where we are building the
7257   /// candidate type set.
7258   Sema &SemaRef;
7259 
7260   /// Context - The AST context in which we will build the type sets.
7261   ASTContext &Context;
7262 
7263   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7264                                                const Qualifiers &VisibleQuals);
7265   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7266 
7267 public:
7268   /// iterator - Iterates through the types that are part of the set.
7269   typedef TypeSet::iterator iterator;
7270 
7271   BuiltinCandidateTypeSet(Sema &SemaRef)
7272     : HasNonRecordTypes(false),
7273       HasArithmeticOrEnumeralTypes(false),
7274       HasNullPtrType(false),
7275       SemaRef(SemaRef),
7276       Context(SemaRef.Context) { }
7277 
7278   void AddTypesConvertedFrom(QualType Ty,
7279                              SourceLocation Loc,
7280                              bool AllowUserConversions,
7281                              bool AllowExplicitConversions,
7282                              const Qualifiers &VisibleTypeConversionsQuals);
7283 
7284   /// pointer_begin - First pointer type found;
7285   iterator pointer_begin() { return PointerTypes.begin(); }
7286 
7287   /// pointer_end - Past the last pointer type found;
7288   iterator pointer_end() { return PointerTypes.end(); }
7289 
7290   /// member_pointer_begin - First member pointer type found;
7291   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7292 
7293   /// member_pointer_end - Past the last member pointer type found;
7294   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7295 
7296   /// enumeration_begin - First enumeration type found;
7297   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7298 
7299   /// enumeration_end - Past the last enumeration type found;
7300   iterator enumeration_end() { return EnumerationTypes.end(); }
7301 
7302   iterator vector_begin() { return VectorTypes.begin(); }
7303   iterator vector_end() { return VectorTypes.end(); }
7304 
7305   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7306   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7307   bool hasNullPtrType() const { return HasNullPtrType; }
7308 };
7309 
7310 } // end anonymous namespace
7311 
7312 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7313 /// the set of pointer types along with any more-qualified variants of
7314 /// that type. For example, if @p Ty is "int const *", this routine
7315 /// will add "int const *", "int const volatile *", "int const
7316 /// restrict *", and "int const volatile restrict *" to the set of
7317 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7318 /// false otherwise.
7319 ///
7320 /// FIXME: what to do about extended qualifiers?
7321 bool
7322 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7323                                              const Qualifiers &VisibleQuals) {
7324 
7325   // Insert this type.
7326   if (!PointerTypes.insert(Ty))
7327     return false;
7328 
7329   QualType PointeeTy;
7330   const PointerType *PointerTy = Ty->getAs<PointerType>();
7331   bool buildObjCPtr = false;
7332   if (!PointerTy) {
7333     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7334     PointeeTy = PTy->getPointeeType();
7335     buildObjCPtr = true;
7336   } else {
7337     PointeeTy = PointerTy->getPointeeType();
7338   }
7339 
7340   // Don't add qualified variants of arrays. For one, they're not allowed
7341   // (the qualifier would sink to the element type), and for another, the
7342   // only overload situation where it matters is subscript or pointer +- int,
7343   // and those shouldn't have qualifier variants anyway.
7344   if (PointeeTy->isArrayType())
7345     return true;
7346 
7347   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7348   bool hasVolatile = VisibleQuals.hasVolatile();
7349   bool hasRestrict = VisibleQuals.hasRestrict();
7350 
7351   // Iterate through all strict supersets of BaseCVR.
7352   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7353     if ((CVR | BaseCVR) != CVR) continue;
7354     // Skip over volatile if no volatile found anywhere in the types.
7355     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7356 
7357     // Skip over restrict if no restrict found anywhere in the types, or if
7358     // the type cannot be restrict-qualified.
7359     if ((CVR & Qualifiers::Restrict) &&
7360         (!hasRestrict ||
7361          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7362       continue;
7363 
7364     // Build qualified pointee type.
7365     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7366 
7367     // Build qualified pointer type.
7368     QualType QPointerTy;
7369     if (!buildObjCPtr)
7370       QPointerTy = Context.getPointerType(QPointeeTy);
7371     else
7372       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7373 
7374     // Insert qualified pointer type.
7375     PointerTypes.insert(QPointerTy);
7376   }
7377 
7378   return true;
7379 }
7380 
7381 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7382 /// to the set of pointer types along with any more-qualified variants of
7383 /// that type. For example, if @p Ty is "int const *", this routine
7384 /// will add "int const *", "int const volatile *", "int const
7385 /// restrict *", and "int const volatile restrict *" to the set of
7386 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7387 /// false otherwise.
7388 ///
7389 /// FIXME: what to do about extended qualifiers?
7390 bool
7391 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7392     QualType Ty) {
7393   // Insert this type.
7394   if (!MemberPointerTypes.insert(Ty))
7395     return false;
7396 
7397   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7398   assert(PointerTy && "type was not a member pointer type!");
7399 
7400   QualType PointeeTy = PointerTy->getPointeeType();
7401   // Don't add qualified variants of arrays. For one, they're not allowed
7402   // (the qualifier would sink to the element type), and for another, the
7403   // only overload situation where it matters is subscript or pointer +- int,
7404   // and those shouldn't have qualifier variants anyway.
7405   if (PointeeTy->isArrayType())
7406     return true;
7407   const Type *ClassTy = PointerTy->getClass();
7408 
7409   // Iterate through all strict supersets of the pointee type's CVR
7410   // qualifiers.
7411   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7412   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7413     if ((CVR | BaseCVR) != CVR) continue;
7414 
7415     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7416     MemberPointerTypes.insert(
7417       Context.getMemberPointerType(QPointeeTy, ClassTy));
7418   }
7419 
7420   return true;
7421 }
7422 
7423 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7424 /// Ty can be implicit converted to the given set of @p Types. We're
7425 /// primarily interested in pointer types and enumeration types. We also
7426 /// take member pointer types, for the conditional operator.
7427 /// AllowUserConversions is true if we should look at the conversion
7428 /// functions of a class type, and AllowExplicitConversions if we
7429 /// should also include the explicit conversion functions of a class
7430 /// type.
7431 void
7432 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7433                                                SourceLocation Loc,
7434                                                bool AllowUserConversions,
7435                                                bool AllowExplicitConversions,
7436                                                const Qualifiers &VisibleQuals) {
7437   // Only deal with canonical types.
7438   Ty = Context.getCanonicalType(Ty);
7439 
7440   // Look through reference types; they aren't part of the type of an
7441   // expression for the purposes of conversions.
7442   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7443     Ty = RefTy->getPointeeType();
7444 
7445   // If we're dealing with an array type, decay to the pointer.
7446   if (Ty->isArrayType())
7447     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7448 
7449   // Otherwise, we don't care about qualifiers on the type.
7450   Ty = Ty.getLocalUnqualifiedType();
7451 
7452   // Flag if we ever add a non-record type.
7453   const RecordType *TyRec = Ty->getAs<RecordType>();
7454   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7455 
7456   // Flag if we encounter an arithmetic type.
7457   HasArithmeticOrEnumeralTypes =
7458     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7459 
7460   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7461     PointerTypes.insert(Ty);
7462   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7463     // Insert our type, and its more-qualified variants, into the set
7464     // of types.
7465     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7466       return;
7467   } else if (Ty->isMemberPointerType()) {
7468     // Member pointers are far easier, since the pointee can't be converted.
7469     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7470       return;
7471   } else if (Ty->isEnumeralType()) {
7472     HasArithmeticOrEnumeralTypes = true;
7473     EnumerationTypes.insert(Ty);
7474   } else if (Ty->isVectorType()) {
7475     // We treat vector types as arithmetic types in many contexts as an
7476     // extension.
7477     HasArithmeticOrEnumeralTypes = true;
7478     VectorTypes.insert(Ty);
7479   } else if (Ty->isNullPtrType()) {
7480     HasNullPtrType = true;
7481   } else if (AllowUserConversions && TyRec) {
7482     // No conversion functions in incomplete types.
7483     if (!SemaRef.isCompleteType(Loc, Ty))
7484       return;
7485 
7486     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7487     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7488       if (isa<UsingShadowDecl>(D))
7489         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7490 
7491       // Skip conversion function templates; they don't tell us anything
7492       // about which builtin types we can convert to.
7493       if (isa<FunctionTemplateDecl>(D))
7494         continue;
7495 
7496       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7497       if (AllowExplicitConversions || !Conv->isExplicit()) {
7498         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7499                               VisibleQuals);
7500       }
7501     }
7502   }
7503 }
7504 
7505 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7506 /// the volatile- and non-volatile-qualified assignment operators for the
7507 /// given type to the candidate set.
7508 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7509                                                    QualType T,
7510                                                    ArrayRef<Expr *> Args,
7511                                     OverloadCandidateSet &CandidateSet) {
7512   QualType ParamTypes[2];
7513 
7514   // T& operator=(T&, T)
7515   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7516   ParamTypes[1] = T;
7517   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7518                         /*IsAssignmentOperator=*/true);
7519 
7520   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7521     // volatile T& operator=(volatile T&, T)
7522     ParamTypes[0]
7523       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7524     ParamTypes[1] = T;
7525     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7526                           /*IsAssignmentOperator=*/true);
7527   }
7528 }
7529 
7530 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7531 /// if any, found in visible type conversion functions found in ArgExpr's type.
7532 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7533     Qualifiers VRQuals;
7534     const RecordType *TyRec;
7535     if (const MemberPointerType *RHSMPType =
7536         ArgExpr->getType()->getAs<MemberPointerType>())
7537       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7538     else
7539       TyRec = ArgExpr->getType()->getAs<RecordType>();
7540     if (!TyRec) {
7541       // Just to be safe, assume the worst case.
7542       VRQuals.addVolatile();
7543       VRQuals.addRestrict();
7544       return VRQuals;
7545     }
7546 
7547     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7548     if (!ClassDecl->hasDefinition())
7549       return VRQuals;
7550 
7551     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7552       if (isa<UsingShadowDecl>(D))
7553         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7554       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7555         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7556         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7557           CanTy = ResTypeRef->getPointeeType();
7558         // Need to go down the pointer/mempointer chain and add qualifiers
7559         // as see them.
7560         bool done = false;
7561         while (!done) {
7562           if (CanTy.isRestrictQualified())
7563             VRQuals.addRestrict();
7564           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7565             CanTy = ResTypePtr->getPointeeType();
7566           else if (const MemberPointerType *ResTypeMPtr =
7567                 CanTy->getAs<MemberPointerType>())
7568             CanTy = ResTypeMPtr->getPointeeType();
7569           else
7570             done = true;
7571           if (CanTy.isVolatileQualified())
7572             VRQuals.addVolatile();
7573           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7574             return VRQuals;
7575         }
7576       }
7577     }
7578     return VRQuals;
7579 }
7580 
7581 namespace {
7582 
7583 /// \brief Helper class to manage the addition of builtin operator overload
7584 /// candidates. It provides shared state and utility methods used throughout
7585 /// the process, as well as a helper method to add each group of builtin
7586 /// operator overloads from the standard to a candidate set.
7587 class BuiltinOperatorOverloadBuilder {
7588   // Common instance state available to all overload candidate addition methods.
7589   Sema &S;
7590   ArrayRef<Expr *> Args;
7591   Qualifiers VisibleTypeConversionsQuals;
7592   bool HasArithmeticOrEnumeralCandidateType;
7593   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7594   OverloadCandidateSet &CandidateSet;
7595 
7596   // Define some constants used to index and iterate over the arithemetic types
7597   // provided via the getArithmeticType() method below.
7598   // The "promoted arithmetic types" are the arithmetic
7599   // types are that preserved by promotion (C++ [over.built]p2).
7600   static const unsigned FirstIntegralType = 4;
7601   static const unsigned LastIntegralType = 21;
7602   static const unsigned FirstPromotedIntegralType = 4,
7603                         LastPromotedIntegralType = 12;
7604   static const unsigned FirstPromotedArithmeticType = 0,
7605                         LastPromotedArithmeticType = 12;
7606   static const unsigned NumArithmeticTypes = 21;
7607 
7608   /// \brief Get the canonical type for a given arithmetic type index.
7609   CanQualType getArithmeticType(unsigned index) {
7610     assert(index < NumArithmeticTypes);
7611     static CanQualType ASTContext::* const
7612       ArithmeticTypes[NumArithmeticTypes] = {
7613       // Start of promoted types.
7614       &ASTContext::FloatTy,
7615       &ASTContext::DoubleTy,
7616       &ASTContext::LongDoubleTy,
7617       &ASTContext::Float128Ty,
7618 
7619       // Start of integral types.
7620       &ASTContext::IntTy,
7621       &ASTContext::LongTy,
7622       &ASTContext::LongLongTy,
7623       &ASTContext::Int128Ty,
7624       &ASTContext::UnsignedIntTy,
7625       &ASTContext::UnsignedLongTy,
7626       &ASTContext::UnsignedLongLongTy,
7627       &ASTContext::UnsignedInt128Ty,
7628       // End of promoted types.
7629 
7630       &ASTContext::BoolTy,
7631       &ASTContext::CharTy,
7632       &ASTContext::WCharTy,
7633       &ASTContext::Char16Ty,
7634       &ASTContext::Char32Ty,
7635       &ASTContext::SignedCharTy,
7636       &ASTContext::ShortTy,
7637       &ASTContext::UnsignedCharTy,
7638       &ASTContext::UnsignedShortTy,
7639       // End of integral types.
7640       // FIXME: What about complex? What about half?
7641     };
7642     return S.Context.*ArithmeticTypes[index];
7643   }
7644 
7645   /// \brief Gets the canonical type resulting from the usual arithemetic
7646   /// converions for the given arithmetic types.
7647   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7648     // Accelerator table for performing the usual arithmetic conversions.
7649     // The rules are basically:
7650     //   - if either is floating-point, use the wider floating-point
7651     //   - if same signedness, use the higher rank
7652     //   - if same size, use unsigned of the higher rank
7653     //   - use the larger type
7654     // These rules, together with the axiom that higher ranks are
7655     // never smaller, are sufficient to precompute all of these results
7656     // *except* when dealing with signed types of higher rank.
7657     // (we could precompute SLL x UI for all known platforms, but it's
7658     // better not to make any assumptions).
7659     // We assume that int128 has a higher rank than long long on all platforms.
7660     enum PromotedType : int8_t {
7661             Dep=-1,
7662             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7663     };
7664     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7665                                         [LastPromotedArithmeticType] = {
7666 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7667 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7668 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7669 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7670 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7671 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7672 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7673 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7674 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7675 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7676 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7677     };
7678 
7679     assert(L < LastPromotedArithmeticType);
7680     assert(R < LastPromotedArithmeticType);
7681     int Idx = ConversionsTable[L][R];
7682 
7683     // Fast path: the table gives us a concrete answer.
7684     if (Idx != Dep) return getArithmeticType(Idx);
7685 
7686     // Slow path: we need to compare widths.
7687     // An invariant is that the signed type has higher rank.
7688     CanQualType LT = getArithmeticType(L),
7689                 RT = getArithmeticType(R);
7690     unsigned LW = S.Context.getIntWidth(LT),
7691              RW = S.Context.getIntWidth(RT);
7692 
7693     // If they're different widths, use the signed type.
7694     if (LW > RW) return LT;
7695     else if (LW < RW) return RT;
7696 
7697     // Otherwise, use the unsigned type of the signed type's rank.
7698     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7699     assert(L == SLL || R == SLL);
7700     return S.Context.UnsignedLongLongTy;
7701   }
7702 
7703   /// \brief Helper method to factor out the common pattern of adding overloads
7704   /// for '++' and '--' builtin operators.
7705   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7706                                            bool HasVolatile,
7707                                            bool HasRestrict) {
7708     QualType ParamTypes[2] = {
7709       S.Context.getLValueReferenceType(CandidateTy),
7710       S.Context.IntTy
7711     };
7712 
7713     // Non-volatile version.
7714     if (Args.size() == 1)
7715       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7716     else
7717       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7718 
7719     // Use a heuristic to reduce number of builtin candidates in the set:
7720     // add volatile version only if there are conversions to a volatile type.
7721     if (HasVolatile) {
7722       ParamTypes[0] =
7723         S.Context.getLValueReferenceType(
7724           S.Context.getVolatileType(CandidateTy));
7725       if (Args.size() == 1)
7726         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7727       else
7728         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7729     }
7730 
7731     // Add restrict version only if there are conversions to a restrict type
7732     // and our candidate type is a non-restrict-qualified pointer.
7733     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7734         !CandidateTy.isRestrictQualified()) {
7735       ParamTypes[0]
7736         = S.Context.getLValueReferenceType(
7737             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7738       if (Args.size() == 1)
7739         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7740       else
7741         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7742 
7743       if (HasVolatile) {
7744         ParamTypes[0]
7745           = S.Context.getLValueReferenceType(
7746               S.Context.getCVRQualifiedType(CandidateTy,
7747                                             (Qualifiers::Volatile |
7748                                              Qualifiers::Restrict)));
7749         if (Args.size() == 1)
7750           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7751         else
7752           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7753       }
7754     }
7755 
7756   }
7757 
7758 public:
7759   BuiltinOperatorOverloadBuilder(
7760     Sema &S, ArrayRef<Expr *> Args,
7761     Qualifiers VisibleTypeConversionsQuals,
7762     bool HasArithmeticOrEnumeralCandidateType,
7763     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7764     OverloadCandidateSet &CandidateSet)
7765     : S(S), Args(Args),
7766       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7767       HasArithmeticOrEnumeralCandidateType(
7768         HasArithmeticOrEnumeralCandidateType),
7769       CandidateTypes(CandidateTypes),
7770       CandidateSet(CandidateSet) {
7771     // Validate some of our static helper constants in debug builds.
7772     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7773            "Invalid first promoted integral type");
7774     assert(getArithmeticType(LastPromotedIntegralType - 1)
7775              == S.Context.UnsignedInt128Ty &&
7776            "Invalid last promoted integral type");
7777     assert(getArithmeticType(FirstPromotedArithmeticType)
7778              == S.Context.FloatTy &&
7779            "Invalid first promoted arithmetic type");
7780     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7781              == S.Context.UnsignedInt128Ty &&
7782            "Invalid last promoted arithmetic type");
7783   }
7784 
7785   // C++ [over.built]p3:
7786   //
7787   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7788   //   is either volatile or empty, there exist candidate operator
7789   //   functions of the form
7790   //
7791   //       VQ T&      operator++(VQ T&);
7792   //       T          operator++(VQ T&, int);
7793   //
7794   // C++ [over.built]p4:
7795   //
7796   //   For every pair (T, VQ), where T is an arithmetic type other
7797   //   than bool, and VQ is either volatile or empty, there exist
7798   //   candidate operator functions of the form
7799   //
7800   //       VQ T&      operator--(VQ T&);
7801   //       T          operator--(VQ T&, int);
7802   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7803     if (!HasArithmeticOrEnumeralCandidateType)
7804       return;
7805 
7806     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7807          Arith < NumArithmeticTypes; ++Arith) {
7808       addPlusPlusMinusMinusStyleOverloads(
7809         getArithmeticType(Arith),
7810         VisibleTypeConversionsQuals.hasVolatile(),
7811         VisibleTypeConversionsQuals.hasRestrict());
7812     }
7813   }
7814 
7815   // C++ [over.built]p5:
7816   //
7817   //   For every pair (T, VQ), where T is a cv-qualified or
7818   //   cv-unqualified object type, and VQ is either volatile or
7819   //   empty, there exist candidate operator functions of the form
7820   //
7821   //       T*VQ&      operator++(T*VQ&);
7822   //       T*VQ&      operator--(T*VQ&);
7823   //       T*         operator++(T*VQ&, int);
7824   //       T*         operator--(T*VQ&, int);
7825   void addPlusPlusMinusMinusPointerOverloads() {
7826     for (BuiltinCandidateTypeSet::iterator
7827               Ptr = CandidateTypes[0].pointer_begin(),
7828            PtrEnd = CandidateTypes[0].pointer_end();
7829          Ptr != PtrEnd; ++Ptr) {
7830       // Skip pointer types that aren't pointers to object types.
7831       if (!(*Ptr)->getPointeeType()->isObjectType())
7832         continue;
7833 
7834       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7835         (!(*Ptr).isVolatileQualified() &&
7836          VisibleTypeConversionsQuals.hasVolatile()),
7837         (!(*Ptr).isRestrictQualified() &&
7838          VisibleTypeConversionsQuals.hasRestrict()));
7839     }
7840   }
7841 
7842   // C++ [over.built]p6:
7843   //   For every cv-qualified or cv-unqualified object type T, there
7844   //   exist candidate operator functions of the form
7845   //
7846   //       T&         operator*(T*);
7847   //
7848   // C++ [over.built]p7:
7849   //   For every function type T that does not have cv-qualifiers or a
7850   //   ref-qualifier, there exist candidate operator functions of the form
7851   //       T&         operator*(T*);
7852   void addUnaryStarPointerOverloads() {
7853     for (BuiltinCandidateTypeSet::iterator
7854               Ptr = CandidateTypes[0].pointer_begin(),
7855            PtrEnd = CandidateTypes[0].pointer_end();
7856          Ptr != PtrEnd; ++Ptr) {
7857       QualType ParamTy = *Ptr;
7858       QualType PointeeTy = ParamTy->getPointeeType();
7859       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7860         continue;
7861 
7862       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7863         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7864           continue;
7865 
7866       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7867                             &ParamTy, Args, CandidateSet);
7868     }
7869   }
7870 
7871   // C++ [over.built]p9:
7872   //  For every promoted arithmetic type T, there exist candidate
7873   //  operator functions of the form
7874   //
7875   //       T         operator+(T);
7876   //       T         operator-(T);
7877   void addUnaryPlusOrMinusArithmeticOverloads() {
7878     if (!HasArithmeticOrEnumeralCandidateType)
7879       return;
7880 
7881     for (unsigned Arith = FirstPromotedArithmeticType;
7882          Arith < LastPromotedArithmeticType; ++Arith) {
7883       QualType ArithTy = getArithmeticType(Arith);
7884       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7885     }
7886 
7887     // Extension: We also add these operators for vector types.
7888     for (BuiltinCandidateTypeSet::iterator
7889               Vec = CandidateTypes[0].vector_begin(),
7890            VecEnd = CandidateTypes[0].vector_end();
7891          Vec != VecEnd; ++Vec) {
7892       QualType VecTy = *Vec;
7893       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7894     }
7895   }
7896 
7897   // C++ [over.built]p8:
7898   //   For every type T, there exist candidate operator functions of
7899   //   the form
7900   //
7901   //       T*         operator+(T*);
7902   void addUnaryPlusPointerOverloads() {
7903     for (BuiltinCandidateTypeSet::iterator
7904               Ptr = CandidateTypes[0].pointer_begin(),
7905            PtrEnd = CandidateTypes[0].pointer_end();
7906          Ptr != PtrEnd; ++Ptr) {
7907       QualType ParamTy = *Ptr;
7908       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7909     }
7910   }
7911 
7912   // C++ [over.built]p10:
7913   //   For every promoted integral type T, there exist candidate
7914   //   operator functions of the form
7915   //
7916   //        T         operator~(T);
7917   void addUnaryTildePromotedIntegralOverloads() {
7918     if (!HasArithmeticOrEnumeralCandidateType)
7919       return;
7920 
7921     for (unsigned Int = FirstPromotedIntegralType;
7922          Int < LastPromotedIntegralType; ++Int) {
7923       QualType IntTy = getArithmeticType(Int);
7924       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7925     }
7926 
7927     // Extension: We also add this operator for vector types.
7928     for (BuiltinCandidateTypeSet::iterator
7929               Vec = CandidateTypes[0].vector_begin(),
7930            VecEnd = CandidateTypes[0].vector_end();
7931          Vec != VecEnd; ++Vec) {
7932       QualType VecTy = *Vec;
7933       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7934     }
7935   }
7936 
7937   // C++ [over.match.oper]p16:
7938   //   For every pointer to member type T or type std::nullptr_t, there
7939   //   exist candidate operator functions of the form
7940   //
7941   //        bool operator==(T,T);
7942   //        bool operator!=(T,T);
7943   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7944     /// Set of (canonical) types that we've already handled.
7945     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7946 
7947     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7948       for (BuiltinCandidateTypeSet::iterator
7949                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7950              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7951            MemPtr != MemPtrEnd;
7952            ++MemPtr) {
7953         // Don't add the same builtin candidate twice.
7954         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7955           continue;
7956 
7957         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7958         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7959       }
7960 
7961       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7962         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7963         if (AddedTypes.insert(NullPtrTy).second) {
7964           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7965           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7966                                 CandidateSet);
7967         }
7968       }
7969     }
7970   }
7971 
7972   // C++ [over.built]p15:
7973   //
7974   //   For every T, where T is an enumeration type or a pointer type,
7975   //   there exist candidate operator functions of the form
7976   //
7977   //        bool       operator<(T, T);
7978   //        bool       operator>(T, T);
7979   //        bool       operator<=(T, T);
7980   //        bool       operator>=(T, T);
7981   //        bool       operator==(T, T);
7982   //        bool       operator!=(T, T);
7983   void addRelationalPointerOrEnumeralOverloads() {
7984     // C++ [over.match.oper]p3:
7985     //   [...]the built-in candidates include all of the candidate operator
7986     //   functions defined in 13.6 that, compared to the given operator, [...]
7987     //   do not have the same parameter-type-list as any non-template non-member
7988     //   candidate.
7989     //
7990     // Note that in practice, this only affects enumeration types because there
7991     // aren't any built-in candidates of record type, and a user-defined operator
7992     // must have an operand of record or enumeration type. Also, the only other
7993     // overloaded operator with enumeration arguments, operator=,
7994     // cannot be overloaded for enumeration types, so this is the only place
7995     // where we must suppress candidates like this.
7996     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7997       UserDefinedBinaryOperators;
7998 
7999     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8000       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8001           CandidateTypes[ArgIdx].enumeration_end()) {
8002         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8003                                          CEnd = CandidateSet.end();
8004              C != CEnd; ++C) {
8005           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8006             continue;
8007 
8008           if (C->Function->isFunctionTemplateSpecialization())
8009             continue;
8010 
8011           QualType FirstParamType =
8012             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8013           QualType SecondParamType =
8014             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8015 
8016           // Skip if either parameter isn't of enumeral type.
8017           if (!FirstParamType->isEnumeralType() ||
8018               !SecondParamType->isEnumeralType())
8019             continue;
8020 
8021           // Add this operator to the set of known user-defined operators.
8022           UserDefinedBinaryOperators.insert(
8023             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8024                            S.Context.getCanonicalType(SecondParamType)));
8025         }
8026       }
8027     }
8028 
8029     /// Set of (canonical) types that we've already handled.
8030     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8031 
8032     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8033       for (BuiltinCandidateTypeSet::iterator
8034                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8035              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8036            Ptr != PtrEnd; ++Ptr) {
8037         // Don't add the same builtin candidate twice.
8038         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8039           continue;
8040 
8041         QualType ParamTypes[2] = { *Ptr, *Ptr };
8042         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8043       }
8044       for (BuiltinCandidateTypeSet::iterator
8045                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8046              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8047            Enum != EnumEnd; ++Enum) {
8048         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8049 
8050         // Don't add the same builtin candidate twice, or if a user defined
8051         // candidate exists.
8052         if (!AddedTypes.insert(CanonType).second ||
8053             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8054                                                             CanonType)))
8055           continue;
8056 
8057         QualType ParamTypes[2] = { *Enum, *Enum };
8058         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8059       }
8060     }
8061   }
8062 
8063   // C++ [over.built]p13:
8064   //
8065   //   For every cv-qualified or cv-unqualified object type T
8066   //   there exist candidate operator functions of the form
8067   //
8068   //      T*         operator+(T*, ptrdiff_t);
8069   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8070   //      T*         operator-(T*, ptrdiff_t);
8071   //      T*         operator+(ptrdiff_t, T*);
8072   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8073   //
8074   // C++ [over.built]p14:
8075   //
8076   //   For every T, where T is a pointer to object type, there
8077   //   exist candidate operator functions of the form
8078   //
8079   //      ptrdiff_t  operator-(T, T);
8080   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8081     /// Set of (canonical) types that we've already handled.
8082     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8083 
8084     for (int Arg = 0; Arg < 2; ++Arg) {
8085       QualType AsymmetricParamTypes[2] = {
8086         S.Context.getPointerDiffType(),
8087         S.Context.getPointerDiffType(),
8088       };
8089       for (BuiltinCandidateTypeSet::iterator
8090                 Ptr = CandidateTypes[Arg].pointer_begin(),
8091              PtrEnd = CandidateTypes[Arg].pointer_end();
8092            Ptr != PtrEnd; ++Ptr) {
8093         QualType PointeeTy = (*Ptr)->getPointeeType();
8094         if (!PointeeTy->isObjectType())
8095           continue;
8096 
8097         AsymmetricParamTypes[Arg] = *Ptr;
8098         if (Arg == 0 || Op == OO_Plus) {
8099           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8100           // T* operator+(ptrdiff_t, T*);
8101           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
8102         }
8103         if (Op == OO_Minus) {
8104           // ptrdiff_t operator-(T, T);
8105           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8106             continue;
8107 
8108           QualType ParamTypes[2] = { *Ptr, *Ptr };
8109           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
8110                                 Args, CandidateSet);
8111         }
8112       }
8113     }
8114   }
8115 
8116   // C++ [over.built]p12:
8117   //
8118   //   For every pair of promoted arithmetic types L and R, there
8119   //   exist candidate operator functions of the form
8120   //
8121   //        LR         operator*(L, R);
8122   //        LR         operator/(L, R);
8123   //        LR         operator+(L, R);
8124   //        LR         operator-(L, R);
8125   //        bool       operator<(L, R);
8126   //        bool       operator>(L, R);
8127   //        bool       operator<=(L, R);
8128   //        bool       operator>=(L, R);
8129   //        bool       operator==(L, R);
8130   //        bool       operator!=(L, R);
8131   //
8132   //   where LR is the result of the usual arithmetic conversions
8133   //   between types L and R.
8134   //
8135   // C++ [over.built]p24:
8136   //
8137   //   For every pair of promoted arithmetic types L and R, there exist
8138   //   candidate operator functions of the form
8139   //
8140   //        LR       operator?(bool, L, R);
8141   //
8142   //   where LR is the result of the usual arithmetic conversions
8143   //   between types L and R.
8144   // Our candidates ignore the first parameter.
8145   void addGenericBinaryArithmeticOverloads(bool isComparison) {
8146     if (!HasArithmeticOrEnumeralCandidateType)
8147       return;
8148 
8149     for (unsigned Left = FirstPromotedArithmeticType;
8150          Left < LastPromotedArithmeticType; ++Left) {
8151       for (unsigned Right = FirstPromotedArithmeticType;
8152            Right < LastPromotedArithmeticType; ++Right) {
8153         QualType LandR[2] = { getArithmeticType(Left),
8154                               getArithmeticType(Right) };
8155         QualType Result =
8156           isComparison ? S.Context.BoolTy
8157                        : getUsualArithmeticConversions(Left, Right);
8158         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8159       }
8160     }
8161 
8162     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8163     // conditional operator for vector types.
8164     for (BuiltinCandidateTypeSet::iterator
8165               Vec1 = CandidateTypes[0].vector_begin(),
8166            Vec1End = CandidateTypes[0].vector_end();
8167          Vec1 != Vec1End; ++Vec1) {
8168       for (BuiltinCandidateTypeSet::iterator
8169                 Vec2 = CandidateTypes[1].vector_begin(),
8170              Vec2End = CandidateTypes[1].vector_end();
8171            Vec2 != Vec2End; ++Vec2) {
8172         QualType LandR[2] = { *Vec1, *Vec2 };
8173         QualType Result = S.Context.BoolTy;
8174         if (!isComparison) {
8175           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8176             Result = *Vec1;
8177           else
8178             Result = *Vec2;
8179         }
8180 
8181         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8182       }
8183     }
8184   }
8185 
8186   // C++ [over.built]p17:
8187   //
8188   //   For every pair of promoted integral types L and R, there
8189   //   exist candidate operator functions of the form
8190   //
8191   //      LR         operator%(L, R);
8192   //      LR         operator&(L, R);
8193   //      LR         operator^(L, R);
8194   //      LR         operator|(L, R);
8195   //      L          operator<<(L, R);
8196   //      L          operator>>(L, R);
8197   //
8198   //   where LR is the result of the usual arithmetic conversions
8199   //   between types L and R.
8200   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8201     if (!HasArithmeticOrEnumeralCandidateType)
8202       return;
8203 
8204     for (unsigned Left = FirstPromotedIntegralType;
8205          Left < LastPromotedIntegralType; ++Left) {
8206       for (unsigned Right = FirstPromotedIntegralType;
8207            Right < LastPromotedIntegralType; ++Right) {
8208         QualType LandR[2] = { getArithmeticType(Left),
8209                               getArithmeticType(Right) };
8210         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8211             ? LandR[0]
8212             : getUsualArithmeticConversions(Left, Right);
8213         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8214       }
8215     }
8216   }
8217 
8218   // C++ [over.built]p20:
8219   //
8220   //   For every pair (T, VQ), where T is an enumeration or
8221   //   pointer to member type and VQ is either volatile or
8222   //   empty, there exist candidate operator functions of the form
8223   //
8224   //        VQ T&      operator=(VQ T&, T);
8225   void addAssignmentMemberPointerOrEnumeralOverloads() {
8226     /// Set of (canonical) types that we've already handled.
8227     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8228 
8229     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8230       for (BuiltinCandidateTypeSet::iterator
8231                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8232              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8233            Enum != EnumEnd; ++Enum) {
8234         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8235           continue;
8236 
8237         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8238       }
8239 
8240       for (BuiltinCandidateTypeSet::iterator
8241                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8242              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8243            MemPtr != MemPtrEnd; ++MemPtr) {
8244         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8245           continue;
8246 
8247         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8248       }
8249     }
8250   }
8251 
8252   // C++ [over.built]p19:
8253   //
8254   //   For every pair (T, VQ), where T is any type and VQ is either
8255   //   volatile or empty, there exist candidate operator functions
8256   //   of the form
8257   //
8258   //        T*VQ&      operator=(T*VQ&, T*);
8259   //
8260   // C++ [over.built]p21:
8261   //
8262   //   For every pair (T, VQ), where T is a cv-qualified or
8263   //   cv-unqualified object type and VQ is either volatile or
8264   //   empty, there exist candidate operator functions of the form
8265   //
8266   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8267   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8268   void addAssignmentPointerOverloads(bool isEqualOp) {
8269     /// Set of (canonical) types that we've already handled.
8270     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8271 
8272     for (BuiltinCandidateTypeSet::iterator
8273               Ptr = CandidateTypes[0].pointer_begin(),
8274            PtrEnd = CandidateTypes[0].pointer_end();
8275          Ptr != PtrEnd; ++Ptr) {
8276       // If this is operator=, keep track of the builtin candidates we added.
8277       if (isEqualOp)
8278         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8279       else if (!(*Ptr)->getPointeeType()->isObjectType())
8280         continue;
8281 
8282       // non-volatile version
8283       QualType ParamTypes[2] = {
8284         S.Context.getLValueReferenceType(*Ptr),
8285         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8286       };
8287       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8288                             /*IsAssigmentOperator=*/ isEqualOp);
8289 
8290       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8291                           VisibleTypeConversionsQuals.hasVolatile();
8292       if (NeedVolatile) {
8293         // volatile version
8294         ParamTypes[0] =
8295           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8296         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8297                               /*IsAssigmentOperator=*/isEqualOp);
8298       }
8299 
8300       if (!(*Ptr).isRestrictQualified() &&
8301           VisibleTypeConversionsQuals.hasRestrict()) {
8302         // restrict version
8303         ParamTypes[0]
8304           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8305         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8306                               /*IsAssigmentOperator=*/isEqualOp);
8307 
8308         if (NeedVolatile) {
8309           // volatile restrict version
8310           ParamTypes[0]
8311             = S.Context.getLValueReferenceType(
8312                 S.Context.getCVRQualifiedType(*Ptr,
8313                                               (Qualifiers::Volatile |
8314                                                Qualifiers::Restrict)));
8315           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8316                                 /*IsAssigmentOperator=*/isEqualOp);
8317         }
8318       }
8319     }
8320 
8321     if (isEqualOp) {
8322       for (BuiltinCandidateTypeSet::iterator
8323                 Ptr = CandidateTypes[1].pointer_begin(),
8324              PtrEnd = CandidateTypes[1].pointer_end();
8325            Ptr != PtrEnd; ++Ptr) {
8326         // Make sure we don't add the same candidate twice.
8327         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8328           continue;
8329 
8330         QualType ParamTypes[2] = {
8331           S.Context.getLValueReferenceType(*Ptr),
8332           *Ptr,
8333         };
8334 
8335         // non-volatile version
8336         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8337                               /*IsAssigmentOperator=*/true);
8338 
8339         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8340                            VisibleTypeConversionsQuals.hasVolatile();
8341         if (NeedVolatile) {
8342           // volatile version
8343           ParamTypes[0] =
8344             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8345           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8346                                 /*IsAssigmentOperator=*/true);
8347         }
8348 
8349         if (!(*Ptr).isRestrictQualified() &&
8350             VisibleTypeConversionsQuals.hasRestrict()) {
8351           // restrict version
8352           ParamTypes[0]
8353             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8354           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8355                                 /*IsAssigmentOperator=*/true);
8356 
8357           if (NeedVolatile) {
8358             // volatile restrict version
8359             ParamTypes[0]
8360               = S.Context.getLValueReferenceType(
8361                   S.Context.getCVRQualifiedType(*Ptr,
8362                                                 (Qualifiers::Volatile |
8363                                                  Qualifiers::Restrict)));
8364             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8365                                   /*IsAssigmentOperator=*/true);
8366           }
8367         }
8368       }
8369     }
8370   }
8371 
8372   // C++ [over.built]p18:
8373   //
8374   //   For every triple (L, VQ, R), where L is an arithmetic type,
8375   //   VQ is either volatile or empty, and R is a promoted
8376   //   arithmetic type, there exist candidate operator functions of
8377   //   the form
8378   //
8379   //        VQ L&      operator=(VQ L&, R);
8380   //        VQ L&      operator*=(VQ L&, R);
8381   //        VQ L&      operator/=(VQ L&, R);
8382   //        VQ L&      operator+=(VQ L&, R);
8383   //        VQ L&      operator-=(VQ L&, R);
8384   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8385     if (!HasArithmeticOrEnumeralCandidateType)
8386       return;
8387 
8388     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8389       for (unsigned Right = FirstPromotedArithmeticType;
8390            Right < LastPromotedArithmeticType; ++Right) {
8391         QualType ParamTypes[2];
8392         ParamTypes[1] = getArithmeticType(Right);
8393 
8394         // Add this built-in operator as a candidate (VQ is empty).
8395         ParamTypes[0] =
8396           S.Context.getLValueReferenceType(getArithmeticType(Left));
8397         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8398                               /*IsAssigmentOperator=*/isEqualOp);
8399 
8400         // Add this built-in operator as a candidate (VQ is 'volatile').
8401         if (VisibleTypeConversionsQuals.hasVolatile()) {
8402           ParamTypes[0] =
8403             S.Context.getVolatileType(getArithmeticType(Left));
8404           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8405           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8406                                 /*IsAssigmentOperator=*/isEqualOp);
8407         }
8408       }
8409     }
8410 
8411     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8412     for (BuiltinCandidateTypeSet::iterator
8413               Vec1 = CandidateTypes[0].vector_begin(),
8414            Vec1End = CandidateTypes[0].vector_end();
8415          Vec1 != Vec1End; ++Vec1) {
8416       for (BuiltinCandidateTypeSet::iterator
8417                 Vec2 = CandidateTypes[1].vector_begin(),
8418              Vec2End = CandidateTypes[1].vector_end();
8419            Vec2 != Vec2End; ++Vec2) {
8420         QualType ParamTypes[2];
8421         ParamTypes[1] = *Vec2;
8422         // Add this built-in operator as a candidate (VQ is empty).
8423         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8424         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8425                               /*IsAssigmentOperator=*/isEqualOp);
8426 
8427         // Add this built-in operator as a candidate (VQ is 'volatile').
8428         if (VisibleTypeConversionsQuals.hasVolatile()) {
8429           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8430           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8431           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8432                                 /*IsAssigmentOperator=*/isEqualOp);
8433         }
8434       }
8435     }
8436   }
8437 
8438   // C++ [over.built]p22:
8439   //
8440   //   For every triple (L, VQ, R), where L is an integral type, VQ
8441   //   is either volatile or empty, and R is a promoted integral
8442   //   type, there exist candidate operator functions of the form
8443   //
8444   //        VQ L&       operator%=(VQ L&, R);
8445   //        VQ L&       operator<<=(VQ L&, R);
8446   //        VQ L&       operator>>=(VQ L&, R);
8447   //        VQ L&       operator&=(VQ L&, R);
8448   //        VQ L&       operator^=(VQ L&, R);
8449   //        VQ L&       operator|=(VQ L&, R);
8450   void addAssignmentIntegralOverloads() {
8451     if (!HasArithmeticOrEnumeralCandidateType)
8452       return;
8453 
8454     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8455       for (unsigned Right = FirstPromotedIntegralType;
8456            Right < LastPromotedIntegralType; ++Right) {
8457         QualType ParamTypes[2];
8458         ParamTypes[1] = getArithmeticType(Right);
8459 
8460         // Add this built-in operator as a candidate (VQ is empty).
8461         ParamTypes[0] =
8462           S.Context.getLValueReferenceType(getArithmeticType(Left));
8463         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8464         if (VisibleTypeConversionsQuals.hasVolatile()) {
8465           // Add this built-in operator as a candidate (VQ is 'volatile').
8466           ParamTypes[0] = getArithmeticType(Left);
8467           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8468           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8469           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8470         }
8471       }
8472     }
8473   }
8474 
8475   // C++ [over.operator]p23:
8476   //
8477   //   There also exist candidate operator functions of the form
8478   //
8479   //        bool        operator!(bool);
8480   //        bool        operator&&(bool, bool);
8481   //        bool        operator||(bool, bool);
8482   void addExclaimOverload() {
8483     QualType ParamTy = S.Context.BoolTy;
8484     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8485                           /*IsAssignmentOperator=*/false,
8486                           /*NumContextualBoolArguments=*/1);
8487   }
8488   void addAmpAmpOrPipePipeOverload() {
8489     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8490     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8491                           /*IsAssignmentOperator=*/false,
8492                           /*NumContextualBoolArguments=*/2);
8493   }
8494 
8495   // C++ [over.built]p13:
8496   //
8497   //   For every cv-qualified or cv-unqualified object type T there
8498   //   exist candidate operator functions of the form
8499   //
8500   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8501   //        T&         operator[](T*, ptrdiff_t);
8502   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8503   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8504   //        T&         operator[](ptrdiff_t, T*);
8505   void addSubscriptOverloads() {
8506     for (BuiltinCandidateTypeSet::iterator
8507               Ptr = CandidateTypes[0].pointer_begin(),
8508            PtrEnd = CandidateTypes[0].pointer_end();
8509          Ptr != PtrEnd; ++Ptr) {
8510       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8511       QualType PointeeType = (*Ptr)->getPointeeType();
8512       if (!PointeeType->isObjectType())
8513         continue;
8514 
8515       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8516 
8517       // T& operator[](T*, ptrdiff_t)
8518       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8519     }
8520 
8521     for (BuiltinCandidateTypeSet::iterator
8522               Ptr = CandidateTypes[1].pointer_begin(),
8523            PtrEnd = CandidateTypes[1].pointer_end();
8524          Ptr != PtrEnd; ++Ptr) {
8525       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8526       QualType PointeeType = (*Ptr)->getPointeeType();
8527       if (!PointeeType->isObjectType())
8528         continue;
8529 
8530       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8531 
8532       // T& operator[](ptrdiff_t, T*)
8533       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8534     }
8535   }
8536 
8537   // C++ [over.built]p11:
8538   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8539   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8540   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8541   //    there exist candidate operator functions of the form
8542   //
8543   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8544   //
8545   //    where CV12 is the union of CV1 and CV2.
8546   void addArrowStarOverloads() {
8547     for (BuiltinCandidateTypeSet::iterator
8548              Ptr = CandidateTypes[0].pointer_begin(),
8549            PtrEnd = CandidateTypes[0].pointer_end();
8550          Ptr != PtrEnd; ++Ptr) {
8551       QualType C1Ty = (*Ptr);
8552       QualType C1;
8553       QualifierCollector Q1;
8554       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8555       if (!isa<RecordType>(C1))
8556         continue;
8557       // heuristic to reduce number of builtin candidates in the set.
8558       // Add volatile/restrict version only if there are conversions to a
8559       // volatile/restrict type.
8560       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8561         continue;
8562       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8563         continue;
8564       for (BuiltinCandidateTypeSet::iterator
8565                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8566              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8567            MemPtr != MemPtrEnd; ++MemPtr) {
8568         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8569         QualType C2 = QualType(mptr->getClass(), 0);
8570         C2 = C2.getUnqualifiedType();
8571         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8572           break;
8573         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8574         // build CV12 T&
8575         QualType T = mptr->getPointeeType();
8576         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8577             T.isVolatileQualified())
8578           continue;
8579         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8580             T.isRestrictQualified())
8581           continue;
8582         T = Q1.apply(S.Context, T);
8583         QualType ResultTy = S.Context.getLValueReferenceType(T);
8584         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8585       }
8586     }
8587   }
8588 
8589   // Note that we don't consider the first argument, since it has been
8590   // contextually converted to bool long ago. The candidates below are
8591   // therefore added as binary.
8592   //
8593   // C++ [over.built]p25:
8594   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8595   //   enumeration type, there exist candidate operator functions of the form
8596   //
8597   //        T        operator?(bool, T, T);
8598   //
8599   void addConditionalOperatorOverloads() {
8600     /// Set of (canonical) types that we've already handled.
8601     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8602 
8603     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8604       for (BuiltinCandidateTypeSet::iterator
8605                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8606              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8607            Ptr != PtrEnd; ++Ptr) {
8608         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8609           continue;
8610 
8611         QualType ParamTypes[2] = { *Ptr, *Ptr };
8612         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8613       }
8614 
8615       for (BuiltinCandidateTypeSet::iterator
8616                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8617              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8618            MemPtr != MemPtrEnd; ++MemPtr) {
8619         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8620           continue;
8621 
8622         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8623         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8624       }
8625 
8626       if (S.getLangOpts().CPlusPlus11) {
8627         for (BuiltinCandidateTypeSet::iterator
8628                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8629                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8630              Enum != EnumEnd; ++Enum) {
8631           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8632             continue;
8633 
8634           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8635             continue;
8636 
8637           QualType ParamTypes[2] = { *Enum, *Enum };
8638           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8639         }
8640       }
8641     }
8642   }
8643 };
8644 
8645 } // end anonymous namespace
8646 
8647 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8648 /// operator overloads to the candidate set (C++ [over.built]), based
8649 /// on the operator @p Op and the arguments given. For example, if the
8650 /// operator is a binary '+', this routine might add "int
8651 /// operator+(int, int)" to cover integer addition.
8652 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8653                                         SourceLocation OpLoc,
8654                                         ArrayRef<Expr *> Args,
8655                                         OverloadCandidateSet &CandidateSet) {
8656   // Find all of the types that the arguments can convert to, but only
8657   // if the operator we're looking at has built-in operator candidates
8658   // that make use of these types. Also record whether we encounter non-record
8659   // candidate types or either arithmetic or enumeral candidate types.
8660   Qualifiers VisibleTypeConversionsQuals;
8661   VisibleTypeConversionsQuals.addConst();
8662   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8663     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8664 
8665   bool HasNonRecordCandidateType = false;
8666   bool HasArithmeticOrEnumeralCandidateType = false;
8667   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8668   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8669     CandidateTypes.emplace_back(*this);
8670     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8671                                                  OpLoc,
8672                                                  true,
8673                                                  (Op == OO_Exclaim ||
8674                                                   Op == OO_AmpAmp ||
8675                                                   Op == OO_PipePipe),
8676                                                  VisibleTypeConversionsQuals);
8677     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8678         CandidateTypes[ArgIdx].hasNonRecordTypes();
8679     HasArithmeticOrEnumeralCandidateType =
8680         HasArithmeticOrEnumeralCandidateType ||
8681         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8682   }
8683 
8684   // Exit early when no non-record types have been added to the candidate set
8685   // for any of the arguments to the operator.
8686   //
8687   // We can't exit early for !, ||, or &&, since there we have always have
8688   // 'bool' overloads.
8689   if (!HasNonRecordCandidateType &&
8690       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8691     return;
8692 
8693   // Setup an object to manage the common state for building overloads.
8694   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8695                                            VisibleTypeConversionsQuals,
8696                                            HasArithmeticOrEnumeralCandidateType,
8697                                            CandidateTypes, CandidateSet);
8698 
8699   // Dispatch over the operation to add in only those overloads which apply.
8700   switch (Op) {
8701   case OO_None:
8702   case NUM_OVERLOADED_OPERATORS:
8703     llvm_unreachable("Expected an overloaded operator");
8704 
8705   case OO_New:
8706   case OO_Delete:
8707   case OO_Array_New:
8708   case OO_Array_Delete:
8709   case OO_Call:
8710     llvm_unreachable(
8711                     "Special operators don't use AddBuiltinOperatorCandidates");
8712 
8713   case OO_Comma:
8714   case OO_Arrow:
8715   case OO_Coawait:
8716     // C++ [over.match.oper]p3:
8717     //   -- For the operator ',', the unary operator '&', the
8718     //      operator '->', or the operator 'co_await', the
8719     //      built-in candidates set is empty.
8720     break;
8721 
8722   case OO_Plus: // '+' is either unary or binary
8723     if (Args.size() == 1)
8724       OpBuilder.addUnaryPlusPointerOverloads();
8725     // Fall through.
8726 
8727   case OO_Minus: // '-' is either unary or binary
8728     if (Args.size() == 1) {
8729       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8730     } else {
8731       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8732       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8733     }
8734     break;
8735 
8736   case OO_Star: // '*' is either unary or binary
8737     if (Args.size() == 1)
8738       OpBuilder.addUnaryStarPointerOverloads();
8739     else
8740       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8741     break;
8742 
8743   case OO_Slash:
8744     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8745     break;
8746 
8747   case OO_PlusPlus:
8748   case OO_MinusMinus:
8749     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8750     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8751     break;
8752 
8753   case OO_EqualEqual:
8754   case OO_ExclaimEqual:
8755     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8756     // Fall through.
8757 
8758   case OO_Less:
8759   case OO_Greater:
8760   case OO_LessEqual:
8761   case OO_GreaterEqual:
8762     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8763     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8764     break;
8765 
8766   case OO_Percent:
8767   case OO_Caret:
8768   case OO_Pipe:
8769   case OO_LessLess:
8770   case OO_GreaterGreater:
8771     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8772     break;
8773 
8774   case OO_Amp: // '&' is either unary or binary
8775     if (Args.size() == 1)
8776       // C++ [over.match.oper]p3:
8777       //   -- For the operator ',', the unary operator '&', or the
8778       //      operator '->', the built-in candidates set is empty.
8779       break;
8780 
8781     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8782     break;
8783 
8784   case OO_Tilde:
8785     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8786     break;
8787 
8788   case OO_Equal:
8789     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8790     // Fall through.
8791 
8792   case OO_PlusEqual:
8793   case OO_MinusEqual:
8794     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8795     // Fall through.
8796 
8797   case OO_StarEqual:
8798   case OO_SlashEqual:
8799     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8800     break;
8801 
8802   case OO_PercentEqual:
8803   case OO_LessLessEqual:
8804   case OO_GreaterGreaterEqual:
8805   case OO_AmpEqual:
8806   case OO_CaretEqual:
8807   case OO_PipeEqual:
8808     OpBuilder.addAssignmentIntegralOverloads();
8809     break;
8810 
8811   case OO_Exclaim:
8812     OpBuilder.addExclaimOverload();
8813     break;
8814 
8815   case OO_AmpAmp:
8816   case OO_PipePipe:
8817     OpBuilder.addAmpAmpOrPipePipeOverload();
8818     break;
8819 
8820   case OO_Subscript:
8821     OpBuilder.addSubscriptOverloads();
8822     break;
8823 
8824   case OO_ArrowStar:
8825     OpBuilder.addArrowStarOverloads();
8826     break;
8827 
8828   case OO_Conditional:
8829     OpBuilder.addConditionalOperatorOverloads();
8830     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8831     break;
8832   }
8833 }
8834 
8835 /// \brief Add function candidates found via argument-dependent lookup
8836 /// to the set of overloading candidates.
8837 ///
8838 /// This routine performs argument-dependent name lookup based on the
8839 /// given function name (which may also be an operator name) and adds
8840 /// all of the overload candidates found by ADL to the overload
8841 /// candidate set (C++ [basic.lookup.argdep]).
8842 void
8843 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8844                                            SourceLocation Loc,
8845                                            ArrayRef<Expr *> Args,
8846                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8847                                            OverloadCandidateSet& CandidateSet,
8848                                            bool PartialOverloading) {
8849   ADLResult Fns;
8850 
8851   // FIXME: This approach for uniquing ADL results (and removing
8852   // redundant candidates from the set) relies on pointer-equality,
8853   // which means we need to key off the canonical decl.  However,
8854   // always going back to the canonical decl might not get us the
8855   // right set of default arguments.  What default arguments are
8856   // we supposed to consider on ADL candidates, anyway?
8857 
8858   // FIXME: Pass in the explicit template arguments?
8859   ArgumentDependentLookup(Name, Loc, Args, Fns);
8860 
8861   // Erase all of the candidates we already knew about.
8862   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8863                                    CandEnd = CandidateSet.end();
8864        Cand != CandEnd; ++Cand)
8865     if (Cand->Function) {
8866       Fns.erase(Cand->Function);
8867       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8868         Fns.erase(FunTmpl);
8869     }
8870 
8871   // For each of the ADL candidates we found, add it to the overload
8872   // set.
8873   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8874     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8875     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8876       if (ExplicitTemplateArgs)
8877         continue;
8878 
8879       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8880                            PartialOverloading);
8881     } else
8882       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8883                                    FoundDecl, ExplicitTemplateArgs,
8884                                    Args, CandidateSet, PartialOverloading);
8885   }
8886 }
8887 
8888 namespace {
8889 enum class Comparison { Equal, Better, Worse };
8890 }
8891 
8892 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8893 /// overload resolution.
8894 ///
8895 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8896 /// Cand1's first N enable_if attributes have precisely the same conditions as
8897 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8898 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8899 ///
8900 /// Note that you can have a pair of candidates such that Cand1's enable_if
8901 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8902 /// worse than Cand1's.
8903 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8904                                        const FunctionDecl *Cand2) {
8905   // Common case: One (or both) decls don't have enable_if attrs.
8906   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8907   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8908   if (!Cand1Attr || !Cand2Attr) {
8909     if (Cand1Attr == Cand2Attr)
8910       return Comparison::Equal;
8911     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8912   }
8913 
8914   // FIXME: The next several lines are just
8915   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8916   // instead of reverse order which is how they're stored in the AST.
8917   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8918   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8919 
8920   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8921   // has fewer enable_if attributes than Cand2.
8922   if (Cand1Attrs.size() < Cand2Attrs.size())
8923     return Comparison::Worse;
8924 
8925   auto Cand1I = Cand1Attrs.begin();
8926   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8927   for (auto &Cand2A : Cand2Attrs) {
8928     Cand1ID.clear();
8929     Cand2ID.clear();
8930 
8931     auto &Cand1A = *Cand1I++;
8932     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8933     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8934     if (Cand1ID != Cand2ID)
8935       return Comparison::Worse;
8936   }
8937 
8938   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8939 }
8940 
8941 /// isBetterOverloadCandidate - Determines whether the first overload
8942 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8943 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8944                                       const OverloadCandidate &Cand2,
8945                                       SourceLocation Loc,
8946                                       bool UserDefinedConversion) {
8947   // Define viable functions to be better candidates than non-viable
8948   // functions.
8949   if (!Cand2.Viable)
8950     return Cand1.Viable;
8951   else if (!Cand1.Viable)
8952     return false;
8953 
8954   // C++ [over.match.best]p1:
8955   //
8956   //   -- if F is a static member function, ICS1(F) is defined such
8957   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8958   //      any function G, and, symmetrically, ICS1(G) is neither
8959   //      better nor worse than ICS1(F).
8960   unsigned StartArg = 0;
8961   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8962     StartArg = 1;
8963 
8964   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8965     // We don't allow incompatible pointer conversions in C++.
8966     if (!S.getLangOpts().CPlusPlus)
8967       return ICS.isStandard() &&
8968              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8969 
8970     // The only ill-formed conversion we allow in C++ is the string literal to
8971     // char* conversion, which is only considered ill-formed after C++11.
8972     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8973            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8974   };
8975 
8976   // Define functions that don't require ill-formed conversions for a given
8977   // argument to be better candidates than functions that do.
8978   unsigned NumArgs = Cand1.Conversions.size();
8979   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8980   bool HasBetterConversion = false;
8981   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8982     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8983     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8984     if (Cand1Bad != Cand2Bad) {
8985       if (Cand1Bad)
8986         return false;
8987       HasBetterConversion = true;
8988     }
8989   }
8990 
8991   if (HasBetterConversion)
8992     return true;
8993 
8994   // C++ [over.match.best]p1:
8995   //   A viable function F1 is defined to be a better function than another
8996   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8997   //   conversion sequence than ICSi(F2), and then...
8998   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8999     switch (CompareImplicitConversionSequences(S, Loc,
9000                                                Cand1.Conversions[ArgIdx],
9001                                                Cand2.Conversions[ArgIdx])) {
9002     case ImplicitConversionSequence::Better:
9003       // Cand1 has a better conversion sequence.
9004       HasBetterConversion = true;
9005       break;
9006 
9007     case ImplicitConversionSequence::Worse:
9008       // Cand1 can't be better than Cand2.
9009       return false;
9010 
9011     case ImplicitConversionSequence::Indistinguishable:
9012       // Do nothing.
9013       break;
9014     }
9015   }
9016 
9017   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9018   //       ICSj(F2), or, if not that,
9019   if (HasBetterConversion)
9020     return true;
9021 
9022   //   -- the context is an initialization by user-defined conversion
9023   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9024   //      from the return type of F1 to the destination type (i.e.,
9025   //      the type of the entity being initialized) is a better
9026   //      conversion sequence than the standard conversion sequence
9027   //      from the return type of F2 to the destination type.
9028   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
9029       isa<CXXConversionDecl>(Cand1.Function) &&
9030       isa<CXXConversionDecl>(Cand2.Function)) {
9031     // First check whether we prefer one of the conversion functions over the
9032     // other. This only distinguishes the results in non-standard, extension
9033     // cases such as the conversion from a lambda closure type to a function
9034     // pointer or block.
9035     ImplicitConversionSequence::CompareKind Result =
9036         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9037     if (Result == ImplicitConversionSequence::Indistinguishable)
9038       Result = CompareStandardConversionSequences(S, Loc,
9039                                                   Cand1.FinalConversion,
9040                                                   Cand2.FinalConversion);
9041 
9042     if (Result != ImplicitConversionSequence::Indistinguishable)
9043       return Result == ImplicitConversionSequence::Better;
9044 
9045     // FIXME: Compare kind of reference binding if conversion functions
9046     // convert to a reference type used in direct reference binding, per
9047     // C++14 [over.match.best]p1 section 2 bullet 3.
9048   }
9049 
9050   //    -- F1 is a non-template function and F2 is a function template
9051   //       specialization, or, if not that,
9052   bool Cand1IsSpecialization = Cand1.Function &&
9053                                Cand1.Function->getPrimaryTemplate();
9054   bool Cand2IsSpecialization = Cand2.Function &&
9055                                Cand2.Function->getPrimaryTemplate();
9056   if (Cand1IsSpecialization != Cand2IsSpecialization)
9057     return Cand2IsSpecialization;
9058 
9059   //   -- F1 and F2 are function template specializations, and the function
9060   //      template for F1 is more specialized than the template for F2
9061   //      according to the partial ordering rules described in 14.5.5.2, or,
9062   //      if not that,
9063   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9064     if (FunctionTemplateDecl *BetterTemplate
9065           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9066                                          Cand2.Function->getPrimaryTemplate(),
9067                                          Loc,
9068                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9069                                                              : TPOC_Call,
9070                                          Cand1.ExplicitCallArguments,
9071                                          Cand2.ExplicitCallArguments))
9072       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9073   }
9074 
9075   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9076   // A derived-class constructor beats an (inherited) base class constructor.
9077   bool Cand1IsInherited =
9078       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9079   bool Cand2IsInherited =
9080       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9081   if (Cand1IsInherited != Cand2IsInherited)
9082     return Cand2IsInherited;
9083   else if (Cand1IsInherited) {
9084     assert(Cand2IsInherited);
9085     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9086     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9087     if (Cand1Class->isDerivedFrom(Cand2Class))
9088       return true;
9089     if (Cand2Class->isDerivedFrom(Cand1Class))
9090       return false;
9091     // Inherited from sibling base classes: still ambiguous.
9092   }
9093 
9094   // Check for enable_if value-based overload resolution.
9095   if (Cand1.Function && Cand2.Function) {
9096     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9097     if (Cmp != Comparison::Equal)
9098       return Cmp == Comparison::Better;
9099   }
9100 
9101   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9102     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9103     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9104            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9105   }
9106 
9107   bool HasPS1 = Cand1.Function != nullptr &&
9108                 functionHasPassObjectSizeParams(Cand1.Function);
9109   bool HasPS2 = Cand2.Function != nullptr &&
9110                 functionHasPassObjectSizeParams(Cand2.Function);
9111   return HasPS1 != HasPS2 && HasPS1;
9112 }
9113 
9114 /// Determine whether two declarations are "equivalent" for the purposes of
9115 /// name lookup and overload resolution. This applies when the same internal/no
9116 /// linkage entity is defined by two modules (probably by textually including
9117 /// the same header). In such a case, we don't consider the declarations to
9118 /// declare the same entity, but we also don't want lookups with both
9119 /// declarations visible to be ambiguous in some cases (this happens when using
9120 /// a modularized libstdc++).
9121 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9122                                                   const NamedDecl *B) {
9123   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9124   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9125   if (!VA || !VB)
9126     return false;
9127 
9128   // The declarations must be declaring the same name as an internal linkage
9129   // entity in different modules.
9130   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9131           VB->getDeclContext()->getRedeclContext()) ||
9132       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9133           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9134       VA->isExternallyVisible() || VB->isExternallyVisible())
9135     return false;
9136 
9137   // Check that the declarations appear to be equivalent.
9138   //
9139   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9140   // For constants and functions, we should check the initializer or body is
9141   // the same. For non-constant variables, we shouldn't allow it at all.
9142   if (Context.hasSameType(VA->getType(), VB->getType()))
9143     return true;
9144 
9145   // Enum constants within unnamed enumerations will have different types, but
9146   // may still be similar enough to be interchangeable for our purposes.
9147   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9148     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9149       // Only handle anonymous enums. If the enumerations were named and
9150       // equivalent, they would have been merged to the same type.
9151       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9152       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9153       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9154           !Context.hasSameType(EnumA->getIntegerType(),
9155                                EnumB->getIntegerType()))
9156         return false;
9157       // Allow this only if the value is the same for both enumerators.
9158       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9159     }
9160   }
9161 
9162   // Nothing else is sufficiently similar.
9163   return false;
9164 }
9165 
9166 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9167     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9168   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9169 
9170   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9171   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9172       << !M << (M ? M->getFullModuleName() : "");
9173 
9174   for (auto *E : Equiv) {
9175     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9176     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9177         << !M << (M ? M->getFullModuleName() : "");
9178   }
9179 }
9180 
9181 static bool isCandidateUnavailableDueToDiagnoseIf(const OverloadCandidate &OC) {
9182   ArrayRef<DiagnoseIfAttr *> Info = OC.getDiagnoseIfInfo();
9183   if (!Info.empty() && Info[0]->isError())
9184     return true;
9185 
9186   assert(llvm::all_of(Info,
9187                       [](const DiagnoseIfAttr *A) { return !A->isError(); }) &&
9188          "DiagnoseIf info shouldn't have mixed warnings and errors.");
9189   return false;
9190 }
9191 
9192 /// \brief Computes the best viable function (C++ 13.3.3)
9193 /// within an overload candidate set.
9194 ///
9195 /// \param Loc The location of the function name (or operator symbol) for
9196 /// which overload resolution occurs.
9197 ///
9198 /// \param Best If overload resolution was successful or found a deleted
9199 /// function, \p Best points to the candidate function found.
9200 ///
9201 /// \returns The result of overload resolution.
9202 OverloadingResult
9203 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9204                                          iterator &Best,
9205                                          bool UserDefinedConversion) {
9206   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9207   std::transform(begin(), end(), std::back_inserter(Candidates),
9208                  [](OverloadCandidate &Cand) { return &Cand; });
9209 
9210   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9211   // are accepted by both clang and NVCC. However, during a particular
9212   // compilation mode only one call variant is viable. We need to
9213   // exclude non-viable overload candidates from consideration based
9214   // only on their host/device attributes. Specifically, if one
9215   // candidate call is WrongSide and the other is SameSide, we ignore
9216   // the WrongSide candidate.
9217   if (S.getLangOpts().CUDA) {
9218     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9219     bool ContainsSameSideCandidate =
9220         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9221           return Cand->Function &&
9222                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9223                      Sema::CFP_SameSide;
9224         });
9225     if (ContainsSameSideCandidate) {
9226       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9227         return Cand->Function &&
9228                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9229                    Sema::CFP_WrongSide;
9230       };
9231       llvm::erase_if(Candidates, IsWrongSideCandidate);
9232     }
9233   }
9234 
9235   // Find the best viable function.
9236   Best = end();
9237   for (auto *Cand : Candidates)
9238     if (Cand->Viable)
9239       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
9240                                                      UserDefinedConversion))
9241         Best = Cand;
9242 
9243   // If we didn't find any viable functions, abort.
9244   if (Best == end())
9245     return OR_No_Viable_Function;
9246 
9247   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9248 
9249   // Make sure that this function is better than every other viable
9250   // function. If not, we have an ambiguity.
9251   for (auto *Cand : Candidates) {
9252     if (Cand->Viable &&
9253         Cand != Best &&
9254         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
9255                                    UserDefinedConversion)) {
9256       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9257                                                    Cand->Function)) {
9258         EquivalentCands.push_back(Cand->Function);
9259         continue;
9260       }
9261 
9262       Best = end();
9263       return OR_Ambiguous;
9264     }
9265   }
9266 
9267   // Best is the best viable function.
9268   if (Best->Function &&
9269       (Best->Function->isDeleted() ||
9270        S.isFunctionConsideredUnavailable(Best->Function) ||
9271        isCandidateUnavailableDueToDiagnoseIf(*Best)))
9272     return OR_Deleted;
9273 
9274   if (!EquivalentCands.empty())
9275     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9276                                                     EquivalentCands);
9277 
9278   for (const auto *W : Best->getDiagnoseIfInfo()) {
9279     assert(W->isWarning() && "Errors should've been caught earlier!");
9280     S.emitDiagnoseIfDiagnostic(Loc, W);
9281   }
9282 
9283   return OR_Success;
9284 }
9285 
9286 namespace {
9287 
9288 enum OverloadCandidateKind {
9289   oc_function,
9290   oc_method,
9291   oc_constructor,
9292   oc_function_template,
9293   oc_method_template,
9294   oc_constructor_template,
9295   oc_implicit_default_constructor,
9296   oc_implicit_copy_constructor,
9297   oc_implicit_move_constructor,
9298   oc_implicit_copy_assignment,
9299   oc_implicit_move_assignment,
9300   oc_inherited_constructor,
9301   oc_inherited_constructor_template
9302 };
9303 
9304 static OverloadCandidateKind
9305 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9306                           std::string &Description) {
9307   bool isTemplate = false;
9308 
9309   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9310     isTemplate = true;
9311     Description = S.getTemplateArgumentBindingsText(
9312       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9313   }
9314 
9315   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9316     if (!Ctor->isImplicit()) {
9317       if (isa<ConstructorUsingShadowDecl>(Found))
9318         return isTemplate ? oc_inherited_constructor_template
9319                           : oc_inherited_constructor;
9320       else
9321         return isTemplate ? oc_constructor_template : oc_constructor;
9322     }
9323 
9324     if (Ctor->isDefaultConstructor())
9325       return oc_implicit_default_constructor;
9326 
9327     if (Ctor->isMoveConstructor())
9328       return oc_implicit_move_constructor;
9329 
9330     assert(Ctor->isCopyConstructor() &&
9331            "unexpected sort of implicit constructor");
9332     return oc_implicit_copy_constructor;
9333   }
9334 
9335   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9336     // This actually gets spelled 'candidate function' for now, but
9337     // it doesn't hurt to split it out.
9338     if (!Meth->isImplicit())
9339       return isTemplate ? oc_method_template : oc_method;
9340 
9341     if (Meth->isMoveAssignmentOperator())
9342       return oc_implicit_move_assignment;
9343 
9344     if (Meth->isCopyAssignmentOperator())
9345       return oc_implicit_copy_assignment;
9346 
9347     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9348     return oc_method;
9349   }
9350 
9351   return isTemplate ? oc_function_template : oc_function;
9352 }
9353 
9354 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9355   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9356   // set.
9357   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9358     S.Diag(FoundDecl->getLocation(),
9359            diag::note_ovl_candidate_inherited_constructor)
9360       << Shadow->getNominatedBaseClass();
9361 }
9362 
9363 } // end anonymous namespace
9364 
9365 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9366                                     const FunctionDecl *FD) {
9367   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9368     bool AlwaysTrue;
9369     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9370       return false;
9371     if (!AlwaysTrue)
9372       return false;
9373   }
9374   return true;
9375 }
9376 
9377 /// \brief Returns true if we can take the address of the function.
9378 ///
9379 /// \param Complain - If true, we'll emit a diagnostic
9380 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9381 ///   we in overload resolution?
9382 /// \param Loc - The location of the statement we're complaining about. Ignored
9383 ///   if we're not complaining, or if we're in overload resolution.
9384 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9385                                               bool Complain,
9386                                               bool InOverloadResolution,
9387                                               SourceLocation Loc) {
9388   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9389     if (Complain) {
9390       if (InOverloadResolution)
9391         S.Diag(FD->getLocStart(),
9392                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9393       else
9394         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9395     }
9396     return false;
9397   }
9398 
9399   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9400     return P->hasAttr<PassObjectSizeAttr>();
9401   });
9402   if (I == FD->param_end())
9403     return true;
9404 
9405   if (Complain) {
9406     // Add one to ParamNo because it's user-facing
9407     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9408     if (InOverloadResolution)
9409       S.Diag(FD->getLocation(),
9410              diag::note_ovl_candidate_has_pass_object_size_params)
9411           << ParamNo;
9412     else
9413       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9414           << FD << ParamNo;
9415   }
9416   return false;
9417 }
9418 
9419 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9420                                                const FunctionDecl *FD) {
9421   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9422                                            /*InOverloadResolution=*/true,
9423                                            /*Loc=*/SourceLocation());
9424 }
9425 
9426 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9427                                              bool Complain,
9428                                              SourceLocation Loc) {
9429   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9430                                              /*InOverloadResolution=*/false,
9431                                              Loc);
9432 }
9433 
9434 // Notes the location of an overload candidate.
9435 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9436                                  QualType DestType, bool TakingAddress) {
9437   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9438     return;
9439 
9440   std::string FnDesc;
9441   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9442   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9443                              << (unsigned) K << Fn << FnDesc;
9444 
9445   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9446   Diag(Fn->getLocation(), PD);
9447   MaybeEmitInheritedConstructorNote(*this, Found);
9448 }
9449 
9450 // Notes the location of all overload candidates designated through
9451 // OverloadedExpr
9452 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9453                                      bool TakingAddress) {
9454   assert(OverloadedExpr->getType() == Context.OverloadTy);
9455 
9456   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9457   OverloadExpr *OvlExpr = Ovl.Expression;
9458 
9459   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9460                             IEnd = OvlExpr->decls_end();
9461        I != IEnd; ++I) {
9462     if (FunctionTemplateDecl *FunTmpl =
9463                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9464       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9465                             TakingAddress);
9466     } else if (FunctionDecl *Fun
9467                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9468       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9469     }
9470   }
9471 }
9472 
9473 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9474 /// "lead" diagnostic; it will be given two arguments, the source and
9475 /// target types of the conversion.
9476 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9477                                  Sema &S,
9478                                  SourceLocation CaretLoc,
9479                                  const PartialDiagnostic &PDiag) const {
9480   S.Diag(CaretLoc, PDiag)
9481     << Ambiguous.getFromType() << Ambiguous.getToType();
9482   // FIXME: The note limiting machinery is borrowed from
9483   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9484   // refactoring here.
9485   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9486   unsigned CandsShown = 0;
9487   AmbiguousConversionSequence::const_iterator I, E;
9488   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9489     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9490       break;
9491     ++CandsShown;
9492     S.NoteOverloadCandidate(I->first, I->second);
9493   }
9494   if (I != E)
9495     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9496 }
9497 
9498 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9499                                   unsigned I, bool TakingCandidateAddress) {
9500   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9501   assert(Conv.isBad());
9502   assert(Cand->Function && "for now, candidate must be a function");
9503   FunctionDecl *Fn = Cand->Function;
9504 
9505   // There's a conversion slot for the object argument if this is a
9506   // non-constructor method.  Note that 'I' corresponds the
9507   // conversion-slot index.
9508   bool isObjectArgument = false;
9509   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9510     if (I == 0)
9511       isObjectArgument = true;
9512     else
9513       I--;
9514   }
9515 
9516   std::string FnDesc;
9517   OverloadCandidateKind FnKind =
9518       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9519 
9520   Expr *FromExpr = Conv.Bad.FromExpr;
9521   QualType FromTy = Conv.Bad.getFromType();
9522   QualType ToTy = Conv.Bad.getToType();
9523 
9524   if (FromTy == S.Context.OverloadTy) {
9525     assert(FromExpr && "overload set argument came from implicit argument?");
9526     Expr *E = FromExpr->IgnoreParens();
9527     if (isa<UnaryOperator>(E))
9528       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9529     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9530 
9531     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9532       << (unsigned) FnKind << FnDesc
9533       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9534       << ToTy << Name << I+1;
9535     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9536     return;
9537   }
9538 
9539   // Do some hand-waving analysis to see if the non-viability is due
9540   // to a qualifier mismatch.
9541   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9542   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9543   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9544     CToTy = RT->getPointeeType();
9545   else {
9546     // TODO: detect and diagnose the full richness of const mismatches.
9547     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9548       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9549         CFromTy = FromPT->getPointeeType();
9550         CToTy = ToPT->getPointeeType();
9551       }
9552   }
9553 
9554   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9555       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9556     Qualifiers FromQs = CFromTy.getQualifiers();
9557     Qualifiers ToQs = CToTy.getQualifiers();
9558 
9559     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9560       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9561         << (unsigned) FnKind << FnDesc
9562         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9563         << FromTy
9564         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9565         << (unsigned) isObjectArgument << I+1;
9566       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9567       return;
9568     }
9569 
9570     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9571       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9572         << (unsigned) FnKind << FnDesc
9573         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9574         << FromTy
9575         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9576         << (unsigned) isObjectArgument << I+1;
9577       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9578       return;
9579     }
9580 
9581     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9582       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9583       << (unsigned) FnKind << FnDesc
9584       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9585       << FromTy
9586       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9587       << (unsigned) isObjectArgument << I+1;
9588       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9589       return;
9590     }
9591 
9592     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9593       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9594         << (unsigned) FnKind << FnDesc
9595         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9596         << FromTy << FromQs.hasUnaligned() << I+1;
9597       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9598       return;
9599     }
9600 
9601     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9602     assert(CVR && "unexpected qualifiers mismatch");
9603 
9604     if (isObjectArgument) {
9605       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9606         << (unsigned) FnKind << FnDesc
9607         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9608         << FromTy << (CVR - 1);
9609     } else {
9610       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9611         << (unsigned) FnKind << FnDesc
9612         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9613         << FromTy << (CVR - 1) << I+1;
9614     }
9615     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9616     return;
9617   }
9618 
9619   // Special diagnostic for failure to convert an initializer list, since
9620   // telling the user that it has type void is not useful.
9621   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9622     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9623       << (unsigned) FnKind << FnDesc
9624       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9625       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9626     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9627     return;
9628   }
9629 
9630   // Diagnose references or pointers to incomplete types differently,
9631   // since it's far from impossible that the incompleteness triggered
9632   // the failure.
9633   QualType TempFromTy = FromTy.getNonReferenceType();
9634   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9635     TempFromTy = PTy->getPointeeType();
9636   if (TempFromTy->isIncompleteType()) {
9637     // Emit the generic diagnostic and, optionally, add the hints to it.
9638     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9639       << (unsigned) FnKind << FnDesc
9640       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9641       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9642       << (unsigned) (Cand->Fix.Kind);
9643 
9644     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9645     return;
9646   }
9647 
9648   // Diagnose base -> derived pointer conversions.
9649   unsigned BaseToDerivedConversion = 0;
9650   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9651     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9652       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9653                                                FromPtrTy->getPointeeType()) &&
9654           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9655           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9656           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9657                           FromPtrTy->getPointeeType()))
9658         BaseToDerivedConversion = 1;
9659     }
9660   } else if (const ObjCObjectPointerType *FromPtrTy
9661                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9662     if (const ObjCObjectPointerType *ToPtrTy
9663                                         = ToTy->getAs<ObjCObjectPointerType>())
9664       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9665         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9666           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9667                                                 FromPtrTy->getPointeeType()) &&
9668               FromIface->isSuperClassOf(ToIface))
9669             BaseToDerivedConversion = 2;
9670   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9671     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9672         !FromTy->isIncompleteType() &&
9673         !ToRefTy->getPointeeType()->isIncompleteType() &&
9674         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9675       BaseToDerivedConversion = 3;
9676     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9677                ToTy.getNonReferenceType().getCanonicalType() ==
9678                FromTy.getNonReferenceType().getCanonicalType()) {
9679       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9680         << (unsigned) FnKind << FnDesc
9681         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9682         << (unsigned) isObjectArgument << I + 1;
9683       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9684       return;
9685     }
9686   }
9687 
9688   if (BaseToDerivedConversion) {
9689     S.Diag(Fn->getLocation(),
9690            diag::note_ovl_candidate_bad_base_to_derived_conv)
9691       << (unsigned) FnKind << FnDesc
9692       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9693       << (BaseToDerivedConversion - 1)
9694       << FromTy << ToTy << I+1;
9695     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9696     return;
9697   }
9698 
9699   if (isa<ObjCObjectPointerType>(CFromTy) &&
9700       isa<PointerType>(CToTy)) {
9701       Qualifiers FromQs = CFromTy.getQualifiers();
9702       Qualifiers ToQs = CToTy.getQualifiers();
9703       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9704         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9705         << (unsigned) FnKind << FnDesc
9706         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9707         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9708         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9709         return;
9710       }
9711   }
9712 
9713   if (TakingCandidateAddress &&
9714       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9715     return;
9716 
9717   // Emit the generic diagnostic and, optionally, add the hints to it.
9718   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9719   FDiag << (unsigned) FnKind << FnDesc
9720     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9721     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9722     << (unsigned) (Cand->Fix.Kind);
9723 
9724   // If we can fix the conversion, suggest the FixIts.
9725   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9726        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9727     FDiag << *HI;
9728   S.Diag(Fn->getLocation(), FDiag);
9729 
9730   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9731 }
9732 
9733 /// Additional arity mismatch diagnosis specific to a function overload
9734 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9735 /// over a candidate in any candidate set.
9736 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9737                                unsigned NumArgs) {
9738   FunctionDecl *Fn = Cand->Function;
9739   unsigned MinParams = Fn->getMinRequiredArguments();
9740 
9741   // With invalid overloaded operators, it's possible that we think we
9742   // have an arity mismatch when in fact it looks like we have the
9743   // right number of arguments, because only overloaded operators have
9744   // the weird behavior of overloading member and non-member functions.
9745   // Just don't report anything.
9746   if (Fn->isInvalidDecl() &&
9747       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9748     return true;
9749 
9750   if (NumArgs < MinParams) {
9751     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9752            (Cand->FailureKind == ovl_fail_bad_deduction &&
9753             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9754   } else {
9755     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9756            (Cand->FailureKind == ovl_fail_bad_deduction &&
9757             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9758   }
9759 
9760   return false;
9761 }
9762 
9763 /// General arity mismatch diagnosis over a candidate in a candidate set.
9764 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9765                                   unsigned NumFormalArgs) {
9766   assert(isa<FunctionDecl>(D) &&
9767       "The templated declaration should at least be a function"
9768       " when diagnosing bad template argument deduction due to too many"
9769       " or too few arguments");
9770 
9771   FunctionDecl *Fn = cast<FunctionDecl>(D);
9772 
9773   // TODO: treat calls to a missing default constructor as a special case
9774   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9775   unsigned MinParams = Fn->getMinRequiredArguments();
9776 
9777   // at least / at most / exactly
9778   unsigned mode, modeCount;
9779   if (NumFormalArgs < MinParams) {
9780     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9781         FnTy->isTemplateVariadic())
9782       mode = 0; // "at least"
9783     else
9784       mode = 2; // "exactly"
9785     modeCount = MinParams;
9786   } else {
9787     if (MinParams != FnTy->getNumParams())
9788       mode = 1; // "at most"
9789     else
9790       mode = 2; // "exactly"
9791     modeCount = FnTy->getNumParams();
9792   }
9793 
9794   std::string Description;
9795   OverloadCandidateKind FnKind =
9796       ClassifyOverloadCandidate(S, Found, Fn, Description);
9797 
9798   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9799     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9800       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9801       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9802   else
9803     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9804       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9805       << mode << modeCount << NumFormalArgs;
9806   MaybeEmitInheritedConstructorNote(S, Found);
9807 }
9808 
9809 /// Arity mismatch diagnosis specific to a function overload candidate.
9810 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9811                                   unsigned NumFormalArgs) {
9812   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9813     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9814 }
9815 
9816 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9817   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9818     return TD;
9819   llvm_unreachable("Unsupported: Getting the described template declaration"
9820                    " for bad deduction diagnosis");
9821 }
9822 
9823 /// Diagnose a failed template-argument deduction.
9824 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9825                                  DeductionFailureInfo &DeductionFailure,
9826                                  unsigned NumArgs,
9827                                  bool TakingCandidateAddress) {
9828   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9829   NamedDecl *ParamD;
9830   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9831   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9832   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9833   switch (DeductionFailure.Result) {
9834   case Sema::TDK_Success:
9835     llvm_unreachable("TDK_success while diagnosing bad deduction");
9836 
9837   case Sema::TDK_Incomplete: {
9838     assert(ParamD && "no parameter found for incomplete deduction result");
9839     S.Diag(Templated->getLocation(),
9840            diag::note_ovl_candidate_incomplete_deduction)
9841         << ParamD->getDeclName();
9842     MaybeEmitInheritedConstructorNote(S, Found);
9843     return;
9844   }
9845 
9846   case Sema::TDK_Underqualified: {
9847     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9848     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9849 
9850     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9851 
9852     // Param will have been canonicalized, but it should just be a
9853     // qualified version of ParamD, so move the qualifiers to that.
9854     QualifierCollector Qs;
9855     Qs.strip(Param);
9856     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9857     assert(S.Context.hasSameType(Param, NonCanonParam));
9858 
9859     // Arg has also been canonicalized, but there's nothing we can do
9860     // about that.  It also doesn't matter as much, because it won't
9861     // have any template parameters in it (because deduction isn't
9862     // done on dependent types).
9863     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9864 
9865     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9866         << ParamD->getDeclName() << Arg << NonCanonParam;
9867     MaybeEmitInheritedConstructorNote(S, Found);
9868     return;
9869   }
9870 
9871   case Sema::TDK_Inconsistent: {
9872     assert(ParamD && "no parameter found for inconsistent deduction result");
9873     int which = 0;
9874     if (isa<TemplateTypeParmDecl>(ParamD))
9875       which = 0;
9876     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9877       // Deduction might have failed because we deduced arguments of two
9878       // different types for a non-type template parameter.
9879       // FIXME: Use a different TDK value for this.
9880       QualType T1 =
9881           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9882       QualType T2 =
9883           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9884       if (!S.Context.hasSameType(T1, T2)) {
9885         S.Diag(Templated->getLocation(),
9886                diag::note_ovl_candidate_inconsistent_deduction_types)
9887           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9888           << *DeductionFailure.getSecondArg() << T2;
9889         MaybeEmitInheritedConstructorNote(S, Found);
9890         return;
9891       }
9892 
9893       which = 1;
9894     } else {
9895       which = 2;
9896     }
9897 
9898     S.Diag(Templated->getLocation(),
9899            diag::note_ovl_candidate_inconsistent_deduction)
9900         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9901         << *DeductionFailure.getSecondArg();
9902     MaybeEmitInheritedConstructorNote(S, Found);
9903     return;
9904   }
9905 
9906   case Sema::TDK_InvalidExplicitArguments:
9907     assert(ParamD && "no parameter found for invalid explicit arguments");
9908     if (ParamD->getDeclName())
9909       S.Diag(Templated->getLocation(),
9910              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9911           << ParamD->getDeclName();
9912     else {
9913       int index = 0;
9914       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9915         index = TTP->getIndex();
9916       else if (NonTypeTemplateParmDecl *NTTP
9917                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9918         index = NTTP->getIndex();
9919       else
9920         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9921       S.Diag(Templated->getLocation(),
9922              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9923           << (index + 1);
9924     }
9925     MaybeEmitInheritedConstructorNote(S, Found);
9926     return;
9927 
9928   case Sema::TDK_TooManyArguments:
9929   case Sema::TDK_TooFewArguments:
9930     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9931     return;
9932 
9933   case Sema::TDK_InstantiationDepth:
9934     S.Diag(Templated->getLocation(),
9935            diag::note_ovl_candidate_instantiation_depth);
9936     MaybeEmitInheritedConstructorNote(S, Found);
9937     return;
9938 
9939   case Sema::TDK_SubstitutionFailure: {
9940     // Format the template argument list into the argument string.
9941     SmallString<128> TemplateArgString;
9942     if (TemplateArgumentList *Args =
9943             DeductionFailure.getTemplateArgumentList()) {
9944       TemplateArgString = " ";
9945       TemplateArgString += S.getTemplateArgumentBindingsText(
9946           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9947     }
9948 
9949     // If this candidate was disabled by enable_if, say so.
9950     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9951     if (PDiag && PDiag->second.getDiagID() ==
9952           diag::err_typename_nested_not_found_enable_if) {
9953       // FIXME: Use the source range of the condition, and the fully-qualified
9954       //        name of the enable_if template. These are both present in PDiag.
9955       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9956         << "'enable_if'" << TemplateArgString;
9957       return;
9958     }
9959 
9960     // Format the SFINAE diagnostic into the argument string.
9961     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9962     //        formatted message in another diagnostic.
9963     SmallString<128> SFINAEArgString;
9964     SourceRange R;
9965     if (PDiag) {
9966       SFINAEArgString = ": ";
9967       R = SourceRange(PDiag->first, PDiag->first);
9968       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9969     }
9970 
9971     S.Diag(Templated->getLocation(),
9972            diag::note_ovl_candidate_substitution_failure)
9973         << TemplateArgString << SFINAEArgString << R;
9974     MaybeEmitInheritedConstructorNote(S, Found);
9975     return;
9976   }
9977 
9978   case Sema::TDK_DeducedMismatch:
9979   case Sema::TDK_DeducedMismatchNested: {
9980     // Format the template argument list into the argument string.
9981     SmallString<128> TemplateArgString;
9982     if (TemplateArgumentList *Args =
9983             DeductionFailure.getTemplateArgumentList()) {
9984       TemplateArgString = " ";
9985       TemplateArgString += S.getTemplateArgumentBindingsText(
9986           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9987     }
9988 
9989     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9990         << (*DeductionFailure.getCallArgIndex() + 1)
9991         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9992         << TemplateArgString
9993         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9994     break;
9995   }
9996 
9997   case Sema::TDK_NonDeducedMismatch: {
9998     // FIXME: Provide a source location to indicate what we couldn't match.
9999     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10000     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10001     if (FirstTA.getKind() == TemplateArgument::Template &&
10002         SecondTA.getKind() == TemplateArgument::Template) {
10003       TemplateName FirstTN = FirstTA.getAsTemplate();
10004       TemplateName SecondTN = SecondTA.getAsTemplate();
10005       if (FirstTN.getKind() == TemplateName::Template &&
10006           SecondTN.getKind() == TemplateName::Template) {
10007         if (FirstTN.getAsTemplateDecl()->getName() ==
10008             SecondTN.getAsTemplateDecl()->getName()) {
10009           // FIXME: This fixes a bad diagnostic where both templates are named
10010           // the same.  This particular case is a bit difficult since:
10011           // 1) It is passed as a string to the diagnostic printer.
10012           // 2) The diagnostic printer only attempts to find a better
10013           //    name for types, not decls.
10014           // Ideally, this should folded into the diagnostic printer.
10015           S.Diag(Templated->getLocation(),
10016                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10017               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10018           return;
10019         }
10020       }
10021     }
10022 
10023     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10024         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10025       return;
10026 
10027     // FIXME: For generic lambda parameters, check if the function is a lambda
10028     // call operator, and if so, emit a prettier and more informative
10029     // diagnostic that mentions 'auto' and lambda in addition to
10030     // (or instead of?) the canonical template type parameters.
10031     S.Diag(Templated->getLocation(),
10032            diag::note_ovl_candidate_non_deduced_mismatch)
10033         << FirstTA << SecondTA;
10034     return;
10035   }
10036   // TODO: diagnose these individually, then kill off
10037   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10038   case Sema::TDK_MiscellaneousDeductionFailure:
10039     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10040     MaybeEmitInheritedConstructorNote(S, Found);
10041     return;
10042   case Sema::TDK_CUDATargetMismatch:
10043     S.Diag(Templated->getLocation(),
10044            diag::note_cuda_ovl_candidate_target_mismatch);
10045     return;
10046   }
10047 }
10048 
10049 /// Diagnose a failed template-argument deduction, for function calls.
10050 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10051                                  unsigned NumArgs,
10052                                  bool TakingCandidateAddress) {
10053   unsigned TDK = Cand->DeductionFailure.Result;
10054   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10055     if (CheckArityMismatch(S, Cand, NumArgs))
10056       return;
10057   }
10058   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10059                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10060 }
10061 
10062 /// CUDA: diagnose an invalid call across targets.
10063 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10064   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10065   FunctionDecl *Callee = Cand->Function;
10066 
10067   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10068                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10069 
10070   std::string FnDesc;
10071   OverloadCandidateKind FnKind =
10072       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10073 
10074   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10075       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10076 
10077   // This could be an implicit constructor for which we could not infer the
10078   // target due to a collsion. Diagnose that case.
10079   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10080   if (Meth != nullptr && Meth->isImplicit()) {
10081     CXXRecordDecl *ParentClass = Meth->getParent();
10082     Sema::CXXSpecialMember CSM;
10083 
10084     switch (FnKind) {
10085     default:
10086       return;
10087     case oc_implicit_default_constructor:
10088       CSM = Sema::CXXDefaultConstructor;
10089       break;
10090     case oc_implicit_copy_constructor:
10091       CSM = Sema::CXXCopyConstructor;
10092       break;
10093     case oc_implicit_move_constructor:
10094       CSM = Sema::CXXMoveConstructor;
10095       break;
10096     case oc_implicit_copy_assignment:
10097       CSM = Sema::CXXCopyAssignment;
10098       break;
10099     case oc_implicit_move_assignment:
10100       CSM = Sema::CXXMoveAssignment;
10101       break;
10102     };
10103 
10104     bool ConstRHS = false;
10105     if (Meth->getNumParams()) {
10106       if (const ReferenceType *RT =
10107               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10108         ConstRHS = RT->getPointeeType().isConstQualified();
10109       }
10110     }
10111 
10112     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10113                                               /* ConstRHS */ ConstRHS,
10114                                               /* Diagnose */ true);
10115   }
10116 }
10117 
10118 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10119   FunctionDecl *Callee = Cand->Function;
10120   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10121 
10122   S.Diag(Callee->getLocation(),
10123          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10124       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10125 }
10126 
10127 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10128   FunctionDecl *Callee = Cand->Function;
10129 
10130   S.Diag(Callee->getLocation(),
10131          diag::note_ovl_candidate_disabled_by_extension);
10132 }
10133 
10134 /// Generates a 'note' diagnostic for an overload candidate.  We've
10135 /// already generated a primary error at the call site.
10136 ///
10137 /// It really does need to be a single diagnostic with its caret
10138 /// pointed at the candidate declaration.  Yes, this creates some
10139 /// major challenges of technical writing.  Yes, this makes pointing
10140 /// out problems with specific arguments quite awkward.  It's still
10141 /// better than generating twenty screens of text for every failed
10142 /// overload.
10143 ///
10144 /// It would be great to be able to express per-candidate problems
10145 /// more richly for those diagnostic clients that cared, but we'd
10146 /// still have to be just as careful with the default diagnostics.
10147 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10148                                   unsigned NumArgs,
10149                                   bool TakingCandidateAddress) {
10150   FunctionDecl *Fn = Cand->Function;
10151 
10152   // Note deleted candidates, but only if they're viable.
10153   if (Cand->Viable) {
10154     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10155       std::string FnDesc;
10156       OverloadCandidateKind FnKind =
10157         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10158 
10159       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10160         << FnKind << FnDesc
10161         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10162       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10163       return;
10164     }
10165     if (isCandidateUnavailableDueToDiagnoseIf(*Cand)) {
10166       auto *A = Cand->DiagnoseIfInfo.get<DiagnoseIfAttr *>();
10167       assert(A->isError() && "Non-error diagnose_if disables a candidate?");
10168       S.Diag(Cand->Function->getLocation(),
10169              diag::note_ovl_candidate_disabled_by_function_cond_attr)
10170           << A->getCond()->getSourceRange() << A->getMessage();
10171       return;
10172     }
10173 
10174     // We don't really have anything else to say about viable candidates.
10175     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10176     return;
10177   }
10178 
10179   switch (Cand->FailureKind) {
10180   case ovl_fail_too_many_arguments:
10181   case ovl_fail_too_few_arguments:
10182     return DiagnoseArityMismatch(S, Cand, NumArgs);
10183 
10184   case ovl_fail_bad_deduction:
10185     return DiagnoseBadDeduction(S, Cand, NumArgs,
10186                                 TakingCandidateAddress);
10187 
10188   case ovl_fail_illegal_constructor: {
10189     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10190       << (Fn->getPrimaryTemplate() ? 1 : 0);
10191     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10192     return;
10193   }
10194 
10195   case ovl_fail_trivial_conversion:
10196   case ovl_fail_bad_final_conversion:
10197   case ovl_fail_final_conversion_not_exact:
10198     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10199 
10200   case ovl_fail_bad_conversion: {
10201     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10202     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10203       if (Cand->Conversions[I].isBad())
10204         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10205 
10206     // FIXME: this currently happens when we're called from SemaInit
10207     // when user-conversion overload fails.  Figure out how to handle
10208     // those conditions and diagnose them well.
10209     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10210   }
10211 
10212   case ovl_fail_bad_target:
10213     return DiagnoseBadTarget(S, Cand);
10214 
10215   case ovl_fail_enable_if:
10216     return DiagnoseFailedEnableIfAttr(S, Cand);
10217 
10218   case ovl_fail_ext_disabled:
10219     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10220 
10221   case ovl_fail_inhctor_slice:
10222     // It's generally not interesting to note copy/move constructors here.
10223     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10224       return;
10225     S.Diag(Fn->getLocation(),
10226            diag::note_ovl_candidate_inherited_constructor_slice)
10227       << (Fn->getPrimaryTemplate() ? 1 : 0)
10228       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10229     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10230     return;
10231 
10232   case ovl_fail_addr_not_available: {
10233     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10234     (void)Available;
10235     assert(!Available);
10236     break;
10237   }
10238   }
10239 }
10240 
10241 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10242   // Desugar the type of the surrogate down to a function type,
10243   // retaining as many typedefs as possible while still showing
10244   // the function type (and, therefore, its parameter types).
10245   QualType FnType = Cand->Surrogate->getConversionType();
10246   bool isLValueReference = false;
10247   bool isRValueReference = false;
10248   bool isPointer = false;
10249   if (const LValueReferenceType *FnTypeRef =
10250         FnType->getAs<LValueReferenceType>()) {
10251     FnType = FnTypeRef->getPointeeType();
10252     isLValueReference = true;
10253   } else if (const RValueReferenceType *FnTypeRef =
10254                FnType->getAs<RValueReferenceType>()) {
10255     FnType = FnTypeRef->getPointeeType();
10256     isRValueReference = true;
10257   }
10258   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10259     FnType = FnTypePtr->getPointeeType();
10260     isPointer = true;
10261   }
10262   // Desugar down to a function type.
10263   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10264   // Reconstruct the pointer/reference as appropriate.
10265   if (isPointer) FnType = S.Context.getPointerType(FnType);
10266   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10267   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10268 
10269   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10270     << FnType;
10271 }
10272 
10273 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10274                                          SourceLocation OpLoc,
10275                                          OverloadCandidate *Cand) {
10276   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10277   std::string TypeStr("operator");
10278   TypeStr += Opc;
10279   TypeStr += "(";
10280   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
10281   if (Cand->Conversions.size() == 1) {
10282     TypeStr += ")";
10283     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10284   } else {
10285     TypeStr += ", ";
10286     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10287     TypeStr += ")";
10288     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10289   }
10290 }
10291 
10292 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10293                                          OverloadCandidate *Cand) {
10294   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10295     if (ICS.isBad()) break; // all meaningless after first invalid
10296     if (!ICS.isAmbiguous()) continue;
10297 
10298     ICS.DiagnoseAmbiguousConversion(
10299         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10300   }
10301 }
10302 
10303 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10304   if (Cand->Function)
10305     return Cand->Function->getLocation();
10306   if (Cand->IsSurrogate)
10307     return Cand->Surrogate->getLocation();
10308   return SourceLocation();
10309 }
10310 
10311 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10312   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10313   case Sema::TDK_Success:
10314   case Sema::TDK_NonDependentConversionFailure:
10315     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10316 
10317   case Sema::TDK_Invalid:
10318   case Sema::TDK_Incomplete:
10319     return 1;
10320 
10321   case Sema::TDK_Underqualified:
10322   case Sema::TDK_Inconsistent:
10323     return 2;
10324 
10325   case Sema::TDK_SubstitutionFailure:
10326   case Sema::TDK_DeducedMismatch:
10327   case Sema::TDK_DeducedMismatchNested:
10328   case Sema::TDK_NonDeducedMismatch:
10329   case Sema::TDK_MiscellaneousDeductionFailure:
10330   case Sema::TDK_CUDATargetMismatch:
10331     return 3;
10332 
10333   case Sema::TDK_InstantiationDepth:
10334     return 4;
10335 
10336   case Sema::TDK_InvalidExplicitArguments:
10337     return 5;
10338 
10339   case Sema::TDK_TooManyArguments:
10340   case Sema::TDK_TooFewArguments:
10341     return 6;
10342   }
10343   llvm_unreachable("Unhandled deduction result");
10344 }
10345 
10346 namespace {
10347 struct CompareOverloadCandidatesForDisplay {
10348   Sema &S;
10349   SourceLocation Loc;
10350   size_t NumArgs;
10351 
10352   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10353       : S(S), NumArgs(nArgs) {}
10354 
10355   bool operator()(const OverloadCandidate *L,
10356                   const OverloadCandidate *R) {
10357     // Fast-path this check.
10358     if (L == R) return false;
10359 
10360     // Order first by viability.
10361     if (L->Viable) {
10362       if (!R->Viable) return true;
10363 
10364       // TODO: introduce a tri-valued comparison for overload
10365       // candidates.  Would be more worthwhile if we had a sort
10366       // that could exploit it.
10367       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10368       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10369     } else if (R->Viable)
10370       return false;
10371 
10372     assert(L->Viable == R->Viable);
10373 
10374     // Criteria by which we can sort non-viable candidates:
10375     if (!L->Viable) {
10376       // 1. Arity mismatches come after other candidates.
10377       if (L->FailureKind == ovl_fail_too_many_arguments ||
10378           L->FailureKind == ovl_fail_too_few_arguments) {
10379         if (R->FailureKind == ovl_fail_too_many_arguments ||
10380             R->FailureKind == ovl_fail_too_few_arguments) {
10381           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10382           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10383           if (LDist == RDist) {
10384             if (L->FailureKind == R->FailureKind)
10385               // Sort non-surrogates before surrogates.
10386               return !L->IsSurrogate && R->IsSurrogate;
10387             // Sort candidates requiring fewer parameters than there were
10388             // arguments given after candidates requiring more parameters
10389             // than there were arguments given.
10390             return L->FailureKind == ovl_fail_too_many_arguments;
10391           }
10392           return LDist < RDist;
10393         }
10394         return false;
10395       }
10396       if (R->FailureKind == ovl_fail_too_many_arguments ||
10397           R->FailureKind == ovl_fail_too_few_arguments)
10398         return true;
10399 
10400       // 2. Bad conversions come first and are ordered by the number
10401       // of bad conversions and quality of good conversions.
10402       if (L->FailureKind == ovl_fail_bad_conversion) {
10403         if (R->FailureKind != ovl_fail_bad_conversion)
10404           return true;
10405 
10406         // The conversion that can be fixed with a smaller number of changes,
10407         // comes first.
10408         unsigned numLFixes = L->Fix.NumConversionsFixed;
10409         unsigned numRFixes = R->Fix.NumConversionsFixed;
10410         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10411         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10412         if (numLFixes != numRFixes) {
10413           return numLFixes < numRFixes;
10414         }
10415 
10416         // If there's any ordering between the defined conversions...
10417         // FIXME: this might not be transitive.
10418         assert(L->Conversions.size() == R->Conversions.size());
10419 
10420         int leftBetter = 0;
10421         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10422         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10423           switch (CompareImplicitConversionSequences(S, Loc,
10424                                                      L->Conversions[I],
10425                                                      R->Conversions[I])) {
10426           case ImplicitConversionSequence::Better:
10427             leftBetter++;
10428             break;
10429 
10430           case ImplicitConversionSequence::Worse:
10431             leftBetter--;
10432             break;
10433 
10434           case ImplicitConversionSequence::Indistinguishable:
10435             break;
10436           }
10437         }
10438         if (leftBetter > 0) return true;
10439         if (leftBetter < 0) return false;
10440 
10441       } else if (R->FailureKind == ovl_fail_bad_conversion)
10442         return false;
10443 
10444       if (L->FailureKind == ovl_fail_bad_deduction) {
10445         if (R->FailureKind != ovl_fail_bad_deduction)
10446           return true;
10447 
10448         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10449           return RankDeductionFailure(L->DeductionFailure)
10450                < RankDeductionFailure(R->DeductionFailure);
10451       } else if (R->FailureKind == ovl_fail_bad_deduction)
10452         return false;
10453 
10454       // TODO: others?
10455     }
10456 
10457     // Sort everything else by location.
10458     SourceLocation LLoc = GetLocationForCandidate(L);
10459     SourceLocation RLoc = GetLocationForCandidate(R);
10460 
10461     // Put candidates without locations (e.g. builtins) at the end.
10462     if (LLoc.isInvalid()) return false;
10463     if (RLoc.isInvalid()) return true;
10464 
10465     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10466   }
10467 };
10468 }
10469 
10470 /// CompleteNonViableCandidate - Normally, overload resolution only
10471 /// computes up to the first bad conversion. Produces the FixIt set if
10472 /// possible.
10473 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10474                                        ArrayRef<Expr *> Args) {
10475   assert(!Cand->Viable);
10476 
10477   // Don't do anything on failures other than bad conversion.
10478   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10479 
10480   // We only want the FixIts if all the arguments can be corrected.
10481   bool Unfixable = false;
10482   // Use a implicit copy initialization to check conversion fixes.
10483   Cand->Fix.setConversionChecker(TryCopyInitialization);
10484 
10485   // Attempt to fix the bad conversion.
10486   unsigned ConvCount = Cand->Conversions.size();
10487   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10488        ++ConvIdx) {
10489     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10490     if (Cand->Conversions[ConvIdx].isInitialized() &&
10491         Cand->Conversions[ConvIdx].isBad()) {
10492       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10493       break;
10494     }
10495   }
10496 
10497   // FIXME: this should probably be preserved from the overload
10498   // operation somehow.
10499   bool SuppressUserConversions = false;
10500 
10501   unsigned ConvIdx = 0;
10502   ArrayRef<QualType> ParamTypes;
10503 
10504   if (Cand->IsSurrogate) {
10505     QualType ConvType
10506       = Cand->Surrogate->getConversionType().getNonReferenceType();
10507     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10508       ConvType = ConvPtrType->getPointeeType();
10509     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10510     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10511     ConvIdx = 1;
10512   } else if (Cand->Function) {
10513     ParamTypes =
10514         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10515     if (isa<CXXMethodDecl>(Cand->Function) &&
10516         !isa<CXXConstructorDecl>(Cand->Function)) {
10517       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10518       ConvIdx = 1;
10519     }
10520   } else {
10521     // Builtin operator.
10522     assert(ConvCount <= 3);
10523     ParamTypes = Cand->BuiltinTypes.ParamTypes;
10524   }
10525 
10526   // Fill in the rest of the conversions.
10527   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10528     if (Cand->Conversions[ConvIdx].isInitialized()) {
10529       // We've already checked this conversion.
10530     } else if (ArgIdx < ParamTypes.size()) {
10531       if (ParamTypes[ArgIdx]->isDependentType())
10532         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10533             Args[ArgIdx]->getType());
10534       else {
10535         Cand->Conversions[ConvIdx] =
10536             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10537                                   SuppressUserConversions,
10538                                   /*InOverloadResolution=*/true,
10539                                   /*AllowObjCWritebackConversion=*/
10540                                   S.getLangOpts().ObjCAutoRefCount);
10541         // Store the FixIt in the candidate if it exists.
10542         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10543           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10544       }
10545     } else
10546       Cand->Conversions[ConvIdx].setEllipsis();
10547   }
10548 }
10549 
10550 /// PrintOverloadCandidates - When overload resolution fails, prints
10551 /// diagnostic messages containing the candidates in the candidate
10552 /// set.
10553 void OverloadCandidateSet::NoteCandidates(
10554     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10555     StringRef Opc, SourceLocation OpLoc,
10556     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10557   // Sort the candidates by viability and position.  Sorting directly would
10558   // be prohibitive, so we make a set of pointers and sort those.
10559   SmallVector<OverloadCandidate*, 32> Cands;
10560   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10561   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10562     if (!Filter(*Cand))
10563       continue;
10564     if (Cand->Viable)
10565       Cands.push_back(Cand);
10566     else if (OCD == OCD_AllCandidates) {
10567       CompleteNonViableCandidate(S, Cand, Args);
10568       if (Cand->Function || Cand->IsSurrogate)
10569         Cands.push_back(Cand);
10570       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10571       // want to list every possible builtin candidate.
10572     }
10573   }
10574 
10575   std::sort(Cands.begin(), Cands.end(),
10576             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10577 
10578   bool ReportedAmbiguousConversions = false;
10579 
10580   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10581   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10582   unsigned CandsShown = 0;
10583   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10584     OverloadCandidate *Cand = *I;
10585 
10586     // Set an arbitrary limit on the number of candidate functions we'll spam
10587     // the user with.  FIXME: This limit should depend on details of the
10588     // candidate list.
10589     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10590       break;
10591     }
10592     ++CandsShown;
10593 
10594     if (Cand->Function)
10595       NoteFunctionCandidate(S, Cand, Args.size(),
10596                             /*TakingCandidateAddress=*/false);
10597     else if (Cand->IsSurrogate)
10598       NoteSurrogateCandidate(S, Cand);
10599     else {
10600       assert(Cand->Viable &&
10601              "Non-viable built-in candidates are not added to Cands.");
10602       // Generally we only see ambiguities including viable builtin
10603       // operators if overload resolution got screwed up by an
10604       // ambiguous user-defined conversion.
10605       //
10606       // FIXME: It's quite possible for different conversions to see
10607       // different ambiguities, though.
10608       if (!ReportedAmbiguousConversions) {
10609         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10610         ReportedAmbiguousConversions = true;
10611       }
10612 
10613       // If this is a viable builtin, print it.
10614       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10615     }
10616   }
10617 
10618   if (I != E)
10619     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10620 }
10621 
10622 static SourceLocation
10623 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10624   return Cand->Specialization ? Cand->Specialization->getLocation()
10625                               : SourceLocation();
10626 }
10627 
10628 namespace {
10629 struct CompareTemplateSpecCandidatesForDisplay {
10630   Sema &S;
10631   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10632 
10633   bool operator()(const TemplateSpecCandidate *L,
10634                   const TemplateSpecCandidate *R) {
10635     // Fast-path this check.
10636     if (L == R)
10637       return false;
10638 
10639     // Assuming that both candidates are not matches...
10640 
10641     // Sort by the ranking of deduction failures.
10642     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10643       return RankDeductionFailure(L->DeductionFailure) <
10644              RankDeductionFailure(R->DeductionFailure);
10645 
10646     // Sort everything else by location.
10647     SourceLocation LLoc = GetLocationForCandidate(L);
10648     SourceLocation RLoc = GetLocationForCandidate(R);
10649 
10650     // Put candidates without locations (e.g. builtins) at the end.
10651     if (LLoc.isInvalid())
10652       return false;
10653     if (RLoc.isInvalid())
10654       return true;
10655 
10656     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10657   }
10658 };
10659 }
10660 
10661 /// Diagnose a template argument deduction failure.
10662 /// We are treating these failures as overload failures due to bad
10663 /// deductions.
10664 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10665                                                  bool ForTakingAddress) {
10666   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10667                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10668 }
10669 
10670 void TemplateSpecCandidateSet::destroyCandidates() {
10671   for (iterator i = begin(), e = end(); i != e; ++i) {
10672     i->DeductionFailure.Destroy();
10673   }
10674 }
10675 
10676 void TemplateSpecCandidateSet::clear() {
10677   destroyCandidates();
10678   Candidates.clear();
10679 }
10680 
10681 /// NoteCandidates - When no template specialization match is found, prints
10682 /// diagnostic messages containing the non-matching specializations that form
10683 /// the candidate set.
10684 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10685 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10686 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10687   // Sort the candidates by position (assuming no candidate is a match).
10688   // Sorting directly would be prohibitive, so we make a set of pointers
10689   // and sort those.
10690   SmallVector<TemplateSpecCandidate *, 32> Cands;
10691   Cands.reserve(size());
10692   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10693     if (Cand->Specialization)
10694       Cands.push_back(Cand);
10695     // Otherwise, this is a non-matching builtin candidate.  We do not,
10696     // in general, want to list every possible builtin candidate.
10697   }
10698 
10699   std::sort(Cands.begin(), Cands.end(),
10700             CompareTemplateSpecCandidatesForDisplay(S));
10701 
10702   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10703   // for generalization purposes (?).
10704   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10705 
10706   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10707   unsigned CandsShown = 0;
10708   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10709     TemplateSpecCandidate *Cand = *I;
10710 
10711     // Set an arbitrary limit on the number of candidates we'll spam
10712     // the user with.  FIXME: This limit should depend on details of the
10713     // candidate list.
10714     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10715       break;
10716     ++CandsShown;
10717 
10718     assert(Cand->Specialization &&
10719            "Non-matching built-in candidates are not added to Cands.");
10720     Cand->NoteDeductionFailure(S, ForTakingAddress);
10721   }
10722 
10723   if (I != E)
10724     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10725 }
10726 
10727 // [PossiblyAFunctionType]  -->   [Return]
10728 // NonFunctionType --> NonFunctionType
10729 // R (A) --> R(A)
10730 // R (*)(A) --> R (A)
10731 // R (&)(A) --> R (A)
10732 // R (S::*)(A) --> R (A)
10733 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10734   QualType Ret = PossiblyAFunctionType;
10735   if (const PointerType *ToTypePtr =
10736     PossiblyAFunctionType->getAs<PointerType>())
10737     Ret = ToTypePtr->getPointeeType();
10738   else if (const ReferenceType *ToTypeRef =
10739     PossiblyAFunctionType->getAs<ReferenceType>())
10740     Ret = ToTypeRef->getPointeeType();
10741   else if (const MemberPointerType *MemTypePtr =
10742     PossiblyAFunctionType->getAs<MemberPointerType>())
10743     Ret = MemTypePtr->getPointeeType();
10744   Ret =
10745     Context.getCanonicalType(Ret).getUnqualifiedType();
10746   return Ret;
10747 }
10748 
10749 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10750                                  bool Complain = true) {
10751   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10752       S.DeduceReturnType(FD, Loc, Complain))
10753     return true;
10754 
10755   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10756   if (S.getLangOpts().CPlusPlus1z &&
10757       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10758       !S.ResolveExceptionSpec(Loc, FPT))
10759     return true;
10760 
10761   return false;
10762 }
10763 
10764 namespace {
10765 // A helper class to help with address of function resolution
10766 // - allows us to avoid passing around all those ugly parameters
10767 class AddressOfFunctionResolver {
10768   Sema& S;
10769   Expr* SourceExpr;
10770   const QualType& TargetType;
10771   QualType TargetFunctionType; // Extracted function type from target type
10772 
10773   bool Complain;
10774   //DeclAccessPair& ResultFunctionAccessPair;
10775   ASTContext& Context;
10776 
10777   bool TargetTypeIsNonStaticMemberFunction;
10778   bool FoundNonTemplateFunction;
10779   bool StaticMemberFunctionFromBoundPointer;
10780   bool HasComplained;
10781 
10782   OverloadExpr::FindResult OvlExprInfo;
10783   OverloadExpr *OvlExpr;
10784   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10785   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10786   TemplateSpecCandidateSet FailedCandidates;
10787 
10788 public:
10789   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10790                             const QualType &TargetType, bool Complain)
10791       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10792         Complain(Complain), Context(S.getASTContext()),
10793         TargetTypeIsNonStaticMemberFunction(
10794             !!TargetType->getAs<MemberPointerType>()),
10795         FoundNonTemplateFunction(false),
10796         StaticMemberFunctionFromBoundPointer(false),
10797         HasComplained(false),
10798         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10799         OvlExpr(OvlExprInfo.Expression),
10800         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10801     ExtractUnqualifiedFunctionTypeFromTargetType();
10802 
10803     if (TargetFunctionType->isFunctionType()) {
10804       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10805         if (!UME->isImplicitAccess() &&
10806             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10807           StaticMemberFunctionFromBoundPointer = true;
10808     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10809       DeclAccessPair dap;
10810       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10811               OvlExpr, false, &dap)) {
10812         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10813           if (!Method->isStatic()) {
10814             // If the target type is a non-function type and the function found
10815             // is a non-static member function, pretend as if that was the
10816             // target, it's the only possible type to end up with.
10817             TargetTypeIsNonStaticMemberFunction = true;
10818 
10819             // And skip adding the function if its not in the proper form.
10820             // We'll diagnose this due to an empty set of functions.
10821             if (!OvlExprInfo.HasFormOfMemberPointer)
10822               return;
10823           }
10824 
10825         Matches.push_back(std::make_pair(dap, Fn));
10826       }
10827       return;
10828     }
10829 
10830     if (OvlExpr->hasExplicitTemplateArgs())
10831       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10832 
10833     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10834       // C++ [over.over]p4:
10835       //   If more than one function is selected, [...]
10836       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10837         if (FoundNonTemplateFunction)
10838           EliminateAllTemplateMatches();
10839         else
10840           EliminateAllExceptMostSpecializedTemplate();
10841       }
10842     }
10843 
10844     if (S.getLangOpts().CUDA && Matches.size() > 1)
10845       EliminateSuboptimalCudaMatches();
10846   }
10847 
10848   bool hasComplained() const { return HasComplained; }
10849 
10850 private:
10851   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10852     QualType Discard;
10853     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10854            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10855   }
10856 
10857   /// \return true if A is considered a better overload candidate for the
10858   /// desired type than B.
10859   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10860     // If A doesn't have exactly the correct type, we don't want to classify it
10861     // as "better" than anything else. This way, the user is required to
10862     // disambiguate for us if there are multiple candidates and no exact match.
10863     return candidateHasExactlyCorrectType(A) &&
10864            (!candidateHasExactlyCorrectType(B) ||
10865             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10866   }
10867 
10868   /// \return true if we were able to eliminate all but one overload candidate,
10869   /// false otherwise.
10870   bool eliminiateSuboptimalOverloadCandidates() {
10871     // Same algorithm as overload resolution -- one pass to pick the "best",
10872     // another pass to be sure that nothing is better than the best.
10873     auto Best = Matches.begin();
10874     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10875       if (isBetterCandidate(I->second, Best->second))
10876         Best = I;
10877 
10878     const FunctionDecl *BestFn = Best->second;
10879     auto IsBestOrInferiorToBest = [this, BestFn](
10880         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10881       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10882     };
10883 
10884     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10885     // option, so we can potentially give the user a better error
10886     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10887       return false;
10888     Matches[0] = *Best;
10889     Matches.resize(1);
10890     return true;
10891   }
10892 
10893   bool isTargetTypeAFunction() const {
10894     return TargetFunctionType->isFunctionType();
10895   }
10896 
10897   // [ToType]     [Return]
10898 
10899   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10900   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10901   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10902   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10903     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10904   }
10905 
10906   // return true if any matching specializations were found
10907   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10908                                    const DeclAccessPair& CurAccessFunPair) {
10909     if (CXXMethodDecl *Method
10910               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10911       // Skip non-static function templates when converting to pointer, and
10912       // static when converting to member pointer.
10913       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10914         return false;
10915     }
10916     else if (TargetTypeIsNonStaticMemberFunction)
10917       return false;
10918 
10919     // C++ [over.over]p2:
10920     //   If the name is a function template, template argument deduction is
10921     //   done (14.8.2.2), and if the argument deduction succeeds, the
10922     //   resulting template argument list is used to generate a single
10923     //   function template specialization, which is added to the set of
10924     //   overloaded functions considered.
10925     FunctionDecl *Specialization = nullptr;
10926     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10927     if (Sema::TemplateDeductionResult Result
10928           = S.DeduceTemplateArguments(FunctionTemplate,
10929                                       &OvlExplicitTemplateArgs,
10930                                       TargetFunctionType, Specialization,
10931                                       Info, /*IsAddressOfFunction*/true)) {
10932       // Make a note of the failed deduction for diagnostics.
10933       FailedCandidates.addCandidate()
10934           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10935                MakeDeductionFailureInfo(Context, Result, Info));
10936       return false;
10937     }
10938 
10939     // Template argument deduction ensures that we have an exact match or
10940     // compatible pointer-to-function arguments that would be adjusted by ICS.
10941     // This function template specicalization works.
10942     assert(S.isSameOrCompatibleFunctionType(
10943               Context.getCanonicalType(Specialization->getType()),
10944               Context.getCanonicalType(TargetFunctionType)));
10945 
10946     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10947       return false;
10948 
10949     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10950     return true;
10951   }
10952 
10953   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10954                                       const DeclAccessPair& CurAccessFunPair) {
10955     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10956       // Skip non-static functions when converting to pointer, and static
10957       // when converting to member pointer.
10958       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10959         return false;
10960     }
10961     else if (TargetTypeIsNonStaticMemberFunction)
10962       return false;
10963 
10964     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10965       if (S.getLangOpts().CUDA)
10966         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10967           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10968             return false;
10969 
10970       // If any candidate has a placeholder return type, trigger its deduction
10971       // now.
10972       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10973                                Complain)) {
10974         HasComplained |= Complain;
10975         return false;
10976       }
10977 
10978       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10979         return false;
10980 
10981       // If we're in C, we need to support types that aren't exactly identical.
10982       if (!S.getLangOpts().CPlusPlus ||
10983           candidateHasExactlyCorrectType(FunDecl)) {
10984         Matches.push_back(std::make_pair(
10985             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10986         FoundNonTemplateFunction = true;
10987         return true;
10988       }
10989     }
10990 
10991     return false;
10992   }
10993 
10994   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10995     bool Ret = false;
10996 
10997     // If the overload expression doesn't have the form of a pointer to
10998     // member, don't try to convert it to a pointer-to-member type.
10999     if (IsInvalidFormOfPointerToMemberFunction())
11000       return false;
11001 
11002     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11003                                E = OvlExpr->decls_end();
11004          I != E; ++I) {
11005       // Look through any using declarations to find the underlying function.
11006       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11007 
11008       // C++ [over.over]p3:
11009       //   Non-member functions and static member functions match
11010       //   targets of type "pointer-to-function" or "reference-to-function."
11011       //   Nonstatic member functions match targets of
11012       //   type "pointer-to-member-function."
11013       // Note that according to DR 247, the containing class does not matter.
11014       if (FunctionTemplateDecl *FunctionTemplate
11015                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11016         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11017           Ret = true;
11018       }
11019       // If we have explicit template arguments supplied, skip non-templates.
11020       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11021                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11022         Ret = true;
11023     }
11024     assert(Ret || Matches.empty());
11025     return Ret;
11026   }
11027 
11028   void EliminateAllExceptMostSpecializedTemplate() {
11029     //   [...] and any given function template specialization F1 is
11030     //   eliminated if the set contains a second function template
11031     //   specialization whose function template is more specialized
11032     //   than the function template of F1 according to the partial
11033     //   ordering rules of 14.5.5.2.
11034 
11035     // The algorithm specified above is quadratic. We instead use a
11036     // two-pass algorithm (similar to the one used to identify the
11037     // best viable function in an overload set) that identifies the
11038     // best function template (if it exists).
11039 
11040     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11041     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11042       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11043 
11044     // TODO: It looks like FailedCandidates does not serve much purpose
11045     // here, since the no_viable diagnostic has index 0.
11046     UnresolvedSetIterator Result = S.getMostSpecialized(
11047         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11048         SourceExpr->getLocStart(), S.PDiag(),
11049         S.PDiag(diag::err_addr_ovl_ambiguous)
11050           << Matches[0].second->getDeclName(),
11051         S.PDiag(diag::note_ovl_candidate)
11052           << (unsigned)oc_function_template,
11053         Complain, TargetFunctionType);
11054 
11055     if (Result != MatchesCopy.end()) {
11056       // Make it the first and only element
11057       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11058       Matches[0].second = cast<FunctionDecl>(*Result);
11059       Matches.resize(1);
11060     } else
11061       HasComplained |= Complain;
11062   }
11063 
11064   void EliminateAllTemplateMatches() {
11065     //   [...] any function template specializations in the set are
11066     //   eliminated if the set also contains a non-template function, [...]
11067     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11068       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11069         ++I;
11070       else {
11071         Matches[I] = Matches[--N];
11072         Matches.resize(N);
11073       }
11074     }
11075   }
11076 
11077   void EliminateSuboptimalCudaMatches() {
11078     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11079   }
11080 
11081 public:
11082   void ComplainNoMatchesFound() const {
11083     assert(Matches.empty());
11084     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11085         << OvlExpr->getName() << TargetFunctionType
11086         << OvlExpr->getSourceRange();
11087     if (FailedCandidates.empty())
11088       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11089                                   /*TakingAddress=*/true);
11090     else {
11091       // We have some deduction failure messages. Use them to diagnose
11092       // the function templates, and diagnose the non-template candidates
11093       // normally.
11094       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11095                                  IEnd = OvlExpr->decls_end();
11096            I != IEnd; ++I)
11097         if (FunctionDecl *Fun =
11098                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11099           if (!functionHasPassObjectSizeParams(Fun))
11100             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11101                                     /*TakingAddress=*/true);
11102       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11103     }
11104   }
11105 
11106   bool IsInvalidFormOfPointerToMemberFunction() const {
11107     return TargetTypeIsNonStaticMemberFunction &&
11108       !OvlExprInfo.HasFormOfMemberPointer;
11109   }
11110 
11111   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11112       // TODO: Should we condition this on whether any functions might
11113       // have matched, or is it more appropriate to do that in callers?
11114       // TODO: a fixit wouldn't hurt.
11115       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11116         << TargetType << OvlExpr->getSourceRange();
11117   }
11118 
11119   bool IsStaticMemberFunctionFromBoundPointer() const {
11120     return StaticMemberFunctionFromBoundPointer;
11121   }
11122 
11123   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11124     S.Diag(OvlExpr->getLocStart(),
11125            diag::err_invalid_form_pointer_member_function)
11126       << OvlExpr->getSourceRange();
11127   }
11128 
11129   void ComplainOfInvalidConversion() const {
11130     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11131       << OvlExpr->getName() << TargetType;
11132   }
11133 
11134   void ComplainMultipleMatchesFound() const {
11135     assert(Matches.size() > 1);
11136     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11137       << OvlExpr->getName()
11138       << OvlExpr->getSourceRange();
11139     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11140                                 /*TakingAddress=*/true);
11141   }
11142 
11143   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11144 
11145   int getNumMatches() const { return Matches.size(); }
11146 
11147   FunctionDecl* getMatchingFunctionDecl() const {
11148     if (Matches.size() != 1) return nullptr;
11149     return Matches[0].second;
11150   }
11151 
11152   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11153     if (Matches.size() != 1) return nullptr;
11154     return &Matches[0].first;
11155   }
11156 };
11157 }
11158 
11159 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11160 /// an overloaded function (C++ [over.over]), where @p From is an
11161 /// expression with overloaded function type and @p ToType is the type
11162 /// we're trying to resolve to. For example:
11163 ///
11164 /// @code
11165 /// int f(double);
11166 /// int f(int);
11167 ///
11168 /// int (*pfd)(double) = f; // selects f(double)
11169 /// @endcode
11170 ///
11171 /// This routine returns the resulting FunctionDecl if it could be
11172 /// resolved, and NULL otherwise. When @p Complain is true, this
11173 /// routine will emit diagnostics if there is an error.
11174 FunctionDecl *
11175 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11176                                          QualType TargetType,
11177                                          bool Complain,
11178                                          DeclAccessPair &FoundResult,
11179                                          bool *pHadMultipleCandidates) {
11180   assert(AddressOfExpr->getType() == Context.OverloadTy);
11181 
11182   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11183                                      Complain);
11184   int NumMatches = Resolver.getNumMatches();
11185   FunctionDecl *Fn = nullptr;
11186   bool ShouldComplain = Complain && !Resolver.hasComplained();
11187   if (NumMatches == 0 && ShouldComplain) {
11188     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11189       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11190     else
11191       Resolver.ComplainNoMatchesFound();
11192   }
11193   else if (NumMatches > 1 && ShouldComplain)
11194     Resolver.ComplainMultipleMatchesFound();
11195   else if (NumMatches == 1) {
11196     Fn = Resolver.getMatchingFunctionDecl();
11197     assert(Fn);
11198     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11199       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11200     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11201     if (Complain) {
11202       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11203         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11204       else
11205         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11206     }
11207   }
11208 
11209   if (pHadMultipleCandidates)
11210     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11211   return Fn;
11212 }
11213 
11214 /// \brief Given an expression that refers to an overloaded function, try to
11215 /// resolve that function to a single function that can have its address taken.
11216 /// This will modify `Pair` iff it returns non-null.
11217 ///
11218 /// This routine can only realistically succeed if all but one candidates in the
11219 /// overload set for SrcExpr cannot have their addresses taken.
11220 FunctionDecl *
11221 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11222                                                   DeclAccessPair &Pair) {
11223   OverloadExpr::FindResult R = OverloadExpr::find(E);
11224   OverloadExpr *Ovl = R.Expression;
11225   FunctionDecl *Result = nullptr;
11226   DeclAccessPair DAP;
11227   // Don't use the AddressOfResolver because we're specifically looking for
11228   // cases where we have one overload candidate that lacks
11229   // enable_if/pass_object_size/...
11230   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11231     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11232     if (!FD)
11233       return nullptr;
11234 
11235     if (!checkAddressOfFunctionIsAvailable(FD))
11236       continue;
11237 
11238     // We have more than one result; quit.
11239     if (Result)
11240       return nullptr;
11241     DAP = I.getPair();
11242     Result = FD;
11243   }
11244 
11245   if (Result)
11246     Pair = DAP;
11247   return Result;
11248 }
11249 
11250 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11251 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11252 /// will perform access checks, diagnose the use of the resultant decl, and, if
11253 /// necessary, perform a function-to-pointer decay.
11254 ///
11255 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11256 /// Otherwise, returns true. This may emit diagnostics and return true.
11257 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11258     ExprResult &SrcExpr) {
11259   Expr *E = SrcExpr.get();
11260   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11261 
11262   DeclAccessPair DAP;
11263   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11264   if (!Found)
11265     return false;
11266 
11267   // Emitting multiple diagnostics for a function that is both inaccessible and
11268   // unavailable is consistent with our behavior elsewhere. So, always check
11269   // for both.
11270   DiagnoseUseOfDecl(Found, E->getExprLoc());
11271   CheckAddressOfMemberAccess(E, DAP);
11272   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11273   if (Fixed->getType()->isFunctionType())
11274     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11275   else
11276     SrcExpr = Fixed;
11277   return true;
11278 }
11279 
11280 /// \brief Given an expression that refers to an overloaded function, try to
11281 /// resolve that overloaded function expression down to a single function.
11282 ///
11283 /// This routine can only resolve template-ids that refer to a single function
11284 /// template, where that template-id refers to a single template whose template
11285 /// arguments are either provided by the template-id or have defaults,
11286 /// as described in C++0x [temp.arg.explicit]p3.
11287 ///
11288 /// If no template-ids are found, no diagnostics are emitted and NULL is
11289 /// returned.
11290 FunctionDecl *
11291 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11292                                                   bool Complain,
11293                                                   DeclAccessPair *FoundResult) {
11294   // C++ [over.over]p1:
11295   //   [...] [Note: any redundant set of parentheses surrounding the
11296   //   overloaded function name is ignored (5.1). ]
11297   // C++ [over.over]p1:
11298   //   [...] The overloaded function name can be preceded by the &
11299   //   operator.
11300 
11301   // If we didn't actually find any template-ids, we're done.
11302   if (!ovl->hasExplicitTemplateArgs())
11303     return nullptr;
11304 
11305   TemplateArgumentListInfo ExplicitTemplateArgs;
11306   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11307   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11308 
11309   // Look through all of the overloaded functions, searching for one
11310   // whose type matches exactly.
11311   FunctionDecl *Matched = nullptr;
11312   for (UnresolvedSetIterator I = ovl->decls_begin(),
11313          E = ovl->decls_end(); I != E; ++I) {
11314     // C++0x [temp.arg.explicit]p3:
11315     //   [...] In contexts where deduction is done and fails, or in contexts
11316     //   where deduction is not done, if a template argument list is
11317     //   specified and it, along with any default template arguments,
11318     //   identifies a single function template specialization, then the
11319     //   template-id is an lvalue for the function template specialization.
11320     FunctionTemplateDecl *FunctionTemplate
11321       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11322 
11323     // C++ [over.over]p2:
11324     //   If the name is a function template, template argument deduction is
11325     //   done (14.8.2.2), and if the argument deduction succeeds, the
11326     //   resulting template argument list is used to generate a single
11327     //   function template specialization, which is added to the set of
11328     //   overloaded functions considered.
11329     FunctionDecl *Specialization = nullptr;
11330     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11331     if (TemplateDeductionResult Result
11332           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11333                                     Specialization, Info,
11334                                     /*IsAddressOfFunction*/true)) {
11335       // Make a note of the failed deduction for diagnostics.
11336       // TODO: Actually use the failed-deduction info?
11337       FailedCandidates.addCandidate()
11338           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11339                MakeDeductionFailureInfo(Context, Result, Info));
11340       continue;
11341     }
11342 
11343     assert(Specialization && "no specialization and no error?");
11344 
11345     // Multiple matches; we can't resolve to a single declaration.
11346     if (Matched) {
11347       if (Complain) {
11348         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11349           << ovl->getName();
11350         NoteAllOverloadCandidates(ovl);
11351       }
11352       return nullptr;
11353     }
11354 
11355     Matched = Specialization;
11356     if (FoundResult) *FoundResult = I.getPair();
11357   }
11358 
11359   if (Matched &&
11360       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11361     return nullptr;
11362 
11363   return Matched;
11364 }
11365 
11366 
11367 
11368 
11369 // Resolve and fix an overloaded expression that can be resolved
11370 // because it identifies a single function template specialization.
11371 //
11372 // Last three arguments should only be supplied if Complain = true
11373 //
11374 // Return true if it was logically possible to so resolve the
11375 // expression, regardless of whether or not it succeeded.  Always
11376 // returns true if 'complain' is set.
11377 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11378                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11379                       bool complain, SourceRange OpRangeForComplaining,
11380                                            QualType DestTypeForComplaining,
11381                                             unsigned DiagIDForComplaining) {
11382   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11383 
11384   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11385 
11386   DeclAccessPair found;
11387   ExprResult SingleFunctionExpression;
11388   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11389                            ovl.Expression, /*complain*/ false, &found)) {
11390     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11391       SrcExpr = ExprError();
11392       return true;
11393     }
11394 
11395     // It is only correct to resolve to an instance method if we're
11396     // resolving a form that's permitted to be a pointer to member.
11397     // Otherwise we'll end up making a bound member expression, which
11398     // is illegal in all the contexts we resolve like this.
11399     if (!ovl.HasFormOfMemberPointer &&
11400         isa<CXXMethodDecl>(fn) &&
11401         cast<CXXMethodDecl>(fn)->isInstance()) {
11402       if (!complain) return false;
11403 
11404       Diag(ovl.Expression->getExprLoc(),
11405            diag::err_bound_member_function)
11406         << 0 << ovl.Expression->getSourceRange();
11407 
11408       // TODO: I believe we only end up here if there's a mix of
11409       // static and non-static candidates (otherwise the expression
11410       // would have 'bound member' type, not 'overload' type).
11411       // Ideally we would note which candidate was chosen and why
11412       // the static candidates were rejected.
11413       SrcExpr = ExprError();
11414       return true;
11415     }
11416 
11417     // Fix the expression to refer to 'fn'.
11418     SingleFunctionExpression =
11419         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11420 
11421     // If desired, do function-to-pointer decay.
11422     if (doFunctionPointerConverion) {
11423       SingleFunctionExpression =
11424         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11425       if (SingleFunctionExpression.isInvalid()) {
11426         SrcExpr = ExprError();
11427         return true;
11428       }
11429     }
11430   }
11431 
11432   if (!SingleFunctionExpression.isUsable()) {
11433     if (complain) {
11434       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11435         << ovl.Expression->getName()
11436         << DestTypeForComplaining
11437         << OpRangeForComplaining
11438         << ovl.Expression->getQualifierLoc().getSourceRange();
11439       NoteAllOverloadCandidates(SrcExpr.get());
11440 
11441       SrcExpr = ExprError();
11442       return true;
11443     }
11444 
11445     return false;
11446   }
11447 
11448   SrcExpr = SingleFunctionExpression;
11449   return true;
11450 }
11451 
11452 /// \brief Add a single candidate to the overload set.
11453 static void AddOverloadedCallCandidate(Sema &S,
11454                                        DeclAccessPair FoundDecl,
11455                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11456                                        ArrayRef<Expr *> Args,
11457                                        OverloadCandidateSet &CandidateSet,
11458                                        bool PartialOverloading,
11459                                        bool KnownValid) {
11460   NamedDecl *Callee = FoundDecl.getDecl();
11461   if (isa<UsingShadowDecl>(Callee))
11462     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11463 
11464   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11465     if (ExplicitTemplateArgs) {
11466       assert(!KnownValid && "Explicit template arguments?");
11467       return;
11468     }
11469     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11470                            /*SuppressUsedConversions=*/false,
11471                            PartialOverloading);
11472     return;
11473   }
11474 
11475   if (FunctionTemplateDecl *FuncTemplate
11476       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11477     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11478                                    ExplicitTemplateArgs, Args, CandidateSet,
11479                                    /*SuppressUsedConversions=*/false,
11480                                    PartialOverloading);
11481     return;
11482   }
11483 
11484   assert(!KnownValid && "unhandled case in overloaded call candidate");
11485 }
11486 
11487 /// \brief Add the overload candidates named by callee and/or found by argument
11488 /// dependent lookup to the given overload set.
11489 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11490                                        ArrayRef<Expr *> Args,
11491                                        OverloadCandidateSet &CandidateSet,
11492                                        bool PartialOverloading) {
11493 
11494 #ifndef NDEBUG
11495   // Verify that ArgumentDependentLookup is consistent with the rules
11496   // in C++0x [basic.lookup.argdep]p3:
11497   //
11498   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11499   //   and let Y be the lookup set produced by argument dependent
11500   //   lookup (defined as follows). If X contains
11501   //
11502   //     -- a declaration of a class member, or
11503   //
11504   //     -- a block-scope function declaration that is not a
11505   //        using-declaration, or
11506   //
11507   //     -- a declaration that is neither a function or a function
11508   //        template
11509   //
11510   //   then Y is empty.
11511 
11512   if (ULE->requiresADL()) {
11513     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11514            E = ULE->decls_end(); I != E; ++I) {
11515       assert(!(*I)->getDeclContext()->isRecord());
11516       assert(isa<UsingShadowDecl>(*I) ||
11517              !(*I)->getDeclContext()->isFunctionOrMethod());
11518       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11519     }
11520   }
11521 #endif
11522 
11523   // It would be nice to avoid this copy.
11524   TemplateArgumentListInfo TABuffer;
11525   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11526   if (ULE->hasExplicitTemplateArgs()) {
11527     ULE->copyTemplateArgumentsInto(TABuffer);
11528     ExplicitTemplateArgs = &TABuffer;
11529   }
11530 
11531   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11532          E = ULE->decls_end(); I != E; ++I)
11533     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11534                                CandidateSet, PartialOverloading,
11535                                /*KnownValid*/ true);
11536 
11537   if (ULE->requiresADL())
11538     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11539                                          Args, ExplicitTemplateArgs,
11540                                          CandidateSet, PartialOverloading);
11541 }
11542 
11543 /// Determine whether a declaration with the specified name could be moved into
11544 /// a different namespace.
11545 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11546   switch (Name.getCXXOverloadedOperator()) {
11547   case OO_New: case OO_Array_New:
11548   case OO_Delete: case OO_Array_Delete:
11549     return false;
11550 
11551   default:
11552     return true;
11553   }
11554 }
11555 
11556 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11557 /// template, where the non-dependent name was declared after the template
11558 /// was defined. This is common in code written for a compilers which do not
11559 /// correctly implement two-stage name lookup.
11560 ///
11561 /// Returns true if a viable candidate was found and a diagnostic was issued.
11562 static bool
11563 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11564                        const CXXScopeSpec &SS, LookupResult &R,
11565                        OverloadCandidateSet::CandidateSetKind CSK,
11566                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11567                        ArrayRef<Expr *> Args,
11568                        bool *DoDiagnoseEmptyLookup = nullptr) {
11569   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11570     return false;
11571 
11572   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11573     if (DC->isTransparentContext())
11574       continue;
11575 
11576     SemaRef.LookupQualifiedName(R, DC);
11577 
11578     if (!R.empty()) {
11579       R.suppressDiagnostics();
11580 
11581       if (isa<CXXRecordDecl>(DC)) {
11582         // Don't diagnose names we find in classes; we get much better
11583         // diagnostics for these from DiagnoseEmptyLookup.
11584         R.clear();
11585         if (DoDiagnoseEmptyLookup)
11586           *DoDiagnoseEmptyLookup = true;
11587         return false;
11588       }
11589 
11590       OverloadCandidateSet Candidates(FnLoc, CSK);
11591       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11592         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11593                                    ExplicitTemplateArgs, Args,
11594                                    Candidates, false, /*KnownValid*/ false);
11595 
11596       OverloadCandidateSet::iterator Best;
11597       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11598         // No viable functions. Don't bother the user with notes for functions
11599         // which don't work and shouldn't be found anyway.
11600         R.clear();
11601         return false;
11602       }
11603 
11604       // Find the namespaces where ADL would have looked, and suggest
11605       // declaring the function there instead.
11606       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11607       Sema::AssociatedClassSet AssociatedClasses;
11608       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11609                                                  AssociatedNamespaces,
11610                                                  AssociatedClasses);
11611       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11612       if (canBeDeclaredInNamespace(R.getLookupName())) {
11613         DeclContext *Std = SemaRef.getStdNamespace();
11614         for (Sema::AssociatedNamespaceSet::iterator
11615                it = AssociatedNamespaces.begin(),
11616                end = AssociatedNamespaces.end(); it != end; ++it) {
11617           // Never suggest declaring a function within namespace 'std'.
11618           if (Std && Std->Encloses(*it))
11619             continue;
11620 
11621           // Never suggest declaring a function within a namespace with a
11622           // reserved name, like __gnu_cxx.
11623           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11624           if (NS &&
11625               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11626             continue;
11627 
11628           SuggestedNamespaces.insert(*it);
11629         }
11630       }
11631 
11632       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11633         << R.getLookupName();
11634       if (SuggestedNamespaces.empty()) {
11635         SemaRef.Diag(Best->Function->getLocation(),
11636                      diag::note_not_found_by_two_phase_lookup)
11637           << R.getLookupName() << 0;
11638       } else if (SuggestedNamespaces.size() == 1) {
11639         SemaRef.Diag(Best->Function->getLocation(),
11640                      diag::note_not_found_by_two_phase_lookup)
11641           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11642       } else {
11643         // FIXME: It would be useful to list the associated namespaces here,
11644         // but the diagnostics infrastructure doesn't provide a way to produce
11645         // a localized representation of a list of items.
11646         SemaRef.Diag(Best->Function->getLocation(),
11647                      diag::note_not_found_by_two_phase_lookup)
11648           << R.getLookupName() << 2;
11649       }
11650 
11651       // Try to recover by calling this function.
11652       return true;
11653     }
11654 
11655     R.clear();
11656   }
11657 
11658   return false;
11659 }
11660 
11661 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11662 /// template, where the non-dependent operator was declared after the template
11663 /// was defined.
11664 ///
11665 /// Returns true if a viable candidate was found and a diagnostic was issued.
11666 static bool
11667 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11668                                SourceLocation OpLoc,
11669                                ArrayRef<Expr *> Args) {
11670   DeclarationName OpName =
11671     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11672   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11673   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11674                                 OverloadCandidateSet::CSK_Operator,
11675                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11676 }
11677 
11678 namespace {
11679 class BuildRecoveryCallExprRAII {
11680   Sema &SemaRef;
11681 public:
11682   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11683     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11684     SemaRef.IsBuildingRecoveryCallExpr = true;
11685   }
11686 
11687   ~BuildRecoveryCallExprRAII() {
11688     SemaRef.IsBuildingRecoveryCallExpr = false;
11689   }
11690 };
11691 
11692 }
11693 
11694 static std::unique_ptr<CorrectionCandidateCallback>
11695 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11696               bool HasTemplateArgs, bool AllowTypoCorrection) {
11697   if (!AllowTypoCorrection)
11698     return llvm::make_unique<NoTypoCorrectionCCC>();
11699   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11700                                                   HasTemplateArgs, ME);
11701 }
11702 
11703 /// Attempts to recover from a call where no functions were found.
11704 ///
11705 /// Returns true if new candidates were found.
11706 static ExprResult
11707 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11708                       UnresolvedLookupExpr *ULE,
11709                       SourceLocation LParenLoc,
11710                       MutableArrayRef<Expr *> Args,
11711                       SourceLocation RParenLoc,
11712                       bool EmptyLookup, bool AllowTypoCorrection) {
11713   // Do not try to recover if it is already building a recovery call.
11714   // This stops infinite loops for template instantiations like
11715   //
11716   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11717   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11718   //
11719   if (SemaRef.IsBuildingRecoveryCallExpr)
11720     return ExprError();
11721   BuildRecoveryCallExprRAII RCE(SemaRef);
11722 
11723   CXXScopeSpec SS;
11724   SS.Adopt(ULE->getQualifierLoc());
11725   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11726 
11727   TemplateArgumentListInfo TABuffer;
11728   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11729   if (ULE->hasExplicitTemplateArgs()) {
11730     ULE->copyTemplateArgumentsInto(TABuffer);
11731     ExplicitTemplateArgs = &TABuffer;
11732   }
11733 
11734   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11735                  Sema::LookupOrdinaryName);
11736   bool DoDiagnoseEmptyLookup = EmptyLookup;
11737   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11738                               OverloadCandidateSet::CSK_Normal,
11739                               ExplicitTemplateArgs, Args,
11740                               &DoDiagnoseEmptyLookup) &&
11741     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11742         S, SS, R,
11743         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11744                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11745         ExplicitTemplateArgs, Args)))
11746     return ExprError();
11747 
11748   assert(!R.empty() && "lookup results empty despite recovery");
11749 
11750   // If recovery created an ambiguity, just bail out.
11751   if (R.isAmbiguous()) {
11752     R.suppressDiagnostics();
11753     return ExprError();
11754   }
11755 
11756   // Build an implicit member call if appropriate.  Just drop the
11757   // casts and such from the call, we don't really care.
11758   ExprResult NewFn = ExprError();
11759   if ((*R.begin())->isCXXClassMember())
11760     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11761                                                     ExplicitTemplateArgs, S);
11762   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11763     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11764                                         ExplicitTemplateArgs);
11765   else
11766     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11767 
11768   if (NewFn.isInvalid())
11769     return ExprError();
11770 
11771   // This shouldn't cause an infinite loop because we're giving it
11772   // an expression with viable lookup results, which should never
11773   // end up here.
11774   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11775                                MultiExprArg(Args.data(), Args.size()),
11776                                RParenLoc);
11777 }
11778 
11779 /// \brief Constructs and populates an OverloadedCandidateSet from
11780 /// the given function.
11781 /// \returns true when an the ExprResult output parameter has been set.
11782 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11783                                   UnresolvedLookupExpr *ULE,
11784                                   MultiExprArg Args,
11785                                   SourceLocation RParenLoc,
11786                                   OverloadCandidateSet *CandidateSet,
11787                                   ExprResult *Result) {
11788 #ifndef NDEBUG
11789   if (ULE->requiresADL()) {
11790     // To do ADL, we must have found an unqualified name.
11791     assert(!ULE->getQualifier() && "qualified name with ADL");
11792 
11793     // We don't perform ADL for implicit declarations of builtins.
11794     // Verify that this was correctly set up.
11795     FunctionDecl *F;
11796     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11797         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11798         F->getBuiltinID() && F->isImplicit())
11799       llvm_unreachable("performing ADL for builtin");
11800 
11801     // We don't perform ADL in C.
11802     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11803   }
11804 #endif
11805 
11806   UnbridgedCastsSet UnbridgedCasts;
11807   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11808     *Result = ExprError();
11809     return true;
11810   }
11811 
11812   // Add the functions denoted by the callee to the set of candidate
11813   // functions, including those from argument-dependent lookup.
11814   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11815 
11816   if (getLangOpts().MSVCCompat &&
11817       CurContext->isDependentContext() && !isSFINAEContext() &&
11818       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11819 
11820     OverloadCandidateSet::iterator Best;
11821     if (CandidateSet->empty() ||
11822         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11823             OR_No_Viable_Function) {
11824       // In Microsoft mode, if we are inside a template class member function then
11825       // create a type dependent CallExpr. The goal is to postpone name lookup
11826       // to instantiation time to be able to search into type dependent base
11827       // classes.
11828       CallExpr *CE = new (Context) CallExpr(
11829           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11830       CE->setTypeDependent(true);
11831       CE->setValueDependent(true);
11832       CE->setInstantiationDependent(true);
11833       *Result = CE;
11834       return true;
11835     }
11836   }
11837 
11838   if (CandidateSet->empty())
11839     return false;
11840 
11841   UnbridgedCasts.restore();
11842   return false;
11843 }
11844 
11845 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11846 /// the completed call expression. If overload resolution fails, emits
11847 /// diagnostics and returns ExprError()
11848 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11849                                            UnresolvedLookupExpr *ULE,
11850                                            SourceLocation LParenLoc,
11851                                            MultiExprArg Args,
11852                                            SourceLocation RParenLoc,
11853                                            Expr *ExecConfig,
11854                                            OverloadCandidateSet *CandidateSet,
11855                                            OverloadCandidateSet::iterator *Best,
11856                                            OverloadingResult OverloadResult,
11857                                            bool AllowTypoCorrection) {
11858   if (CandidateSet->empty())
11859     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11860                                  RParenLoc, /*EmptyLookup=*/true,
11861                                  AllowTypoCorrection);
11862 
11863   switch (OverloadResult) {
11864   case OR_Success: {
11865     FunctionDecl *FDecl = (*Best)->Function;
11866     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11867     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11868       return ExprError();
11869     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11870     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11871                                          ExecConfig);
11872   }
11873 
11874   case OR_No_Viable_Function: {
11875     // Try to recover by looking for viable functions which the user might
11876     // have meant to call.
11877     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11878                                                 Args, RParenLoc,
11879                                                 /*EmptyLookup=*/false,
11880                                                 AllowTypoCorrection);
11881     if (!Recovery.isInvalid())
11882       return Recovery;
11883 
11884     // If the user passes in a function that we can't take the address of, we
11885     // generally end up emitting really bad error messages. Here, we attempt to
11886     // emit better ones.
11887     for (const Expr *Arg : Args) {
11888       if (!Arg->getType()->isFunctionType())
11889         continue;
11890       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11891         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11892         if (FD &&
11893             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11894                                                        Arg->getExprLoc()))
11895           return ExprError();
11896       }
11897     }
11898 
11899     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11900         << ULE->getName() << Fn->getSourceRange();
11901     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11902     break;
11903   }
11904 
11905   case OR_Ambiguous:
11906     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11907       << ULE->getName() << Fn->getSourceRange();
11908     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11909     break;
11910 
11911   case OR_Deleted: {
11912     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11913       << (*Best)->Function->isDeleted()
11914       << ULE->getName()
11915       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11916       << Fn->getSourceRange();
11917     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11918 
11919     // We emitted an error for the unvailable/deleted function call but keep
11920     // the call in the AST.
11921     FunctionDecl *FDecl = (*Best)->Function;
11922     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11923     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11924                                          ExecConfig);
11925   }
11926   }
11927 
11928   // Overload resolution failed.
11929   return ExprError();
11930 }
11931 
11932 static void markUnaddressableCandidatesUnviable(Sema &S,
11933                                                 OverloadCandidateSet &CS) {
11934   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11935     if (I->Viable &&
11936         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11937       I->Viable = false;
11938       I->FailureKind = ovl_fail_addr_not_available;
11939     }
11940   }
11941 }
11942 
11943 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11944 /// (which eventually refers to the declaration Func) and the call
11945 /// arguments Args/NumArgs, attempt to resolve the function call down
11946 /// to a specific function. If overload resolution succeeds, returns
11947 /// the call expression produced by overload resolution.
11948 /// Otherwise, emits diagnostics and returns ExprError.
11949 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11950                                          UnresolvedLookupExpr *ULE,
11951                                          SourceLocation LParenLoc,
11952                                          MultiExprArg Args,
11953                                          SourceLocation RParenLoc,
11954                                          Expr *ExecConfig,
11955                                          bool AllowTypoCorrection,
11956                                          bool CalleesAddressIsTaken) {
11957   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11958                                     OverloadCandidateSet::CSK_Normal);
11959   ExprResult result;
11960 
11961   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11962                              &result))
11963     return result;
11964 
11965   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11966   // functions that aren't addressible are considered unviable.
11967   if (CalleesAddressIsTaken)
11968     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11969 
11970   OverloadCandidateSet::iterator Best;
11971   OverloadingResult OverloadResult =
11972       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11973 
11974   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11975                                   RParenLoc, ExecConfig, &CandidateSet,
11976                                   &Best, OverloadResult,
11977                                   AllowTypoCorrection);
11978 }
11979 
11980 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11981   return Functions.size() > 1 ||
11982     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11983 }
11984 
11985 /// \brief Create a unary operation that may resolve to an overloaded
11986 /// operator.
11987 ///
11988 /// \param OpLoc The location of the operator itself (e.g., '*').
11989 ///
11990 /// \param Opc The UnaryOperatorKind that describes this operator.
11991 ///
11992 /// \param Fns The set of non-member functions that will be
11993 /// considered by overload resolution. The caller needs to build this
11994 /// set based on the context using, e.g.,
11995 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11996 /// set should not contain any member functions; those will be added
11997 /// by CreateOverloadedUnaryOp().
11998 ///
11999 /// \param Input The input argument.
12000 ExprResult
12001 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12002                               const UnresolvedSetImpl &Fns,
12003                               Expr *Input) {
12004   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12005   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12006   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12007   // TODO: provide better source location info.
12008   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12009 
12010   if (checkPlaceholderForOverload(*this, Input))
12011     return ExprError();
12012 
12013   Expr *Args[2] = { Input, nullptr };
12014   unsigned NumArgs = 1;
12015 
12016   // For post-increment and post-decrement, add the implicit '0' as
12017   // the second argument, so that we know this is a post-increment or
12018   // post-decrement.
12019   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12020     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12021     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12022                                      SourceLocation());
12023     NumArgs = 2;
12024   }
12025 
12026   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12027 
12028   if (Input->isTypeDependent()) {
12029     if (Fns.empty())
12030       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12031                                          VK_RValue, OK_Ordinary, OpLoc);
12032 
12033     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12034     UnresolvedLookupExpr *Fn
12035       = UnresolvedLookupExpr::Create(Context, NamingClass,
12036                                      NestedNameSpecifierLoc(), OpNameInfo,
12037                                      /*ADL*/ true, IsOverloaded(Fns),
12038                                      Fns.begin(), Fns.end());
12039     return new (Context)
12040         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12041                             VK_RValue, OpLoc, false);
12042   }
12043 
12044   // Build an empty overload set.
12045   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12046 
12047   // Add the candidates from the given function set.
12048   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12049 
12050   // Add operator candidates that are member functions.
12051   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12052 
12053   // Add candidates from ADL.
12054   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12055                                        /*ExplicitTemplateArgs*/nullptr,
12056                                        CandidateSet);
12057 
12058   // Add builtin operator candidates.
12059   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12060 
12061   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12062 
12063   // Perform overload resolution.
12064   OverloadCandidateSet::iterator Best;
12065   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12066   case OR_Success: {
12067     // We found a built-in operator or an overloaded operator.
12068     FunctionDecl *FnDecl = Best->Function;
12069 
12070     if (FnDecl) {
12071       // We matched an overloaded operator. Build a call to that
12072       // operator.
12073 
12074       // Convert the arguments.
12075       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12076         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12077 
12078         ExprResult InputRes =
12079           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12080                                               Best->FoundDecl, Method);
12081         if (InputRes.isInvalid())
12082           return ExprError();
12083         Input = InputRes.get();
12084       } else {
12085         // Convert the arguments.
12086         ExprResult InputInit
12087           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12088                                                       Context,
12089                                                       FnDecl->getParamDecl(0)),
12090                                       SourceLocation(),
12091                                       Input);
12092         if (InputInit.isInvalid())
12093           return ExprError();
12094         Input = InputInit.get();
12095       }
12096 
12097       // Build the actual expression node.
12098       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12099                                                 HadMultipleCandidates, OpLoc);
12100       if (FnExpr.isInvalid())
12101         return ExprError();
12102 
12103       // Determine the result type.
12104       QualType ResultTy = FnDecl->getReturnType();
12105       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12106       ResultTy = ResultTy.getNonLValueExprType(Context);
12107 
12108       Args[0] = Input;
12109       CallExpr *TheCall =
12110         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12111                                           ResultTy, VK, OpLoc, false);
12112 
12113       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12114         return ExprError();
12115 
12116       return MaybeBindToTemporary(TheCall);
12117     } else {
12118       // We matched a built-in operator. Convert the arguments, then
12119       // break out so that we will build the appropriate built-in
12120       // operator node.
12121       ExprResult InputRes =
12122         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12123                                   Best->Conversions[0], AA_Passing);
12124       if (InputRes.isInvalid())
12125         return ExprError();
12126       Input = InputRes.get();
12127       break;
12128     }
12129   }
12130 
12131   case OR_No_Viable_Function:
12132     // This is an erroneous use of an operator which can be overloaded by
12133     // a non-member function. Check for non-member operators which were
12134     // defined too late to be candidates.
12135     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12136       // FIXME: Recover by calling the found function.
12137       return ExprError();
12138 
12139     // No viable function; fall through to handling this as a
12140     // built-in operator, which will produce an error message for us.
12141     break;
12142 
12143   case OR_Ambiguous:
12144     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12145         << UnaryOperator::getOpcodeStr(Opc)
12146         << Input->getType()
12147         << Input->getSourceRange();
12148     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12149                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12150     return ExprError();
12151 
12152   case OR_Deleted:
12153     Diag(OpLoc, diag::err_ovl_deleted_oper)
12154       << Best->Function->isDeleted()
12155       << UnaryOperator::getOpcodeStr(Opc)
12156       << getDeletedOrUnavailableSuffix(Best->Function)
12157       << Input->getSourceRange();
12158     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12159                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12160     return ExprError();
12161   }
12162 
12163   // Either we found no viable overloaded operator or we matched a
12164   // built-in operator. In either case, fall through to trying to
12165   // build a built-in operation.
12166   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12167 }
12168 
12169 /// \brief Create a binary operation that may resolve to an overloaded
12170 /// operator.
12171 ///
12172 /// \param OpLoc The location of the operator itself (e.g., '+').
12173 ///
12174 /// \param Opc The BinaryOperatorKind that describes this operator.
12175 ///
12176 /// \param Fns The set of non-member functions that will be
12177 /// considered by overload resolution. The caller needs to build this
12178 /// set based on the context using, e.g.,
12179 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12180 /// set should not contain any member functions; those will be added
12181 /// by CreateOverloadedBinOp().
12182 ///
12183 /// \param LHS Left-hand argument.
12184 /// \param RHS Right-hand argument.
12185 ExprResult
12186 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12187                             BinaryOperatorKind Opc,
12188                             const UnresolvedSetImpl &Fns,
12189                             Expr *LHS, Expr *RHS) {
12190   Expr *Args[2] = { LHS, RHS };
12191   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12192 
12193   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12194   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12195 
12196   // If either side is type-dependent, create an appropriate dependent
12197   // expression.
12198   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12199     if (Fns.empty()) {
12200       // If there are no functions to store, just build a dependent
12201       // BinaryOperator or CompoundAssignment.
12202       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12203         return new (Context) BinaryOperator(
12204             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12205             OpLoc, FPFeatures.fp_contract);
12206 
12207       return new (Context) CompoundAssignOperator(
12208           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12209           Context.DependentTy, Context.DependentTy, OpLoc,
12210           FPFeatures.fp_contract);
12211     }
12212 
12213     // FIXME: save results of ADL from here?
12214     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12215     // TODO: provide better source location info in DNLoc component.
12216     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12217     UnresolvedLookupExpr *Fn
12218       = UnresolvedLookupExpr::Create(Context, NamingClass,
12219                                      NestedNameSpecifierLoc(), OpNameInfo,
12220                                      /*ADL*/ true, IsOverloaded(Fns),
12221                                      Fns.begin(), Fns.end());
12222     return new (Context)
12223         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12224                             VK_RValue, OpLoc, FPFeatures.fp_contract);
12225   }
12226 
12227   // Always do placeholder-like conversions on the RHS.
12228   if (checkPlaceholderForOverload(*this, Args[1]))
12229     return ExprError();
12230 
12231   // Do placeholder-like conversion on the LHS; note that we should
12232   // not get here with a PseudoObject LHS.
12233   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12234   if (checkPlaceholderForOverload(*this, Args[0]))
12235     return ExprError();
12236 
12237   // If this is the assignment operator, we only perform overload resolution
12238   // if the left-hand side is a class or enumeration type. This is actually
12239   // a hack. The standard requires that we do overload resolution between the
12240   // various built-in candidates, but as DR507 points out, this can lead to
12241   // problems. So we do it this way, which pretty much follows what GCC does.
12242   // Note that we go the traditional code path for compound assignment forms.
12243   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12244     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12245 
12246   // If this is the .* operator, which is not overloadable, just
12247   // create a built-in binary operator.
12248   if (Opc == BO_PtrMemD)
12249     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12250 
12251   // Build an empty overload set.
12252   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12253 
12254   // Add the candidates from the given function set.
12255   AddFunctionCandidates(Fns, Args, CandidateSet);
12256 
12257   // Add operator candidates that are member functions.
12258   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12259 
12260   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12261   // performed for an assignment operator (nor for operator[] nor operator->,
12262   // which don't get here).
12263   if (Opc != BO_Assign)
12264     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12265                                          /*ExplicitTemplateArgs*/ nullptr,
12266                                          CandidateSet);
12267 
12268   // Add builtin operator candidates.
12269   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12270 
12271   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12272 
12273   // Perform overload resolution.
12274   OverloadCandidateSet::iterator Best;
12275   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12276     case OR_Success: {
12277       // We found a built-in operator or an overloaded operator.
12278       FunctionDecl *FnDecl = Best->Function;
12279 
12280       if (FnDecl) {
12281         // We matched an overloaded operator. Build a call to that
12282         // operator.
12283 
12284         // Convert the arguments.
12285         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12286           // Best->Access is only meaningful for class members.
12287           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12288 
12289           ExprResult Arg1 =
12290             PerformCopyInitialization(
12291               InitializedEntity::InitializeParameter(Context,
12292                                                      FnDecl->getParamDecl(0)),
12293               SourceLocation(), Args[1]);
12294           if (Arg1.isInvalid())
12295             return ExprError();
12296 
12297           ExprResult Arg0 =
12298             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12299                                                 Best->FoundDecl, Method);
12300           if (Arg0.isInvalid())
12301             return ExprError();
12302           Args[0] = Arg0.getAs<Expr>();
12303           Args[1] = RHS = Arg1.getAs<Expr>();
12304         } else {
12305           // Convert the arguments.
12306           ExprResult Arg0 = PerformCopyInitialization(
12307             InitializedEntity::InitializeParameter(Context,
12308                                                    FnDecl->getParamDecl(0)),
12309             SourceLocation(), Args[0]);
12310           if (Arg0.isInvalid())
12311             return ExprError();
12312 
12313           ExprResult Arg1 =
12314             PerformCopyInitialization(
12315               InitializedEntity::InitializeParameter(Context,
12316                                                      FnDecl->getParamDecl(1)),
12317               SourceLocation(), Args[1]);
12318           if (Arg1.isInvalid())
12319             return ExprError();
12320           Args[0] = LHS = Arg0.getAs<Expr>();
12321           Args[1] = RHS = Arg1.getAs<Expr>();
12322         }
12323 
12324         // Build the actual expression node.
12325         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12326                                                   Best->FoundDecl,
12327                                                   HadMultipleCandidates, OpLoc);
12328         if (FnExpr.isInvalid())
12329           return ExprError();
12330 
12331         // Determine the result type.
12332         QualType ResultTy = FnDecl->getReturnType();
12333         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12334         ResultTy = ResultTy.getNonLValueExprType(Context);
12335 
12336         CXXOperatorCallExpr *TheCall =
12337           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12338                                             Args, ResultTy, VK, OpLoc,
12339                                             FPFeatures.fp_contract);
12340 
12341         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12342                                 FnDecl))
12343           return ExprError();
12344 
12345         ArrayRef<const Expr *> ArgsArray(Args, 2);
12346         // Cut off the implicit 'this'.
12347         if (isa<CXXMethodDecl>(FnDecl))
12348           ArgsArray = ArgsArray.slice(1);
12349 
12350         // Check for a self move.
12351         if (Op == OO_Equal)
12352           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12353 
12354         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
12355                   TheCall->getSourceRange(), VariadicDoesNotApply);
12356 
12357         return MaybeBindToTemporary(TheCall);
12358       } else {
12359         // We matched a built-in operator. Convert the arguments, then
12360         // break out so that we will build the appropriate built-in
12361         // operator node.
12362         ExprResult ArgsRes0 =
12363           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12364                                     Best->Conversions[0], AA_Passing);
12365         if (ArgsRes0.isInvalid())
12366           return ExprError();
12367         Args[0] = ArgsRes0.get();
12368 
12369         ExprResult ArgsRes1 =
12370           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12371                                     Best->Conversions[1], AA_Passing);
12372         if (ArgsRes1.isInvalid())
12373           return ExprError();
12374         Args[1] = ArgsRes1.get();
12375         break;
12376       }
12377     }
12378 
12379     case OR_No_Viable_Function: {
12380       // C++ [over.match.oper]p9:
12381       //   If the operator is the operator , [...] and there are no
12382       //   viable functions, then the operator is assumed to be the
12383       //   built-in operator and interpreted according to clause 5.
12384       if (Opc == BO_Comma)
12385         break;
12386 
12387       // For class as left operand for assignment or compound assigment
12388       // operator do not fall through to handling in built-in, but report that
12389       // no overloaded assignment operator found
12390       ExprResult Result = ExprError();
12391       if (Args[0]->getType()->isRecordType() &&
12392           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12393         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12394              << BinaryOperator::getOpcodeStr(Opc)
12395              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12396         if (Args[0]->getType()->isIncompleteType()) {
12397           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12398             << Args[0]->getType()
12399             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12400         }
12401       } else {
12402         // This is an erroneous use of an operator which can be overloaded by
12403         // a non-member function. Check for non-member operators which were
12404         // defined too late to be candidates.
12405         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12406           // FIXME: Recover by calling the found function.
12407           return ExprError();
12408 
12409         // No viable function; try to create a built-in operation, which will
12410         // produce an error. Then, show the non-viable candidates.
12411         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12412       }
12413       assert(Result.isInvalid() &&
12414              "C++ binary operator overloading is missing candidates!");
12415       if (Result.isInvalid())
12416         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12417                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12418       return Result;
12419     }
12420 
12421     case OR_Ambiguous:
12422       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12423           << BinaryOperator::getOpcodeStr(Opc)
12424           << Args[0]->getType() << Args[1]->getType()
12425           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12426       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12427                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12428       return ExprError();
12429 
12430     case OR_Deleted:
12431       if (isImplicitlyDeleted(Best->Function)) {
12432         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12433         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12434           << Context.getRecordType(Method->getParent())
12435           << getSpecialMember(Method);
12436 
12437         // The user probably meant to call this special member. Just
12438         // explain why it's deleted.
12439         NoteDeletedFunction(Method);
12440         return ExprError();
12441       } else {
12442         Diag(OpLoc, diag::err_ovl_deleted_oper)
12443           << Best->Function->isDeleted()
12444           << BinaryOperator::getOpcodeStr(Opc)
12445           << getDeletedOrUnavailableSuffix(Best->Function)
12446           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12447       }
12448       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12449                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12450       return ExprError();
12451   }
12452 
12453   // We matched a built-in operator; build it.
12454   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12455 }
12456 
12457 ExprResult
12458 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12459                                          SourceLocation RLoc,
12460                                          Expr *Base, Expr *Idx) {
12461   Expr *Args[2] = { Base, Idx };
12462   DeclarationName OpName =
12463       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12464 
12465   // If either side is type-dependent, create an appropriate dependent
12466   // expression.
12467   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12468 
12469     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12470     // CHECKME: no 'operator' keyword?
12471     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12472     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12473     UnresolvedLookupExpr *Fn
12474       = UnresolvedLookupExpr::Create(Context, NamingClass,
12475                                      NestedNameSpecifierLoc(), OpNameInfo,
12476                                      /*ADL*/ true, /*Overloaded*/ false,
12477                                      UnresolvedSetIterator(),
12478                                      UnresolvedSetIterator());
12479     // Can't add any actual overloads yet
12480 
12481     return new (Context)
12482         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12483                             Context.DependentTy, VK_RValue, RLoc, false);
12484   }
12485 
12486   // Handle placeholders on both operands.
12487   if (checkPlaceholderForOverload(*this, Args[0]))
12488     return ExprError();
12489   if (checkPlaceholderForOverload(*this, Args[1]))
12490     return ExprError();
12491 
12492   // Build an empty overload set.
12493   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12494 
12495   // Subscript can only be overloaded as a member function.
12496 
12497   // Add operator candidates that are member functions.
12498   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12499 
12500   // Add builtin operator candidates.
12501   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12502 
12503   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12504 
12505   // Perform overload resolution.
12506   OverloadCandidateSet::iterator Best;
12507   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12508     case OR_Success: {
12509       // We found a built-in operator or an overloaded operator.
12510       FunctionDecl *FnDecl = Best->Function;
12511 
12512       if (FnDecl) {
12513         // We matched an overloaded operator. Build a call to that
12514         // operator.
12515 
12516         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12517 
12518         // Convert the arguments.
12519         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12520         ExprResult Arg0 =
12521           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12522                                               Best->FoundDecl, Method);
12523         if (Arg0.isInvalid())
12524           return ExprError();
12525         Args[0] = Arg0.get();
12526 
12527         // Convert the arguments.
12528         ExprResult InputInit
12529           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12530                                                       Context,
12531                                                       FnDecl->getParamDecl(0)),
12532                                       SourceLocation(),
12533                                       Args[1]);
12534         if (InputInit.isInvalid())
12535           return ExprError();
12536 
12537         Args[1] = InputInit.getAs<Expr>();
12538 
12539         // Build the actual expression node.
12540         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12541         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12542         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12543                                                   Best->FoundDecl,
12544                                                   HadMultipleCandidates,
12545                                                   OpLocInfo.getLoc(),
12546                                                   OpLocInfo.getInfo());
12547         if (FnExpr.isInvalid())
12548           return ExprError();
12549 
12550         // Determine the result type
12551         QualType ResultTy = FnDecl->getReturnType();
12552         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12553         ResultTy = ResultTy.getNonLValueExprType(Context);
12554 
12555         CXXOperatorCallExpr *TheCall =
12556           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12557                                             FnExpr.get(), Args,
12558                                             ResultTy, VK, RLoc,
12559                                             false);
12560 
12561         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12562           return ExprError();
12563 
12564         return MaybeBindToTemporary(TheCall);
12565       } else {
12566         // We matched a built-in operator. Convert the arguments, then
12567         // break out so that we will build the appropriate built-in
12568         // operator node.
12569         ExprResult ArgsRes0 =
12570           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12571                                     Best->Conversions[0], AA_Passing);
12572         if (ArgsRes0.isInvalid())
12573           return ExprError();
12574         Args[0] = ArgsRes0.get();
12575 
12576         ExprResult ArgsRes1 =
12577           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12578                                     Best->Conversions[1], AA_Passing);
12579         if (ArgsRes1.isInvalid())
12580           return ExprError();
12581         Args[1] = ArgsRes1.get();
12582 
12583         break;
12584       }
12585     }
12586 
12587     case OR_No_Viable_Function: {
12588       if (CandidateSet.empty())
12589         Diag(LLoc, diag::err_ovl_no_oper)
12590           << Args[0]->getType() << /*subscript*/ 0
12591           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12592       else
12593         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12594           << Args[0]->getType()
12595           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12596       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12597                                   "[]", LLoc);
12598       return ExprError();
12599     }
12600 
12601     case OR_Ambiguous:
12602       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12603           << "[]"
12604           << Args[0]->getType() << Args[1]->getType()
12605           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12606       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12607                                   "[]", LLoc);
12608       return ExprError();
12609 
12610     case OR_Deleted:
12611       Diag(LLoc, diag::err_ovl_deleted_oper)
12612         << Best->Function->isDeleted() << "[]"
12613         << getDeletedOrUnavailableSuffix(Best->Function)
12614         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12615       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12616                                   "[]", LLoc);
12617       return ExprError();
12618     }
12619 
12620   // We matched a built-in operator; build it.
12621   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12622 }
12623 
12624 /// BuildCallToMemberFunction - Build a call to a member
12625 /// function. MemExpr is the expression that refers to the member
12626 /// function (and includes the object parameter), Args/NumArgs are the
12627 /// arguments to the function call (not including the object
12628 /// parameter). The caller needs to validate that the member
12629 /// expression refers to a non-static member function or an overloaded
12630 /// member function.
12631 ExprResult
12632 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12633                                 SourceLocation LParenLoc,
12634                                 MultiExprArg Args,
12635                                 SourceLocation RParenLoc) {
12636   assert(MemExprE->getType() == Context.BoundMemberTy ||
12637          MemExprE->getType() == Context.OverloadTy);
12638 
12639   // Dig out the member expression. This holds both the object
12640   // argument and the member function we're referring to.
12641   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12642 
12643   // Determine whether this is a call to a pointer-to-member function.
12644   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12645     assert(op->getType() == Context.BoundMemberTy);
12646     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12647 
12648     QualType fnType =
12649       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12650 
12651     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12652     QualType resultType = proto->getCallResultType(Context);
12653     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12654 
12655     // Check that the object type isn't more qualified than the
12656     // member function we're calling.
12657     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12658 
12659     QualType objectType = op->getLHS()->getType();
12660     if (op->getOpcode() == BO_PtrMemI)
12661       objectType = objectType->castAs<PointerType>()->getPointeeType();
12662     Qualifiers objectQuals = objectType.getQualifiers();
12663 
12664     Qualifiers difference = objectQuals - funcQuals;
12665     difference.removeObjCGCAttr();
12666     difference.removeAddressSpace();
12667     if (difference) {
12668       std::string qualsString = difference.getAsString();
12669       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12670         << fnType.getUnqualifiedType()
12671         << qualsString
12672         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12673     }
12674 
12675     CXXMemberCallExpr *call
12676       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12677                                         resultType, valueKind, RParenLoc);
12678 
12679     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12680                             call, nullptr))
12681       return ExprError();
12682 
12683     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12684       return ExprError();
12685 
12686     if (CheckOtherCall(call, proto))
12687       return ExprError();
12688 
12689     return MaybeBindToTemporary(call);
12690   }
12691 
12692   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12693     return new (Context)
12694         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12695 
12696   UnbridgedCastsSet UnbridgedCasts;
12697   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12698     return ExprError();
12699 
12700   MemberExpr *MemExpr;
12701   CXXMethodDecl *Method = nullptr;
12702   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12703   NestedNameSpecifier *Qualifier = nullptr;
12704   if (isa<MemberExpr>(NakedMemExpr)) {
12705     MemExpr = cast<MemberExpr>(NakedMemExpr);
12706     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12707     FoundDecl = MemExpr->getFoundDecl();
12708     Qualifier = MemExpr->getQualifier();
12709     UnbridgedCasts.restore();
12710   } else {
12711     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12712     Qualifier = UnresExpr->getQualifier();
12713 
12714     QualType ObjectType = UnresExpr->getBaseType();
12715     Expr::Classification ObjectClassification
12716       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12717                             : UnresExpr->getBase()->Classify(Context);
12718 
12719     // Add overload candidates
12720     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12721                                       OverloadCandidateSet::CSK_Normal);
12722 
12723     // FIXME: avoid copy.
12724     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12725     if (UnresExpr->hasExplicitTemplateArgs()) {
12726       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12727       TemplateArgs = &TemplateArgsBuffer;
12728     }
12729 
12730     // Poor-programmer's Lazy<Expr *>; isImplicitAccess requires stripping
12731     // parens/casts, which would be nice to avoid potentially doing multiple
12732     // times.
12733     llvm::Optional<Expr *> UnresolvedBase;
12734     auto GetUnresolvedBase = [&] {
12735       if (!UnresolvedBase.hasValue())
12736         UnresolvedBase =
12737           UnresExpr->isImplicitAccess() ? nullptr : UnresExpr->getBase();
12738       return *UnresolvedBase;
12739     };
12740     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12741            E = UnresExpr->decls_end(); I != E; ++I) {
12742 
12743       NamedDecl *Func = *I;
12744       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12745       if (isa<UsingShadowDecl>(Func))
12746         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12747 
12748 
12749       // Microsoft supports direct constructor calls.
12750       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12751         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12752                              Args, CandidateSet);
12753       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12754         // If explicit template arguments were provided, we can't call a
12755         // non-template member function.
12756         if (TemplateArgs)
12757           continue;
12758 
12759         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12760                            ObjectClassification,
12761                            /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet,
12762                            /*SuppressUserConversions=*/false);
12763       } else {
12764         AddMethodTemplateCandidate(
12765             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12766             TemplateArgs, ObjectType, ObjectClassification,
12767             /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet,
12768             /*SuppressUsedConversions=*/false);
12769       }
12770     }
12771 
12772     DeclarationName DeclName = UnresExpr->getMemberName();
12773 
12774     UnbridgedCasts.restore();
12775 
12776     OverloadCandidateSet::iterator Best;
12777     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12778                                             Best)) {
12779     case OR_Success:
12780       Method = cast<CXXMethodDecl>(Best->Function);
12781       FoundDecl = Best->FoundDecl;
12782       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12783       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12784         return ExprError();
12785       // If FoundDecl is different from Method (such as if one is a template
12786       // and the other a specialization), make sure DiagnoseUseOfDecl is
12787       // called on both.
12788       // FIXME: This would be more comprehensively addressed by modifying
12789       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12790       // being used.
12791       if (Method != FoundDecl.getDecl() &&
12792                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12793         return ExprError();
12794       break;
12795 
12796     case OR_No_Viable_Function:
12797       Diag(UnresExpr->getMemberLoc(),
12798            diag::err_ovl_no_viable_member_function_in_call)
12799         << DeclName << MemExprE->getSourceRange();
12800       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12801       // FIXME: Leaking incoming expressions!
12802       return ExprError();
12803 
12804     case OR_Ambiguous:
12805       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12806         << DeclName << MemExprE->getSourceRange();
12807       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12808       // FIXME: Leaking incoming expressions!
12809       return ExprError();
12810 
12811     case OR_Deleted:
12812       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12813         << Best->Function->isDeleted()
12814         << DeclName
12815         << getDeletedOrUnavailableSuffix(Best->Function)
12816         << MemExprE->getSourceRange();
12817       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12818       // FIXME: Leaking incoming expressions!
12819       return ExprError();
12820     }
12821 
12822     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12823 
12824     // If overload resolution picked a static member, build a
12825     // non-member call based on that function.
12826     if (Method->isStatic()) {
12827       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12828                                    RParenLoc);
12829     }
12830 
12831     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12832   }
12833 
12834   QualType ResultType = Method->getReturnType();
12835   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12836   ResultType = ResultType.getNonLValueExprType(Context);
12837 
12838   assert(Method && "Member call to something that isn't a method?");
12839   CXXMemberCallExpr *TheCall =
12840     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12841                                     ResultType, VK, RParenLoc);
12842 
12843   // Check for a valid return type.
12844   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12845                           TheCall, Method))
12846     return ExprError();
12847 
12848   // Convert the object argument (for a non-static member function call).
12849   // We only need to do this if there was actually an overload; otherwise
12850   // it was done at lookup.
12851   if (!Method->isStatic()) {
12852     ExprResult ObjectArg =
12853       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12854                                           FoundDecl, Method);
12855     if (ObjectArg.isInvalid())
12856       return ExprError();
12857     MemExpr->setBase(ObjectArg.get());
12858   }
12859 
12860   // Convert the rest of the arguments
12861   const FunctionProtoType *Proto =
12862     Method->getType()->getAs<FunctionProtoType>();
12863   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12864                               RParenLoc))
12865     return ExprError();
12866 
12867   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12868 
12869   if (CheckFunctionCall(Method, TheCall, Proto))
12870     return ExprError();
12871 
12872   // In the case the method to call was not selected by the overloading
12873   // resolution process, we still need to handle the enable_if attribute. Do
12874   // that here, so it will not hide previous -- and more relevant -- errors.
12875   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12876     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12877       Diag(MemE->getMemberLoc(),
12878            diag::err_ovl_no_viable_member_function_in_call)
12879           << Method << Method->getSourceRange();
12880       Diag(Method->getLocation(),
12881            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12882           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12883       return ExprError();
12884     }
12885 
12886     SmallVector<DiagnoseIfAttr *, 4> Nonfatal;
12887     if (const DiagnoseIfAttr *Attr = checkArgDependentDiagnoseIf(
12888             Method, Args, Nonfatal, false, MemE->getBase())) {
12889       emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr);
12890       return ExprError();
12891     }
12892 
12893     for (const auto *Attr : Nonfatal)
12894       emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr);
12895   }
12896 
12897   if ((isa<CXXConstructorDecl>(CurContext) ||
12898        isa<CXXDestructorDecl>(CurContext)) &&
12899       TheCall->getMethodDecl()->isPure()) {
12900     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12901 
12902     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12903         MemExpr->performsVirtualDispatch(getLangOpts())) {
12904       Diag(MemExpr->getLocStart(),
12905            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12906         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12907         << MD->getParent()->getDeclName();
12908 
12909       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12910       if (getLangOpts().AppleKext)
12911         Diag(MemExpr->getLocStart(),
12912              diag::note_pure_qualified_call_kext)
12913              << MD->getParent()->getDeclName()
12914              << MD->getDeclName();
12915     }
12916   }
12917 
12918   if (CXXDestructorDecl *DD =
12919           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12920     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12921     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12922     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12923                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12924                          MemExpr->getMemberLoc());
12925   }
12926 
12927   return MaybeBindToTemporary(TheCall);
12928 }
12929 
12930 /// BuildCallToObjectOfClassType - Build a call to an object of class
12931 /// type (C++ [over.call.object]), which can end up invoking an
12932 /// overloaded function call operator (@c operator()) or performing a
12933 /// user-defined conversion on the object argument.
12934 ExprResult
12935 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12936                                    SourceLocation LParenLoc,
12937                                    MultiExprArg Args,
12938                                    SourceLocation RParenLoc) {
12939   if (checkPlaceholderForOverload(*this, Obj))
12940     return ExprError();
12941   ExprResult Object = Obj;
12942 
12943   UnbridgedCastsSet UnbridgedCasts;
12944   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12945     return ExprError();
12946 
12947   assert(Object.get()->getType()->isRecordType() &&
12948          "Requires object type argument");
12949   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12950 
12951   // C++ [over.call.object]p1:
12952   //  If the primary-expression E in the function call syntax
12953   //  evaluates to a class object of type "cv T", then the set of
12954   //  candidate functions includes at least the function call
12955   //  operators of T. The function call operators of T are obtained by
12956   //  ordinary lookup of the name operator() in the context of
12957   //  (E).operator().
12958   OverloadCandidateSet CandidateSet(LParenLoc,
12959                                     OverloadCandidateSet::CSK_Operator);
12960   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12961 
12962   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12963                           diag::err_incomplete_object_call, Object.get()))
12964     return true;
12965 
12966   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12967   LookupQualifiedName(R, Record->getDecl());
12968   R.suppressDiagnostics();
12969 
12970   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12971        Oper != OperEnd; ++Oper) {
12972     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12973                        Object.get()->Classify(Context),
12974                        Object.get(), Args, CandidateSet,
12975                        /*SuppressUserConversions=*/ false);
12976   }
12977 
12978   // C++ [over.call.object]p2:
12979   //   In addition, for each (non-explicit in C++0x) conversion function
12980   //   declared in T of the form
12981   //
12982   //        operator conversion-type-id () cv-qualifier;
12983   //
12984   //   where cv-qualifier is the same cv-qualification as, or a
12985   //   greater cv-qualification than, cv, and where conversion-type-id
12986   //   denotes the type "pointer to function of (P1,...,Pn) returning
12987   //   R", or the type "reference to pointer to function of
12988   //   (P1,...,Pn) returning R", or the type "reference to function
12989   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12990   //   is also considered as a candidate function. Similarly,
12991   //   surrogate call functions are added to the set of candidate
12992   //   functions for each conversion function declared in an
12993   //   accessible base class provided the function is not hidden
12994   //   within T by another intervening declaration.
12995   const auto &Conversions =
12996       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12997   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12998     NamedDecl *D = *I;
12999     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13000     if (isa<UsingShadowDecl>(D))
13001       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13002 
13003     // Skip over templated conversion functions; they aren't
13004     // surrogates.
13005     if (isa<FunctionTemplateDecl>(D))
13006       continue;
13007 
13008     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13009     if (!Conv->isExplicit()) {
13010       // Strip the reference type (if any) and then the pointer type (if
13011       // any) to get down to what might be a function type.
13012       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13013       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13014         ConvType = ConvPtrType->getPointeeType();
13015 
13016       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13017       {
13018         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13019                               Object.get(), Args, CandidateSet);
13020       }
13021     }
13022   }
13023 
13024   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13025 
13026   // Perform overload resolution.
13027   OverloadCandidateSet::iterator Best;
13028   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13029                              Best)) {
13030   case OR_Success:
13031     // Overload resolution succeeded; we'll build the appropriate call
13032     // below.
13033     break;
13034 
13035   case OR_No_Viable_Function:
13036     if (CandidateSet.empty())
13037       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13038         << Object.get()->getType() << /*call*/ 1
13039         << Object.get()->getSourceRange();
13040     else
13041       Diag(Object.get()->getLocStart(),
13042            diag::err_ovl_no_viable_object_call)
13043         << Object.get()->getType() << Object.get()->getSourceRange();
13044     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13045     break;
13046 
13047   case OR_Ambiguous:
13048     Diag(Object.get()->getLocStart(),
13049          diag::err_ovl_ambiguous_object_call)
13050       << Object.get()->getType() << Object.get()->getSourceRange();
13051     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13052     break;
13053 
13054   case OR_Deleted:
13055     Diag(Object.get()->getLocStart(),
13056          diag::err_ovl_deleted_object_call)
13057       << Best->Function->isDeleted()
13058       << Object.get()->getType()
13059       << getDeletedOrUnavailableSuffix(Best->Function)
13060       << Object.get()->getSourceRange();
13061     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13062     break;
13063   }
13064 
13065   if (Best == CandidateSet.end())
13066     return true;
13067 
13068   UnbridgedCasts.restore();
13069 
13070   if (Best->Function == nullptr) {
13071     // Since there is no function declaration, this is one of the
13072     // surrogate candidates. Dig out the conversion function.
13073     CXXConversionDecl *Conv
13074       = cast<CXXConversionDecl>(
13075                          Best->Conversions[0].UserDefined.ConversionFunction);
13076 
13077     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13078                               Best->FoundDecl);
13079     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13080       return ExprError();
13081     assert(Conv == Best->FoundDecl.getDecl() &&
13082              "Found Decl & conversion-to-functionptr should be same, right?!");
13083     // We selected one of the surrogate functions that converts the
13084     // object parameter to a function pointer. Perform the conversion
13085     // on the object argument, then let ActOnCallExpr finish the job.
13086 
13087     // Create an implicit member expr to refer to the conversion operator.
13088     // and then call it.
13089     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13090                                              Conv, HadMultipleCandidates);
13091     if (Call.isInvalid())
13092       return ExprError();
13093     // Record usage of conversion in an implicit cast.
13094     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13095                                     CK_UserDefinedConversion, Call.get(),
13096                                     nullptr, VK_RValue);
13097 
13098     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13099   }
13100 
13101   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13102 
13103   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13104   // that calls this method, using Object for the implicit object
13105   // parameter and passing along the remaining arguments.
13106   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13107 
13108   // An error diagnostic has already been printed when parsing the declaration.
13109   if (Method->isInvalidDecl())
13110     return ExprError();
13111 
13112   const FunctionProtoType *Proto =
13113     Method->getType()->getAs<FunctionProtoType>();
13114 
13115   unsigned NumParams = Proto->getNumParams();
13116 
13117   DeclarationNameInfo OpLocInfo(
13118                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13119   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13120   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13121                                            HadMultipleCandidates,
13122                                            OpLocInfo.getLoc(),
13123                                            OpLocInfo.getInfo());
13124   if (NewFn.isInvalid())
13125     return true;
13126 
13127   // Build the full argument list for the method call (the implicit object
13128   // parameter is placed at the beginning of the list).
13129   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13130   MethodArgs[0] = Object.get();
13131   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13132 
13133   // Once we've built TheCall, all of the expressions are properly
13134   // owned.
13135   QualType ResultTy = Method->getReturnType();
13136   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13137   ResultTy = ResultTy.getNonLValueExprType(Context);
13138 
13139   CXXOperatorCallExpr *TheCall = new (Context)
13140       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13141                           VK, RParenLoc, false);
13142 
13143   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13144     return true;
13145 
13146   // We may have default arguments. If so, we need to allocate more
13147   // slots in the call for them.
13148   if (Args.size() < NumParams)
13149     TheCall->setNumArgs(Context, NumParams + 1);
13150 
13151   bool IsError = false;
13152 
13153   // Initialize the implicit object parameter.
13154   ExprResult ObjRes =
13155     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13156                                         Best->FoundDecl, Method);
13157   if (ObjRes.isInvalid())
13158     IsError = true;
13159   else
13160     Object = ObjRes;
13161   TheCall->setArg(0, Object.get());
13162 
13163   // Check the argument types.
13164   for (unsigned i = 0; i != NumParams; i++) {
13165     Expr *Arg;
13166     if (i < Args.size()) {
13167       Arg = Args[i];
13168 
13169       // Pass the argument.
13170 
13171       ExprResult InputInit
13172         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13173                                                     Context,
13174                                                     Method->getParamDecl(i)),
13175                                     SourceLocation(), Arg);
13176 
13177       IsError |= InputInit.isInvalid();
13178       Arg = InputInit.getAs<Expr>();
13179     } else {
13180       ExprResult DefArg
13181         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13182       if (DefArg.isInvalid()) {
13183         IsError = true;
13184         break;
13185       }
13186 
13187       Arg = DefArg.getAs<Expr>();
13188     }
13189 
13190     TheCall->setArg(i + 1, Arg);
13191   }
13192 
13193   // If this is a variadic call, handle args passed through "...".
13194   if (Proto->isVariadic()) {
13195     // Promote the arguments (C99 6.5.2.2p7).
13196     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13197       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13198                                                         nullptr);
13199       IsError |= Arg.isInvalid();
13200       TheCall->setArg(i + 1, Arg.get());
13201     }
13202   }
13203 
13204   if (IsError) return true;
13205 
13206   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13207 
13208   if (CheckFunctionCall(Method, TheCall, Proto))
13209     return true;
13210 
13211   return MaybeBindToTemporary(TheCall);
13212 }
13213 
13214 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13215 ///  (if one exists), where @c Base is an expression of class type and
13216 /// @c Member is the name of the member we're trying to find.
13217 ExprResult
13218 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13219                                bool *NoArrowOperatorFound) {
13220   assert(Base->getType()->isRecordType() &&
13221          "left-hand side must have class type");
13222 
13223   if (checkPlaceholderForOverload(*this, Base))
13224     return ExprError();
13225 
13226   SourceLocation Loc = Base->getExprLoc();
13227 
13228   // C++ [over.ref]p1:
13229   //
13230   //   [...] An expression x->m is interpreted as (x.operator->())->m
13231   //   for a class object x of type T if T::operator->() exists and if
13232   //   the operator is selected as the best match function by the
13233   //   overload resolution mechanism (13.3).
13234   DeclarationName OpName =
13235     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13236   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13237   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13238 
13239   if (RequireCompleteType(Loc, Base->getType(),
13240                           diag::err_typecheck_incomplete_tag, Base))
13241     return ExprError();
13242 
13243   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13244   LookupQualifiedName(R, BaseRecord->getDecl());
13245   R.suppressDiagnostics();
13246 
13247   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13248        Oper != OperEnd; ++Oper) {
13249     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13250                        Base, None, CandidateSet,
13251                        /*SuppressUserConversions=*/false);
13252   }
13253 
13254   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13255 
13256   // Perform overload resolution.
13257   OverloadCandidateSet::iterator Best;
13258   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13259   case OR_Success:
13260     // Overload resolution succeeded; we'll build the call below.
13261     break;
13262 
13263   case OR_No_Viable_Function:
13264     if (CandidateSet.empty()) {
13265       QualType BaseType = Base->getType();
13266       if (NoArrowOperatorFound) {
13267         // Report this specific error to the caller instead of emitting a
13268         // diagnostic, as requested.
13269         *NoArrowOperatorFound = true;
13270         return ExprError();
13271       }
13272       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13273         << BaseType << Base->getSourceRange();
13274       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13275         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13276           << FixItHint::CreateReplacement(OpLoc, ".");
13277       }
13278     } else
13279       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13280         << "operator->" << Base->getSourceRange();
13281     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13282     return ExprError();
13283 
13284   case OR_Ambiguous:
13285     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13286       << "->" << Base->getType() << Base->getSourceRange();
13287     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13288     return ExprError();
13289 
13290   case OR_Deleted:
13291     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13292       << Best->Function->isDeleted()
13293       << "->"
13294       << getDeletedOrUnavailableSuffix(Best->Function)
13295       << Base->getSourceRange();
13296     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13297     return ExprError();
13298   }
13299 
13300   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13301 
13302   // Convert the object parameter.
13303   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13304   ExprResult BaseResult =
13305     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13306                                         Best->FoundDecl, Method);
13307   if (BaseResult.isInvalid())
13308     return ExprError();
13309   Base = BaseResult.get();
13310 
13311   // Build the operator call.
13312   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13313                                             HadMultipleCandidates, OpLoc);
13314   if (FnExpr.isInvalid())
13315     return ExprError();
13316 
13317   QualType ResultTy = Method->getReturnType();
13318   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13319   ResultTy = ResultTy.getNonLValueExprType(Context);
13320   CXXOperatorCallExpr *TheCall =
13321     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13322                                       Base, ResultTy, VK, OpLoc, false);
13323 
13324   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13325           return ExprError();
13326 
13327   return MaybeBindToTemporary(TheCall);
13328 }
13329 
13330 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13331 /// a literal operator described by the provided lookup results.
13332 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13333                                           DeclarationNameInfo &SuffixInfo,
13334                                           ArrayRef<Expr*> Args,
13335                                           SourceLocation LitEndLoc,
13336                                        TemplateArgumentListInfo *TemplateArgs) {
13337   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13338 
13339   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13340                                     OverloadCandidateSet::CSK_Normal);
13341   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13342                         /*SuppressUserConversions=*/true);
13343 
13344   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13345 
13346   // Perform overload resolution. This will usually be trivial, but might need
13347   // to perform substitutions for a literal operator template.
13348   OverloadCandidateSet::iterator Best;
13349   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13350   case OR_Success:
13351   case OR_Deleted:
13352     break;
13353 
13354   case OR_No_Viable_Function:
13355     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13356       << R.getLookupName();
13357     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13358     return ExprError();
13359 
13360   case OR_Ambiguous:
13361     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13362     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13363     return ExprError();
13364   }
13365 
13366   FunctionDecl *FD = Best->Function;
13367   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13368                                         HadMultipleCandidates,
13369                                         SuffixInfo.getLoc(),
13370                                         SuffixInfo.getInfo());
13371   if (Fn.isInvalid())
13372     return true;
13373 
13374   // Check the argument types. This should almost always be a no-op, except
13375   // that array-to-pointer decay is applied to string literals.
13376   Expr *ConvArgs[2];
13377   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13378     ExprResult InputInit = PerformCopyInitialization(
13379       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13380       SourceLocation(), Args[ArgIdx]);
13381     if (InputInit.isInvalid())
13382       return true;
13383     ConvArgs[ArgIdx] = InputInit.get();
13384   }
13385 
13386   QualType ResultTy = FD->getReturnType();
13387   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13388   ResultTy = ResultTy.getNonLValueExprType(Context);
13389 
13390   UserDefinedLiteral *UDL =
13391     new (Context) UserDefinedLiteral(Context, Fn.get(),
13392                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13393                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13394 
13395   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13396     return ExprError();
13397 
13398   if (CheckFunctionCall(FD, UDL, nullptr))
13399     return ExprError();
13400 
13401   return MaybeBindToTemporary(UDL);
13402 }
13403 
13404 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13405 /// given LookupResult is non-empty, it is assumed to describe a member which
13406 /// will be invoked. Otherwise, the function will be found via argument
13407 /// dependent lookup.
13408 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13409 /// otherwise CallExpr is set to ExprError() and some non-success value
13410 /// is returned.
13411 Sema::ForRangeStatus
13412 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13413                                 SourceLocation RangeLoc,
13414                                 const DeclarationNameInfo &NameInfo,
13415                                 LookupResult &MemberLookup,
13416                                 OverloadCandidateSet *CandidateSet,
13417                                 Expr *Range, ExprResult *CallExpr) {
13418   Scope *S = nullptr;
13419 
13420   CandidateSet->clear();
13421   if (!MemberLookup.empty()) {
13422     ExprResult MemberRef =
13423         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13424                                  /*IsPtr=*/false, CXXScopeSpec(),
13425                                  /*TemplateKWLoc=*/SourceLocation(),
13426                                  /*FirstQualifierInScope=*/nullptr,
13427                                  MemberLookup,
13428                                  /*TemplateArgs=*/nullptr, S);
13429     if (MemberRef.isInvalid()) {
13430       *CallExpr = ExprError();
13431       return FRS_DiagnosticIssued;
13432     }
13433     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13434     if (CallExpr->isInvalid()) {
13435       *CallExpr = ExprError();
13436       return FRS_DiagnosticIssued;
13437     }
13438   } else {
13439     UnresolvedSet<0> FoundNames;
13440     UnresolvedLookupExpr *Fn =
13441       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13442                                    NestedNameSpecifierLoc(), NameInfo,
13443                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13444                                    FoundNames.begin(), FoundNames.end());
13445 
13446     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13447                                                     CandidateSet, CallExpr);
13448     if (CandidateSet->empty() || CandidateSetError) {
13449       *CallExpr = ExprError();
13450       return FRS_NoViableFunction;
13451     }
13452     OverloadCandidateSet::iterator Best;
13453     OverloadingResult OverloadResult =
13454         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13455 
13456     if (OverloadResult == OR_No_Viable_Function) {
13457       *CallExpr = ExprError();
13458       return FRS_NoViableFunction;
13459     }
13460     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13461                                          Loc, nullptr, CandidateSet, &Best,
13462                                          OverloadResult,
13463                                          /*AllowTypoCorrection=*/false);
13464     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13465       *CallExpr = ExprError();
13466       return FRS_DiagnosticIssued;
13467     }
13468   }
13469   return FRS_Success;
13470 }
13471 
13472 
13473 /// FixOverloadedFunctionReference - E is an expression that refers to
13474 /// a C++ overloaded function (possibly with some parentheses and
13475 /// perhaps a '&' around it). We have resolved the overloaded function
13476 /// to the function declaration Fn, so patch up the expression E to
13477 /// refer (possibly indirectly) to Fn. Returns the new expr.
13478 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13479                                            FunctionDecl *Fn) {
13480   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13481     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13482                                                    Found, Fn);
13483     if (SubExpr == PE->getSubExpr())
13484       return PE;
13485 
13486     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13487   }
13488 
13489   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13490     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13491                                                    Found, Fn);
13492     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13493                                SubExpr->getType()) &&
13494            "Implicit cast type cannot be determined from overload");
13495     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13496     if (SubExpr == ICE->getSubExpr())
13497       return ICE;
13498 
13499     return ImplicitCastExpr::Create(Context, ICE->getType(),
13500                                     ICE->getCastKind(),
13501                                     SubExpr, nullptr,
13502                                     ICE->getValueKind());
13503   }
13504 
13505   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13506     if (!GSE->isResultDependent()) {
13507       Expr *SubExpr =
13508           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13509       if (SubExpr == GSE->getResultExpr())
13510         return GSE;
13511 
13512       // Replace the resulting type information before rebuilding the generic
13513       // selection expression.
13514       ArrayRef<Expr *> A = GSE->getAssocExprs();
13515       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13516       unsigned ResultIdx = GSE->getResultIndex();
13517       AssocExprs[ResultIdx] = SubExpr;
13518 
13519       return new (Context) GenericSelectionExpr(
13520           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13521           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13522           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13523           ResultIdx);
13524     }
13525     // Rather than fall through to the unreachable, return the original generic
13526     // selection expression.
13527     return GSE;
13528   }
13529 
13530   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13531     assert(UnOp->getOpcode() == UO_AddrOf &&
13532            "Can only take the address of an overloaded function");
13533     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13534       if (Method->isStatic()) {
13535         // Do nothing: static member functions aren't any different
13536         // from non-member functions.
13537       } else {
13538         // Fix the subexpression, which really has to be an
13539         // UnresolvedLookupExpr holding an overloaded member function
13540         // or template.
13541         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13542                                                        Found, Fn);
13543         if (SubExpr == UnOp->getSubExpr())
13544           return UnOp;
13545 
13546         assert(isa<DeclRefExpr>(SubExpr)
13547                && "fixed to something other than a decl ref");
13548         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13549                && "fixed to a member ref with no nested name qualifier");
13550 
13551         // We have taken the address of a pointer to member
13552         // function. Perform the computation here so that we get the
13553         // appropriate pointer to member type.
13554         QualType ClassType
13555           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13556         QualType MemPtrType
13557           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13558         // Under the MS ABI, lock down the inheritance model now.
13559         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13560           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13561 
13562         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13563                                            VK_RValue, OK_Ordinary,
13564                                            UnOp->getOperatorLoc());
13565       }
13566     }
13567     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13568                                                    Found, Fn);
13569     if (SubExpr == UnOp->getSubExpr())
13570       return UnOp;
13571 
13572     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13573                                      Context.getPointerType(SubExpr->getType()),
13574                                        VK_RValue, OK_Ordinary,
13575                                        UnOp->getOperatorLoc());
13576   }
13577 
13578   // C++ [except.spec]p17:
13579   //   An exception-specification is considered to be needed when:
13580   //   - in an expression the function is the unique lookup result or the
13581   //     selected member of a set of overloaded functions
13582   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13583     ResolveExceptionSpec(E->getExprLoc(), FPT);
13584 
13585   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13586     // FIXME: avoid copy.
13587     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13588     if (ULE->hasExplicitTemplateArgs()) {
13589       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13590       TemplateArgs = &TemplateArgsBuffer;
13591     }
13592 
13593     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13594                                            ULE->getQualifierLoc(),
13595                                            ULE->getTemplateKeywordLoc(),
13596                                            Fn,
13597                                            /*enclosing*/ false, // FIXME?
13598                                            ULE->getNameLoc(),
13599                                            Fn->getType(),
13600                                            VK_LValue,
13601                                            Found.getDecl(),
13602                                            TemplateArgs);
13603     MarkDeclRefReferenced(DRE);
13604     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13605     return DRE;
13606   }
13607 
13608   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13609     // FIXME: avoid copy.
13610     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13611     if (MemExpr->hasExplicitTemplateArgs()) {
13612       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13613       TemplateArgs = &TemplateArgsBuffer;
13614     }
13615 
13616     Expr *Base;
13617 
13618     // If we're filling in a static method where we used to have an
13619     // implicit member access, rewrite to a simple decl ref.
13620     if (MemExpr->isImplicitAccess()) {
13621       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13622         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13623                                                MemExpr->getQualifierLoc(),
13624                                                MemExpr->getTemplateKeywordLoc(),
13625                                                Fn,
13626                                                /*enclosing*/ false,
13627                                                MemExpr->getMemberLoc(),
13628                                                Fn->getType(),
13629                                                VK_LValue,
13630                                                Found.getDecl(),
13631                                                TemplateArgs);
13632         MarkDeclRefReferenced(DRE);
13633         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13634         return DRE;
13635       } else {
13636         SourceLocation Loc = MemExpr->getMemberLoc();
13637         if (MemExpr->getQualifier())
13638           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13639         CheckCXXThisCapture(Loc);
13640         Base = new (Context) CXXThisExpr(Loc,
13641                                          MemExpr->getBaseType(),
13642                                          /*isImplicit=*/true);
13643       }
13644     } else
13645       Base = MemExpr->getBase();
13646 
13647     ExprValueKind valueKind;
13648     QualType type;
13649     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13650       valueKind = VK_LValue;
13651       type = Fn->getType();
13652     } else {
13653       valueKind = VK_RValue;
13654       type = Context.BoundMemberTy;
13655     }
13656 
13657     MemberExpr *ME = MemberExpr::Create(
13658         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13659         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13660         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13661         OK_Ordinary);
13662     ME->setHadMultipleCandidates(true);
13663     MarkMemberReferenced(ME);
13664     return ME;
13665   }
13666 
13667   llvm_unreachable("Invalid reference to overloaded function");
13668 }
13669 
13670 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13671                                                 DeclAccessPair Found,
13672                                                 FunctionDecl *Fn) {
13673   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13674 }
13675