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                       const Expr *Base, 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, Base);
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_OCL_Scalar_Widening,
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       assert(Initializer && "Unknown conversion expression");
334 
335       // If it's value-dependent, we can't tell whether it's narrowing.
336       if (Initializer->isValueDependent())
337         return NK_Dependent_Narrowing;
338 
339       if (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   SlabAllocator.Reset();
843   NumInlineBytesUsed = 0;
844   Candidates.clear();
845   Functions.clear();
846 }
847 
848 namespace {
849   class UnbridgedCastsSet {
850     struct Entry {
851       Expr **Addr;
852       Expr *Saved;
853     };
854     SmallVector<Entry, 2> Entries;
855 
856   public:
857     void save(Sema &S, Expr *&E) {
858       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
859       Entry entry = { &E, E };
860       Entries.push_back(entry);
861       E = S.stripARCUnbridgedCast(E);
862     }
863 
864     void restore() {
865       for (SmallVectorImpl<Entry>::iterator
866              i = Entries.begin(), e = Entries.end(); i != e; ++i)
867         *i->Addr = i->Saved;
868     }
869   };
870 }
871 
872 /// checkPlaceholderForOverload - Do any interesting placeholder-like
873 /// preprocessing on the given expression.
874 ///
875 /// \param unbridgedCasts a collection to which to add unbridged casts;
876 ///   without this, they will be immediately diagnosed as errors
877 ///
878 /// Return true on unrecoverable error.
879 static bool
880 checkPlaceholderForOverload(Sema &S, Expr *&E,
881                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
882   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
883     // We can't handle overloaded expressions here because overload
884     // resolution might reasonably tweak them.
885     if (placeholder->getKind() == BuiltinType::Overload) return false;
886 
887     // If the context potentially accepts unbridged ARC casts, strip
888     // the unbridged cast and add it to the collection for later restoration.
889     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890         unbridgedCasts) {
891       unbridgedCasts->save(S, E);
892       return false;
893     }
894 
895     // Go ahead and check everything else.
896     ExprResult result = S.CheckPlaceholderExpr(E);
897     if (result.isInvalid())
898       return true;
899 
900     E = result.get();
901     return false;
902   }
903 
904   // Nothing to do.
905   return false;
906 }
907 
908 /// checkArgPlaceholdersForOverload - Check a set of call operands for
909 /// placeholders.
910 static bool checkArgPlaceholdersForOverload(Sema &S,
911                                             MultiExprArg Args,
912                                             UnbridgedCastsSet &unbridged) {
913   for (unsigned i = 0, e = Args.size(); i != e; ++i)
914     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
915       return true;
916 
917   return false;
918 }
919 
920 /// Determine whether the given New declaration is an overload of the
921 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
922 /// New and Old cannot be overloaded, e.g., if New has the same signature as
923 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
924 /// functions (or function templates) at all. When it does return Ovl_Match or
925 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
926 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
927 /// declaration.
928 ///
929 /// Example: Given the following input:
930 ///
931 ///   void f(int, float); // #1
932 ///   void f(int, int); // #2
933 ///   int f(int, int); // #3
934 ///
935 /// When we process #1, there is no previous declaration of "f", so IsOverload
936 /// will not be used.
937 ///
938 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
939 /// the parameter types, we see that #1 and #2 are overloaded (since they have
940 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
941 /// unchanged.
942 ///
943 /// When we process #3, Old is an overload set containing #1 and #2. We compare
944 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
945 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
946 /// functions are not part of the signature), IsOverload returns Ovl_Match and
947 /// MatchedDecl will be set to point to the FunctionDecl for #2.
948 ///
949 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
950 /// by a using declaration. The rules for whether to hide shadow declarations
951 /// ignore some properties which otherwise figure into a function template's
952 /// signature.
953 Sema::OverloadKind
954 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
955                     NamedDecl *&Match, bool NewIsUsingDecl) {
956   for (LookupResult::iterator I = Old.begin(), E = Old.end();
957          I != E; ++I) {
958     NamedDecl *OldD = *I;
959 
960     bool OldIsUsingDecl = false;
961     if (isa<UsingShadowDecl>(OldD)) {
962       OldIsUsingDecl = true;
963 
964       // We can always introduce two using declarations into the same
965       // context, even if they have identical signatures.
966       if (NewIsUsingDecl) continue;
967 
968       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
969     }
970 
971     // A using-declaration does not conflict with another declaration
972     // if one of them is hidden.
973     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
974       continue;
975 
976     // If either declaration was introduced by a using declaration,
977     // we'll need to use slightly different rules for matching.
978     // Essentially, these rules are the normal rules, except that
979     // function templates hide function templates with different
980     // return types or template parameter lists.
981     bool UseMemberUsingDeclRules =
982       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
983       !New->getFriendObjectKind();
984 
985     if (FunctionDecl *OldF = OldD->getAsFunction()) {
986       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
987         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
988           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
989           continue;
990         }
991 
992         if (!isa<FunctionTemplateDecl>(OldD) &&
993             !shouldLinkPossiblyHiddenDecl(*I, New))
994           continue;
995 
996         Match = *I;
997         return Ovl_Match;
998       }
999     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1000       // We can overload with these, which can show up when doing
1001       // redeclaration checks for UsingDecls.
1002       assert(Old.getLookupKind() == LookupUsingDeclName);
1003     } else if (isa<TagDecl>(OldD)) {
1004       // We can always overload with tags by hiding them.
1005     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1006       // Optimistically assume that an unresolved using decl will
1007       // overload; if it doesn't, we'll have to diagnose during
1008       // template instantiation.
1009       //
1010       // Exception: if the scope is dependent and this is not a class
1011       // member, the using declaration can only introduce an enumerator.
1012       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1013         Match = *I;
1014         return Ovl_NonFunction;
1015       }
1016     } else {
1017       // (C++ 13p1):
1018       //   Only function declarations can be overloaded; object and type
1019       //   declarations cannot be overloaded.
1020       Match = *I;
1021       return Ovl_NonFunction;
1022     }
1023   }
1024 
1025   return Ovl_Overload;
1026 }
1027 
1028 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1029                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1030   // C++ [basic.start.main]p2: This function shall not be overloaded.
1031   if (New->isMain())
1032     return false;
1033 
1034   // MSVCRT user defined entry points cannot be overloaded.
1035   if (New->isMSVCRTEntryPoint())
1036     return false;
1037 
1038   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1039   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1040 
1041   // C++ [temp.fct]p2:
1042   //   A function template can be overloaded with other function templates
1043   //   and with normal (non-template) functions.
1044   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1045     return true;
1046 
1047   // Is the function New an overload of the function Old?
1048   QualType OldQType = Context.getCanonicalType(Old->getType());
1049   QualType NewQType = Context.getCanonicalType(New->getType());
1050 
1051   // Compare the signatures (C++ 1.3.10) of the two functions to
1052   // determine whether they are overloads. If we find any mismatch
1053   // in the signature, they are overloads.
1054 
1055   // If either of these functions is a K&R-style function (no
1056   // prototype), then we consider them to have matching signatures.
1057   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1058       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1059     return false;
1060 
1061   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1062   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1063 
1064   // The signature of a function includes the types of its
1065   // parameters (C++ 1.3.10), which includes the presence or absence
1066   // of the ellipsis; see C++ DR 357).
1067   if (OldQType != NewQType &&
1068       (OldType->getNumParams() != NewType->getNumParams() ||
1069        OldType->isVariadic() != NewType->isVariadic() ||
1070        !FunctionParamTypesAreEqual(OldType, NewType)))
1071     return true;
1072 
1073   // C++ [temp.over.link]p4:
1074   //   The signature of a function template consists of its function
1075   //   signature, its return type and its template parameter list. The names
1076   //   of the template parameters are significant only for establishing the
1077   //   relationship between the template parameters and the rest of the
1078   //   signature.
1079   //
1080   // We check the return type and template parameter lists for function
1081   // templates first; the remaining checks follow.
1082   //
1083   // However, we don't consider either of these when deciding whether
1084   // a member introduced by a shadow declaration is hidden.
1085   if (!UseMemberUsingDeclRules && NewTemplate &&
1086       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1087                                        OldTemplate->getTemplateParameters(),
1088                                        false, TPL_TemplateMatch) ||
1089        OldType->getReturnType() != NewType->getReturnType()))
1090     return true;
1091 
1092   // If the function is a class member, its signature includes the
1093   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1094   //
1095   // As part of this, also check whether one of the member functions
1096   // is static, in which case they are not overloads (C++
1097   // 13.1p2). While not part of the definition of the signature,
1098   // this check is important to determine whether these functions
1099   // can be overloaded.
1100   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1101   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1102   if (OldMethod && NewMethod &&
1103       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1104     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1105       if (!UseMemberUsingDeclRules &&
1106           (OldMethod->getRefQualifier() == RQ_None ||
1107            NewMethod->getRefQualifier() == RQ_None)) {
1108         // C++0x [over.load]p2:
1109         //   - Member function declarations with the same name and the same
1110         //     parameter-type-list as well as member function template
1111         //     declarations with the same name, the same parameter-type-list, and
1112         //     the same template parameter lists cannot be overloaded if any of
1113         //     them, but not all, have a ref-qualifier (8.3.5).
1114         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1115           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1116         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1117       }
1118       return true;
1119     }
1120 
1121     // We may not have applied the implicit const for a constexpr member
1122     // function yet (because we haven't yet resolved whether this is a static
1123     // or non-static member function). Add it now, on the assumption that this
1124     // is a redeclaration of OldMethod.
1125     unsigned OldQuals = OldMethod->getTypeQualifiers();
1126     unsigned NewQuals = NewMethod->getTypeQualifiers();
1127     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1128         !isa<CXXConstructorDecl>(NewMethod))
1129       NewQuals |= Qualifiers::Const;
1130 
1131     // We do not allow overloading based off of '__restrict'.
1132     OldQuals &= ~Qualifiers::Restrict;
1133     NewQuals &= ~Qualifiers::Restrict;
1134     if (OldQuals != NewQuals)
1135       return true;
1136   }
1137 
1138   // Though pass_object_size is placed on parameters and takes an argument, we
1139   // consider it to be a function-level modifier for the sake of function
1140   // identity. Either the function has one or more parameters with
1141   // pass_object_size or it doesn't.
1142   if (functionHasPassObjectSizeParams(New) !=
1143       functionHasPassObjectSizeParams(Old))
1144     return true;
1145 
1146   // enable_if attributes are an order-sensitive part of the signature.
1147   for (specific_attr_iterator<EnableIfAttr>
1148          NewI = New->specific_attr_begin<EnableIfAttr>(),
1149          NewE = New->specific_attr_end<EnableIfAttr>(),
1150          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1151          OldE = Old->specific_attr_end<EnableIfAttr>();
1152        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1153     if (NewI == NewE || OldI == OldE)
1154       return true;
1155     llvm::FoldingSetNodeID NewID, OldID;
1156     NewI->getCond()->Profile(NewID, Context, true);
1157     OldI->getCond()->Profile(OldID, Context, true);
1158     if (NewID != OldID)
1159       return true;
1160   }
1161 
1162   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1163     // Don't allow overloading of destructors.  (In theory we could, but it
1164     // would be a giant change to clang.)
1165     if (isa<CXXDestructorDecl>(New))
1166       return false;
1167 
1168     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1169                        OldTarget = IdentifyCUDATarget(Old);
1170     if (NewTarget == CFT_InvalidTarget)
1171       return false;
1172 
1173     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1174 
1175     // Allow overloading of functions with same signature and different CUDA
1176     // target attributes.
1177     return NewTarget != OldTarget;
1178   }
1179 
1180   // The signatures match; this is not an overload.
1181   return false;
1182 }
1183 
1184 /// \brief Checks availability of the function depending on the current
1185 /// function context. Inside an unavailable function, unavailability is ignored.
1186 ///
1187 /// \returns true if \arg FD is unavailable and current context is inside
1188 /// an available function, false otherwise.
1189 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1190   if (!FD->isUnavailable())
1191     return false;
1192 
1193   // Walk up the context of the caller.
1194   Decl *C = cast<Decl>(CurContext);
1195   do {
1196     if (C->isUnavailable())
1197       return false;
1198   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1199   return true;
1200 }
1201 
1202 /// \brief Tries a user-defined conversion from From to ToType.
1203 ///
1204 /// Produces an implicit conversion sequence for when a standard conversion
1205 /// is not an option. See TryImplicitConversion for more information.
1206 static ImplicitConversionSequence
1207 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1208                          bool SuppressUserConversions,
1209                          bool AllowExplicit,
1210                          bool InOverloadResolution,
1211                          bool CStyle,
1212                          bool AllowObjCWritebackConversion,
1213                          bool AllowObjCConversionOnExplicit) {
1214   ImplicitConversionSequence ICS;
1215 
1216   if (SuppressUserConversions) {
1217     // We're not in the case above, so there is no conversion that
1218     // we can perform.
1219     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1220     return ICS;
1221   }
1222 
1223   // Attempt user-defined conversion.
1224   OverloadCandidateSet Conversions(From->getExprLoc(),
1225                                    OverloadCandidateSet::CSK_Normal);
1226   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1227                                   Conversions, AllowExplicit,
1228                                   AllowObjCConversionOnExplicit)) {
1229   case OR_Success:
1230   case OR_Deleted:
1231     ICS.setUserDefined();
1232     // C++ [over.ics.user]p4:
1233     //   A conversion of an expression of class type to the same class
1234     //   type is given Exact Match rank, and a conversion of an
1235     //   expression of class type to a base class of that type is
1236     //   given Conversion rank, in spite of the fact that a copy
1237     //   constructor (i.e., a user-defined conversion function) is
1238     //   called for those cases.
1239     if (CXXConstructorDecl *Constructor
1240           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1241       QualType FromCanon
1242         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1243       QualType ToCanon
1244         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1245       if (Constructor->isCopyConstructor() &&
1246           (FromCanon == ToCanon ||
1247            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1248         // Turn this into a "standard" conversion sequence, so that it
1249         // gets ranked with standard conversion sequences.
1250         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1251         ICS.setStandard();
1252         ICS.Standard.setAsIdentityConversion();
1253         ICS.Standard.setFromType(From->getType());
1254         ICS.Standard.setAllToTypes(ToType);
1255         ICS.Standard.CopyConstructor = Constructor;
1256         ICS.Standard.FoundCopyConstructor = Found;
1257         if (ToCanon != FromCanon)
1258           ICS.Standard.Second = ICK_Derived_To_Base;
1259       }
1260     }
1261     break;
1262 
1263   case OR_Ambiguous:
1264     ICS.setAmbiguous();
1265     ICS.Ambiguous.setFromType(From->getType());
1266     ICS.Ambiguous.setToType(ToType);
1267     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1268          Cand != Conversions.end(); ++Cand)
1269       if (Cand->Viable)
1270         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1271     break;
1272 
1273     // Fall through.
1274   case OR_No_Viable_Function:
1275     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1276     break;
1277   }
1278 
1279   return ICS;
1280 }
1281 
1282 /// TryImplicitConversion - Attempt to perform an implicit conversion
1283 /// from the given expression (Expr) to the given type (ToType). This
1284 /// function returns an implicit conversion sequence that can be used
1285 /// to perform the initialization. Given
1286 ///
1287 ///   void f(float f);
1288 ///   void g(int i) { f(i); }
1289 ///
1290 /// this routine would produce an implicit conversion sequence to
1291 /// describe the initialization of f from i, which will be a standard
1292 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1293 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1294 //
1295 /// Note that this routine only determines how the conversion can be
1296 /// performed; it does not actually perform the conversion. As such,
1297 /// it will not produce any diagnostics if no conversion is available,
1298 /// but will instead return an implicit conversion sequence of kind
1299 /// "BadConversion".
1300 ///
1301 /// If @p SuppressUserConversions, then user-defined conversions are
1302 /// not permitted.
1303 /// If @p AllowExplicit, then explicit user-defined conversions are
1304 /// permitted.
1305 ///
1306 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1307 /// writeback conversion, which allows __autoreleasing id* parameters to
1308 /// be initialized with __strong id* or __weak id* arguments.
1309 static ImplicitConversionSequence
1310 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1311                       bool SuppressUserConversions,
1312                       bool AllowExplicit,
1313                       bool InOverloadResolution,
1314                       bool CStyle,
1315                       bool AllowObjCWritebackConversion,
1316                       bool AllowObjCConversionOnExplicit) {
1317   ImplicitConversionSequence ICS;
1318   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1319                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1320     ICS.setStandard();
1321     return ICS;
1322   }
1323 
1324   if (!S.getLangOpts().CPlusPlus) {
1325     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1326     return ICS;
1327   }
1328 
1329   // C++ [over.ics.user]p4:
1330   //   A conversion of an expression of class type to the same class
1331   //   type is given Exact Match rank, and a conversion of an
1332   //   expression of class type to a base class of that type is
1333   //   given Conversion rank, in spite of the fact that a copy/move
1334   //   constructor (i.e., a user-defined conversion function) is
1335   //   called for those cases.
1336   QualType FromType = From->getType();
1337   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1338       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1339        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1340     ICS.setStandard();
1341     ICS.Standard.setAsIdentityConversion();
1342     ICS.Standard.setFromType(FromType);
1343     ICS.Standard.setAllToTypes(ToType);
1344 
1345     // We don't actually check at this point whether there is a valid
1346     // copy/move constructor, since overloading just assumes that it
1347     // exists. When we actually perform initialization, we'll find the
1348     // appropriate constructor to copy the returned object, if needed.
1349     ICS.Standard.CopyConstructor = nullptr;
1350 
1351     // Determine whether this is considered a derived-to-base conversion.
1352     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1353       ICS.Standard.Second = ICK_Derived_To_Base;
1354 
1355     return ICS;
1356   }
1357 
1358   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1359                                   AllowExplicit, InOverloadResolution, CStyle,
1360                                   AllowObjCWritebackConversion,
1361                                   AllowObjCConversionOnExplicit);
1362 }
1363 
1364 ImplicitConversionSequence
1365 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1366                             bool SuppressUserConversions,
1367                             bool AllowExplicit,
1368                             bool InOverloadResolution,
1369                             bool CStyle,
1370                             bool AllowObjCWritebackConversion) {
1371   return ::TryImplicitConversion(*this, From, ToType,
1372                                  SuppressUserConversions, AllowExplicit,
1373                                  InOverloadResolution, CStyle,
1374                                  AllowObjCWritebackConversion,
1375                                  /*AllowObjCConversionOnExplicit=*/false);
1376 }
1377 
1378 /// PerformImplicitConversion - Perform an implicit conversion of the
1379 /// expression From to the type ToType. Returns the
1380 /// converted expression. Flavor is the kind of conversion we're
1381 /// performing, used in the error message. If @p AllowExplicit,
1382 /// explicit user-defined conversions are permitted.
1383 ExprResult
1384 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1385                                 AssignmentAction Action, bool AllowExplicit) {
1386   ImplicitConversionSequence ICS;
1387   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1388 }
1389 
1390 ExprResult
1391 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1392                                 AssignmentAction Action, bool AllowExplicit,
1393                                 ImplicitConversionSequence& ICS) {
1394   if (checkPlaceholderForOverload(*this, From))
1395     return ExprError();
1396 
1397   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1398   bool AllowObjCWritebackConversion
1399     = getLangOpts().ObjCAutoRefCount &&
1400       (Action == AA_Passing || Action == AA_Sending);
1401   if (getLangOpts().ObjC1)
1402     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1403                                       ToType, From->getType(), From);
1404   ICS = ::TryImplicitConversion(*this, From, ToType,
1405                                 /*SuppressUserConversions=*/false,
1406                                 AllowExplicit,
1407                                 /*InOverloadResolution=*/false,
1408                                 /*CStyle=*/false,
1409                                 AllowObjCWritebackConversion,
1410                                 /*AllowObjCConversionOnExplicit=*/false);
1411   return PerformImplicitConversion(From, ToType, ICS, Action);
1412 }
1413 
1414 /// \brief Determine whether the conversion from FromType to ToType is a valid
1415 /// conversion that strips "noexcept" or "noreturn" off the nested function
1416 /// type.
1417 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1418                                 QualType &ResultTy) {
1419   if (Context.hasSameUnqualifiedType(FromType, ToType))
1420     return false;
1421 
1422   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1423   //                    or F(t noexcept) -> F(t)
1424   // where F adds one of the following at most once:
1425   //   - a pointer
1426   //   - a member pointer
1427   //   - a block pointer
1428   // Changes here need matching changes in FindCompositePointerType.
1429   CanQualType CanTo = Context.getCanonicalType(ToType);
1430   CanQualType CanFrom = Context.getCanonicalType(FromType);
1431   Type::TypeClass TyClass = CanTo->getTypeClass();
1432   if (TyClass != CanFrom->getTypeClass()) return false;
1433   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1434     if (TyClass == Type::Pointer) {
1435       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1436       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1437     } else if (TyClass == Type::BlockPointer) {
1438       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1439       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1440     } else if (TyClass == Type::MemberPointer) {
1441       auto ToMPT = CanTo.getAs<MemberPointerType>();
1442       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1443       // A function pointer conversion cannot change the class of the function.
1444       if (ToMPT->getClass() != FromMPT->getClass())
1445         return false;
1446       CanTo = ToMPT->getPointeeType();
1447       CanFrom = FromMPT->getPointeeType();
1448     } else {
1449       return false;
1450     }
1451 
1452     TyClass = CanTo->getTypeClass();
1453     if (TyClass != CanFrom->getTypeClass()) return false;
1454     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1455       return false;
1456   }
1457 
1458   const auto *FromFn = cast<FunctionType>(CanFrom);
1459   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1460 
1461   const auto *ToFn = cast<FunctionType>(CanTo);
1462   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1463 
1464   bool Changed = false;
1465 
1466   // Drop 'noreturn' if not present in target type.
1467   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1468     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1469     Changed = true;
1470   }
1471 
1472   // Drop 'noexcept' if not present in target type.
1473   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1474     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1475     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1476       FromFn = cast<FunctionType>(
1477           Context.getFunctionType(FromFPT->getReturnType(),
1478                                   FromFPT->getParamTypes(),
1479                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1480                                       FunctionProtoType::ExceptionSpecInfo()))
1481                  .getTypePtr());
1482       Changed = true;
1483     }
1484 
1485     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1486     // only if the ExtParameterInfo lists of the two function prototypes can be
1487     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1488     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1489     bool CanUseToFPT, CanUseFromFPT;
1490     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1491                                       CanUseFromFPT, NewParamInfos) &&
1492         CanUseToFPT && !CanUseFromFPT) {
1493       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1494       ExtInfo.ExtParameterInfos =
1495           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1496       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1497                                             FromFPT->getParamTypes(), ExtInfo);
1498       FromFn = QT->getAs<FunctionType>();
1499       Changed = true;
1500     }
1501   }
1502 
1503   if (!Changed)
1504     return false;
1505 
1506   assert(QualType(FromFn, 0).isCanonical());
1507   if (QualType(FromFn, 0) != CanTo) return false;
1508 
1509   ResultTy = ToType;
1510   return true;
1511 }
1512 
1513 /// \brief Determine whether the conversion from FromType to ToType is a valid
1514 /// vector conversion.
1515 ///
1516 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1517 /// conversion.
1518 static bool IsVectorConversion(Sema &S, QualType FromType,
1519                                QualType ToType, ImplicitConversionKind &ICK) {
1520   // We need at least one of these types to be a vector type to have a vector
1521   // conversion.
1522   if (!ToType->isVectorType() && !FromType->isVectorType())
1523     return false;
1524 
1525   // Identical types require no conversions.
1526   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1527     return false;
1528 
1529   // There are no conversions between extended vector types, only identity.
1530   if (ToType->isExtVectorType()) {
1531     // There are no conversions between extended vector types other than the
1532     // identity conversion.
1533     if (FromType->isExtVectorType())
1534       return false;
1535 
1536     // Vector splat from any arithmetic type to a vector.
1537     if (FromType->isArithmeticType()) {
1538       ICK = ICK_Vector_Splat;
1539       return true;
1540     }
1541   }
1542 
1543   // We can perform the conversion between vector types in the following cases:
1544   // 1)vector types are equivalent AltiVec and GCC vector types
1545   // 2)lax vector conversions are permitted and the vector types are of the
1546   //   same size
1547   if (ToType->isVectorType() && FromType->isVectorType()) {
1548     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1549         S.isLaxVectorConversion(FromType, ToType)) {
1550       ICK = ICK_Vector_Conversion;
1551       return true;
1552     }
1553   }
1554 
1555   return false;
1556 }
1557 
1558 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1559                                 bool InOverloadResolution,
1560                                 StandardConversionSequence &SCS,
1561                                 bool CStyle);
1562 
1563 /// IsStandardConversion - Determines whether there is a standard
1564 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1565 /// expression From to the type ToType. Standard conversion sequences
1566 /// only consider non-class types; for conversions that involve class
1567 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1568 /// contain the standard conversion sequence required to perform this
1569 /// conversion and this routine will return true. Otherwise, this
1570 /// routine will return false and the value of SCS is unspecified.
1571 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1572                                  bool InOverloadResolution,
1573                                  StandardConversionSequence &SCS,
1574                                  bool CStyle,
1575                                  bool AllowObjCWritebackConversion) {
1576   QualType FromType = From->getType();
1577 
1578   // Standard conversions (C++ [conv])
1579   SCS.setAsIdentityConversion();
1580   SCS.IncompatibleObjC = false;
1581   SCS.setFromType(FromType);
1582   SCS.CopyConstructor = nullptr;
1583 
1584   // There are no standard conversions for class types in C++, so
1585   // abort early. When overloading in C, however, we do permit them.
1586   if (S.getLangOpts().CPlusPlus &&
1587       (FromType->isRecordType() || ToType->isRecordType()))
1588     return false;
1589 
1590   // The first conversion can be an lvalue-to-rvalue conversion,
1591   // array-to-pointer conversion, or function-to-pointer conversion
1592   // (C++ 4p1).
1593 
1594   if (FromType == S.Context.OverloadTy) {
1595     DeclAccessPair AccessPair;
1596     if (FunctionDecl *Fn
1597           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1598                                                  AccessPair)) {
1599       // We were able to resolve the address of the overloaded function,
1600       // so we can convert to the type of that function.
1601       FromType = Fn->getType();
1602       SCS.setFromType(FromType);
1603 
1604       // we can sometimes resolve &foo<int> regardless of ToType, so check
1605       // if the type matches (identity) or we are converting to bool
1606       if (!S.Context.hasSameUnqualifiedType(
1607                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1608         QualType resultTy;
1609         // if the function type matches except for [[noreturn]], it's ok
1610         if (!S.IsFunctionConversion(FromType,
1611               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1612           // otherwise, only a boolean conversion is standard
1613           if (!ToType->isBooleanType())
1614             return false;
1615       }
1616 
1617       // Check if the "from" expression is taking the address of an overloaded
1618       // function and recompute the FromType accordingly. Take advantage of the
1619       // fact that non-static member functions *must* have such an address-of
1620       // expression.
1621       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1622       if (Method && !Method->isStatic()) {
1623         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1624                "Non-unary operator on non-static member address");
1625         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1626                == UO_AddrOf &&
1627                "Non-address-of operator on non-static member address");
1628         const Type *ClassType
1629           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1630         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1631       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1632         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1633                UO_AddrOf &&
1634                "Non-address-of operator for overloaded function expression");
1635         FromType = S.Context.getPointerType(FromType);
1636       }
1637 
1638       // Check that we've computed the proper type after overload resolution.
1639       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1640       // be calling it from within an NDEBUG block.
1641       assert(S.Context.hasSameType(
1642         FromType,
1643         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1644     } else {
1645       return false;
1646     }
1647   }
1648   // Lvalue-to-rvalue conversion (C++11 4.1):
1649   //   A glvalue (3.10) of a non-function, non-array type T can
1650   //   be converted to a prvalue.
1651   bool argIsLValue = From->isGLValue();
1652   if (argIsLValue &&
1653       !FromType->isFunctionType() && !FromType->isArrayType() &&
1654       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1655     SCS.First = ICK_Lvalue_To_Rvalue;
1656 
1657     // C11 6.3.2.1p2:
1658     //   ... if the lvalue has atomic type, the value has the non-atomic version
1659     //   of the type of the lvalue ...
1660     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1661       FromType = Atomic->getValueType();
1662 
1663     // If T is a non-class type, the type of the rvalue is the
1664     // cv-unqualified version of T. Otherwise, the type of the rvalue
1665     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1666     // just strip the qualifiers because they don't matter.
1667     FromType = FromType.getUnqualifiedType();
1668   } else if (FromType->isArrayType()) {
1669     // Array-to-pointer conversion (C++ 4.2)
1670     SCS.First = ICK_Array_To_Pointer;
1671 
1672     // An lvalue or rvalue of type "array of N T" or "array of unknown
1673     // bound of T" can be converted to an rvalue of type "pointer to
1674     // T" (C++ 4.2p1).
1675     FromType = S.Context.getArrayDecayedType(FromType);
1676 
1677     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1678       // This conversion is deprecated in C++03 (D.4)
1679       SCS.DeprecatedStringLiteralToCharPtr = true;
1680 
1681       // For the purpose of ranking in overload resolution
1682       // (13.3.3.1.1), this conversion is considered an
1683       // array-to-pointer conversion followed by a qualification
1684       // conversion (4.4). (C++ 4.2p2)
1685       SCS.Second = ICK_Identity;
1686       SCS.Third = ICK_Qualification;
1687       SCS.QualificationIncludesObjCLifetime = false;
1688       SCS.setAllToTypes(FromType);
1689       return true;
1690     }
1691   } else if (FromType->isFunctionType() && argIsLValue) {
1692     // Function-to-pointer conversion (C++ 4.3).
1693     SCS.First = ICK_Function_To_Pointer;
1694 
1695     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1696       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1697         if (!S.checkAddressOfFunctionIsAvailable(FD))
1698           return false;
1699 
1700     // An lvalue of function type T can be converted to an rvalue of
1701     // type "pointer to T." The result is a pointer to the
1702     // function. (C++ 4.3p1).
1703     FromType = S.Context.getPointerType(FromType);
1704   } else {
1705     // We don't require any conversions for the first step.
1706     SCS.First = ICK_Identity;
1707   }
1708   SCS.setToType(0, FromType);
1709 
1710   // The second conversion can be an integral promotion, floating
1711   // point promotion, integral conversion, floating point conversion,
1712   // floating-integral conversion, pointer conversion,
1713   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1714   // For overloading in C, this can also be a "compatible-type"
1715   // conversion.
1716   bool IncompatibleObjC = false;
1717   ImplicitConversionKind SecondICK = ICK_Identity;
1718   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1719     // The unqualified versions of the types are the same: there's no
1720     // conversion to do.
1721     SCS.Second = ICK_Identity;
1722   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1723     // Integral promotion (C++ 4.5).
1724     SCS.Second = ICK_Integral_Promotion;
1725     FromType = ToType.getUnqualifiedType();
1726   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1727     // Floating point promotion (C++ 4.6).
1728     SCS.Second = ICK_Floating_Promotion;
1729     FromType = ToType.getUnqualifiedType();
1730   } else if (S.IsComplexPromotion(FromType, ToType)) {
1731     // Complex promotion (Clang extension)
1732     SCS.Second = ICK_Complex_Promotion;
1733     FromType = ToType.getUnqualifiedType();
1734   } else if (ToType->isBooleanType() &&
1735              (FromType->isArithmeticType() ||
1736               FromType->isAnyPointerType() ||
1737               FromType->isBlockPointerType() ||
1738               FromType->isMemberPointerType() ||
1739               FromType->isNullPtrType())) {
1740     // Boolean conversions (C++ 4.12).
1741     SCS.Second = ICK_Boolean_Conversion;
1742     FromType = S.Context.BoolTy;
1743   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1744              ToType->isIntegralType(S.Context)) {
1745     // Integral conversions (C++ 4.7).
1746     SCS.Second = ICK_Integral_Conversion;
1747     FromType = ToType.getUnqualifiedType();
1748   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1749     // Complex conversions (C99 6.3.1.6)
1750     SCS.Second = ICK_Complex_Conversion;
1751     FromType = ToType.getUnqualifiedType();
1752   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1753              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1754     // Complex-real conversions (C99 6.3.1.7)
1755     SCS.Second = ICK_Complex_Real;
1756     FromType = ToType.getUnqualifiedType();
1757   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1758     // FIXME: disable conversions between long double and __float128 if
1759     // their representation is different until there is back end support
1760     // We of course allow this conversion if long double is really double.
1761     if (&S.Context.getFloatTypeSemantics(FromType) !=
1762         &S.Context.getFloatTypeSemantics(ToType)) {
1763       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1764                                     ToType == S.Context.LongDoubleTy) ||
1765                                    (FromType == S.Context.LongDoubleTy &&
1766                                     ToType == S.Context.Float128Ty));
1767       if (Float128AndLongDouble &&
1768           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1769            &llvm::APFloat::IEEEdouble()))
1770         return false;
1771     }
1772     // Floating point conversions (C++ 4.8).
1773     SCS.Second = ICK_Floating_Conversion;
1774     FromType = ToType.getUnqualifiedType();
1775   } else if ((FromType->isRealFloatingType() &&
1776               ToType->isIntegralType(S.Context)) ||
1777              (FromType->isIntegralOrUnscopedEnumerationType() &&
1778               ToType->isRealFloatingType())) {
1779     // Floating-integral conversions (C++ 4.9).
1780     SCS.Second = ICK_Floating_Integral;
1781     FromType = ToType.getUnqualifiedType();
1782   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1783     SCS.Second = ICK_Block_Pointer_Conversion;
1784   } else if (AllowObjCWritebackConversion &&
1785              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1786     SCS.Second = ICK_Writeback_Conversion;
1787   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1788                                    FromType, IncompatibleObjC)) {
1789     // Pointer conversions (C++ 4.10).
1790     SCS.Second = ICK_Pointer_Conversion;
1791     SCS.IncompatibleObjC = IncompatibleObjC;
1792     FromType = FromType.getUnqualifiedType();
1793   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1794                                          InOverloadResolution, FromType)) {
1795     // Pointer to member conversions (4.11).
1796     SCS.Second = ICK_Pointer_Member;
1797   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1798     SCS.Second = SecondICK;
1799     FromType = ToType.getUnqualifiedType();
1800   } else if (!S.getLangOpts().CPlusPlus &&
1801              S.Context.typesAreCompatible(ToType, FromType)) {
1802     // Compatible conversions (Clang extension for C function overloading)
1803     SCS.Second = ICK_Compatible_Conversion;
1804     FromType = ToType.getUnqualifiedType();
1805   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1806                                              InOverloadResolution,
1807                                              SCS, CStyle)) {
1808     SCS.Second = ICK_TransparentUnionConversion;
1809     FromType = ToType;
1810   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1811                                  CStyle)) {
1812     // tryAtomicConversion has updated the standard conversion sequence
1813     // appropriately.
1814     return true;
1815   } else if (ToType->isEventT() &&
1816              From->isIntegerConstantExpr(S.getASTContext()) &&
1817              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1818     SCS.Second = ICK_Zero_Event_Conversion;
1819     FromType = ToType;
1820   } else if (ToType->isQueueT() &&
1821              From->isIntegerConstantExpr(S.getASTContext()) &&
1822              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1823     SCS.Second = ICK_Zero_Queue_Conversion;
1824     FromType = ToType;
1825   } else {
1826     // No second conversion required.
1827     SCS.Second = ICK_Identity;
1828   }
1829   SCS.setToType(1, FromType);
1830 
1831   // The third conversion can be a function pointer conversion or a
1832   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1833   bool ObjCLifetimeConversion;
1834   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1835     // Function pointer conversions (removing 'noexcept') including removal of
1836     // 'noreturn' (Clang extension).
1837     SCS.Third = ICK_Function_Conversion;
1838   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1839                                          ObjCLifetimeConversion)) {
1840     SCS.Third = ICK_Qualification;
1841     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1842     FromType = ToType;
1843   } else {
1844     // No conversion required
1845     SCS.Third = ICK_Identity;
1846   }
1847 
1848   // C++ [over.best.ics]p6:
1849   //   [...] Any difference in top-level cv-qualification is
1850   //   subsumed by the initialization itself and does not constitute
1851   //   a conversion. [...]
1852   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1853   QualType CanonTo = S.Context.getCanonicalType(ToType);
1854   if (CanonFrom.getLocalUnqualifiedType()
1855                                      == CanonTo.getLocalUnqualifiedType() &&
1856       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1857     FromType = ToType;
1858     CanonFrom = CanonTo;
1859   }
1860 
1861   SCS.setToType(2, FromType);
1862 
1863   if (CanonFrom == CanonTo)
1864     return true;
1865 
1866   // If we have not converted the argument type to the parameter type,
1867   // this is a bad conversion sequence, unless we're resolving an overload in C.
1868   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1869     return false;
1870 
1871   ExprResult ER = ExprResult{From};
1872   Sema::AssignConvertType Conv =
1873       S.CheckSingleAssignmentConstraints(ToType, ER,
1874                                          /*Diagnose=*/false,
1875                                          /*DiagnoseCFAudited=*/false,
1876                                          /*ConvertRHS=*/false);
1877   ImplicitConversionKind SecondConv;
1878   switch (Conv) {
1879   case Sema::Compatible:
1880     SecondConv = ICK_C_Only_Conversion;
1881     break;
1882   // For our purposes, discarding qualifiers is just as bad as using an
1883   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1884   // qualifiers, as well.
1885   case Sema::CompatiblePointerDiscardsQualifiers:
1886   case Sema::IncompatiblePointer:
1887   case Sema::IncompatiblePointerSign:
1888     SecondConv = ICK_Incompatible_Pointer_Conversion;
1889     break;
1890   default:
1891     return false;
1892   }
1893 
1894   // First can only be an lvalue conversion, so we pretend that this was the
1895   // second conversion. First should already be valid from earlier in the
1896   // function.
1897   SCS.Second = SecondConv;
1898   SCS.setToType(1, ToType);
1899 
1900   // Third is Identity, because Second should rank us worse than any other
1901   // conversion. This could also be ICK_Qualification, but it's simpler to just
1902   // lump everything in with the second conversion, and we don't gain anything
1903   // from making this ICK_Qualification.
1904   SCS.Third = ICK_Identity;
1905   SCS.setToType(2, ToType);
1906   return true;
1907 }
1908 
1909 static bool
1910 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1911                                      QualType &ToType,
1912                                      bool InOverloadResolution,
1913                                      StandardConversionSequence &SCS,
1914                                      bool CStyle) {
1915 
1916   const RecordType *UT = ToType->getAsUnionType();
1917   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1918     return false;
1919   // The field to initialize within the transparent union.
1920   RecordDecl *UD = UT->getDecl();
1921   // It's compatible if the expression matches any of the fields.
1922   for (const auto *it : UD->fields()) {
1923     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1924                              CStyle, /*ObjCWritebackConversion=*/false)) {
1925       ToType = it->getType();
1926       return true;
1927     }
1928   }
1929   return false;
1930 }
1931 
1932 /// IsIntegralPromotion - Determines whether the conversion from the
1933 /// expression From (whose potentially-adjusted type is FromType) to
1934 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1935 /// sets PromotedType to the promoted type.
1936 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1937   const BuiltinType *To = ToType->getAs<BuiltinType>();
1938   // All integers are built-in.
1939   if (!To) {
1940     return false;
1941   }
1942 
1943   // An rvalue of type char, signed char, unsigned char, short int, or
1944   // unsigned short int can be converted to an rvalue of type int if
1945   // int can represent all the values of the source type; otherwise,
1946   // the source rvalue can be converted to an rvalue of type unsigned
1947   // int (C++ 4.5p1).
1948   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1949       !FromType->isEnumeralType()) {
1950     if (// We can promote any signed, promotable integer type to an int
1951         (FromType->isSignedIntegerType() ||
1952          // We can promote any unsigned integer type whose size is
1953          // less than int to an int.
1954          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1955       return To->getKind() == BuiltinType::Int;
1956     }
1957 
1958     return To->getKind() == BuiltinType::UInt;
1959   }
1960 
1961   // C++11 [conv.prom]p3:
1962   //   A prvalue of an unscoped enumeration type whose underlying type is not
1963   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1964   //   following types that can represent all the values of the enumeration
1965   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1966   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1967   //   long long int. If none of the types in that list can represent all the
1968   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1969   //   type can be converted to an rvalue a prvalue of the extended integer type
1970   //   with lowest integer conversion rank (4.13) greater than the rank of long
1971   //   long in which all the values of the enumeration can be represented. If
1972   //   there are two such extended types, the signed one is chosen.
1973   // C++11 [conv.prom]p4:
1974   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1975   //   can be converted to a prvalue of its underlying type. Moreover, if
1976   //   integral promotion can be applied to its underlying type, a prvalue of an
1977   //   unscoped enumeration type whose underlying type is fixed can also be
1978   //   converted to a prvalue of the promoted underlying type.
1979   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1980     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1981     // provided for a scoped enumeration.
1982     if (FromEnumType->getDecl()->isScoped())
1983       return false;
1984 
1985     // We can perform an integral promotion to the underlying type of the enum,
1986     // even if that's not the promoted type. Note that the check for promoting
1987     // the underlying type is based on the type alone, and does not consider
1988     // the bitfield-ness of the actual source expression.
1989     if (FromEnumType->getDecl()->isFixed()) {
1990       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1991       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1992              IsIntegralPromotion(nullptr, Underlying, ToType);
1993     }
1994 
1995     // We have already pre-calculated the promotion type, so this is trivial.
1996     if (ToType->isIntegerType() &&
1997         isCompleteType(From->getLocStart(), FromType))
1998       return Context.hasSameUnqualifiedType(
1999           ToType, FromEnumType->getDecl()->getPromotionType());
2000   }
2001 
2002   // C++0x [conv.prom]p2:
2003   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2004   //   to an rvalue a prvalue of the first of the following types that can
2005   //   represent all the values of its underlying type: int, unsigned int,
2006   //   long int, unsigned long int, long long int, or unsigned long long int.
2007   //   If none of the types in that list can represent all the values of its
2008   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2009   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2010   //   type.
2011   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2012       ToType->isIntegerType()) {
2013     // Determine whether the type we're converting from is signed or
2014     // unsigned.
2015     bool FromIsSigned = FromType->isSignedIntegerType();
2016     uint64_t FromSize = Context.getTypeSize(FromType);
2017 
2018     // The types we'll try to promote to, in the appropriate
2019     // order. Try each of these types.
2020     QualType PromoteTypes[6] = {
2021       Context.IntTy, Context.UnsignedIntTy,
2022       Context.LongTy, Context.UnsignedLongTy ,
2023       Context.LongLongTy, Context.UnsignedLongLongTy
2024     };
2025     for (int Idx = 0; Idx < 6; ++Idx) {
2026       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2027       if (FromSize < ToSize ||
2028           (FromSize == ToSize &&
2029            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2030         // We found the type that we can promote to. If this is the
2031         // type we wanted, we have a promotion. Otherwise, no
2032         // promotion.
2033         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2034       }
2035     }
2036   }
2037 
2038   // An rvalue for an integral bit-field (9.6) can be converted to an
2039   // rvalue of type int if int can represent all the values of the
2040   // bit-field; otherwise, it can be converted to unsigned int if
2041   // unsigned int can represent all the values of the bit-field. If
2042   // the bit-field is larger yet, no integral promotion applies to
2043   // it. If the bit-field has an enumerated type, it is treated as any
2044   // other value of that type for promotion purposes (C++ 4.5p3).
2045   // FIXME: We should delay checking of bit-fields until we actually perform the
2046   // conversion.
2047   if (From) {
2048     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2049       llvm::APSInt BitWidth;
2050       if (FromType->isIntegralType(Context) &&
2051           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2052         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2053         ToSize = Context.getTypeSize(ToType);
2054 
2055         // Are we promoting to an int from a bitfield that fits in an int?
2056         if (BitWidth < ToSize ||
2057             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2058           return To->getKind() == BuiltinType::Int;
2059         }
2060 
2061         // Are we promoting to an unsigned int from an unsigned bitfield
2062         // that fits into an unsigned int?
2063         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2064           return To->getKind() == BuiltinType::UInt;
2065         }
2066 
2067         return false;
2068       }
2069     }
2070   }
2071 
2072   // An rvalue of type bool can be converted to an rvalue of type int,
2073   // with false becoming zero and true becoming one (C++ 4.5p4).
2074   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2075     return true;
2076   }
2077 
2078   return false;
2079 }
2080 
2081 /// IsFloatingPointPromotion - Determines whether the conversion from
2082 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2083 /// returns true and sets PromotedType to the promoted type.
2084 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2085   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2086     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2087       /// An rvalue of type float can be converted to an rvalue of type
2088       /// double. (C++ 4.6p1).
2089       if (FromBuiltin->getKind() == BuiltinType::Float &&
2090           ToBuiltin->getKind() == BuiltinType::Double)
2091         return true;
2092 
2093       // C99 6.3.1.5p1:
2094       //   When a float is promoted to double or long double, or a
2095       //   double is promoted to long double [...].
2096       if (!getLangOpts().CPlusPlus &&
2097           (FromBuiltin->getKind() == BuiltinType::Float ||
2098            FromBuiltin->getKind() == BuiltinType::Double) &&
2099           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2100            ToBuiltin->getKind() == BuiltinType::Float128))
2101         return true;
2102 
2103       // Half can be promoted to float.
2104       if (!getLangOpts().NativeHalfType &&
2105            FromBuiltin->getKind() == BuiltinType::Half &&
2106           ToBuiltin->getKind() == BuiltinType::Float)
2107         return true;
2108     }
2109 
2110   return false;
2111 }
2112 
2113 /// \brief Determine if a conversion is a complex promotion.
2114 ///
2115 /// A complex promotion is defined as a complex -> complex conversion
2116 /// where the conversion between the underlying real types is a
2117 /// floating-point or integral promotion.
2118 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2119   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2120   if (!FromComplex)
2121     return false;
2122 
2123   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2124   if (!ToComplex)
2125     return false;
2126 
2127   return IsFloatingPointPromotion(FromComplex->getElementType(),
2128                                   ToComplex->getElementType()) ||
2129     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2130                         ToComplex->getElementType());
2131 }
2132 
2133 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2134 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2135 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2136 /// if non-empty, will be a pointer to ToType that may or may not have
2137 /// the right set of qualifiers on its pointee.
2138 ///
2139 static QualType
2140 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2141                                    QualType ToPointee, QualType ToType,
2142                                    ASTContext &Context,
2143                                    bool StripObjCLifetime = false) {
2144   assert((FromPtr->getTypeClass() == Type::Pointer ||
2145           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2146          "Invalid similarly-qualified pointer type");
2147 
2148   /// Conversions to 'id' subsume cv-qualifier conversions.
2149   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2150     return ToType.getUnqualifiedType();
2151 
2152   QualType CanonFromPointee
2153     = Context.getCanonicalType(FromPtr->getPointeeType());
2154   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2155   Qualifiers Quals = CanonFromPointee.getQualifiers();
2156 
2157   if (StripObjCLifetime)
2158     Quals.removeObjCLifetime();
2159 
2160   // Exact qualifier match -> return the pointer type we're converting to.
2161   if (CanonToPointee.getLocalQualifiers() == Quals) {
2162     // ToType is exactly what we need. Return it.
2163     if (!ToType.isNull())
2164       return ToType.getUnqualifiedType();
2165 
2166     // Build a pointer to ToPointee. It has the right qualifiers
2167     // already.
2168     if (isa<ObjCObjectPointerType>(ToType))
2169       return Context.getObjCObjectPointerType(ToPointee);
2170     return Context.getPointerType(ToPointee);
2171   }
2172 
2173   // Just build a canonical type that has the right qualifiers.
2174   QualType QualifiedCanonToPointee
2175     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2176 
2177   if (isa<ObjCObjectPointerType>(ToType))
2178     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2179   return Context.getPointerType(QualifiedCanonToPointee);
2180 }
2181 
2182 static bool isNullPointerConstantForConversion(Expr *Expr,
2183                                                bool InOverloadResolution,
2184                                                ASTContext &Context) {
2185   // Handle value-dependent integral null pointer constants correctly.
2186   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2187   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2188       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2189     return !InOverloadResolution;
2190 
2191   return Expr->isNullPointerConstant(Context,
2192                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2193                                         : Expr::NPC_ValueDependentIsNull);
2194 }
2195 
2196 /// IsPointerConversion - Determines whether the conversion of the
2197 /// expression From, which has the (possibly adjusted) type FromType,
2198 /// can be converted to the type ToType via a pointer conversion (C++
2199 /// 4.10). If so, returns true and places the converted type (that
2200 /// might differ from ToType in its cv-qualifiers at some level) into
2201 /// ConvertedType.
2202 ///
2203 /// This routine also supports conversions to and from block pointers
2204 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2205 /// pointers to interfaces. FIXME: Once we've determined the
2206 /// appropriate overloading rules for Objective-C, we may want to
2207 /// split the Objective-C checks into a different routine; however,
2208 /// GCC seems to consider all of these conversions to be pointer
2209 /// conversions, so for now they live here. IncompatibleObjC will be
2210 /// set if the conversion is an allowed Objective-C conversion that
2211 /// should result in a warning.
2212 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2213                                bool InOverloadResolution,
2214                                QualType& ConvertedType,
2215                                bool &IncompatibleObjC) {
2216   IncompatibleObjC = false;
2217   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2218                               IncompatibleObjC))
2219     return true;
2220 
2221   // Conversion from a null pointer constant to any Objective-C pointer type.
2222   if (ToType->isObjCObjectPointerType() &&
2223       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2224     ConvertedType = ToType;
2225     return true;
2226   }
2227 
2228   // Blocks: Block pointers can be converted to void*.
2229   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2230       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2231     ConvertedType = ToType;
2232     return true;
2233   }
2234   // Blocks: A null pointer constant can be converted to a block
2235   // pointer type.
2236   if (ToType->isBlockPointerType() &&
2237       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2238     ConvertedType = ToType;
2239     return true;
2240   }
2241 
2242   // If the left-hand-side is nullptr_t, the right side can be a null
2243   // pointer constant.
2244   if (ToType->isNullPtrType() &&
2245       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2246     ConvertedType = ToType;
2247     return true;
2248   }
2249 
2250   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2251   if (!ToTypePtr)
2252     return false;
2253 
2254   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2255   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2256     ConvertedType = ToType;
2257     return true;
2258   }
2259 
2260   // Beyond this point, both types need to be pointers
2261   // , including objective-c pointers.
2262   QualType ToPointeeType = ToTypePtr->getPointeeType();
2263   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2264       !getLangOpts().ObjCAutoRefCount) {
2265     ConvertedType = BuildSimilarlyQualifiedPointerType(
2266                                       FromType->getAs<ObjCObjectPointerType>(),
2267                                                        ToPointeeType,
2268                                                        ToType, Context);
2269     return true;
2270   }
2271   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2272   if (!FromTypePtr)
2273     return false;
2274 
2275   QualType FromPointeeType = FromTypePtr->getPointeeType();
2276 
2277   // If the unqualified pointee types are the same, this can't be a
2278   // pointer conversion, so don't do all of the work below.
2279   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2280     return false;
2281 
2282   // An rvalue of type "pointer to cv T," where T is an object type,
2283   // can be converted to an rvalue of type "pointer to cv void" (C++
2284   // 4.10p2).
2285   if (FromPointeeType->isIncompleteOrObjectType() &&
2286       ToPointeeType->isVoidType()) {
2287     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2288                                                        ToPointeeType,
2289                                                        ToType, Context,
2290                                                    /*StripObjCLifetime=*/true);
2291     return true;
2292   }
2293 
2294   // MSVC allows implicit function to void* type conversion.
2295   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2296       ToPointeeType->isVoidType()) {
2297     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2298                                                        ToPointeeType,
2299                                                        ToType, Context);
2300     return true;
2301   }
2302 
2303   // When we're overloading in C, we allow a special kind of pointer
2304   // conversion for compatible-but-not-identical pointee types.
2305   if (!getLangOpts().CPlusPlus &&
2306       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2307     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2308                                                        ToPointeeType,
2309                                                        ToType, Context);
2310     return true;
2311   }
2312 
2313   // C++ [conv.ptr]p3:
2314   //
2315   //   An rvalue of type "pointer to cv D," where D is a class type,
2316   //   can be converted to an rvalue of type "pointer to cv B," where
2317   //   B is a base class (clause 10) of D. If B is an inaccessible
2318   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2319   //   necessitates this conversion is ill-formed. The result of the
2320   //   conversion is a pointer to the base class sub-object of the
2321   //   derived class object. The null pointer value is converted to
2322   //   the null pointer value of the destination type.
2323   //
2324   // Note that we do not check for ambiguity or inaccessibility
2325   // here. That is handled by CheckPointerConversion.
2326   if (getLangOpts().CPlusPlus &&
2327       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2328       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2329       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2330     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331                                                        ToPointeeType,
2332                                                        ToType, Context);
2333     return true;
2334   }
2335 
2336   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2337       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2338     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                        ToPointeeType,
2340                                                        ToType, Context);
2341     return true;
2342   }
2343 
2344   return false;
2345 }
2346 
2347 /// \brief Adopt the given qualifiers for the given type.
2348 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2349   Qualifiers TQs = T.getQualifiers();
2350 
2351   // Check whether qualifiers already match.
2352   if (TQs == Qs)
2353     return T;
2354 
2355   if (Qs.compatiblyIncludes(TQs))
2356     return Context.getQualifiedType(T, Qs);
2357 
2358   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2359 }
2360 
2361 /// isObjCPointerConversion - Determines whether this is an
2362 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2363 /// with the same arguments and return values.
2364 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2365                                    QualType& ConvertedType,
2366                                    bool &IncompatibleObjC) {
2367   if (!getLangOpts().ObjC1)
2368     return false;
2369 
2370   // The set of qualifiers on the type we're converting from.
2371   Qualifiers FromQualifiers = FromType.getQualifiers();
2372 
2373   // First, we handle all conversions on ObjC object pointer types.
2374   const ObjCObjectPointerType* ToObjCPtr =
2375     ToType->getAs<ObjCObjectPointerType>();
2376   const ObjCObjectPointerType *FromObjCPtr =
2377     FromType->getAs<ObjCObjectPointerType>();
2378 
2379   if (ToObjCPtr && FromObjCPtr) {
2380     // If the pointee types are the same (ignoring qualifications),
2381     // then this is not a pointer conversion.
2382     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2383                                        FromObjCPtr->getPointeeType()))
2384       return false;
2385 
2386     // Conversion between Objective-C pointers.
2387     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2388       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2389       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2390       if (getLangOpts().CPlusPlus && LHS && RHS &&
2391           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2392                                                 FromObjCPtr->getPointeeType()))
2393         return false;
2394       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2395                                                    ToObjCPtr->getPointeeType(),
2396                                                          ToType, Context);
2397       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2398       return true;
2399     }
2400 
2401     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2402       // Okay: this is some kind of implicit downcast of Objective-C
2403       // interfaces, which is permitted. However, we're going to
2404       // complain about it.
2405       IncompatibleObjC = true;
2406       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2407                                                    ToObjCPtr->getPointeeType(),
2408                                                          ToType, Context);
2409       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2410       return true;
2411     }
2412   }
2413   // Beyond this point, both types need to be C pointers or block pointers.
2414   QualType ToPointeeType;
2415   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2416     ToPointeeType = ToCPtr->getPointeeType();
2417   else if (const BlockPointerType *ToBlockPtr =
2418             ToType->getAs<BlockPointerType>()) {
2419     // Objective C++: We're able to convert from a pointer to any object
2420     // to a block pointer type.
2421     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2422       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2423       return true;
2424     }
2425     ToPointeeType = ToBlockPtr->getPointeeType();
2426   }
2427   else if (FromType->getAs<BlockPointerType>() &&
2428            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2429     // Objective C++: We're able to convert from a block pointer type to a
2430     // pointer to any object.
2431     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2432     return true;
2433   }
2434   else
2435     return false;
2436 
2437   QualType FromPointeeType;
2438   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2439     FromPointeeType = FromCPtr->getPointeeType();
2440   else if (const BlockPointerType *FromBlockPtr =
2441            FromType->getAs<BlockPointerType>())
2442     FromPointeeType = FromBlockPtr->getPointeeType();
2443   else
2444     return false;
2445 
2446   // If we have pointers to pointers, recursively check whether this
2447   // is an Objective-C conversion.
2448   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2449       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2450                               IncompatibleObjC)) {
2451     // We always complain about this conversion.
2452     IncompatibleObjC = true;
2453     ConvertedType = Context.getPointerType(ConvertedType);
2454     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2455     return true;
2456   }
2457   // Allow conversion of pointee being objective-c pointer to another one;
2458   // as in I* to id.
2459   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2460       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2461       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2462                               IncompatibleObjC)) {
2463 
2464     ConvertedType = Context.getPointerType(ConvertedType);
2465     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2466     return true;
2467   }
2468 
2469   // If we have pointers to functions or blocks, check whether the only
2470   // differences in the argument and result types are in Objective-C
2471   // pointer conversions. If so, we permit the conversion (but
2472   // complain about it).
2473   const FunctionProtoType *FromFunctionType
2474     = FromPointeeType->getAs<FunctionProtoType>();
2475   const FunctionProtoType *ToFunctionType
2476     = ToPointeeType->getAs<FunctionProtoType>();
2477   if (FromFunctionType && ToFunctionType) {
2478     // If the function types are exactly the same, this isn't an
2479     // Objective-C pointer conversion.
2480     if (Context.getCanonicalType(FromPointeeType)
2481           == Context.getCanonicalType(ToPointeeType))
2482       return false;
2483 
2484     // Perform the quick checks that will tell us whether these
2485     // function types are obviously different.
2486     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2487         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2488         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2489       return false;
2490 
2491     bool HasObjCConversion = false;
2492     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2493         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2494       // Okay, the types match exactly. Nothing to do.
2495     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2496                                        ToFunctionType->getReturnType(),
2497                                        ConvertedType, IncompatibleObjC)) {
2498       // Okay, we have an Objective-C pointer conversion.
2499       HasObjCConversion = true;
2500     } else {
2501       // Function types are too different. Abort.
2502       return false;
2503     }
2504 
2505     // Check argument types.
2506     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2507          ArgIdx != NumArgs; ++ArgIdx) {
2508       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2509       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2510       if (Context.getCanonicalType(FromArgType)
2511             == Context.getCanonicalType(ToArgType)) {
2512         // Okay, the types match exactly. Nothing to do.
2513       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2514                                          ConvertedType, IncompatibleObjC)) {
2515         // Okay, we have an Objective-C pointer conversion.
2516         HasObjCConversion = true;
2517       } else {
2518         // Argument types are too different. Abort.
2519         return false;
2520       }
2521     }
2522 
2523     if (HasObjCConversion) {
2524       // We had an Objective-C conversion. Allow this pointer
2525       // conversion, but complain about it.
2526       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2527       IncompatibleObjC = true;
2528       return true;
2529     }
2530   }
2531 
2532   return false;
2533 }
2534 
2535 /// \brief Determine whether this is an Objective-C writeback conversion,
2536 /// used for parameter passing when performing automatic reference counting.
2537 ///
2538 /// \param FromType The type we're converting form.
2539 ///
2540 /// \param ToType The type we're converting to.
2541 ///
2542 /// \param ConvertedType The type that will be produced after applying
2543 /// this conversion.
2544 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2545                                      QualType &ConvertedType) {
2546   if (!getLangOpts().ObjCAutoRefCount ||
2547       Context.hasSameUnqualifiedType(FromType, ToType))
2548     return false;
2549 
2550   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2551   QualType ToPointee;
2552   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2553     ToPointee = ToPointer->getPointeeType();
2554   else
2555     return false;
2556 
2557   Qualifiers ToQuals = ToPointee.getQualifiers();
2558   if (!ToPointee->isObjCLifetimeType() ||
2559       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2560       !ToQuals.withoutObjCLifetime().empty())
2561     return false;
2562 
2563   // Argument must be a pointer to __strong to __weak.
2564   QualType FromPointee;
2565   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2566     FromPointee = FromPointer->getPointeeType();
2567   else
2568     return false;
2569 
2570   Qualifiers FromQuals = FromPointee.getQualifiers();
2571   if (!FromPointee->isObjCLifetimeType() ||
2572       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2573        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2574     return false;
2575 
2576   // Make sure that we have compatible qualifiers.
2577   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2578   if (!ToQuals.compatiblyIncludes(FromQuals))
2579     return false;
2580 
2581   // Remove qualifiers from the pointee type we're converting from; they
2582   // aren't used in the compatibility check belong, and we'll be adding back
2583   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2584   FromPointee = FromPointee.getUnqualifiedType();
2585 
2586   // The unqualified form of the pointee types must be compatible.
2587   ToPointee = ToPointee.getUnqualifiedType();
2588   bool IncompatibleObjC;
2589   if (Context.typesAreCompatible(FromPointee, ToPointee))
2590     FromPointee = ToPointee;
2591   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2592                                     IncompatibleObjC))
2593     return false;
2594 
2595   /// \brief Construct the type we're converting to, which is a pointer to
2596   /// __autoreleasing pointee.
2597   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2598   ConvertedType = Context.getPointerType(FromPointee);
2599   return true;
2600 }
2601 
2602 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2603                                     QualType& ConvertedType) {
2604   QualType ToPointeeType;
2605   if (const BlockPointerType *ToBlockPtr =
2606         ToType->getAs<BlockPointerType>())
2607     ToPointeeType = ToBlockPtr->getPointeeType();
2608   else
2609     return false;
2610 
2611   QualType FromPointeeType;
2612   if (const BlockPointerType *FromBlockPtr =
2613       FromType->getAs<BlockPointerType>())
2614     FromPointeeType = FromBlockPtr->getPointeeType();
2615   else
2616     return false;
2617   // We have pointer to blocks, check whether the only
2618   // differences in the argument and result types are in Objective-C
2619   // pointer conversions. If so, we permit the conversion.
2620 
2621   const FunctionProtoType *FromFunctionType
2622     = FromPointeeType->getAs<FunctionProtoType>();
2623   const FunctionProtoType *ToFunctionType
2624     = ToPointeeType->getAs<FunctionProtoType>();
2625 
2626   if (!FromFunctionType || !ToFunctionType)
2627     return false;
2628 
2629   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2630     return true;
2631 
2632   // Perform the quick checks that will tell us whether these
2633   // function types are obviously different.
2634   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2635       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2636     return false;
2637 
2638   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2639   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2640   if (FromEInfo != ToEInfo)
2641     return false;
2642 
2643   bool IncompatibleObjC = false;
2644   if (Context.hasSameType(FromFunctionType->getReturnType(),
2645                           ToFunctionType->getReturnType())) {
2646     // Okay, the types match exactly. Nothing to do.
2647   } else {
2648     QualType RHS = FromFunctionType->getReturnType();
2649     QualType LHS = ToFunctionType->getReturnType();
2650     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2651         !RHS.hasQualifiers() && LHS.hasQualifiers())
2652        LHS = LHS.getUnqualifiedType();
2653 
2654      if (Context.hasSameType(RHS,LHS)) {
2655        // OK exact match.
2656      } else if (isObjCPointerConversion(RHS, LHS,
2657                                         ConvertedType, IncompatibleObjC)) {
2658      if (IncompatibleObjC)
2659        return false;
2660      // Okay, we have an Objective-C pointer conversion.
2661      }
2662      else
2663        return false;
2664    }
2665 
2666    // Check argument types.
2667    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2668         ArgIdx != NumArgs; ++ArgIdx) {
2669      IncompatibleObjC = false;
2670      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2671      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2672      if (Context.hasSameType(FromArgType, ToArgType)) {
2673        // Okay, the types match exactly. Nothing to do.
2674      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2675                                         ConvertedType, IncompatibleObjC)) {
2676        if (IncompatibleObjC)
2677          return false;
2678        // Okay, we have an Objective-C pointer conversion.
2679      } else
2680        // Argument types are too different. Abort.
2681        return false;
2682    }
2683 
2684    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2685    bool CanUseToFPT, CanUseFromFPT;
2686    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2687                                       CanUseToFPT, CanUseFromFPT,
2688                                       NewParamInfos))
2689      return false;
2690 
2691    ConvertedType = ToType;
2692    return true;
2693 }
2694 
2695 enum {
2696   ft_default,
2697   ft_different_class,
2698   ft_parameter_arity,
2699   ft_parameter_mismatch,
2700   ft_return_type,
2701   ft_qualifer_mismatch,
2702   ft_noexcept
2703 };
2704 
2705 /// Attempts to get the FunctionProtoType from a Type. Handles
2706 /// MemberFunctionPointers properly.
2707 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2708   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2709     return FPT;
2710 
2711   if (auto *MPT = FromType->getAs<MemberPointerType>())
2712     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2713 
2714   return nullptr;
2715 }
2716 
2717 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2718 /// function types.  Catches different number of parameter, mismatch in
2719 /// parameter types, and different return types.
2720 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2721                                       QualType FromType, QualType ToType) {
2722   // If either type is not valid, include no extra info.
2723   if (FromType.isNull() || ToType.isNull()) {
2724     PDiag << ft_default;
2725     return;
2726   }
2727 
2728   // Get the function type from the pointers.
2729   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2730     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2731                             *ToMember = ToType->getAs<MemberPointerType>();
2732     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2733       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2734             << QualType(FromMember->getClass(), 0);
2735       return;
2736     }
2737     FromType = FromMember->getPointeeType();
2738     ToType = ToMember->getPointeeType();
2739   }
2740 
2741   if (FromType->isPointerType())
2742     FromType = FromType->getPointeeType();
2743   if (ToType->isPointerType())
2744     ToType = ToType->getPointeeType();
2745 
2746   // Remove references.
2747   FromType = FromType.getNonReferenceType();
2748   ToType = ToType.getNonReferenceType();
2749 
2750   // Don't print extra info for non-specialized template functions.
2751   if (FromType->isInstantiationDependentType() &&
2752       !FromType->getAs<TemplateSpecializationType>()) {
2753     PDiag << ft_default;
2754     return;
2755   }
2756 
2757   // No extra info for same types.
2758   if (Context.hasSameType(FromType, ToType)) {
2759     PDiag << ft_default;
2760     return;
2761   }
2762 
2763   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2764                           *ToFunction = tryGetFunctionProtoType(ToType);
2765 
2766   // Both types need to be function types.
2767   if (!FromFunction || !ToFunction) {
2768     PDiag << ft_default;
2769     return;
2770   }
2771 
2772   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2773     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2774           << FromFunction->getNumParams();
2775     return;
2776   }
2777 
2778   // Handle different parameter types.
2779   unsigned ArgPos;
2780   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2781     PDiag << ft_parameter_mismatch << ArgPos + 1
2782           << ToFunction->getParamType(ArgPos)
2783           << FromFunction->getParamType(ArgPos);
2784     return;
2785   }
2786 
2787   // Handle different return type.
2788   if (!Context.hasSameType(FromFunction->getReturnType(),
2789                            ToFunction->getReturnType())) {
2790     PDiag << ft_return_type << ToFunction->getReturnType()
2791           << FromFunction->getReturnType();
2792     return;
2793   }
2794 
2795   unsigned FromQuals = FromFunction->getTypeQuals(),
2796            ToQuals = ToFunction->getTypeQuals();
2797   if (FromQuals != ToQuals) {
2798     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2799     return;
2800   }
2801 
2802   // Handle exception specification differences on canonical type (in C++17
2803   // onwards).
2804   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2805           ->isNothrow(Context) !=
2806       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2807           ->isNothrow(Context)) {
2808     PDiag << ft_noexcept;
2809     return;
2810   }
2811 
2812   // Unable to find a difference, so add no extra info.
2813   PDiag << ft_default;
2814 }
2815 
2816 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2817 /// for equality of their argument types. Caller has already checked that
2818 /// they have same number of arguments.  If the parameters are different,
2819 /// ArgPos will have the parameter index of the first different parameter.
2820 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2821                                       const FunctionProtoType *NewType,
2822                                       unsigned *ArgPos) {
2823   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2824                                               N = NewType->param_type_begin(),
2825                                               E = OldType->param_type_end();
2826        O && (O != E); ++O, ++N) {
2827     if (!Context.hasSameType(O->getUnqualifiedType(),
2828                              N->getUnqualifiedType())) {
2829       if (ArgPos)
2830         *ArgPos = O - OldType->param_type_begin();
2831       return false;
2832     }
2833   }
2834   return true;
2835 }
2836 
2837 /// CheckPointerConversion - Check the pointer conversion from the
2838 /// expression From to the type ToType. This routine checks for
2839 /// ambiguous or inaccessible derived-to-base pointer
2840 /// conversions for which IsPointerConversion has already returned
2841 /// true. It returns true and produces a diagnostic if there was an
2842 /// error, or returns false otherwise.
2843 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2844                                   CastKind &Kind,
2845                                   CXXCastPath& BasePath,
2846                                   bool IgnoreBaseAccess,
2847                                   bool Diagnose) {
2848   QualType FromType = From->getType();
2849   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2850 
2851   Kind = CK_BitCast;
2852 
2853   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2854       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2855           Expr::NPCK_ZeroExpression) {
2856     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2857       DiagRuntimeBehavior(From->getExprLoc(), From,
2858                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2859                             << ToType << From->getSourceRange());
2860     else if (!isUnevaluatedContext())
2861       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2862         << ToType << From->getSourceRange();
2863   }
2864   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2865     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2866       QualType FromPointeeType = FromPtrType->getPointeeType(),
2867                ToPointeeType   = ToPtrType->getPointeeType();
2868 
2869       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2870           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2871         // We must have a derived-to-base conversion. Check an
2872         // ambiguous or inaccessible conversion.
2873         unsigned InaccessibleID = 0;
2874         unsigned AmbigiousID = 0;
2875         if (Diagnose) {
2876           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2877           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2878         }
2879         if (CheckDerivedToBaseConversion(
2880                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2881                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2882                 &BasePath, IgnoreBaseAccess))
2883           return true;
2884 
2885         // The conversion was successful.
2886         Kind = CK_DerivedToBase;
2887       }
2888 
2889       if (Diagnose && !IsCStyleOrFunctionalCast &&
2890           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2891         assert(getLangOpts().MSVCCompat &&
2892                "this should only be possible with MSVCCompat!");
2893         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2894             << From->getSourceRange();
2895       }
2896     }
2897   } else if (const ObjCObjectPointerType *ToPtrType =
2898                ToType->getAs<ObjCObjectPointerType>()) {
2899     if (const ObjCObjectPointerType *FromPtrType =
2900           FromType->getAs<ObjCObjectPointerType>()) {
2901       // Objective-C++ conversions are always okay.
2902       // FIXME: We should have a different class of conversions for the
2903       // Objective-C++ implicit conversions.
2904       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2905         return false;
2906     } else if (FromType->isBlockPointerType()) {
2907       Kind = CK_BlockPointerToObjCPointerCast;
2908     } else {
2909       Kind = CK_CPointerToObjCPointerCast;
2910     }
2911   } else if (ToType->isBlockPointerType()) {
2912     if (!FromType->isBlockPointerType())
2913       Kind = CK_AnyPointerToBlockPointerCast;
2914   }
2915 
2916   // We shouldn't fall into this case unless it's valid for other
2917   // reasons.
2918   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2919     Kind = CK_NullToPointer;
2920 
2921   return false;
2922 }
2923 
2924 /// IsMemberPointerConversion - Determines whether the conversion of the
2925 /// expression From, which has the (possibly adjusted) type FromType, can be
2926 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2927 /// If so, returns true and places the converted type (that might differ from
2928 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2929 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2930                                      QualType ToType,
2931                                      bool InOverloadResolution,
2932                                      QualType &ConvertedType) {
2933   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2934   if (!ToTypePtr)
2935     return false;
2936 
2937   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2938   if (From->isNullPointerConstant(Context,
2939                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2940                                         : Expr::NPC_ValueDependentIsNull)) {
2941     ConvertedType = ToType;
2942     return true;
2943   }
2944 
2945   // Otherwise, both types have to be member pointers.
2946   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2947   if (!FromTypePtr)
2948     return false;
2949 
2950   // A pointer to member of B can be converted to a pointer to member of D,
2951   // where D is derived from B (C++ 4.11p2).
2952   QualType FromClass(FromTypePtr->getClass(), 0);
2953   QualType ToClass(ToTypePtr->getClass(), 0);
2954 
2955   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2956       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2957     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2958                                                  ToClass.getTypePtr());
2959     return true;
2960   }
2961 
2962   return false;
2963 }
2964 
2965 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2966 /// expression From to the type ToType. This routine checks for ambiguous or
2967 /// virtual or inaccessible base-to-derived member pointer conversions
2968 /// for which IsMemberPointerConversion has already returned true. It returns
2969 /// true and produces a diagnostic if there was an error, or returns false
2970 /// otherwise.
2971 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2972                                         CastKind &Kind,
2973                                         CXXCastPath &BasePath,
2974                                         bool IgnoreBaseAccess) {
2975   QualType FromType = From->getType();
2976   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2977   if (!FromPtrType) {
2978     // This must be a null pointer to member pointer conversion
2979     assert(From->isNullPointerConstant(Context,
2980                                        Expr::NPC_ValueDependentIsNull) &&
2981            "Expr must be null pointer constant!");
2982     Kind = CK_NullToMemberPointer;
2983     return false;
2984   }
2985 
2986   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2987   assert(ToPtrType && "No member pointer cast has a target type "
2988                       "that is not a member pointer.");
2989 
2990   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2991   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2992 
2993   // FIXME: What about dependent types?
2994   assert(FromClass->isRecordType() && "Pointer into non-class.");
2995   assert(ToClass->isRecordType() && "Pointer into non-class.");
2996 
2997   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2998                      /*DetectVirtual=*/true);
2999   bool DerivationOkay =
3000       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3001   assert(DerivationOkay &&
3002          "Should not have been called if derivation isn't OK.");
3003   (void)DerivationOkay;
3004 
3005   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3006                                   getUnqualifiedType())) {
3007     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3008     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3009       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3010     return true;
3011   }
3012 
3013   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3014     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3015       << FromClass << ToClass << QualType(VBase, 0)
3016       << From->getSourceRange();
3017     return true;
3018   }
3019 
3020   if (!IgnoreBaseAccess)
3021     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3022                          Paths.front(),
3023                          diag::err_downcast_from_inaccessible_base);
3024 
3025   // Must be a base to derived member conversion.
3026   BuildBasePathArray(Paths, BasePath);
3027   Kind = CK_BaseToDerivedMemberPointer;
3028   return false;
3029 }
3030 
3031 /// Determine whether the lifetime conversion between the two given
3032 /// qualifiers sets is nontrivial.
3033 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3034                                                Qualifiers ToQuals) {
3035   // Converting anything to const __unsafe_unretained is trivial.
3036   if (ToQuals.hasConst() &&
3037       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3038     return false;
3039 
3040   return true;
3041 }
3042 
3043 /// IsQualificationConversion - Determines whether the conversion from
3044 /// an rvalue of type FromType to ToType is a qualification conversion
3045 /// (C++ 4.4).
3046 ///
3047 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3048 /// when the qualification conversion involves a change in the Objective-C
3049 /// object lifetime.
3050 bool
3051 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3052                                 bool CStyle, bool &ObjCLifetimeConversion) {
3053   FromType = Context.getCanonicalType(FromType);
3054   ToType = Context.getCanonicalType(ToType);
3055   ObjCLifetimeConversion = false;
3056 
3057   // If FromType and ToType are the same type, this is not a
3058   // qualification conversion.
3059   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3060     return false;
3061 
3062   // (C++ 4.4p4):
3063   //   A conversion can add cv-qualifiers at levels other than the first
3064   //   in multi-level pointers, subject to the following rules: [...]
3065   bool PreviousToQualsIncludeConst = true;
3066   bool UnwrappedAnyPointer = false;
3067   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3068     // Within each iteration of the loop, we check the qualifiers to
3069     // determine if this still looks like a qualification
3070     // conversion. Then, if all is well, we unwrap one more level of
3071     // pointers or pointers-to-members and do it all again
3072     // until there are no more pointers or pointers-to-members left to
3073     // unwrap.
3074     UnwrappedAnyPointer = true;
3075 
3076     Qualifiers FromQuals = FromType.getQualifiers();
3077     Qualifiers ToQuals = ToType.getQualifiers();
3078 
3079     // Ignore __unaligned qualifier if this type is void.
3080     if (ToType.getUnqualifiedType()->isVoidType())
3081       FromQuals.removeUnaligned();
3082 
3083     // Objective-C ARC:
3084     //   Check Objective-C lifetime conversions.
3085     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3086         UnwrappedAnyPointer) {
3087       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3088         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3089           ObjCLifetimeConversion = true;
3090         FromQuals.removeObjCLifetime();
3091         ToQuals.removeObjCLifetime();
3092       } else {
3093         // Qualification conversions cannot cast between different
3094         // Objective-C lifetime qualifiers.
3095         return false;
3096       }
3097     }
3098 
3099     // Allow addition/removal of GC attributes but not changing GC attributes.
3100     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3101         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3102       FromQuals.removeObjCGCAttr();
3103       ToQuals.removeObjCGCAttr();
3104     }
3105 
3106     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3107     //      2,j, and similarly for volatile.
3108     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3109       return false;
3110 
3111     //   -- if the cv 1,j and cv 2,j are different, then const is in
3112     //      every cv for 0 < k < j.
3113     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3114         && !PreviousToQualsIncludeConst)
3115       return false;
3116 
3117     // Keep track of whether all prior cv-qualifiers in the "to" type
3118     // include const.
3119     PreviousToQualsIncludeConst
3120       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3121   }
3122 
3123   // We are left with FromType and ToType being the pointee types
3124   // after unwrapping the original FromType and ToType the same number
3125   // of types. If we unwrapped any pointers, and if FromType and
3126   // ToType have the same unqualified type (since we checked
3127   // qualifiers above), then this is a qualification conversion.
3128   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3129 }
3130 
3131 /// \brief - Determine whether this is a conversion from a scalar type to an
3132 /// atomic type.
3133 ///
3134 /// If successful, updates \c SCS's second and third steps in the conversion
3135 /// sequence to finish the conversion.
3136 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3137                                 bool InOverloadResolution,
3138                                 StandardConversionSequence &SCS,
3139                                 bool CStyle) {
3140   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3141   if (!ToAtomic)
3142     return false;
3143 
3144   StandardConversionSequence InnerSCS;
3145   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3146                             InOverloadResolution, InnerSCS,
3147                             CStyle, /*AllowObjCWritebackConversion=*/false))
3148     return false;
3149 
3150   SCS.Second = InnerSCS.Second;
3151   SCS.setToType(1, InnerSCS.getToType(1));
3152   SCS.Third = InnerSCS.Third;
3153   SCS.QualificationIncludesObjCLifetime
3154     = InnerSCS.QualificationIncludesObjCLifetime;
3155   SCS.setToType(2, InnerSCS.getToType(2));
3156   return true;
3157 }
3158 
3159 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3160                                               CXXConstructorDecl *Constructor,
3161                                               QualType Type) {
3162   const FunctionProtoType *CtorType =
3163       Constructor->getType()->getAs<FunctionProtoType>();
3164   if (CtorType->getNumParams() > 0) {
3165     QualType FirstArg = CtorType->getParamType(0);
3166     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3167       return true;
3168   }
3169   return false;
3170 }
3171 
3172 static OverloadingResult
3173 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3174                                        CXXRecordDecl *To,
3175                                        UserDefinedConversionSequence &User,
3176                                        OverloadCandidateSet &CandidateSet,
3177                                        bool AllowExplicit) {
3178   for (auto *D : S.LookupConstructors(To)) {
3179     auto Info = getConstructorInfo(D);
3180     if (!Info)
3181       continue;
3182 
3183     bool Usable = !Info.Constructor->isInvalidDecl() &&
3184                   S.isInitListConstructor(Info.Constructor) &&
3185                   (AllowExplicit || !Info.Constructor->isExplicit());
3186     if (Usable) {
3187       // If the first argument is (a reference to) the target type,
3188       // suppress conversions.
3189       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3190           S.Context, Info.Constructor, ToType);
3191       if (Info.ConstructorTmpl)
3192         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3193                                        /*ExplicitArgs*/ nullptr, From,
3194                                        CandidateSet, SuppressUserConversions);
3195       else
3196         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3197                                CandidateSet, SuppressUserConversions);
3198     }
3199   }
3200 
3201   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3202 
3203   OverloadCandidateSet::iterator Best;
3204   switch (auto Result =
3205             CandidateSet.BestViableFunction(S, From->getLocStart(),
3206                                             Best, true)) {
3207   case OR_Deleted:
3208   case OR_Success: {
3209     // Record the standard conversion we used and the conversion function.
3210     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3211     QualType ThisType = Constructor->getThisType(S.Context);
3212     // Initializer lists don't have conversions as such.
3213     User.Before.setAsIdentityConversion();
3214     User.HadMultipleCandidates = HadMultipleCandidates;
3215     User.ConversionFunction = Constructor;
3216     User.FoundConversionFunction = Best->FoundDecl;
3217     User.After.setAsIdentityConversion();
3218     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3219     User.After.setAllToTypes(ToType);
3220     return Result;
3221   }
3222 
3223   case OR_No_Viable_Function:
3224     return OR_No_Viable_Function;
3225   case OR_Ambiguous:
3226     return OR_Ambiguous;
3227   }
3228 
3229   llvm_unreachable("Invalid OverloadResult!");
3230 }
3231 
3232 /// Determines whether there is a user-defined conversion sequence
3233 /// (C++ [over.ics.user]) that converts expression From to the type
3234 /// ToType. If such a conversion exists, User will contain the
3235 /// user-defined conversion sequence that performs such a conversion
3236 /// and this routine will return true. Otherwise, this routine returns
3237 /// false and User is unspecified.
3238 ///
3239 /// \param AllowExplicit  true if the conversion should consider C++0x
3240 /// "explicit" conversion functions as well as non-explicit conversion
3241 /// functions (C++0x [class.conv.fct]p2).
3242 ///
3243 /// \param AllowObjCConversionOnExplicit true if the conversion should
3244 /// allow an extra Objective-C pointer conversion on uses of explicit
3245 /// constructors. Requires \c AllowExplicit to also be set.
3246 static OverloadingResult
3247 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3248                         UserDefinedConversionSequence &User,
3249                         OverloadCandidateSet &CandidateSet,
3250                         bool AllowExplicit,
3251                         bool AllowObjCConversionOnExplicit) {
3252   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3253 
3254   // Whether we will only visit constructors.
3255   bool ConstructorsOnly = false;
3256 
3257   // If the type we are conversion to is a class type, enumerate its
3258   // constructors.
3259   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3260     // C++ [over.match.ctor]p1:
3261     //   When objects of class type are direct-initialized (8.5), or
3262     //   copy-initialized from an expression of the same or a
3263     //   derived class type (8.5), overload resolution selects the
3264     //   constructor. [...] For copy-initialization, the candidate
3265     //   functions are all the converting constructors (12.3.1) of
3266     //   that class. The argument list is the expression-list within
3267     //   the parentheses of the initializer.
3268     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3269         (From->getType()->getAs<RecordType>() &&
3270          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3271       ConstructorsOnly = true;
3272 
3273     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3274       // We're not going to find any constructors.
3275     } else if (CXXRecordDecl *ToRecordDecl
3276                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3277 
3278       Expr **Args = &From;
3279       unsigned NumArgs = 1;
3280       bool ListInitializing = false;
3281       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3282         // But first, see if there is an init-list-constructor that will work.
3283         OverloadingResult Result = IsInitializerListConstructorConversion(
3284             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3285         if (Result != OR_No_Viable_Function)
3286           return Result;
3287         // Never mind.
3288         CandidateSet.clear();
3289 
3290         // If we're list-initializing, we pass the individual elements as
3291         // arguments, not the entire list.
3292         Args = InitList->getInits();
3293         NumArgs = InitList->getNumInits();
3294         ListInitializing = true;
3295       }
3296 
3297       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3298         auto Info = getConstructorInfo(D);
3299         if (!Info)
3300           continue;
3301 
3302         bool Usable = !Info.Constructor->isInvalidDecl();
3303         if (ListInitializing)
3304           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3305         else
3306           Usable = Usable &&
3307                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3308         if (Usable) {
3309           bool SuppressUserConversions = !ConstructorsOnly;
3310           if (SuppressUserConversions && ListInitializing) {
3311             SuppressUserConversions = false;
3312             if (NumArgs == 1) {
3313               // If the first argument is (a reference to) the target type,
3314               // suppress conversions.
3315               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3316                   S.Context, Info.Constructor, ToType);
3317             }
3318           }
3319           if (Info.ConstructorTmpl)
3320             S.AddTemplateOverloadCandidate(
3321                 Info.ConstructorTmpl, Info.FoundDecl,
3322                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3323                 CandidateSet, SuppressUserConversions);
3324           else
3325             // Allow one user-defined conversion when user specifies a
3326             // From->ToType conversion via an static cast (c-style, etc).
3327             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3328                                    llvm::makeArrayRef(Args, NumArgs),
3329                                    CandidateSet, SuppressUserConversions);
3330         }
3331       }
3332     }
3333   }
3334 
3335   // Enumerate conversion functions, if we're allowed to.
3336   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3337   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3338     // No conversion functions from incomplete types.
3339   } else if (const RecordType *FromRecordType
3340                                    = From->getType()->getAs<RecordType>()) {
3341     if (CXXRecordDecl *FromRecordDecl
3342          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3343       // Add all of the conversion functions as candidates.
3344       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3345       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3346         DeclAccessPair FoundDecl = I.getPair();
3347         NamedDecl *D = FoundDecl.getDecl();
3348         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3349         if (isa<UsingShadowDecl>(D))
3350           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3351 
3352         CXXConversionDecl *Conv;
3353         FunctionTemplateDecl *ConvTemplate;
3354         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3355           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3356         else
3357           Conv = cast<CXXConversionDecl>(D);
3358 
3359         if (AllowExplicit || !Conv->isExplicit()) {
3360           if (ConvTemplate)
3361             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3362                                              ActingContext, From, ToType,
3363                                              CandidateSet,
3364                                              AllowObjCConversionOnExplicit);
3365           else
3366             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3367                                      From, ToType, CandidateSet,
3368                                      AllowObjCConversionOnExplicit);
3369         }
3370       }
3371     }
3372   }
3373 
3374   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3375 
3376   OverloadCandidateSet::iterator Best;
3377   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3378                                                         Best, true)) {
3379   case OR_Success:
3380   case OR_Deleted:
3381     // Record the standard conversion we used and the conversion function.
3382     if (CXXConstructorDecl *Constructor
3383           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3384       // C++ [over.ics.user]p1:
3385       //   If the user-defined conversion is specified by a
3386       //   constructor (12.3.1), the initial standard conversion
3387       //   sequence converts the source type to the type required by
3388       //   the argument of the constructor.
3389       //
3390       QualType ThisType = Constructor->getThisType(S.Context);
3391       if (isa<InitListExpr>(From)) {
3392         // Initializer lists don't have conversions as such.
3393         User.Before.setAsIdentityConversion();
3394       } else {
3395         if (Best->Conversions[0].isEllipsis())
3396           User.EllipsisConversion = true;
3397         else {
3398           User.Before = Best->Conversions[0].Standard;
3399           User.EllipsisConversion = false;
3400         }
3401       }
3402       User.HadMultipleCandidates = HadMultipleCandidates;
3403       User.ConversionFunction = Constructor;
3404       User.FoundConversionFunction = Best->FoundDecl;
3405       User.After.setAsIdentityConversion();
3406       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3407       User.After.setAllToTypes(ToType);
3408       return Result;
3409     }
3410     if (CXXConversionDecl *Conversion
3411                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3412       // C++ [over.ics.user]p1:
3413       //
3414       //   [...] If the user-defined conversion is specified by a
3415       //   conversion function (12.3.2), the initial standard
3416       //   conversion sequence converts the source type to the
3417       //   implicit object parameter of the conversion function.
3418       User.Before = Best->Conversions[0].Standard;
3419       User.HadMultipleCandidates = HadMultipleCandidates;
3420       User.ConversionFunction = Conversion;
3421       User.FoundConversionFunction = Best->FoundDecl;
3422       User.EllipsisConversion = false;
3423 
3424       // C++ [over.ics.user]p2:
3425       //   The second standard conversion sequence converts the
3426       //   result of the user-defined conversion to the target type
3427       //   for the sequence. Since an implicit conversion sequence
3428       //   is an initialization, the special rules for
3429       //   initialization by user-defined conversion apply when
3430       //   selecting the best user-defined conversion for a
3431       //   user-defined conversion sequence (see 13.3.3 and
3432       //   13.3.3.1).
3433       User.After = Best->FinalConversion;
3434       return Result;
3435     }
3436     llvm_unreachable("Not a constructor or conversion function?");
3437 
3438   case OR_No_Viable_Function:
3439     return OR_No_Viable_Function;
3440 
3441   case OR_Ambiguous:
3442     return OR_Ambiguous;
3443   }
3444 
3445   llvm_unreachable("Invalid OverloadResult!");
3446 }
3447 
3448 bool
3449 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3450   ImplicitConversionSequence ICS;
3451   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3452                                     OverloadCandidateSet::CSK_Normal);
3453   OverloadingResult OvResult =
3454     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3455                             CandidateSet, false, false);
3456   if (OvResult == OR_Ambiguous)
3457     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3458         << From->getType() << ToType << From->getSourceRange();
3459   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3460     if (!RequireCompleteType(From->getLocStart(), ToType,
3461                              diag::err_typecheck_nonviable_condition_incomplete,
3462                              From->getType(), From->getSourceRange()))
3463       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3464           << false << From->getType() << From->getSourceRange() << ToType;
3465   } else
3466     return false;
3467   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3468   return true;
3469 }
3470 
3471 /// \brief Compare the user-defined conversion functions or constructors
3472 /// of two user-defined conversion sequences to determine whether any ordering
3473 /// is possible.
3474 static ImplicitConversionSequence::CompareKind
3475 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3476                            FunctionDecl *Function2) {
3477   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3478     return ImplicitConversionSequence::Indistinguishable;
3479 
3480   // Objective-C++:
3481   //   If both conversion functions are implicitly-declared conversions from
3482   //   a lambda closure type to a function pointer and a block pointer,
3483   //   respectively, always prefer the conversion to a function pointer,
3484   //   because the function pointer is more lightweight and is more likely
3485   //   to keep code working.
3486   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3487   if (!Conv1)
3488     return ImplicitConversionSequence::Indistinguishable;
3489 
3490   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3491   if (!Conv2)
3492     return ImplicitConversionSequence::Indistinguishable;
3493 
3494   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3495     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3496     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3497     if (Block1 != Block2)
3498       return Block1 ? ImplicitConversionSequence::Worse
3499                     : ImplicitConversionSequence::Better;
3500   }
3501 
3502   return ImplicitConversionSequence::Indistinguishable;
3503 }
3504 
3505 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3506     const ImplicitConversionSequence &ICS) {
3507   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3508          (ICS.isUserDefined() &&
3509           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3510 }
3511 
3512 /// CompareImplicitConversionSequences - Compare two implicit
3513 /// conversion sequences to determine whether one is better than the
3514 /// other or if they are indistinguishable (C++ 13.3.3.2).
3515 static ImplicitConversionSequence::CompareKind
3516 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3517                                    const ImplicitConversionSequence& ICS1,
3518                                    const ImplicitConversionSequence& ICS2)
3519 {
3520   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3521   // conversion sequences (as defined in 13.3.3.1)
3522   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3523   //      conversion sequence than a user-defined conversion sequence or
3524   //      an ellipsis conversion sequence, and
3525   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3526   //      conversion sequence than an ellipsis conversion sequence
3527   //      (13.3.3.1.3).
3528   //
3529   // C++0x [over.best.ics]p10:
3530   //   For the purpose of ranking implicit conversion sequences as
3531   //   described in 13.3.3.2, the ambiguous conversion sequence is
3532   //   treated as a user-defined sequence that is indistinguishable
3533   //   from any other user-defined conversion sequence.
3534 
3535   // String literal to 'char *' conversion has been deprecated in C++03. It has
3536   // been removed from C++11. We still accept this conversion, if it happens at
3537   // the best viable function. Otherwise, this conversion is considered worse
3538   // than ellipsis conversion. Consider this as an extension; this is not in the
3539   // standard. For example:
3540   //
3541   // int &f(...);    // #1
3542   // void f(char*);  // #2
3543   // void g() { int &r = f("foo"); }
3544   //
3545   // In C++03, we pick #2 as the best viable function.
3546   // In C++11, we pick #1 as the best viable function, because ellipsis
3547   // conversion is better than string-literal to char* conversion (since there
3548   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3549   // convert arguments, #2 would be the best viable function in C++11.
3550   // If the best viable function has this conversion, a warning will be issued
3551   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3552 
3553   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3554       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3555       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3556     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3557                ? ImplicitConversionSequence::Worse
3558                : ImplicitConversionSequence::Better;
3559 
3560   if (ICS1.getKindRank() < ICS2.getKindRank())
3561     return ImplicitConversionSequence::Better;
3562   if (ICS2.getKindRank() < ICS1.getKindRank())
3563     return ImplicitConversionSequence::Worse;
3564 
3565   // The following checks require both conversion sequences to be of
3566   // the same kind.
3567   if (ICS1.getKind() != ICS2.getKind())
3568     return ImplicitConversionSequence::Indistinguishable;
3569 
3570   ImplicitConversionSequence::CompareKind Result =
3571       ImplicitConversionSequence::Indistinguishable;
3572 
3573   // Two implicit conversion sequences of the same form are
3574   // indistinguishable conversion sequences unless one of the
3575   // following rules apply: (C++ 13.3.3.2p3):
3576 
3577   // List-initialization sequence L1 is a better conversion sequence than
3578   // list-initialization sequence L2 if:
3579   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3580   //   if not that,
3581   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3582   //   and N1 is smaller than N2.,
3583   // even if one of the other rules in this paragraph would otherwise apply.
3584   if (!ICS1.isBad()) {
3585     if (ICS1.isStdInitializerListElement() &&
3586         !ICS2.isStdInitializerListElement())
3587       return ImplicitConversionSequence::Better;
3588     if (!ICS1.isStdInitializerListElement() &&
3589         ICS2.isStdInitializerListElement())
3590       return ImplicitConversionSequence::Worse;
3591   }
3592 
3593   if (ICS1.isStandard())
3594     // Standard conversion sequence S1 is a better conversion sequence than
3595     // standard conversion sequence S2 if [...]
3596     Result = CompareStandardConversionSequences(S, Loc,
3597                                                 ICS1.Standard, ICS2.Standard);
3598   else if (ICS1.isUserDefined()) {
3599     // User-defined conversion sequence U1 is a better conversion
3600     // sequence than another user-defined conversion sequence U2 if
3601     // they contain the same user-defined conversion function or
3602     // constructor and if the second standard conversion sequence of
3603     // U1 is better than the second standard conversion sequence of
3604     // U2 (C++ 13.3.3.2p3).
3605     if (ICS1.UserDefined.ConversionFunction ==
3606           ICS2.UserDefined.ConversionFunction)
3607       Result = CompareStandardConversionSequences(S, Loc,
3608                                                   ICS1.UserDefined.After,
3609                                                   ICS2.UserDefined.After);
3610     else
3611       Result = compareConversionFunctions(S,
3612                                           ICS1.UserDefined.ConversionFunction,
3613                                           ICS2.UserDefined.ConversionFunction);
3614   }
3615 
3616   return Result;
3617 }
3618 
3619 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3620   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3621     Qualifiers Quals;
3622     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3623     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3624   }
3625 
3626   return Context.hasSameUnqualifiedType(T1, T2);
3627 }
3628 
3629 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3630 // determine if one is a proper subset of the other.
3631 static ImplicitConversionSequence::CompareKind
3632 compareStandardConversionSubsets(ASTContext &Context,
3633                                  const StandardConversionSequence& SCS1,
3634                                  const StandardConversionSequence& SCS2) {
3635   ImplicitConversionSequence::CompareKind Result
3636     = ImplicitConversionSequence::Indistinguishable;
3637 
3638   // the identity conversion sequence is considered to be a subsequence of
3639   // any non-identity conversion sequence
3640   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3641     return ImplicitConversionSequence::Better;
3642   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3643     return ImplicitConversionSequence::Worse;
3644 
3645   if (SCS1.Second != SCS2.Second) {
3646     if (SCS1.Second == ICK_Identity)
3647       Result = ImplicitConversionSequence::Better;
3648     else if (SCS2.Second == ICK_Identity)
3649       Result = ImplicitConversionSequence::Worse;
3650     else
3651       return ImplicitConversionSequence::Indistinguishable;
3652   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3653     return ImplicitConversionSequence::Indistinguishable;
3654 
3655   if (SCS1.Third == SCS2.Third) {
3656     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3657                              : ImplicitConversionSequence::Indistinguishable;
3658   }
3659 
3660   if (SCS1.Third == ICK_Identity)
3661     return Result == ImplicitConversionSequence::Worse
3662              ? ImplicitConversionSequence::Indistinguishable
3663              : ImplicitConversionSequence::Better;
3664 
3665   if (SCS2.Third == ICK_Identity)
3666     return Result == ImplicitConversionSequence::Better
3667              ? ImplicitConversionSequence::Indistinguishable
3668              : ImplicitConversionSequence::Worse;
3669 
3670   return ImplicitConversionSequence::Indistinguishable;
3671 }
3672 
3673 /// \brief Determine whether one of the given reference bindings is better
3674 /// than the other based on what kind of bindings they are.
3675 static bool
3676 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3677                              const StandardConversionSequence &SCS2) {
3678   // C++0x [over.ics.rank]p3b4:
3679   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3680   //      implicit object parameter of a non-static member function declared
3681   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3682   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3683   //      lvalue reference to a function lvalue and S2 binds an rvalue
3684   //      reference*.
3685   //
3686   // FIXME: Rvalue references. We're going rogue with the above edits,
3687   // because the semantics in the current C++0x working paper (N3225 at the
3688   // time of this writing) break the standard definition of std::forward
3689   // and std::reference_wrapper when dealing with references to functions.
3690   // Proposed wording changes submitted to CWG for consideration.
3691   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3692       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3693     return false;
3694 
3695   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3696           SCS2.IsLvalueReference) ||
3697          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3698           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3699 }
3700 
3701 /// CompareStandardConversionSequences - Compare two standard
3702 /// conversion sequences to determine whether one is better than the
3703 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3704 static ImplicitConversionSequence::CompareKind
3705 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3706                                    const StandardConversionSequence& SCS1,
3707                                    const StandardConversionSequence& SCS2)
3708 {
3709   // Standard conversion sequence S1 is a better conversion sequence
3710   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3711 
3712   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3713   //     sequences in the canonical form defined by 13.3.3.1.1,
3714   //     excluding any Lvalue Transformation; the identity conversion
3715   //     sequence is considered to be a subsequence of any
3716   //     non-identity conversion sequence) or, if not that,
3717   if (ImplicitConversionSequence::CompareKind CK
3718         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3719     return CK;
3720 
3721   //  -- the rank of S1 is better than the rank of S2 (by the rules
3722   //     defined below), or, if not that,
3723   ImplicitConversionRank Rank1 = SCS1.getRank();
3724   ImplicitConversionRank Rank2 = SCS2.getRank();
3725   if (Rank1 < Rank2)
3726     return ImplicitConversionSequence::Better;
3727   else if (Rank2 < Rank1)
3728     return ImplicitConversionSequence::Worse;
3729 
3730   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3731   // are indistinguishable unless one of the following rules
3732   // applies:
3733 
3734   //   A conversion that is not a conversion of a pointer, or
3735   //   pointer to member, to bool is better than another conversion
3736   //   that is such a conversion.
3737   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3738     return SCS2.isPointerConversionToBool()
3739              ? ImplicitConversionSequence::Better
3740              : ImplicitConversionSequence::Worse;
3741 
3742   // C++ [over.ics.rank]p4b2:
3743   //
3744   //   If class B is derived directly or indirectly from class A,
3745   //   conversion of B* to A* is better than conversion of B* to
3746   //   void*, and conversion of A* to void* is better than conversion
3747   //   of B* to void*.
3748   bool SCS1ConvertsToVoid
3749     = SCS1.isPointerConversionToVoidPointer(S.Context);
3750   bool SCS2ConvertsToVoid
3751     = SCS2.isPointerConversionToVoidPointer(S.Context);
3752   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3753     // Exactly one of the conversion sequences is a conversion to
3754     // a void pointer; it's the worse conversion.
3755     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3756                               : ImplicitConversionSequence::Worse;
3757   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3758     // Neither conversion sequence converts to a void pointer; compare
3759     // their derived-to-base conversions.
3760     if (ImplicitConversionSequence::CompareKind DerivedCK
3761           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3762       return DerivedCK;
3763   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3764              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3765     // Both conversion sequences are conversions to void
3766     // pointers. Compare the source types to determine if there's an
3767     // inheritance relationship in their sources.
3768     QualType FromType1 = SCS1.getFromType();
3769     QualType FromType2 = SCS2.getFromType();
3770 
3771     // Adjust the types we're converting from via the array-to-pointer
3772     // conversion, if we need to.
3773     if (SCS1.First == ICK_Array_To_Pointer)
3774       FromType1 = S.Context.getArrayDecayedType(FromType1);
3775     if (SCS2.First == ICK_Array_To_Pointer)
3776       FromType2 = S.Context.getArrayDecayedType(FromType2);
3777 
3778     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3779     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3780 
3781     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3782       return ImplicitConversionSequence::Better;
3783     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3784       return ImplicitConversionSequence::Worse;
3785 
3786     // Objective-C++: If one interface is more specific than the
3787     // other, it is the better one.
3788     const ObjCObjectPointerType* FromObjCPtr1
3789       = FromType1->getAs<ObjCObjectPointerType>();
3790     const ObjCObjectPointerType* FromObjCPtr2
3791       = FromType2->getAs<ObjCObjectPointerType>();
3792     if (FromObjCPtr1 && FromObjCPtr2) {
3793       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3794                                                           FromObjCPtr2);
3795       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3796                                                            FromObjCPtr1);
3797       if (AssignLeft != AssignRight) {
3798         return AssignLeft? ImplicitConversionSequence::Better
3799                          : ImplicitConversionSequence::Worse;
3800       }
3801     }
3802   }
3803 
3804   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3805   // bullet 3).
3806   if (ImplicitConversionSequence::CompareKind QualCK
3807         = CompareQualificationConversions(S, SCS1, SCS2))
3808     return QualCK;
3809 
3810   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3811     // Check for a better reference binding based on the kind of bindings.
3812     if (isBetterReferenceBindingKind(SCS1, SCS2))
3813       return ImplicitConversionSequence::Better;
3814     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3815       return ImplicitConversionSequence::Worse;
3816 
3817     // C++ [over.ics.rank]p3b4:
3818     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3819     //      which the references refer are the same type except for
3820     //      top-level cv-qualifiers, and the type to which the reference
3821     //      initialized by S2 refers is more cv-qualified than the type
3822     //      to which the reference initialized by S1 refers.
3823     QualType T1 = SCS1.getToType(2);
3824     QualType T2 = SCS2.getToType(2);
3825     T1 = S.Context.getCanonicalType(T1);
3826     T2 = S.Context.getCanonicalType(T2);
3827     Qualifiers T1Quals, T2Quals;
3828     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3829     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3830     if (UnqualT1 == UnqualT2) {
3831       // Objective-C++ ARC: If the references refer to objects with different
3832       // lifetimes, prefer bindings that don't change lifetime.
3833       if (SCS1.ObjCLifetimeConversionBinding !=
3834                                           SCS2.ObjCLifetimeConversionBinding) {
3835         return SCS1.ObjCLifetimeConversionBinding
3836                                            ? ImplicitConversionSequence::Worse
3837                                            : ImplicitConversionSequence::Better;
3838       }
3839 
3840       // If the type is an array type, promote the element qualifiers to the
3841       // type for comparison.
3842       if (isa<ArrayType>(T1) && T1Quals)
3843         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3844       if (isa<ArrayType>(T2) && T2Quals)
3845         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3846       if (T2.isMoreQualifiedThan(T1))
3847         return ImplicitConversionSequence::Better;
3848       else if (T1.isMoreQualifiedThan(T2))
3849         return ImplicitConversionSequence::Worse;
3850     }
3851   }
3852 
3853   // In Microsoft mode, prefer an integral conversion to a
3854   // floating-to-integral conversion if the integral conversion
3855   // is between types of the same size.
3856   // For example:
3857   // void f(float);
3858   // void f(int);
3859   // int main {
3860   //    long a;
3861   //    f(a);
3862   // }
3863   // Here, MSVC will call f(int) instead of generating a compile error
3864   // as clang will do in standard mode.
3865   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3866       SCS2.Second == ICK_Floating_Integral &&
3867       S.Context.getTypeSize(SCS1.getFromType()) ==
3868           S.Context.getTypeSize(SCS1.getToType(2)))
3869     return ImplicitConversionSequence::Better;
3870 
3871   return ImplicitConversionSequence::Indistinguishable;
3872 }
3873 
3874 /// CompareQualificationConversions - Compares two standard conversion
3875 /// sequences to determine whether they can be ranked based on their
3876 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3877 static ImplicitConversionSequence::CompareKind
3878 CompareQualificationConversions(Sema &S,
3879                                 const StandardConversionSequence& SCS1,
3880                                 const StandardConversionSequence& SCS2) {
3881   // C++ 13.3.3.2p3:
3882   //  -- S1 and S2 differ only in their qualification conversion and
3883   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3884   //     cv-qualification signature of type T1 is a proper subset of
3885   //     the cv-qualification signature of type T2, and S1 is not the
3886   //     deprecated string literal array-to-pointer conversion (4.2).
3887   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3888       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3889     return ImplicitConversionSequence::Indistinguishable;
3890 
3891   // FIXME: the example in the standard doesn't use a qualification
3892   // conversion (!)
3893   QualType T1 = SCS1.getToType(2);
3894   QualType T2 = SCS2.getToType(2);
3895   T1 = S.Context.getCanonicalType(T1);
3896   T2 = S.Context.getCanonicalType(T2);
3897   Qualifiers T1Quals, T2Quals;
3898   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3899   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3900 
3901   // If the types are the same, we won't learn anything by unwrapped
3902   // them.
3903   if (UnqualT1 == UnqualT2)
3904     return ImplicitConversionSequence::Indistinguishable;
3905 
3906   // If the type is an array type, promote the element qualifiers to the type
3907   // for comparison.
3908   if (isa<ArrayType>(T1) && T1Quals)
3909     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3910   if (isa<ArrayType>(T2) && T2Quals)
3911     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3912 
3913   ImplicitConversionSequence::CompareKind Result
3914     = ImplicitConversionSequence::Indistinguishable;
3915 
3916   // Objective-C++ ARC:
3917   //   Prefer qualification conversions not involving a change in lifetime
3918   //   to qualification conversions that do not change lifetime.
3919   if (SCS1.QualificationIncludesObjCLifetime !=
3920                                       SCS2.QualificationIncludesObjCLifetime) {
3921     Result = SCS1.QualificationIncludesObjCLifetime
3922                ? ImplicitConversionSequence::Worse
3923                : ImplicitConversionSequence::Better;
3924   }
3925 
3926   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3927     // Within each iteration of the loop, we check the qualifiers to
3928     // determine if this still looks like a qualification
3929     // conversion. Then, if all is well, we unwrap one more level of
3930     // pointers or pointers-to-members and do it all again
3931     // until there are no more pointers or pointers-to-members left
3932     // to unwrap. This essentially mimics what
3933     // IsQualificationConversion does, but here we're checking for a
3934     // strict subset of qualifiers.
3935     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3936       // The qualifiers are the same, so this doesn't tell us anything
3937       // about how the sequences rank.
3938       ;
3939     else if (T2.isMoreQualifiedThan(T1)) {
3940       // T1 has fewer qualifiers, so it could be the better sequence.
3941       if (Result == ImplicitConversionSequence::Worse)
3942         // Neither has qualifiers that are a subset of the other's
3943         // qualifiers.
3944         return ImplicitConversionSequence::Indistinguishable;
3945 
3946       Result = ImplicitConversionSequence::Better;
3947     } else if (T1.isMoreQualifiedThan(T2)) {
3948       // T2 has fewer qualifiers, so it could be the better sequence.
3949       if (Result == ImplicitConversionSequence::Better)
3950         // Neither has qualifiers that are a subset of the other's
3951         // qualifiers.
3952         return ImplicitConversionSequence::Indistinguishable;
3953 
3954       Result = ImplicitConversionSequence::Worse;
3955     } else {
3956       // Qualifiers are disjoint.
3957       return ImplicitConversionSequence::Indistinguishable;
3958     }
3959 
3960     // If the types after this point are equivalent, we're done.
3961     if (S.Context.hasSameUnqualifiedType(T1, T2))
3962       break;
3963   }
3964 
3965   // Check that the winning standard conversion sequence isn't using
3966   // the deprecated string literal array to pointer conversion.
3967   switch (Result) {
3968   case ImplicitConversionSequence::Better:
3969     if (SCS1.DeprecatedStringLiteralToCharPtr)
3970       Result = ImplicitConversionSequence::Indistinguishable;
3971     break;
3972 
3973   case ImplicitConversionSequence::Indistinguishable:
3974     break;
3975 
3976   case ImplicitConversionSequence::Worse:
3977     if (SCS2.DeprecatedStringLiteralToCharPtr)
3978       Result = ImplicitConversionSequence::Indistinguishable;
3979     break;
3980   }
3981 
3982   return Result;
3983 }
3984 
3985 /// CompareDerivedToBaseConversions - Compares two standard conversion
3986 /// sequences to determine whether they can be ranked based on their
3987 /// various kinds of derived-to-base conversions (C++
3988 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3989 /// conversions between Objective-C interface types.
3990 static ImplicitConversionSequence::CompareKind
3991 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3992                                 const StandardConversionSequence& SCS1,
3993                                 const StandardConversionSequence& SCS2) {
3994   QualType FromType1 = SCS1.getFromType();
3995   QualType ToType1 = SCS1.getToType(1);
3996   QualType FromType2 = SCS2.getFromType();
3997   QualType ToType2 = SCS2.getToType(1);
3998 
3999   // Adjust the types we're converting from via the array-to-pointer
4000   // conversion, if we need to.
4001   if (SCS1.First == ICK_Array_To_Pointer)
4002     FromType1 = S.Context.getArrayDecayedType(FromType1);
4003   if (SCS2.First == ICK_Array_To_Pointer)
4004     FromType2 = S.Context.getArrayDecayedType(FromType2);
4005 
4006   // Canonicalize all of the types.
4007   FromType1 = S.Context.getCanonicalType(FromType1);
4008   ToType1 = S.Context.getCanonicalType(ToType1);
4009   FromType2 = S.Context.getCanonicalType(FromType2);
4010   ToType2 = S.Context.getCanonicalType(ToType2);
4011 
4012   // C++ [over.ics.rank]p4b3:
4013   //
4014   //   If class B is derived directly or indirectly from class A and
4015   //   class C is derived directly or indirectly from B,
4016   //
4017   // Compare based on pointer conversions.
4018   if (SCS1.Second == ICK_Pointer_Conversion &&
4019       SCS2.Second == ICK_Pointer_Conversion &&
4020       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4021       FromType1->isPointerType() && FromType2->isPointerType() &&
4022       ToType1->isPointerType() && ToType2->isPointerType()) {
4023     QualType FromPointee1
4024       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4025     QualType ToPointee1
4026       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4027     QualType FromPointee2
4028       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4029     QualType ToPointee2
4030       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4031 
4032     //   -- conversion of C* to B* is better than conversion of C* to A*,
4033     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4034       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4035         return ImplicitConversionSequence::Better;
4036       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4037         return ImplicitConversionSequence::Worse;
4038     }
4039 
4040     //   -- conversion of B* to A* is better than conversion of C* to A*,
4041     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4042       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4043         return ImplicitConversionSequence::Better;
4044       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4045         return ImplicitConversionSequence::Worse;
4046     }
4047   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4048              SCS2.Second == ICK_Pointer_Conversion) {
4049     const ObjCObjectPointerType *FromPtr1
4050       = FromType1->getAs<ObjCObjectPointerType>();
4051     const ObjCObjectPointerType *FromPtr2
4052       = FromType2->getAs<ObjCObjectPointerType>();
4053     const ObjCObjectPointerType *ToPtr1
4054       = ToType1->getAs<ObjCObjectPointerType>();
4055     const ObjCObjectPointerType *ToPtr2
4056       = ToType2->getAs<ObjCObjectPointerType>();
4057 
4058     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4059       // Apply the same conversion ranking rules for Objective-C pointer types
4060       // that we do for C++ pointers to class types. However, we employ the
4061       // Objective-C pseudo-subtyping relationship used for assignment of
4062       // Objective-C pointer types.
4063       bool FromAssignLeft
4064         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4065       bool FromAssignRight
4066         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4067       bool ToAssignLeft
4068         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4069       bool ToAssignRight
4070         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4071 
4072       // A conversion to an a non-id object pointer type or qualified 'id'
4073       // type is better than a conversion to 'id'.
4074       if (ToPtr1->isObjCIdType() &&
4075           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4076         return ImplicitConversionSequence::Worse;
4077       if (ToPtr2->isObjCIdType() &&
4078           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4079         return ImplicitConversionSequence::Better;
4080 
4081       // A conversion to a non-id object pointer type is better than a
4082       // conversion to a qualified 'id' type
4083       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4084         return ImplicitConversionSequence::Worse;
4085       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4086         return ImplicitConversionSequence::Better;
4087 
4088       // A conversion to an a non-Class object pointer type or qualified 'Class'
4089       // type is better than a conversion to 'Class'.
4090       if (ToPtr1->isObjCClassType() &&
4091           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4092         return ImplicitConversionSequence::Worse;
4093       if (ToPtr2->isObjCClassType() &&
4094           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4095         return ImplicitConversionSequence::Better;
4096 
4097       // A conversion to a non-Class object pointer type is better than a
4098       // conversion to a qualified 'Class' type.
4099       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4100         return ImplicitConversionSequence::Worse;
4101       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4102         return ImplicitConversionSequence::Better;
4103 
4104       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4105       if (S.Context.hasSameType(FromType1, FromType2) &&
4106           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4107           (ToAssignLeft != ToAssignRight)) {
4108         if (FromPtr1->isSpecialized()) {
4109           // "conversion of B<A> * to B * is better than conversion of B * to
4110           // C *.
4111           bool IsFirstSame =
4112               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4113           bool IsSecondSame =
4114               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4115           if (IsFirstSame) {
4116             if (!IsSecondSame)
4117               return ImplicitConversionSequence::Better;
4118           } else if (IsSecondSame)
4119             return ImplicitConversionSequence::Worse;
4120         }
4121         return ToAssignLeft? ImplicitConversionSequence::Worse
4122                            : ImplicitConversionSequence::Better;
4123       }
4124 
4125       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4126       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4127           (FromAssignLeft != FromAssignRight))
4128         return FromAssignLeft? ImplicitConversionSequence::Better
4129         : ImplicitConversionSequence::Worse;
4130     }
4131   }
4132 
4133   // Ranking of member-pointer types.
4134   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4135       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4136       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4137     const MemberPointerType * FromMemPointer1 =
4138                                         FromType1->getAs<MemberPointerType>();
4139     const MemberPointerType * ToMemPointer1 =
4140                                           ToType1->getAs<MemberPointerType>();
4141     const MemberPointerType * FromMemPointer2 =
4142                                           FromType2->getAs<MemberPointerType>();
4143     const MemberPointerType * ToMemPointer2 =
4144                                           ToType2->getAs<MemberPointerType>();
4145     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4146     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4147     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4148     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4149     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4150     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4151     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4152     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4153     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4154     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4155       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4156         return ImplicitConversionSequence::Worse;
4157       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4158         return ImplicitConversionSequence::Better;
4159     }
4160     // conversion of B::* to C::* is better than conversion of A::* to C::*
4161     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4162       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4163         return ImplicitConversionSequence::Better;
4164       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4165         return ImplicitConversionSequence::Worse;
4166     }
4167   }
4168 
4169   if (SCS1.Second == ICK_Derived_To_Base) {
4170     //   -- conversion of C to B is better than conversion of C to A,
4171     //   -- binding of an expression of type C to a reference of type
4172     //      B& is better than binding an expression of type C to a
4173     //      reference of type A&,
4174     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4175         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4176       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4177         return ImplicitConversionSequence::Better;
4178       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4179         return ImplicitConversionSequence::Worse;
4180     }
4181 
4182     //   -- conversion of B to A is better than conversion of C to A.
4183     //   -- binding of an expression of type B to a reference of type
4184     //      A& is better than binding an expression of type C to a
4185     //      reference of type A&,
4186     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4187         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4188       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4189         return ImplicitConversionSequence::Better;
4190       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4191         return ImplicitConversionSequence::Worse;
4192     }
4193   }
4194 
4195   return ImplicitConversionSequence::Indistinguishable;
4196 }
4197 
4198 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4199 /// C++ class.
4200 static bool isTypeValid(QualType T) {
4201   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4202     return !Record->isInvalidDecl();
4203 
4204   return true;
4205 }
4206 
4207 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4208 /// determine whether they are reference-related,
4209 /// reference-compatible, reference-compatible with added
4210 /// qualification, or incompatible, for use in C++ initialization by
4211 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4212 /// type, and the first type (T1) is the pointee type of the reference
4213 /// type being initialized.
4214 Sema::ReferenceCompareResult
4215 Sema::CompareReferenceRelationship(SourceLocation Loc,
4216                                    QualType OrigT1, QualType OrigT2,
4217                                    bool &DerivedToBase,
4218                                    bool &ObjCConversion,
4219                                    bool &ObjCLifetimeConversion) {
4220   assert(!OrigT1->isReferenceType() &&
4221     "T1 must be the pointee type of the reference type");
4222   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4223 
4224   QualType T1 = Context.getCanonicalType(OrigT1);
4225   QualType T2 = Context.getCanonicalType(OrigT2);
4226   Qualifiers T1Quals, T2Quals;
4227   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4228   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4229 
4230   // C++ [dcl.init.ref]p4:
4231   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4232   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4233   //   T1 is a base class of T2.
4234   DerivedToBase = false;
4235   ObjCConversion = false;
4236   ObjCLifetimeConversion = false;
4237   QualType ConvertedT2;
4238   if (UnqualT1 == UnqualT2) {
4239     // Nothing to do.
4240   } else if (isCompleteType(Loc, OrigT2) &&
4241              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4242              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4243     DerivedToBase = true;
4244   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4245            UnqualT2->isObjCObjectOrInterfaceType() &&
4246            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4247     ObjCConversion = true;
4248   else if (UnqualT2->isFunctionType() &&
4249            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4250     // C++1z [dcl.init.ref]p4:
4251     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4252     //   function" and T1 is "function"
4253     //
4254     // We extend this to also apply to 'noreturn', so allow any function
4255     // conversion between function types.
4256     return Ref_Compatible;
4257   else
4258     return Ref_Incompatible;
4259 
4260   // At this point, we know that T1 and T2 are reference-related (at
4261   // least).
4262 
4263   // If the type is an array type, promote the element qualifiers to the type
4264   // for comparison.
4265   if (isa<ArrayType>(T1) && T1Quals)
4266     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4267   if (isa<ArrayType>(T2) && T2Quals)
4268     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4269 
4270   // C++ [dcl.init.ref]p4:
4271   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4272   //   reference-related to T2 and cv1 is the same cv-qualification
4273   //   as, or greater cv-qualification than, cv2. For purposes of
4274   //   overload resolution, cases for which cv1 is greater
4275   //   cv-qualification than cv2 are identified as
4276   //   reference-compatible with added qualification (see 13.3.3.2).
4277   //
4278   // Note that we also require equivalence of Objective-C GC and address-space
4279   // qualifiers when performing these computations, so that e.g., an int in
4280   // address space 1 is not reference-compatible with an int in address
4281   // space 2.
4282   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4283       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4284     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4285       ObjCLifetimeConversion = true;
4286 
4287     T1Quals.removeObjCLifetime();
4288     T2Quals.removeObjCLifetime();
4289   }
4290 
4291   // MS compiler ignores __unaligned qualifier for references; do the same.
4292   T1Quals.removeUnaligned();
4293   T2Quals.removeUnaligned();
4294 
4295   if (T1Quals.compatiblyIncludes(T2Quals))
4296     return Ref_Compatible;
4297   else
4298     return Ref_Related;
4299 }
4300 
4301 /// \brief Look for a user-defined conversion to a value reference-compatible
4302 ///        with DeclType. Return true if something definite is found.
4303 static bool
4304 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4305                          QualType DeclType, SourceLocation DeclLoc,
4306                          Expr *Init, QualType T2, bool AllowRvalues,
4307                          bool AllowExplicit) {
4308   assert(T2->isRecordType() && "Can only find conversions of record types.");
4309   CXXRecordDecl *T2RecordDecl
4310     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4311 
4312   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4313   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4314   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4315     NamedDecl *D = *I;
4316     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4317     if (isa<UsingShadowDecl>(D))
4318       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4319 
4320     FunctionTemplateDecl *ConvTemplate
4321       = dyn_cast<FunctionTemplateDecl>(D);
4322     CXXConversionDecl *Conv;
4323     if (ConvTemplate)
4324       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4325     else
4326       Conv = cast<CXXConversionDecl>(D);
4327 
4328     // If this is an explicit conversion, and we're not allowed to consider
4329     // explicit conversions, skip it.
4330     if (!AllowExplicit && Conv->isExplicit())
4331       continue;
4332 
4333     if (AllowRvalues) {
4334       bool DerivedToBase = false;
4335       bool ObjCConversion = false;
4336       bool ObjCLifetimeConversion = false;
4337 
4338       // If we are initializing an rvalue reference, don't permit conversion
4339       // functions that return lvalues.
4340       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4341         const ReferenceType *RefType
4342           = Conv->getConversionType()->getAs<LValueReferenceType>();
4343         if (RefType && !RefType->getPointeeType()->isFunctionType())
4344           continue;
4345       }
4346 
4347       if (!ConvTemplate &&
4348           S.CompareReferenceRelationship(
4349             DeclLoc,
4350             Conv->getConversionType().getNonReferenceType()
4351               .getUnqualifiedType(),
4352             DeclType.getNonReferenceType().getUnqualifiedType(),
4353             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4354           Sema::Ref_Incompatible)
4355         continue;
4356     } else {
4357       // If the conversion function doesn't return a reference type,
4358       // it can't be considered for this conversion. An rvalue reference
4359       // is only acceptable if its referencee is a function type.
4360 
4361       const ReferenceType *RefType =
4362         Conv->getConversionType()->getAs<ReferenceType>();
4363       if (!RefType ||
4364           (!RefType->isLValueReferenceType() &&
4365            !RefType->getPointeeType()->isFunctionType()))
4366         continue;
4367     }
4368 
4369     if (ConvTemplate)
4370       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4371                                        Init, DeclType, CandidateSet,
4372                                        /*AllowObjCConversionOnExplicit=*/false);
4373     else
4374       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4375                                DeclType, CandidateSet,
4376                                /*AllowObjCConversionOnExplicit=*/false);
4377   }
4378 
4379   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4380 
4381   OverloadCandidateSet::iterator Best;
4382   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4383   case OR_Success:
4384     // C++ [over.ics.ref]p1:
4385     //
4386     //   [...] If the parameter binds directly to the result of
4387     //   applying a conversion function to the argument
4388     //   expression, the implicit conversion sequence is a
4389     //   user-defined conversion sequence (13.3.3.1.2), with the
4390     //   second standard conversion sequence either an identity
4391     //   conversion or, if the conversion function returns an
4392     //   entity of a type that is a derived class of the parameter
4393     //   type, a derived-to-base Conversion.
4394     if (!Best->FinalConversion.DirectBinding)
4395       return false;
4396 
4397     ICS.setUserDefined();
4398     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4399     ICS.UserDefined.After = Best->FinalConversion;
4400     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4401     ICS.UserDefined.ConversionFunction = Best->Function;
4402     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4403     ICS.UserDefined.EllipsisConversion = false;
4404     assert(ICS.UserDefined.After.ReferenceBinding &&
4405            ICS.UserDefined.After.DirectBinding &&
4406            "Expected a direct reference binding!");
4407     return true;
4408 
4409   case OR_Ambiguous:
4410     ICS.setAmbiguous();
4411     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4412          Cand != CandidateSet.end(); ++Cand)
4413       if (Cand->Viable)
4414         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4415     return true;
4416 
4417   case OR_No_Viable_Function:
4418   case OR_Deleted:
4419     // There was no suitable conversion, or we found a deleted
4420     // conversion; continue with other checks.
4421     return false;
4422   }
4423 
4424   llvm_unreachable("Invalid OverloadResult!");
4425 }
4426 
4427 /// \brief Compute an implicit conversion sequence for reference
4428 /// initialization.
4429 static ImplicitConversionSequence
4430 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4431                  SourceLocation DeclLoc,
4432                  bool SuppressUserConversions,
4433                  bool AllowExplicit) {
4434   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4435 
4436   // Most paths end in a failed conversion.
4437   ImplicitConversionSequence ICS;
4438   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4439 
4440   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4441   QualType T2 = Init->getType();
4442 
4443   // If the initializer is the address of an overloaded function, try
4444   // to resolve the overloaded function. If all goes well, T2 is the
4445   // type of the resulting function.
4446   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4447     DeclAccessPair Found;
4448     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4449                                                                 false, Found))
4450       T2 = Fn->getType();
4451   }
4452 
4453   // Compute some basic properties of the types and the initializer.
4454   bool isRValRef = DeclType->isRValueReferenceType();
4455   bool DerivedToBase = false;
4456   bool ObjCConversion = false;
4457   bool ObjCLifetimeConversion = false;
4458   Expr::Classification InitCategory = Init->Classify(S.Context);
4459   Sema::ReferenceCompareResult RefRelationship
4460     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4461                                      ObjCConversion, ObjCLifetimeConversion);
4462 
4463 
4464   // C++0x [dcl.init.ref]p5:
4465   //   A reference to type "cv1 T1" is initialized by an expression
4466   //   of type "cv2 T2" as follows:
4467 
4468   //     -- If reference is an lvalue reference and the initializer expression
4469   if (!isRValRef) {
4470     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4471     //        reference-compatible with "cv2 T2," or
4472     //
4473     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4474     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4475       // C++ [over.ics.ref]p1:
4476       //   When a parameter of reference type binds directly (8.5.3)
4477       //   to an argument expression, the implicit conversion sequence
4478       //   is the identity conversion, unless the argument expression
4479       //   has a type that is a derived class of the parameter type,
4480       //   in which case the implicit conversion sequence is a
4481       //   derived-to-base Conversion (13.3.3.1).
4482       ICS.setStandard();
4483       ICS.Standard.First = ICK_Identity;
4484       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4485                          : ObjCConversion? ICK_Compatible_Conversion
4486                          : ICK_Identity;
4487       ICS.Standard.Third = ICK_Identity;
4488       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4489       ICS.Standard.setToType(0, T2);
4490       ICS.Standard.setToType(1, T1);
4491       ICS.Standard.setToType(2, T1);
4492       ICS.Standard.ReferenceBinding = true;
4493       ICS.Standard.DirectBinding = true;
4494       ICS.Standard.IsLvalueReference = !isRValRef;
4495       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4496       ICS.Standard.BindsToRvalue = false;
4497       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4498       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4499       ICS.Standard.CopyConstructor = nullptr;
4500       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4501 
4502       // Nothing more to do: the inaccessibility/ambiguity check for
4503       // derived-to-base conversions is suppressed when we're
4504       // computing the implicit conversion sequence (C++
4505       // [over.best.ics]p2).
4506       return ICS;
4507     }
4508 
4509     //       -- has a class type (i.e., T2 is a class type), where T1 is
4510     //          not reference-related to T2, and can be implicitly
4511     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4512     //          is reference-compatible with "cv3 T3" 92) (this
4513     //          conversion is selected by enumerating the applicable
4514     //          conversion functions (13.3.1.6) and choosing the best
4515     //          one through overload resolution (13.3)),
4516     if (!SuppressUserConversions && T2->isRecordType() &&
4517         S.isCompleteType(DeclLoc, T2) &&
4518         RefRelationship == Sema::Ref_Incompatible) {
4519       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4520                                    Init, T2, /*AllowRvalues=*/false,
4521                                    AllowExplicit))
4522         return ICS;
4523     }
4524   }
4525 
4526   //     -- Otherwise, the reference shall be an lvalue reference to a
4527   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4528   //        shall be an rvalue reference.
4529   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4530     return ICS;
4531 
4532   //       -- If the initializer expression
4533   //
4534   //            -- is an xvalue, class prvalue, array prvalue or function
4535   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4536   if (RefRelationship == Sema::Ref_Compatible &&
4537       (InitCategory.isXValue() ||
4538        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4539        (InitCategory.isLValue() && T2->isFunctionType()))) {
4540     ICS.setStandard();
4541     ICS.Standard.First = ICK_Identity;
4542     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4543                       : ObjCConversion? ICK_Compatible_Conversion
4544                       : ICK_Identity;
4545     ICS.Standard.Third = ICK_Identity;
4546     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4547     ICS.Standard.setToType(0, T2);
4548     ICS.Standard.setToType(1, T1);
4549     ICS.Standard.setToType(2, T1);
4550     ICS.Standard.ReferenceBinding = true;
4551     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4552     // binding unless we're binding to a class prvalue.
4553     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4554     // allow the use of rvalue references in C++98/03 for the benefit of
4555     // standard library implementors; therefore, we need the xvalue check here.
4556     ICS.Standard.DirectBinding =
4557       S.getLangOpts().CPlusPlus11 ||
4558       !(InitCategory.isPRValue() || T2->isRecordType());
4559     ICS.Standard.IsLvalueReference = !isRValRef;
4560     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4561     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4562     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4563     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4564     ICS.Standard.CopyConstructor = nullptr;
4565     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4566     return ICS;
4567   }
4568 
4569   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4570   //               reference-related to T2, and can be implicitly converted to
4571   //               an xvalue, class prvalue, or function lvalue of type
4572   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4573   //               "cv3 T3",
4574   //
4575   //          then the reference is bound to the value of the initializer
4576   //          expression in the first case and to the result of the conversion
4577   //          in the second case (or, in either case, to an appropriate base
4578   //          class subobject).
4579   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4580       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4581       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4582                                Init, T2, /*AllowRvalues=*/true,
4583                                AllowExplicit)) {
4584     // In the second case, if the reference is an rvalue reference
4585     // and the second standard conversion sequence of the
4586     // user-defined conversion sequence includes an lvalue-to-rvalue
4587     // conversion, the program is ill-formed.
4588     if (ICS.isUserDefined() && isRValRef &&
4589         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4590       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4591 
4592     return ICS;
4593   }
4594 
4595   // A temporary of function type cannot be created; don't even try.
4596   if (T1->isFunctionType())
4597     return ICS;
4598 
4599   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4600   //          initialized from the initializer expression using the
4601   //          rules for a non-reference copy initialization (8.5). The
4602   //          reference is then bound to the temporary. If T1 is
4603   //          reference-related to T2, cv1 must be the same
4604   //          cv-qualification as, or greater cv-qualification than,
4605   //          cv2; otherwise, the program is ill-formed.
4606   if (RefRelationship == Sema::Ref_Related) {
4607     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4608     // we would be reference-compatible or reference-compatible with
4609     // added qualification. But that wasn't the case, so the reference
4610     // initialization fails.
4611     //
4612     // Note that we only want to check address spaces and cvr-qualifiers here.
4613     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4614     Qualifiers T1Quals = T1.getQualifiers();
4615     Qualifiers T2Quals = T2.getQualifiers();
4616     T1Quals.removeObjCGCAttr();
4617     T1Quals.removeObjCLifetime();
4618     T2Quals.removeObjCGCAttr();
4619     T2Quals.removeObjCLifetime();
4620     // MS compiler ignores __unaligned qualifier for references; do the same.
4621     T1Quals.removeUnaligned();
4622     T2Quals.removeUnaligned();
4623     if (!T1Quals.compatiblyIncludes(T2Quals))
4624       return ICS;
4625   }
4626 
4627   // If at least one of the types is a class type, the types are not
4628   // related, and we aren't allowed any user conversions, the
4629   // reference binding fails. This case is important for breaking
4630   // recursion, since TryImplicitConversion below will attempt to
4631   // create a temporary through the use of a copy constructor.
4632   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4633       (T1->isRecordType() || T2->isRecordType()))
4634     return ICS;
4635 
4636   // If T1 is reference-related to T2 and the reference is an rvalue
4637   // reference, the initializer expression shall not be an lvalue.
4638   if (RefRelationship >= Sema::Ref_Related &&
4639       isRValRef && Init->Classify(S.Context).isLValue())
4640     return ICS;
4641 
4642   // C++ [over.ics.ref]p2:
4643   //   When a parameter of reference type is not bound directly to
4644   //   an argument expression, the conversion sequence is the one
4645   //   required to convert the argument expression to the
4646   //   underlying type of the reference according to
4647   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4648   //   to copy-initializing a temporary of the underlying type with
4649   //   the argument expression. Any difference in top-level
4650   //   cv-qualification is subsumed by the initialization itself
4651   //   and does not constitute a conversion.
4652   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4653                               /*AllowExplicit=*/false,
4654                               /*InOverloadResolution=*/false,
4655                               /*CStyle=*/false,
4656                               /*AllowObjCWritebackConversion=*/false,
4657                               /*AllowObjCConversionOnExplicit=*/false);
4658 
4659   // Of course, that's still a reference binding.
4660   if (ICS.isStandard()) {
4661     ICS.Standard.ReferenceBinding = true;
4662     ICS.Standard.IsLvalueReference = !isRValRef;
4663     ICS.Standard.BindsToFunctionLvalue = false;
4664     ICS.Standard.BindsToRvalue = true;
4665     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4666     ICS.Standard.ObjCLifetimeConversionBinding = false;
4667   } else if (ICS.isUserDefined()) {
4668     const ReferenceType *LValRefType =
4669         ICS.UserDefined.ConversionFunction->getReturnType()
4670             ->getAs<LValueReferenceType>();
4671 
4672     // C++ [over.ics.ref]p3:
4673     //   Except for an implicit object parameter, for which see 13.3.1, a
4674     //   standard conversion sequence cannot be formed if it requires [...]
4675     //   binding an rvalue reference to an lvalue other than a function
4676     //   lvalue.
4677     // Note that the function case is not possible here.
4678     if (DeclType->isRValueReferenceType() && LValRefType) {
4679       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4680       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4681       // reference to an rvalue!
4682       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4683       return ICS;
4684     }
4685 
4686     ICS.UserDefined.After.ReferenceBinding = true;
4687     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4688     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4689     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4690     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4691     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4692   }
4693 
4694   return ICS;
4695 }
4696 
4697 static ImplicitConversionSequence
4698 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4699                       bool SuppressUserConversions,
4700                       bool InOverloadResolution,
4701                       bool AllowObjCWritebackConversion,
4702                       bool AllowExplicit = false);
4703 
4704 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4705 /// initializer list From.
4706 static ImplicitConversionSequence
4707 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4708                   bool SuppressUserConversions,
4709                   bool InOverloadResolution,
4710                   bool AllowObjCWritebackConversion) {
4711   // C++11 [over.ics.list]p1:
4712   //   When an argument is an initializer list, it is not an expression and
4713   //   special rules apply for converting it to a parameter type.
4714 
4715   ImplicitConversionSequence Result;
4716   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4717 
4718   // We need a complete type for what follows. Incomplete types can never be
4719   // initialized from init lists.
4720   if (!S.isCompleteType(From->getLocStart(), ToType))
4721     return Result;
4722 
4723   // Per DR1467:
4724   //   If the parameter type is a class X and the initializer list has a single
4725   //   element of type cv U, where U is X or a class derived from X, the
4726   //   implicit conversion sequence is the one required to convert the element
4727   //   to the parameter type.
4728   //
4729   //   Otherwise, if the parameter type is a character array [... ]
4730   //   and the initializer list has a single element that is an
4731   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4732   //   implicit conversion sequence is the identity conversion.
4733   if (From->getNumInits() == 1) {
4734     if (ToType->isRecordType()) {
4735       QualType InitType = From->getInit(0)->getType();
4736       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4737           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4738         return TryCopyInitialization(S, From->getInit(0), ToType,
4739                                      SuppressUserConversions,
4740                                      InOverloadResolution,
4741                                      AllowObjCWritebackConversion);
4742     }
4743     // FIXME: Check the other conditions here: array of character type,
4744     // initializer is a string literal.
4745     if (ToType->isArrayType()) {
4746       InitializedEntity Entity =
4747         InitializedEntity::InitializeParameter(S.Context, ToType,
4748                                                /*Consumed=*/false);
4749       if (S.CanPerformCopyInitialization(Entity, From)) {
4750         Result.setStandard();
4751         Result.Standard.setAsIdentityConversion();
4752         Result.Standard.setFromType(ToType);
4753         Result.Standard.setAllToTypes(ToType);
4754         return Result;
4755       }
4756     }
4757   }
4758 
4759   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4760   // C++11 [over.ics.list]p2:
4761   //   If the parameter type is std::initializer_list<X> or "array of X" and
4762   //   all the elements can be implicitly converted to X, the implicit
4763   //   conversion sequence is the worst conversion necessary to convert an
4764   //   element of the list to X.
4765   //
4766   // C++14 [over.ics.list]p3:
4767   //   Otherwise, if the parameter type is "array of N X", if the initializer
4768   //   list has exactly N elements or if it has fewer than N elements and X is
4769   //   default-constructible, and if all the elements of the initializer list
4770   //   can be implicitly converted to X, the implicit conversion sequence is
4771   //   the worst conversion necessary to convert an element of the list to X.
4772   //
4773   // FIXME: We're missing a lot of these checks.
4774   bool toStdInitializerList = false;
4775   QualType X;
4776   if (ToType->isArrayType())
4777     X = S.Context.getAsArrayType(ToType)->getElementType();
4778   else
4779     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4780   if (!X.isNull()) {
4781     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4782       Expr *Init = From->getInit(i);
4783       ImplicitConversionSequence ICS =
4784           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4785                                 InOverloadResolution,
4786                                 AllowObjCWritebackConversion);
4787       // If a single element isn't convertible, fail.
4788       if (ICS.isBad()) {
4789         Result = ICS;
4790         break;
4791       }
4792       // Otherwise, look for the worst conversion.
4793       if (Result.isBad() ||
4794           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4795                                              Result) ==
4796               ImplicitConversionSequence::Worse)
4797         Result = ICS;
4798     }
4799 
4800     // For an empty list, we won't have computed any conversion sequence.
4801     // Introduce the identity conversion sequence.
4802     if (From->getNumInits() == 0) {
4803       Result.setStandard();
4804       Result.Standard.setAsIdentityConversion();
4805       Result.Standard.setFromType(ToType);
4806       Result.Standard.setAllToTypes(ToType);
4807     }
4808 
4809     Result.setStdInitializerListElement(toStdInitializerList);
4810     return Result;
4811   }
4812 
4813   // C++14 [over.ics.list]p4:
4814   // C++11 [over.ics.list]p3:
4815   //   Otherwise, if the parameter is a non-aggregate class X and overload
4816   //   resolution chooses a single best constructor [...] the implicit
4817   //   conversion sequence is a user-defined conversion sequence. If multiple
4818   //   constructors are viable but none is better than the others, the
4819   //   implicit conversion sequence is a user-defined conversion sequence.
4820   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4821     // This function can deal with initializer lists.
4822     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4823                                     /*AllowExplicit=*/false,
4824                                     InOverloadResolution, /*CStyle=*/false,
4825                                     AllowObjCWritebackConversion,
4826                                     /*AllowObjCConversionOnExplicit=*/false);
4827   }
4828 
4829   // C++14 [over.ics.list]p5:
4830   // C++11 [over.ics.list]p4:
4831   //   Otherwise, if the parameter has an aggregate type which can be
4832   //   initialized from the initializer list [...] the implicit conversion
4833   //   sequence is a user-defined conversion sequence.
4834   if (ToType->isAggregateType()) {
4835     // Type is an aggregate, argument is an init list. At this point it comes
4836     // down to checking whether the initialization works.
4837     // FIXME: Find out whether this parameter is consumed or not.
4838     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4839     // need to call into the initialization code here; overload resolution
4840     // should not be doing that.
4841     InitializedEntity Entity =
4842         InitializedEntity::InitializeParameter(S.Context, ToType,
4843                                                /*Consumed=*/false);
4844     if (S.CanPerformCopyInitialization(Entity, From)) {
4845       Result.setUserDefined();
4846       Result.UserDefined.Before.setAsIdentityConversion();
4847       // Initializer lists don't have a type.
4848       Result.UserDefined.Before.setFromType(QualType());
4849       Result.UserDefined.Before.setAllToTypes(QualType());
4850 
4851       Result.UserDefined.After.setAsIdentityConversion();
4852       Result.UserDefined.After.setFromType(ToType);
4853       Result.UserDefined.After.setAllToTypes(ToType);
4854       Result.UserDefined.ConversionFunction = nullptr;
4855     }
4856     return Result;
4857   }
4858 
4859   // C++14 [over.ics.list]p6:
4860   // C++11 [over.ics.list]p5:
4861   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4862   if (ToType->isReferenceType()) {
4863     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4864     // mention initializer lists in any way. So we go by what list-
4865     // initialization would do and try to extrapolate from that.
4866 
4867     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4868 
4869     // If the initializer list has a single element that is reference-related
4870     // to the parameter type, we initialize the reference from that.
4871     if (From->getNumInits() == 1) {
4872       Expr *Init = From->getInit(0);
4873 
4874       QualType T2 = Init->getType();
4875 
4876       // If the initializer is the address of an overloaded function, try
4877       // to resolve the overloaded function. If all goes well, T2 is the
4878       // type of the resulting function.
4879       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4880         DeclAccessPair Found;
4881         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4882                                    Init, ToType, false, Found))
4883           T2 = Fn->getType();
4884       }
4885 
4886       // Compute some basic properties of the types and the initializer.
4887       bool dummy1 = false;
4888       bool dummy2 = false;
4889       bool dummy3 = false;
4890       Sema::ReferenceCompareResult RefRelationship
4891         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4892                                          dummy2, dummy3);
4893 
4894       if (RefRelationship >= Sema::Ref_Related) {
4895         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4896                                 SuppressUserConversions,
4897                                 /*AllowExplicit=*/false);
4898       }
4899     }
4900 
4901     // Otherwise, we bind the reference to a temporary created from the
4902     // initializer list.
4903     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4904                                InOverloadResolution,
4905                                AllowObjCWritebackConversion);
4906     if (Result.isFailure())
4907       return Result;
4908     assert(!Result.isEllipsis() &&
4909            "Sub-initialization cannot result in ellipsis conversion.");
4910 
4911     // Can we even bind to a temporary?
4912     if (ToType->isRValueReferenceType() ||
4913         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4914       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4915                                             Result.UserDefined.After;
4916       SCS.ReferenceBinding = true;
4917       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4918       SCS.BindsToRvalue = true;
4919       SCS.BindsToFunctionLvalue = false;
4920       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4921       SCS.ObjCLifetimeConversionBinding = false;
4922     } else
4923       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4924                     From, ToType);
4925     return Result;
4926   }
4927 
4928   // C++14 [over.ics.list]p7:
4929   // C++11 [over.ics.list]p6:
4930   //   Otherwise, if the parameter type is not a class:
4931   if (!ToType->isRecordType()) {
4932     //    - if the initializer list has one element that is not itself an
4933     //      initializer list, the implicit conversion sequence is the one
4934     //      required to convert the element to the parameter type.
4935     unsigned NumInits = From->getNumInits();
4936     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4937       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4938                                      SuppressUserConversions,
4939                                      InOverloadResolution,
4940                                      AllowObjCWritebackConversion);
4941     //    - if the initializer list has no elements, the implicit conversion
4942     //      sequence is the identity conversion.
4943     else if (NumInits == 0) {
4944       Result.setStandard();
4945       Result.Standard.setAsIdentityConversion();
4946       Result.Standard.setFromType(ToType);
4947       Result.Standard.setAllToTypes(ToType);
4948     }
4949     return Result;
4950   }
4951 
4952   // C++14 [over.ics.list]p8:
4953   // C++11 [over.ics.list]p7:
4954   //   In all cases other than those enumerated above, no conversion is possible
4955   return Result;
4956 }
4957 
4958 /// TryCopyInitialization - Try to copy-initialize a value of type
4959 /// ToType from the expression From. Return the implicit conversion
4960 /// sequence required to pass this argument, which may be a bad
4961 /// conversion sequence (meaning that the argument cannot be passed to
4962 /// a parameter of this type). If @p SuppressUserConversions, then we
4963 /// do not permit any user-defined conversion sequences.
4964 static ImplicitConversionSequence
4965 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4966                       bool SuppressUserConversions,
4967                       bool InOverloadResolution,
4968                       bool AllowObjCWritebackConversion,
4969                       bool AllowExplicit) {
4970   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4971     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4972                              InOverloadResolution,AllowObjCWritebackConversion);
4973 
4974   if (ToType->isReferenceType())
4975     return TryReferenceInit(S, From, ToType,
4976                             /*FIXME:*/From->getLocStart(),
4977                             SuppressUserConversions,
4978                             AllowExplicit);
4979 
4980   return TryImplicitConversion(S, From, ToType,
4981                                SuppressUserConversions,
4982                                /*AllowExplicit=*/false,
4983                                InOverloadResolution,
4984                                /*CStyle=*/false,
4985                                AllowObjCWritebackConversion,
4986                                /*AllowObjCConversionOnExplicit=*/false);
4987 }
4988 
4989 static bool TryCopyInitialization(const CanQualType FromQTy,
4990                                   const CanQualType ToQTy,
4991                                   Sema &S,
4992                                   SourceLocation Loc,
4993                                   ExprValueKind FromVK) {
4994   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4995   ImplicitConversionSequence ICS =
4996     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4997 
4998   return !ICS.isBad();
4999 }
5000 
5001 /// TryObjectArgumentInitialization - Try to initialize the object
5002 /// parameter of the given member function (@c Method) from the
5003 /// expression @p From.
5004 static ImplicitConversionSequence
5005 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5006                                 Expr::Classification FromClassification,
5007                                 CXXMethodDecl *Method,
5008                                 CXXRecordDecl *ActingContext) {
5009   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5010   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5011   //                 const volatile object.
5012   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5013     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5014   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5015 
5016   // Set up the conversion sequence as a "bad" conversion, to allow us
5017   // to exit early.
5018   ImplicitConversionSequence ICS;
5019 
5020   // We need to have an object of class type.
5021   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5022     FromType = PT->getPointeeType();
5023 
5024     // When we had a pointer, it's implicitly dereferenced, so we
5025     // better have an lvalue.
5026     assert(FromClassification.isLValue());
5027   }
5028 
5029   assert(FromType->isRecordType());
5030 
5031   // C++0x [over.match.funcs]p4:
5032   //   For non-static member functions, the type of the implicit object
5033   //   parameter is
5034   //
5035   //     - "lvalue reference to cv X" for functions declared without a
5036   //        ref-qualifier or with the & ref-qualifier
5037   //     - "rvalue reference to cv X" for functions declared with the &&
5038   //        ref-qualifier
5039   //
5040   // where X is the class of which the function is a member and cv is the
5041   // cv-qualification on the member function declaration.
5042   //
5043   // However, when finding an implicit conversion sequence for the argument, we
5044   // are not allowed to perform user-defined conversions
5045   // (C++ [over.match.funcs]p5). We perform a simplified version of
5046   // reference binding here, that allows class rvalues to bind to
5047   // non-constant references.
5048 
5049   // First check the qualifiers.
5050   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5051   if (ImplicitParamType.getCVRQualifiers()
5052                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5053       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5054     ICS.setBad(BadConversionSequence::bad_qualifiers,
5055                FromType, ImplicitParamType);
5056     return ICS;
5057   }
5058 
5059   // Check that we have either the same type or a derived type. It
5060   // affects the conversion rank.
5061   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5062   ImplicitConversionKind SecondKind;
5063   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5064     SecondKind = ICK_Identity;
5065   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5066     SecondKind = ICK_Derived_To_Base;
5067   else {
5068     ICS.setBad(BadConversionSequence::unrelated_class,
5069                FromType, ImplicitParamType);
5070     return ICS;
5071   }
5072 
5073   // Check the ref-qualifier.
5074   switch (Method->getRefQualifier()) {
5075   case RQ_None:
5076     // Do nothing; we don't care about lvalueness or rvalueness.
5077     break;
5078 
5079   case RQ_LValue:
5080     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5081       // non-const lvalue reference cannot bind to an rvalue
5082       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5083                  ImplicitParamType);
5084       return ICS;
5085     }
5086     break;
5087 
5088   case RQ_RValue:
5089     if (!FromClassification.isRValue()) {
5090       // rvalue reference cannot bind to an lvalue
5091       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5092                  ImplicitParamType);
5093       return ICS;
5094     }
5095     break;
5096   }
5097 
5098   // Success. Mark this as a reference binding.
5099   ICS.setStandard();
5100   ICS.Standard.setAsIdentityConversion();
5101   ICS.Standard.Second = SecondKind;
5102   ICS.Standard.setFromType(FromType);
5103   ICS.Standard.setAllToTypes(ImplicitParamType);
5104   ICS.Standard.ReferenceBinding = true;
5105   ICS.Standard.DirectBinding = true;
5106   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5107   ICS.Standard.BindsToFunctionLvalue = false;
5108   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5109   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5110     = (Method->getRefQualifier() == RQ_None);
5111   return ICS;
5112 }
5113 
5114 /// PerformObjectArgumentInitialization - Perform initialization of
5115 /// the implicit object parameter for the given Method with the given
5116 /// expression.
5117 ExprResult
5118 Sema::PerformObjectArgumentInitialization(Expr *From,
5119                                           NestedNameSpecifier *Qualifier,
5120                                           NamedDecl *FoundDecl,
5121                                           CXXMethodDecl *Method) {
5122   QualType FromRecordType, DestType;
5123   QualType ImplicitParamRecordType  =
5124     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5125 
5126   Expr::Classification FromClassification;
5127   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5128     FromRecordType = PT->getPointeeType();
5129     DestType = Method->getThisType(Context);
5130     FromClassification = Expr::Classification::makeSimpleLValue();
5131   } else {
5132     FromRecordType = From->getType();
5133     DestType = ImplicitParamRecordType;
5134     FromClassification = From->Classify(Context);
5135   }
5136 
5137   // Note that we always use the true parent context when performing
5138   // the actual argument initialization.
5139   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5140       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5141       Method->getParent());
5142   if (ICS.isBad()) {
5143     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5144       Qualifiers FromQs = FromRecordType.getQualifiers();
5145       Qualifiers ToQs = DestType.getQualifiers();
5146       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5147       if (CVR) {
5148         Diag(From->getLocStart(),
5149              diag::err_member_function_call_bad_cvr)
5150           << Method->getDeclName() << FromRecordType << (CVR - 1)
5151           << From->getSourceRange();
5152         Diag(Method->getLocation(), diag::note_previous_decl)
5153           << Method->getDeclName();
5154         return ExprError();
5155       }
5156     }
5157 
5158     return Diag(From->getLocStart(),
5159                 diag::err_implicit_object_parameter_init)
5160        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5161   }
5162 
5163   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5164     ExprResult FromRes =
5165       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5166     if (FromRes.isInvalid())
5167       return ExprError();
5168     From = FromRes.get();
5169   }
5170 
5171   if (!Context.hasSameType(From->getType(), DestType))
5172     From = ImpCastExprToType(From, DestType, CK_NoOp,
5173                              From->getValueKind()).get();
5174   return From;
5175 }
5176 
5177 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5178 /// expression From to bool (C++0x [conv]p3).
5179 static ImplicitConversionSequence
5180 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5181   return TryImplicitConversion(S, From, S.Context.BoolTy,
5182                                /*SuppressUserConversions=*/false,
5183                                /*AllowExplicit=*/true,
5184                                /*InOverloadResolution=*/false,
5185                                /*CStyle=*/false,
5186                                /*AllowObjCWritebackConversion=*/false,
5187                                /*AllowObjCConversionOnExplicit=*/false);
5188 }
5189 
5190 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5191 /// of the expression From to bool (C++0x [conv]p3).
5192 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5193   if (checkPlaceholderForOverload(*this, From))
5194     return ExprError();
5195 
5196   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5197   if (!ICS.isBad())
5198     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5199 
5200   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5201     return Diag(From->getLocStart(),
5202                 diag::err_typecheck_bool_condition)
5203                   << From->getType() << From->getSourceRange();
5204   return ExprError();
5205 }
5206 
5207 /// Check that the specified conversion is permitted in a converted constant
5208 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5209 /// is acceptable.
5210 static bool CheckConvertedConstantConversions(Sema &S,
5211                                               StandardConversionSequence &SCS) {
5212   // Since we know that the target type is an integral or unscoped enumeration
5213   // type, most conversion kinds are impossible. All possible First and Third
5214   // conversions are fine.
5215   switch (SCS.Second) {
5216   case ICK_Identity:
5217   case ICK_Function_Conversion:
5218   case ICK_Integral_Promotion:
5219   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5220   case ICK_Zero_Queue_Conversion:
5221     return true;
5222 
5223   case ICK_Boolean_Conversion:
5224     // Conversion from an integral or unscoped enumeration type to bool is
5225     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5226     // conversion, so we allow it in a converted constant expression.
5227     //
5228     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5229     // a lot of popular code. We should at least add a warning for this
5230     // (non-conforming) extension.
5231     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5232            SCS.getToType(2)->isBooleanType();
5233 
5234   case ICK_Pointer_Conversion:
5235   case ICK_Pointer_Member:
5236     // C++1z: null pointer conversions and null member pointer conversions are
5237     // only permitted if the source type is std::nullptr_t.
5238     return SCS.getFromType()->isNullPtrType();
5239 
5240   case ICK_Floating_Promotion:
5241   case ICK_Complex_Promotion:
5242   case ICK_Floating_Conversion:
5243   case ICK_Complex_Conversion:
5244   case ICK_Floating_Integral:
5245   case ICK_Compatible_Conversion:
5246   case ICK_Derived_To_Base:
5247   case ICK_Vector_Conversion:
5248   case ICK_Vector_Splat:
5249   case ICK_Complex_Real:
5250   case ICK_Block_Pointer_Conversion:
5251   case ICK_TransparentUnionConversion:
5252   case ICK_Writeback_Conversion:
5253   case ICK_Zero_Event_Conversion:
5254   case ICK_C_Only_Conversion:
5255   case ICK_Incompatible_Pointer_Conversion:
5256     return false;
5257 
5258   case ICK_Lvalue_To_Rvalue:
5259   case ICK_Array_To_Pointer:
5260   case ICK_Function_To_Pointer:
5261     llvm_unreachable("found a first conversion kind in Second");
5262 
5263   case ICK_Qualification:
5264     llvm_unreachable("found a third conversion kind in Second");
5265 
5266   case ICK_Num_Conversion_Kinds:
5267     break;
5268   }
5269 
5270   llvm_unreachable("unknown conversion kind");
5271 }
5272 
5273 /// CheckConvertedConstantExpression - Check that the expression From is a
5274 /// converted constant expression of type T, perform the conversion and produce
5275 /// the converted expression, per C++11 [expr.const]p3.
5276 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5277                                                    QualType T, APValue &Value,
5278                                                    Sema::CCEKind CCE,
5279                                                    bool RequireInt) {
5280   assert(S.getLangOpts().CPlusPlus11 &&
5281          "converted constant expression outside C++11");
5282 
5283   if (checkPlaceholderForOverload(S, From))
5284     return ExprError();
5285 
5286   // C++1z [expr.const]p3:
5287   //  A converted constant expression of type T is an expression,
5288   //  implicitly converted to type T, where the converted
5289   //  expression is a constant expression and the implicit conversion
5290   //  sequence contains only [... list of conversions ...].
5291   // C++1z [stmt.if]p2:
5292   //  If the if statement is of the form if constexpr, the value of the
5293   //  condition shall be a contextually converted constant expression of type
5294   //  bool.
5295   ImplicitConversionSequence ICS =
5296       CCE == Sema::CCEK_ConstexprIf
5297           ? TryContextuallyConvertToBool(S, From)
5298           : TryCopyInitialization(S, From, T,
5299                                   /*SuppressUserConversions=*/false,
5300                                   /*InOverloadResolution=*/false,
5301                                   /*AllowObjcWritebackConversion=*/false,
5302                                   /*AllowExplicit=*/false);
5303   StandardConversionSequence *SCS = nullptr;
5304   switch (ICS.getKind()) {
5305   case ImplicitConversionSequence::StandardConversion:
5306     SCS = &ICS.Standard;
5307     break;
5308   case ImplicitConversionSequence::UserDefinedConversion:
5309     // We are converting to a non-class type, so the Before sequence
5310     // must be trivial.
5311     SCS = &ICS.UserDefined.After;
5312     break;
5313   case ImplicitConversionSequence::AmbiguousConversion:
5314   case ImplicitConversionSequence::BadConversion:
5315     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5316       return S.Diag(From->getLocStart(),
5317                     diag::err_typecheck_converted_constant_expression)
5318                 << From->getType() << From->getSourceRange() << T;
5319     return ExprError();
5320 
5321   case ImplicitConversionSequence::EllipsisConversion:
5322     llvm_unreachable("ellipsis conversion in converted constant expression");
5323   }
5324 
5325   // Check that we would only use permitted conversions.
5326   if (!CheckConvertedConstantConversions(S, *SCS)) {
5327     return S.Diag(From->getLocStart(),
5328                   diag::err_typecheck_converted_constant_expression_disallowed)
5329              << From->getType() << From->getSourceRange() << T;
5330   }
5331   // [...] and where the reference binding (if any) binds directly.
5332   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5333     return S.Diag(From->getLocStart(),
5334                   diag::err_typecheck_converted_constant_expression_indirect)
5335              << From->getType() << From->getSourceRange() << T;
5336   }
5337 
5338   ExprResult Result =
5339       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5340   if (Result.isInvalid())
5341     return Result;
5342 
5343   // Check for a narrowing implicit conversion.
5344   APValue PreNarrowingValue;
5345   QualType PreNarrowingType;
5346   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5347                                 PreNarrowingType)) {
5348   case NK_Dependent_Narrowing:
5349     // Implicit conversion to a narrower type, but the expression is
5350     // value-dependent so we can't tell whether it's actually narrowing.
5351   case NK_Variable_Narrowing:
5352     // Implicit conversion to a narrower type, and the value is not a constant
5353     // expression. We'll diagnose this in a moment.
5354   case NK_Not_Narrowing:
5355     break;
5356 
5357   case NK_Constant_Narrowing:
5358     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5359       << CCE << /*Constant*/1
5360       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5361     break;
5362 
5363   case NK_Type_Narrowing:
5364     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5365       << CCE << /*Constant*/0 << From->getType() << T;
5366     break;
5367   }
5368 
5369   if (Result.get()->isValueDependent()) {
5370     Value = APValue();
5371     return Result;
5372   }
5373 
5374   // Check the expression is a constant expression.
5375   SmallVector<PartialDiagnosticAt, 8> Notes;
5376   Expr::EvalResult Eval;
5377   Eval.Diag = &Notes;
5378 
5379   if ((T->isReferenceType()
5380            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5381            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5382       (RequireInt && !Eval.Val.isInt())) {
5383     // The expression can't be folded, so we can't keep it at this position in
5384     // the AST.
5385     Result = ExprError();
5386   } else {
5387     Value = Eval.Val;
5388 
5389     if (Notes.empty()) {
5390       // It's a constant expression.
5391       return Result;
5392     }
5393   }
5394 
5395   // It's not a constant expression. Produce an appropriate diagnostic.
5396   if (Notes.size() == 1 &&
5397       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5398     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5399   else {
5400     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5401       << CCE << From->getSourceRange();
5402     for (unsigned I = 0; I < Notes.size(); ++I)
5403       S.Diag(Notes[I].first, Notes[I].second);
5404   }
5405   return ExprError();
5406 }
5407 
5408 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5409                                                   APValue &Value, CCEKind CCE) {
5410   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5411 }
5412 
5413 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5414                                                   llvm::APSInt &Value,
5415                                                   CCEKind CCE) {
5416   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5417 
5418   APValue V;
5419   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5420   if (!R.isInvalid() && !R.get()->isValueDependent())
5421     Value = V.getInt();
5422   return R;
5423 }
5424 
5425 
5426 /// dropPointerConversions - If the given standard conversion sequence
5427 /// involves any pointer conversions, remove them.  This may change
5428 /// the result type of the conversion sequence.
5429 static void dropPointerConversion(StandardConversionSequence &SCS) {
5430   if (SCS.Second == ICK_Pointer_Conversion) {
5431     SCS.Second = ICK_Identity;
5432     SCS.Third = ICK_Identity;
5433     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5434   }
5435 }
5436 
5437 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5438 /// convert the expression From to an Objective-C pointer type.
5439 static ImplicitConversionSequence
5440 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5441   // Do an implicit conversion to 'id'.
5442   QualType Ty = S.Context.getObjCIdType();
5443   ImplicitConversionSequence ICS
5444     = TryImplicitConversion(S, From, Ty,
5445                             // FIXME: Are these flags correct?
5446                             /*SuppressUserConversions=*/false,
5447                             /*AllowExplicit=*/true,
5448                             /*InOverloadResolution=*/false,
5449                             /*CStyle=*/false,
5450                             /*AllowObjCWritebackConversion=*/false,
5451                             /*AllowObjCConversionOnExplicit=*/true);
5452 
5453   // Strip off any final conversions to 'id'.
5454   switch (ICS.getKind()) {
5455   case ImplicitConversionSequence::BadConversion:
5456   case ImplicitConversionSequence::AmbiguousConversion:
5457   case ImplicitConversionSequence::EllipsisConversion:
5458     break;
5459 
5460   case ImplicitConversionSequence::UserDefinedConversion:
5461     dropPointerConversion(ICS.UserDefined.After);
5462     break;
5463 
5464   case ImplicitConversionSequence::StandardConversion:
5465     dropPointerConversion(ICS.Standard);
5466     break;
5467   }
5468 
5469   return ICS;
5470 }
5471 
5472 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5473 /// conversion of the expression From to an Objective-C pointer type.
5474 /// Returns a valid but null ExprResult if no conversion sequence exists.
5475 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5476   if (checkPlaceholderForOverload(*this, From))
5477     return ExprError();
5478 
5479   QualType Ty = Context.getObjCIdType();
5480   ImplicitConversionSequence ICS =
5481     TryContextuallyConvertToObjCPointer(*this, From);
5482   if (!ICS.isBad())
5483     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5484   return ExprResult();
5485 }
5486 
5487 /// Determine whether the provided type is an integral type, or an enumeration
5488 /// type of a permitted flavor.
5489 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5490   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5491                                  : T->isIntegralOrUnscopedEnumerationType();
5492 }
5493 
5494 static ExprResult
5495 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5496                             Sema::ContextualImplicitConverter &Converter,
5497                             QualType T, UnresolvedSetImpl &ViableConversions) {
5498 
5499   if (Converter.Suppress)
5500     return ExprError();
5501 
5502   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5503   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5504     CXXConversionDecl *Conv =
5505         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5506     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5507     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5508   }
5509   return From;
5510 }
5511 
5512 static bool
5513 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5514                            Sema::ContextualImplicitConverter &Converter,
5515                            QualType T, bool HadMultipleCandidates,
5516                            UnresolvedSetImpl &ExplicitConversions) {
5517   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5518     DeclAccessPair Found = ExplicitConversions[0];
5519     CXXConversionDecl *Conversion =
5520         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5521 
5522     // The user probably meant to invoke the given explicit
5523     // conversion; use it.
5524     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5525     std::string TypeStr;
5526     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5527 
5528     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5529         << FixItHint::CreateInsertion(From->getLocStart(),
5530                                       "static_cast<" + TypeStr + ">(")
5531         << FixItHint::CreateInsertion(
5532                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5533     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5534 
5535     // If we aren't in a SFINAE context, build a call to the
5536     // explicit conversion function.
5537     if (SemaRef.isSFINAEContext())
5538       return true;
5539 
5540     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5541     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5542                                                        HadMultipleCandidates);
5543     if (Result.isInvalid())
5544       return true;
5545     // Record usage of conversion in an implicit cast.
5546     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5547                                     CK_UserDefinedConversion, Result.get(),
5548                                     nullptr, Result.get()->getValueKind());
5549   }
5550   return false;
5551 }
5552 
5553 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5554                              Sema::ContextualImplicitConverter &Converter,
5555                              QualType T, bool HadMultipleCandidates,
5556                              DeclAccessPair &Found) {
5557   CXXConversionDecl *Conversion =
5558       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5559   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5560 
5561   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5562   if (!Converter.SuppressConversion) {
5563     if (SemaRef.isSFINAEContext())
5564       return true;
5565 
5566     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5567         << From->getSourceRange();
5568   }
5569 
5570   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5571                                                      HadMultipleCandidates);
5572   if (Result.isInvalid())
5573     return true;
5574   // Record usage of conversion in an implicit cast.
5575   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5576                                   CK_UserDefinedConversion, Result.get(),
5577                                   nullptr, Result.get()->getValueKind());
5578   return false;
5579 }
5580 
5581 static ExprResult finishContextualImplicitConversion(
5582     Sema &SemaRef, SourceLocation Loc, Expr *From,
5583     Sema::ContextualImplicitConverter &Converter) {
5584   if (!Converter.match(From->getType()) && !Converter.Suppress)
5585     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5586         << From->getSourceRange();
5587 
5588   return SemaRef.DefaultLvalueConversion(From);
5589 }
5590 
5591 static void
5592 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5593                                   UnresolvedSetImpl &ViableConversions,
5594                                   OverloadCandidateSet &CandidateSet) {
5595   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5596     DeclAccessPair FoundDecl = ViableConversions[I];
5597     NamedDecl *D = FoundDecl.getDecl();
5598     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5599     if (isa<UsingShadowDecl>(D))
5600       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5601 
5602     CXXConversionDecl *Conv;
5603     FunctionTemplateDecl *ConvTemplate;
5604     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5605       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5606     else
5607       Conv = cast<CXXConversionDecl>(D);
5608 
5609     if (ConvTemplate)
5610       SemaRef.AddTemplateConversionCandidate(
5611         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5612         /*AllowObjCConversionOnExplicit=*/false);
5613     else
5614       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5615                                      ToType, CandidateSet,
5616                                      /*AllowObjCConversionOnExplicit=*/false);
5617   }
5618 }
5619 
5620 /// \brief Attempt to convert the given expression to a type which is accepted
5621 /// by the given converter.
5622 ///
5623 /// This routine will attempt to convert an expression of class type to a
5624 /// type accepted by the specified converter. In C++11 and before, the class
5625 /// must have a single non-explicit conversion function converting to a matching
5626 /// type. In C++1y, there can be multiple such conversion functions, but only
5627 /// one target type.
5628 ///
5629 /// \param Loc The source location of the construct that requires the
5630 /// conversion.
5631 ///
5632 /// \param From The expression we're converting from.
5633 ///
5634 /// \param Converter Used to control and diagnose the conversion process.
5635 ///
5636 /// \returns The expression, converted to an integral or enumeration type if
5637 /// successful.
5638 ExprResult Sema::PerformContextualImplicitConversion(
5639     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5640   // We can't perform any more checking for type-dependent expressions.
5641   if (From->isTypeDependent())
5642     return From;
5643 
5644   // Process placeholders immediately.
5645   if (From->hasPlaceholderType()) {
5646     ExprResult result = CheckPlaceholderExpr(From);
5647     if (result.isInvalid())
5648       return result;
5649     From = result.get();
5650   }
5651 
5652   // If the expression already has a matching type, we're golden.
5653   QualType T = From->getType();
5654   if (Converter.match(T))
5655     return DefaultLvalueConversion(From);
5656 
5657   // FIXME: Check for missing '()' if T is a function type?
5658 
5659   // We can only perform contextual implicit conversions on objects of class
5660   // type.
5661   const RecordType *RecordTy = T->getAs<RecordType>();
5662   if (!RecordTy || !getLangOpts().CPlusPlus) {
5663     if (!Converter.Suppress)
5664       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5665     return From;
5666   }
5667 
5668   // We must have a complete class type.
5669   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5670     ContextualImplicitConverter &Converter;
5671     Expr *From;
5672 
5673     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5674         : Converter(Converter), From(From) {}
5675 
5676     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5677       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5678     }
5679   } IncompleteDiagnoser(Converter, From);
5680 
5681   if (Converter.Suppress ? !isCompleteType(Loc, T)
5682                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5683     return From;
5684 
5685   // Look for a conversion to an integral or enumeration type.
5686   UnresolvedSet<4>
5687       ViableConversions; // These are *potentially* viable in C++1y.
5688   UnresolvedSet<4> ExplicitConversions;
5689   const auto &Conversions =
5690       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5691 
5692   bool HadMultipleCandidates =
5693       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5694 
5695   // To check that there is only one target type, in C++1y:
5696   QualType ToType;
5697   bool HasUniqueTargetType = true;
5698 
5699   // Collect explicit or viable (potentially in C++1y) conversions.
5700   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5701     NamedDecl *D = (*I)->getUnderlyingDecl();
5702     CXXConversionDecl *Conversion;
5703     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5704     if (ConvTemplate) {
5705       if (getLangOpts().CPlusPlus14)
5706         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5707       else
5708         continue; // C++11 does not consider conversion operator templates(?).
5709     } else
5710       Conversion = cast<CXXConversionDecl>(D);
5711 
5712     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5713            "Conversion operator templates are considered potentially "
5714            "viable in C++1y");
5715 
5716     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5717     if (Converter.match(CurToType) || ConvTemplate) {
5718 
5719       if (Conversion->isExplicit()) {
5720         // FIXME: For C++1y, do we need this restriction?
5721         // cf. diagnoseNoViableConversion()
5722         if (!ConvTemplate)
5723           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5724       } else {
5725         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5726           if (ToType.isNull())
5727             ToType = CurToType.getUnqualifiedType();
5728           else if (HasUniqueTargetType &&
5729                    (CurToType.getUnqualifiedType() != ToType))
5730             HasUniqueTargetType = false;
5731         }
5732         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5733       }
5734     }
5735   }
5736 
5737   if (getLangOpts().CPlusPlus14) {
5738     // C++1y [conv]p6:
5739     // ... An expression e of class type E appearing in such a context
5740     // is said to be contextually implicitly converted to a specified
5741     // type T and is well-formed if and only if e can be implicitly
5742     // converted to a type T that is determined as follows: E is searched
5743     // for conversion functions whose return type is cv T or reference to
5744     // cv T such that T is allowed by the context. There shall be
5745     // exactly one such T.
5746 
5747     // If no unique T is found:
5748     if (ToType.isNull()) {
5749       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5750                                      HadMultipleCandidates,
5751                                      ExplicitConversions))
5752         return ExprError();
5753       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5754     }
5755 
5756     // If more than one unique Ts are found:
5757     if (!HasUniqueTargetType)
5758       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5759                                          ViableConversions);
5760 
5761     // If one unique T is found:
5762     // First, build a candidate set from the previously recorded
5763     // potentially viable conversions.
5764     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5765     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5766                                       CandidateSet);
5767 
5768     // Then, perform overload resolution over the candidate set.
5769     OverloadCandidateSet::iterator Best;
5770     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5771     case OR_Success: {
5772       // Apply this conversion.
5773       DeclAccessPair Found =
5774           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5775       if (recordConversion(*this, Loc, From, Converter, T,
5776                            HadMultipleCandidates, Found))
5777         return ExprError();
5778       break;
5779     }
5780     case OR_Ambiguous:
5781       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5782                                          ViableConversions);
5783     case OR_No_Viable_Function:
5784       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5785                                      HadMultipleCandidates,
5786                                      ExplicitConversions))
5787         return ExprError();
5788     // fall through 'OR_Deleted' case.
5789     case OR_Deleted:
5790       // We'll complain below about a non-integral condition type.
5791       break;
5792     }
5793   } else {
5794     switch (ViableConversions.size()) {
5795     case 0: {
5796       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5797                                      HadMultipleCandidates,
5798                                      ExplicitConversions))
5799         return ExprError();
5800 
5801       // We'll complain below about a non-integral condition type.
5802       break;
5803     }
5804     case 1: {
5805       // Apply this conversion.
5806       DeclAccessPair Found = ViableConversions[0];
5807       if (recordConversion(*this, Loc, From, Converter, T,
5808                            HadMultipleCandidates, Found))
5809         return ExprError();
5810       break;
5811     }
5812     default:
5813       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5814                                          ViableConversions);
5815     }
5816   }
5817 
5818   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5819 }
5820 
5821 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5822 /// an acceptable non-member overloaded operator for a call whose
5823 /// arguments have types T1 (and, if non-empty, T2). This routine
5824 /// implements the check in C++ [over.match.oper]p3b2 concerning
5825 /// enumeration types.
5826 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5827                                                    FunctionDecl *Fn,
5828                                                    ArrayRef<Expr *> Args) {
5829   QualType T1 = Args[0]->getType();
5830   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5831 
5832   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5833     return true;
5834 
5835   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5836     return true;
5837 
5838   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5839   if (Proto->getNumParams() < 1)
5840     return false;
5841 
5842   if (T1->isEnumeralType()) {
5843     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5844     if (Context.hasSameUnqualifiedType(T1, ArgType))
5845       return true;
5846   }
5847 
5848   if (Proto->getNumParams() < 2)
5849     return false;
5850 
5851   if (!T2.isNull() && T2->isEnumeralType()) {
5852     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5853     if (Context.hasSameUnqualifiedType(T2, ArgType))
5854       return true;
5855   }
5856 
5857   return false;
5858 }
5859 
5860 /// AddOverloadCandidate - Adds the given function to the set of
5861 /// candidate functions, using the given function call arguments.  If
5862 /// @p SuppressUserConversions, then don't allow user-defined
5863 /// conversions via constructors or conversion operators.
5864 ///
5865 /// \param PartialOverloading true if we are performing "partial" overloading
5866 /// based on an incomplete set of function arguments. This feature is used by
5867 /// code completion.
5868 void
5869 Sema::AddOverloadCandidate(FunctionDecl *Function,
5870                            DeclAccessPair FoundDecl,
5871                            ArrayRef<Expr *> Args,
5872                            OverloadCandidateSet &CandidateSet,
5873                            bool SuppressUserConversions,
5874                            bool PartialOverloading,
5875                            bool AllowExplicit,
5876                            ConversionSequenceList EarlyConversions) {
5877   const FunctionProtoType *Proto
5878     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5879   assert(Proto && "Functions without a prototype cannot be overloaded");
5880   assert(!Function->getDescribedFunctionTemplate() &&
5881          "Use AddTemplateOverloadCandidate for function templates");
5882 
5883   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5884     if (!isa<CXXConstructorDecl>(Method)) {
5885       // If we get here, it's because we're calling a member function
5886       // that is named without a member access expression (e.g.,
5887       // "this->f") that was either written explicitly or created
5888       // implicitly. This can happen with a qualified call to a member
5889       // function, e.g., X::f(). We use an empty type for the implied
5890       // object argument (C++ [over.call.func]p3), and the acting context
5891       // is irrelevant.
5892       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5893                          Expr::Classification::makeSimpleLValue(), Args,
5894                          CandidateSet, SuppressUserConversions,
5895                          PartialOverloading, EarlyConversions);
5896       return;
5897     }
5898     // We treat a constructor like a non-member function, since its object
5899     // argument doesn't participate in overload resolution.
5900   }
5901 
5902   if (!CandidateSet.isNewCandidate(Function))
5903     return;
5904 
5905   // C++ [over.match.oper]p3:
5906   //   if no operand has a class type, only those non-member functions in the
5907   //   lookup set that have a first parameter of type T1 or "reference to
5908   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5909   //   is a right operand) a second parameter of type T2 or "reference to
5910   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5911   //   candidate functions.
5912   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5913       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5914     return;
5915 
5916   // C++11 [class.copy]p11: [DR1402]
5917   //   A defaulted move constructor that is defined as deleted is ignored by
5918   //   overload resolution.
5919   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5920   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5921       Constructor->isMoveConstructor())
5922     return;
5923 
5924   // Overload resolution is always an unevaluated context.
5925   EnterExpressionEvaluationContext Unevaluated(
5926       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5927 
5928   // Add this candidate
5929   OverloadCandidate &Candidate =
5930       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5931   Candidate.FoundDecl = FoundDecl;
5932   Candidate.Function = Function;
5933   Candidate.Viable = true;
5934   Candidate.IsSurrogate = false;
5935   Candidate.IgnoreObjectArgument = false;
5936   Candidate.ExplicitCallArguments = Args.size();
5937 
5938   if (Constructor) {
5939     // C++ [class.copy]p3:
5940     //   A member function template is never instantiated to perform the copy
5941     //   of a class object to an object of its class type.
5942     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5943     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5944         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5945          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5946                        ClassType))) {
5947       Candidate.Viable = false;
5948       Candidate.FailureKind = ovl_fail_illegal_constructor;
5949       return;
5950     }
5951 
5952     // C++ [over.match.funcs]p8: (proposed DR resolution)
5953     //   A constructor inherited from class type C that has a first parameter
5954     //   of type "reference to P" (including such a constructor instantiated
5955     //   from a template) is excluded from the set of candidate functions when
5956     //   constructing an object of type cv D if the argument list has exactly
5957     //   one argument and D is reference-related to P and P is reference-related
5958     //   to C.
5959     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5960     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5961         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5962       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5963       QualType C = Context.getRecordType(Constructor->getParent());
5964       QualType D = Context.getRecordType(Shadow->getParent());
5965       SourceLocation Loc = Args.front()->getExprLoc();
5966       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5967           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5968         Candidate.Viable = false;
5969         Candidate.FailureKind = ovl_fail_inhctor_slice;
5970         return;
5971       }
5972     }
5973   }
5974 
5975   unsigned NumParams = Proto->getNumParams();
5976 
5977   // (C++ 13.3.2p2): A candidate function having fewer than m
5978   // parameters is viable only if it has an ellipsis in its parameter
5979   // list (8.3.5).
5980   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5981       !Proto->isVariadic()) {
5982     Candidate.Viable = false;
5983     Candidate.FailureKind = ovl_fail_too_many_arguments;
5984     return;
5985   }
5986 
5987   // (C++ 13.3.2p2): A candidate function having more than m parameters
5988   // is viable only if the (m+1)st parameter has a default argument
5989   // (8.3.6). For the purposes of overload resolution, the
5990   // parameter list is truncated on the right, so that there are
5991   // exactly m parameters.
5992   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5993   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5994     // Not enough arguments.
5995     Candidate.Viable = false;
5996     Candidate.FailureKind = ovl_fail_too_few_arguments;
5997     return;
5998   }
5999 
6000   // (CUDA B.1): Check for invalid calls between targets.
6001   if (getLangOpts().CUDA)
6002     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6003       // Skip the check for callers that are implicit members, because in this
6004       // case we may not yet know what the member's target is; the target is
6005       // inferred for the member automatically, based on the bases and fields of
6006       // the class.
6007       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6008         Candidate.Viable = false;
6009         Candidate.FailureKind = ovl_fail_bad_target;
6010         return;
6011       }
6012 
6013   // Determine the implicit conversion sequences for each of the
6014   // arguments.
6015   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6016     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6017       // We already formed a conversion sequence for this parameter during
6018       // template argument deduction.
6019     } else if (ArgIdx < NumParams) {
6020       // (C++ 13.3.2p3): for F to be a viable function, there shall
6021       // exist for each argument an implicit conversion sequence
6022       // (13.3.3.1) that converts that argument to the corresponding
6023       // parameter of F.
6024       QualType ParamType = Proto->getParamType(ArgIdx);
6025       Candidate.Conversions[ArgIdx]
6026         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6027                                 SuppressUserConversions,
6028                                 /*InOverloadResolution=*/true,
6029                                 /*AllowObjCWritebackConversion=*/
6030                                   getLangOpts().ObjCAutoRefCount,
6031                                 AllowExplicit);
6032       if (Candidate.Conversions[ArgIdx].isBad()) {
6033         Candidate.Viable = false;
6034         Candidate.FailureKind = ovl_fail_bad_conversion;
6035         return;
6036       }
6037     } else {
6038       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6039       // argument for which there is no corresponding parameter is
6040       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6041       Candidate.Conversions[ArgIdx].setEllipsis();
6042     }
6043   }
6044 
6045   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6046     Candidate.Viable = false;
6047     Candidate.FailureKind = ovl_fail_enable_if;
6048     Candidate.DeductionFailure.Data = FailedAttr;
6049     return;
6050   }
6051 
6052   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6053     Candidate.Viable = false;
6054     Candidate.FailureKind = ovl_fail_ext_disabled;
6055     return;
6056   }
6057 }
6058 
6059 ObjCMethodDecl *
6060 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6061                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6062   if (Methods.size() <= 1)
6063     return nullptr;
6064 
6065   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6066     bool Match = true;
6067     ObjCMethodDecl *Method = Methods[b];
6068     unsigned NumNamedArgs = Sel.getNumArgs();
6069     // Method might have more arguments than selector indicates. This is due
6070     // to addition of c-style arguments in method.
6071     if (Method->param_size() > NumNamedArgs)
6072       NumNamedArgs = Method->param_size();
6073     if (Args.size() < NumNamedArgs)
6074       continue;
6075 
6076     for (unsigned i = 0; i < NumNamedArgs; i++) {
6077       // We can't do any type-checking on a type-dependent argument.
6078       if (Args[i]->isTypeDependent()) {
6079         Match = false;
6080         break;
6081       }
6082 
6083       ParmVarDecl *param = Method->parameters()[i];
6084       Expr *argExpr = Args[i];
6085       assert(argExpr && "SelectBestMethod(): missing expression");
6086 
6087       // Strip the unbridged-cast placeholder expression off unless it's
6088       // a consumed argument.
6089       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6090           !param->hasAttr<CFConsumedAttr>())
6091         argExpr = stripARCUnbridgedCast(argExpr);
6092 
6093       // If the parameter is __unknown_anytype, move on to the next method.
6094       if (param->getType() == Context.UnknownAnyTy) {
6095         Match = false;
6096         break;
6097       }
6098 
6099       ImplicitConversionSequence ConversionState
6100         = TryCopyInitialization(*this, argExpr, param->getType(),
6101                                 /*SuppressUserConversions*/false,
6102                                 /*InOverloadResolution=*/true,
6103                                 /*AllowObjCWritebackConversion=*/
6104                                 getLangOpts().ObjCAutoRefCount,
6105                                 /*AllowExplicit*/false);
6106       // This function looks for a reasonably-exact match, so we consider
6107       // incompatible pointer conversions to be a failure here.
6108       if (ConversionState.isBad() ||
6109           (ConversionState.isStandard() &&
6110            ConversionState.Standard.Second ==
6111                ICK_Incompatible_Pointer_Conversion)) {
6112         Match = false;
6113         break;
6114       }
6115     }
6116     // Promote additional arguments to variadic methods.
6117     if (Match && Method->isVariadic()) {
6118       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6119         if (Args[i]->isTypeDependent()) {
6120           Match = false;
6121           break;
6122         }
6123         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6124                                                           nullptr);
6125         if (Arg.isInvalid()) {
6126           Match = false;
6127           break;
6128         }
6129       }
6130     } else {
6131       // Check for extra arguments to non-variadic methods.
6132       if (Args.size() != NumNamedArgs)
6133         Match = false;
6134       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6135         // Special case when selectors have no argument. In this case, select
6136         // one with the most general result type of 'id'.
6137         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6138           QualType ReturnT = Methods[b]->getReturnType();
6139           if (ReturnT->isObjCIdType())
6140             return Methods[b];
6141         }
6142       }
6143     }
6144 
6145     if (Match)
6146       return Method;
6147   }
6148   return nullptr;
6149 }
6150 
6151 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6152 // enable_if is order-sensitive. As a result, we need to reverse things
6153 // sometimes. Size of 4 elements is arbitrary.
6154 static SmallVector<EnableIfAttr *, 4>
6155 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6156   SmallVector<EnableIfAttr *, 4> Result;
6157   if (!Function->hasAttrs())
6158     return Result;
6159 
6160   const auto &FuncAttrs = Function->getAttrs();
6161   for (Attr *Attr : FuncAttrs)
6162     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6163       Result.push_back(EnableIf);
6164 
6165   std::reverse(Result.begin(), Result.end());
6166   return Result;
6167 }
6168 
6169 static bool
6170 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6171                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6172                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6173                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6174   if (ThisArg) {
6175     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6176     assert(!isa<CXXConstructorDecl>(Method) &&
6177            "Shouldn't have `this` for ctors!");
6178     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6179     ExprResult R = S.PerformObjectArgumentInitialization(
6180         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6181     if (R.isInvalid())
6182       return false;
6183     ConvertedThis = R.get();
6184   } else {
6185     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6186       (void)MD;
6187       assert((MissingImplicitThis || MD->isStatic() ||
6188               isa<CXXConstructorDecl>(MD)) &&
6189              "Expected `this` for non-ctor instance methods");
6190     }
6191     ConvertedThis = nullptr;
6192   }
6193 
6194   // Ignore any variadic arguments. Converting them is pointless, since the
6195   // user can't refer to them in the function condition.
6196   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6197 
6198   // Convert the arguments.
6199   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6200     ExprResult R;
6201     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6202                                         S.Context, Function->getParamDecl(I)),
6203                                     SourceLocation(), Args[I]);
6204 
6205     if (R.isInvalid())
6206       return false;
6207 
6208     ConvertedArgs.push_back(R.get());
6209   }
6210 
6211   if (Trap.hasErrorOccurred())
6212     return false;
6213 
6214   // Push default arguments if needed.
6215   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6216     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6217       ParmVarDecl *P = Function->getParamDecl(i);
6218       ExprResult R = S.PerformCopyInitialization(
6219           InitializedEntity::InitializeParameter(S.Context,
6220                                                  Function->getParamDecl(i)),
6221           SourceLocation(),
6222           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6223                                            : P->getDefaultArg());
6224       if (R.isInvalid())
6225         return false;
6226       ConvertedArgs.push_back(R.get());
6227     }
6228 
6229     if (Trap.hasErrorOccurred())
6230       return false;
6231   }
6232   return true;
6233 }
6234 
6235 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6236                                   bool MissingImplicitThis) {
6237   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6238       getOrderedEnableIfAttrs(Function);
6239   if (EnableIfAttrs.empty())
6240     return nullptr;
6241 
6242   SFINAETrap Trap(*this);
6243   SmallVector<Expr *, 16> ConvertedArgs;
6244   // FIXME: We should look into making enable_if late-parsed.
6245   Expr *DiscardedThis;
6246   if (!convertArgsForAvailabilityChecks(
6247           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6248           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6249     return EnableIfAttrs[0];
6250 
6251   for (auto *EIA : EnableIfAttrs) {
6252     APValue Result;
6253     // FIXME: This doesn't consider value-dependent cases, because doing so is
6254     // very difficult. Ideally, we should handle them more gracefully.
6255     if (!EIA->getCond()->EvaluateWithSubstitution(
6256             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6257       return EIA;
6258 
6259     if (!Result.isInt() || !Result.getInt().getBoolValue())
6260       return EIA;
6261   }
6262   return nullptr;
6263 }
6264 
6265 template <typename CheckFn>
6266 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6267                                         bool ArgDependent, SourceLocation Loc,
6268                                         CheckFn &&IsSuccessful) {
6269   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6270   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6271     if (ArgDependent == DIA->getArgDependent())
6272       Attrs.push_back(DIA);
6273   }
6274 
6275   // Common case: No diagnose_if attributes, so we can quit early.
6276   if (Attrs.empty())
6277     return false;
6278 
6279   auto WarningBegin = std::stable_partition(
6280       Attrs.begin(), Attrs.end(),
6281       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6282 
6283   // Note that diagnose_if attributes are late-parsed, so they appear in the
6284   // correct order (unlike enable_if attributes).
6285   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6286                                IsSuccessful);
6287   if (ErrAttr != WarningBegin) {
6288     const DiagnoseIfAttr *DIA = *ErrAttr;
6289     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6290     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6291         << DIA->getParent() << DIA->getCond()->getSourceRange();
6292     return true;
6293   }
6294 
6295   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6296     if (IsSuccessful(DIA)) {
6297       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6298       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6299           << DIA->getParent() << DIA->getCond()->getSourceRange();
6300     }
6301 
6302   return false;
6303 }
6304 
6305 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6306                                                const Expr *ThisArg,
6307                                                ArrayRef<const Expr *> Args,
6308                                                SourceLocation Loc) {
6309   return diagnoseDiagnoseIfAttrsWith(
6310       *this, Function, /*ArgDependent=*/true, Loc,
6311       [&](const DiagnoseIfAttr *DIA) {
6312         APValue Result;
6313         // It's sane to use the same Args for any redecl of this function, since
6314         // EvaluateWithSubstitution only cares about the position of each
6315         // argument in the arg list, not the ParmVarDecl* it maps to.
6316         if (!DIA->getCond()->EvaluateWithSubstitution(
6317                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6318           return false;
6319         return Result.isInt() && Result.getInt().getBoolValue();
6320       });
6321 }
6322 
6323 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6324                                                  SourceLocation Loc) {
6325   return diagnoseDiagnoseIfAttrsWith(
6326       *this, ND, /*ArgDependent=*/false, Loc,
6327       [&](const DiagnoseIfAttr *DIA) {
6328         bool Result;
6329         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6330                Result;
6331       });
6332 }
6333 
6334 /// \brief Add all of the function declarations in the given function set to
6335 /// the overload candidate set.
6336 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6337                                  ArrayRef<Expr *> Args,
6338                                  OverloadCandidateSet& CandidateSet,
6339                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6340                                  bool SuppressUserConversions,
6341                                  bool PartialOverloading) {
6342   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6343     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6344     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6345       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6346         QualType ObjectType;
6347         Expr::Classification ObjectClassification;
6348         if (Expr *E = Args[0]) {
6349           // Use the explit base to restrict the lookup:
6350           ObjectType = E->getType();
6351           ObjectClassification = E->Classify(Context);
6352         } // .. else there is an implit base.
6353         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6354                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6355                            ObjectClassification, Args.slice(1), CandidateSet,
6356                            SuppressUserConversions, PartialOverloading);
6357       } else {
6358         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6359                              SuppressUserConversions, PartialOverloading);
6360       }
6361     } else {
6362       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6363       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6364           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6365         QualType ObjectType;
6366         Expr::Classification ObjectClassification;
6367         if (Expr *E = Args[0]) {
6368           // Use the explit base to restrict the lookup:
6369           ObjectType = E->getType();
6370           ObjectClassification = E->Classify(Context);
6371         } // .. else there is an implit base.
6372         AddMethodTemplateCandidate(
6373             FunTmpl, F.getPair(),
6374             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6375             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6376             Args.slice(1), CandidateSet, SuppressUserConversions,
6377             PartialOverloading);
6378       } else {
6379         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6380                                      ExplicitTemplateArgs, Args,
6381                                      CandidateSet, SuppressUserConversions,
6382                                      PartialOverloading);
6383       }
6384     }
6385   }
6386 }
6387 
6388 /// AddMethodCandidate - Adds a named decl (which is some kind of
6389 /// method) as a method candidate to the given overload set.
6390 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6391                               QualType ObjectType,
6392                               Expr::Classification ObjectClassification,
6393                               ArrayRef<Expr *> Args,
6394                               OverloadCandidateSet& CandidateSet,
6395                               bool SuppressUserConversions) {
6396   NamedDecl *Decl = FoundDecl.getDecl();
6397   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6398 
6399   if (isa<UsingShadowDecl>(Decl))
6400     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6401 
6402   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6403     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6404            "Expected a member function template");
6405     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6406                                /*ExplicitArgs*/ nullptr, ObjectType,
6407                                ObjectClassification, Args, CandidateSet,
6408                                SuppressUserConversions);
6409   } else {
6410     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6411                        ObjectType, ObjectClassification, Args, CandidateSet,
6412                        SuppressUserConversions);
6413   }
6414 }
6415 
6416 /// AddMethodCandidate - Adds the given C++ member function to the set
6417 /// of candidate functions, using the given function call arguments
6418 /// and the object argument (@c Object). For example, in a call
6419 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6420 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6421 /// allow user-defined conversions via constructors or conversion
6422 /// operators.
6423 void
6424 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6425                          CXXRecordDecl *ActingContext, QualType ObjectType,
6426                          Expr::Classification ObjectClassification,
6427                          ArrayRef<Expr *> Args,
6428                          OverloadCandidateSet &CandidateSet,
6429                          bool SuppressUserConversions,
6430                          bool PartialOverloading,
6431                          ConversionSequenceList EarlyConversions) {
6432   const FunctionProtoType *Proto
6433     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6434   assert(Proto && "Methods without a prototype cannot be overloaded");
6435   assert(!isa<CXXConstructorDecl>(Method) &&
6436          "Use AddOverloadCandidate for constructors");
6437 
6438   if (!CandidateSet.isNewCandidate(Method))
6439     return;
6440 
6441   // C++11 [class.copy]p23: [DR1402]
6442   //   A defaulted move assignment operator that is defined as deleted is
6443   //   ignored by overload resolution.
6444   if (Method->isDefaulted() && Method->isDeleted() &&
6445       Method->isMoveAssignmentOperator())
6446     return;
6447 
6448   // Overload resolution is always an unevaluated context.
6449   EnterExpressionEvaluationContext Unevaluated(
6450       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6451 
6452   // Add this candidate
6453   OverloadCandidate &Candidate =
6454       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6455   Candidate.FoundDecl = FoundDecl;
6456   Candidate.Function = Method;
6457   Candidate.IsSurrogate = false;
6458   Candidate.IgnoreObjectArgument = false;
6459   Candidate.ExplicitCallArguments = Args.size();
6460 
6461   unsigned NumParams = Proto->getNumParams();
6462 
6463   // (C++ 13.3.2p2): A candidate function having fewer than m
6464   // parameters is viable only if it has an ellipsis in its parameter
6465   // list (8.3.5).
6466   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6467       !Proto->isVariadic()) {
6468     Candidate.Viable = false;
6469     Candidate.FailureKind = ovl_fail_too_many_arguments;
6470     return;
6471   }
6472 
6473   // (C++ 13.3.2p2): A candidate function having more than m parameters
6474   // is viable only if the (m+1)st parameter has a default argument
6475   // (8.3.6). For the purposes of overload resolution, the
6476   // parameter list is truncated on the right, so that there are
6477   // exactly m parameters.
6478   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6479   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6480     // Not enough arguments.
6481     Candidate.Viable = false;
6482     Candidate.FailureKind = ovl_fail_too_few_arguments;
6483     return;
6484   }
6485 
6486   Candidate.Viable = true;
6487 
6488   if (Method->isStatic() || ObjectType.isNull())
6489     // The implicit object argument is ignored.
6490     Candidate.IgnoreObjectArgument = true;
6491   else {
6492     // Determine the implicit conversion sequence for the object
6493     // parameter.
6494     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6495         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6496         Method, ActingContext);
6497     if (Candidate.Conversions[0].isBad()) {
6498       Candidate.Viable = false;
6499       Candidate.FailureKind = ovl_fail_bad_conversion;
6500       return;
6501     }
6502   }
6503 
6504   // (CUDA B.1): Check for invalid calls between targets.
6505   if (getLangOpts().CUDA)
6506     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6507       if (!IsAllowedCUDACall(Caller, Method)) {
6508         Candidate.Viable = false;
6509         Candidate.FailureKind = ovl_fail_bad_target;
6510         return;
6511       }
6512 
6513   // Determine the implicit conversion sequences for each of the
6514   // arguments.
6515   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6516     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6517       // We already formed a conversion sequence for this parameter during
6518       // template argument deduction.
6519     } else if (ArgIdx < NumParams) {
6520       // (C++ 13.3.2p3): for F to be a viable function, there shall
6521       // exist for each argument an implicit conversion sequence
6522       // (13.3.3.1) that converts that argument to the corresponding
6523       // parameter of F.
6524       QualType ParamType = Proto->getParamType(ArgIdx);
6525       Candidate.Conversions[ArgIdx + 1]
6526         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6527                                 SuppressUserConversions,
6528                                 /*InOverloadResolution=*/true,
6529                                 /*AllowObjCWritebackConversion=*/
6530                                   getLangOpts().ObjCAutoRefCount);
6531       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6532         Candidate.Viable = false;
6533         Candidate.FailureKind = ovl_fail_bad_conversion;
6534         return;
6535       }
6536     } else {
6537       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6538       // argument for which there is no corresponding parameter is
6539       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6540       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6541     }
6542   }
6543 
6544   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6545     Candidate.Viable = false;
6546     Candidate.FailureKind = ovl_fail_enable_if;
6547     Candidate.DeductionFailure.Data = FailedAttr;
6548     return;
6549   }
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                                  ArrayRef<Expr *> Args,
6563                                  OverloadCandidateSet& CandidateSet,
6564                                  bool SuppressUserConversions,
6565                                  bool PartialOverloading) {
6566   if (!CandidateSet.isNewCandidate(MethodTmpl))
6567     return;
6568 
6569   // C++ [over.match.funcs]p7:
6570   //   In each case where a candidate is a function template, candidate
6571   //   function template specializations are generated using template argument
6572   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6573   //   candidate functions in the usual way.113) A given name can refer to one
6574   //   or more function templates and also to a set of overloaded non-template
6575   //   functions. In such a case, the candidate functions generated from each
6576   //   function template are combined with the set of non-template candidate
6577   //   functions.
6578   TemplateDeductionInfo Info(CandidateSet.getLocation());
6579   FunctionDecl *Specialization = nullptr;
6580   ConversionSequenceList Conversions;
6581   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6582           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6583           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6584             return CheckNonDependentConversions(
6585                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6586                 SuppressUserConversions, ActingContext, ObjectType,
6587                 ObjectClassification);
6588           })) {
6589     OverloadCandidate &Candidate =
6590         CandidateSet.addCandidate(Conversions.size(), Conversions);
6591     Candidate.FoundDecl = FoundDecl;
6592     Candidate.Function = MethodTmpl->getTemplatedDecl();
6593     Candidate.Viable = false;
6594     Candidate.IsSurrogate = false;
6595     Candidate.IgnoreObjectArgument =
6596         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6597         ObjectType.isNull();
6598     Candidate.ExplicitCallArguments = Args.size();
6599     if (Result == TDK_NonDependentConversionFailure)
6600       Candidate.FailureKind = ovl_fail_bad_conversion;
6601     else {
6602       Candidate.FailureKind = ovl_fail_bad_deduction;
6603       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6604                                                             Info);
6605     }
6606     return;
6607   }
6608 
6609   // Add the function template specialization produced by template argument
6610   // deduction as a candidate.
6611   assert(Specialization && "Missing member function template specialization?");
6612   assert(isa<CXXMethodDecl>(Specialization) &&
6613          "Specialization is not a member function?");
6614   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6615                      ActingContext, ObjectType, ObjectClassification, Args,
6616                      CandidateSet, SuppressUserConversions, PartialOverloading,
6617                      Conversions);
6618 }
6619 
6620 /// \brief Add a C++ function template specialization as a candidate
6621 /// in the candidate set, using template argument deduction to produce
6622 /// an appropriate function template specialization.
6623 void
6624 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6625                                    DeclAccessPair FoundDecl,
6626                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6627                                    ArrayRef<Expr *> Args,
6628                                    OverloadCandidateSet& CandidateSet,
6629                                    bool SuppressUserConversions,
6630                                    bool PartialOverloading) {
6631   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6632     return;
6633 
6634   // C++ [over.match.funcs]p7:
6635   //   In each case where a candidate is a function template, candidate
6636   //   function template specializations are generated using template argument
6637   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6638   //   candidate functions in the usual way.113) A given name can refer to one
6639   //   or more function templates and also to a set of overloaded non-template
6640   //   functions. In such a case, the candidate functions generated from each
6641   //   function template are combined with the set of non-template candidate
6642   //   functions.
6643   TemplateDeductionInfo Info(CandidateSet.getLocation());
6644   FunctionDecl *Specialization = nullptr;
6645   ConversionSequenceList Conversions;
6646   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6647           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6648           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6649             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6650                                                 Args, CandidateSet, Conversions,
6651                                                 SuppressUserConversions);
6652           })) {
6653     OverloadCandidate &Candidate =
6654         CandidateSet.addCandidate(Conversions.size(), Conversions);
6655     Candidate.FoundDecl = FoundDecl;
6656     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6657     Candidate.Viable = false;
6658     Candidate.IsSurrogate = false;
6659     // Ignore the object argument if there is one, since we don't have an object
6660     // type.
6661     Candidate.IgnoreObjectArgument =
6662         isa<CXXMethodDecl>(Candidate.Function) &&
6663         !isa<CXXConstructorDecl>(Candidate.Function);
6664     Candidate.ExplicitCallArguments = Args.size();
6665     if (Result == TDK_NonDependentConversionFailure)
6666       Candidate.FailureKind = ovl_fail_bad_conversion;
6667     else {
6668       Candidate.FailureKind = ovl_fail_bad_deduction;
6669       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6670                                                             Info);
6671     }
6672     return;
6673   }
6674 
6675   // Add the function template specialization produced by template argument
6676   // deduction as a candidate.
6677   assert(Specialization && "Missing function template specialization?");
6678   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6679                        SuppressUserConversions, PartialOverloading,
6680                        /*AllowExplicit*/false, Conversions);
6681 }
6682 
6683 /// Check that implicit conversion sequences can be formed for each argument
6684 /// whose corresponding parameter has a non-dependent type, per DR1391's
6685 /// [temp.deduct.call]p10.
6686 bool Sema::CheckNonDependentConversions(
6687     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6688     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6689     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6690     CXXRecordDecl *ActingContext, QualType ObjectType,
6691     Expr::Classification ObjectClassification) {
6692   // FIXME: The cases in which we allow explicit conversions for constructor
6693   // arguments never consider calling a constructor template. It's not clear
6694   // that is correct.
6695   const bool AllowExplicit = false;
6696 
6697   auto *FD = FunctionTemplate->getTemplatedDecl();
6698   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6699   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6700   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6701 
6702   Conversions =
6703       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6704 
6705   // Overload resolution is always an unevaluated context.
6706   EnterExpressionEvaluationContext Unevaluated(
6707       *this, Sema::ExpressionEvaluationContext::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(
6816       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6817 
6818   // Add this candidate
6819   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6820   Candidate.FoundDecl = FoundDecl;
6821   Candidate.Function = Conversion;
6822   Candidate.IsSurrogate = false;
6823   Candidate.IgnoreObjectArgument = false;
6824   Candidate.FinalConversion.setAsIdentityConversion();
6825   Candidate.FinalConversion.setFromType(ConvType);
6826   Candidate.FinalConversion.setAllToTypes(ToType);
6827   Candidate.Viable = true;
6828   Candidate.ExplicitCallArguments = 1;
6829 
6830   // C++ [over.match.funcs]p4:
6831   //   For conversion functions, the function is considered to be a member of
6832   //   the class of the implicit implied object argument for the purpose of
6833   //   defining the type of the implicit object parameter.
6834   //
6835   // Determine the implicit conversion sequence for the implicit
6836   // object parameter.
6837   QualType ImplicitParamType = From->getType();
6838   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6839     ImplicitParamType = FromPtrType->getPointeeType();
6840   CXXRecordDecl *ConversionContext
6841     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6842 
6843   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6844       *this, CandidateSet.getLocation(), From->getType(),
6845       From->Classify(Context), Conversion, ConversionContext);
6846 
6847   if (Candidate.Conversions[0].isBad()) {
6848     Candidate.Viable = false;
6849     Candidate.FailureKind = ovl_fail_bad_conversion;
6850     return;
6851   }
6852 
6853   // We won't go through a user-defined type conversion function to convert a
6854   // derived to base as such conversions are given Conversion Rank. They only
6855   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6856   QualType FromCanon
6857     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6858   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6859   if (FromCanon == ToCanon ||
6860       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6861     Candidate.Viable = false;
6862     Candidate.FailureKind = ovl_fail_trivial_conversion;
6863     return;
6864   }
6865 
6866   // To determine what the conversion from the result of calling the
6867   // conversion function to the type we're eventually trying to
6868   // convert to (ToType), we need to synthesize a call to the
6869   // conversion function and attempt copy initialization from it. This
6870   // makes sure that we get the right semantics with respect to
6871   // lvalues/rvalues and the type. Fortunately, we can allocate this
6872   // call on the stack and we don't need its arguments to be
6873   // well-formed.
6874   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6875                             VK_LValue, From->getLocStart());
6876   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6877                                 Context.getPointerType(Conversion->getType()),
6878                                 CK_FunctionToPointerDecay,
6879                                 &ConversionRef, VK_RValue);
6880 
6881   QualType ConversionType = Conversion->getConversionType();
6882   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6883     Candidate.Viable = false;
6884     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6885     return;
6886   }
6887 
6888   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6889 
6890   // Note that it is safe to allocate CallExpr on the stack here because
6891   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6892   // allocator).
6893   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6894   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6895                 From->getLocStart());
6896   ImplicitConversionSequence ICS =
6897     TryCopyInitialization(*this, &Call, ToType,
6898                           /*SuppressUserConversions=*/true,
6899                           /*InOverloadResolution=*/false,
6900                           /*AllowObjCWritebackConversion=*/false);
6901 
6902   switch (ICS.getKind()) {
6903   case ImplicitConversionSequence::StandardConversion:
6904     Candidate.FinalConversion = ICS.Standard;
6905 
6906     // C++ [over.ics.user]p3:
6907     //   If the user-defined conversion is specified by a specialization of a
6908     //   conversion function template, the second standard conversion sequence
6909     //   shall have exact match rank.
6910     if (Conversion->getPrimaryTemplate() &&
6911         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6912       Candidate.Viable = false;
6913       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6914       return;
6915     }
6916 
6917     // C++0x [dcl.init.ref]p5:
6918     //    In the second case, if the reference is an rvalue reference and
6919     //    the second standard conversion sequence of the user-defined
6920     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6921     //    program is ill-formed.
6922     if (ToType->isRValueReferenceType() &&
6923         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6924       Candidate.Viable = false;
6925       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6926       return;
6927     }
6928     break;
6929 
6930   case ImplicitConversionSequence::BadConversion:
6931     Candidate.Viable = false;
6932     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6933     return;
6934 
6935   default:
6936     llvm_unreachable(
6937            "Can only end up with a standard conversion sequence or failure");
6938   }
6939 
6940   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6941     Candidate.Viable = false;
6942     Candidate.FailureKind = ovl_fail_enable_if;
6943     Candidate.DeductionFailure.Data = FailedAttr;
6944     return;
6945   }
6946 }
6947 
6948 /// \brief Adds a conversion function template specialization
6949 /// candidate to the overload set, using template argument deduction
6950 /// to deduce the template arguments of the conversion function
6951 /// template from the type that we are converting to (C++
6952 /// [temp.deduct.conv]).
6953 void
6954 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6955                                      DeclAccessPair FoundDecl,
6956                                      CXXRecordDecl *ActingDC,
6957                                      Expr *From, QualType ToType,
6958                                      OverloadCandidateSet &CandidateSet,
6959                                      bool AllowObjCConversionOnExplicit) {
6960   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6961          "Only conversion function templates permitted here");
6962 
6963   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6964     return;
6965 
6966   TemplateDeductionInfo Info(CandidateSet.getLocation());
6967   CXXConversionDecl *Specialization = nullptr;
6968   if (TemplateDeductionResult Result
6969         = DeduceTemplateArguments(FunctionTemplate, ToType,
6970                                   Specialization, Info)) {
6971     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6972     Candidate.FoundDecl = FoundDecl;
6973     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6974     Candidate.Viable = false;
6975     Candidate.FailureKind = ovl_fail_bad_deduction;
6976     Candidate.IsSurrogate = false;
6977     Candidate.IgnoreObjectArgument = false;
6978     Candidate.ExplicitCallArguments = 1;
6979     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6980                                                           Info);
6981     return;
6982   }
6983 
6984   // Add the conversion function template specialization produced by
6985   // template argument deduction as a candidate.
6986   assert(Specialization && "Missing function template specialization?");
6987   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6988                          CandidateSet, AllowObjCConversionOnExplicit);
6989 }
6990 
6991 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6992 /// converts the given @c Object to a function pointer via the
6993 /// conversion function @c Conversion, and then attempts to call it
6994 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6995 /// the type of function that we'll eventually be calling.
6996 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6997                                  DeclAccessPair FoundDecl,
6998                                  CXXRecordDecl *ActingContext,
6999                                  const FunctionProtoType *Proto,
7000                                  Expr *Object,
7001                                  ArrayRef<Expr *> Args,
7002                                  OverloadCandidateSet& CandidateSet) {
7003   if (!CandidateSet.isNewCandidate(Conversion))
7004     return;
7005 
7006   // Overload resolution is always an unevaluated context.
7007   EnterExpressionEvaluationContext Unevaluated(
7008       *this, Sema::ExpressionEvaluationContext::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 
7101 /// \brief Add overload candidates for overloaded operators that are
7102 /// member functions.
7103 ///
7104 /// Add the overloaded operator candidates that are member functions
7105 /// for the operator Op that was used in an operator expression such
7106 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7107 /// CandidateSet will store the added overload candidates. (C++
7108 /// [over.match.oper]).
7109 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7110                                        SourceLocation OpLoc,
7111                                        ArrayRef<Expr *> Args,
7112                                        OverloadCandidateSet& CandidateSet,
7113                                        SourceRange OpRange) {
7114   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7115 
7116   // C++ [over.match.oper]p3:
7117   //   For a unary operator @ with an operand of a type whose
7118   //   cv-unqualified version is T1, and for a binary operator @ with
7119   //   a left operand of a type whose cv-unqualified version is T1 and
7120   //   a right operand of a type whose cv-unqualified version is T2,
7121   //   three sets of candidate functions, designated member
7122   //   candidates, non-member candidates and built-in candidates, are
7123   //   constructed as follows:
7124   QualType T1 = Args[0]->getType();
7125 
7126   //     -- If T1 is a complete class type or a class currently being
7127   //        defined, the set of member candidates is the result of the
7128   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7129   //        the set of member candidates is empty.
7130   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7131     // Complete the type if it can be completed.
7132     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7133       return;
7134     // If the type is neither complete nor being defined, bail out now.
7135     if (!T1Rec->getDecl()->getDefinition())
7136       return;
7137 
7138     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7139     LookupQualifiedName(Operators, T1Rec->getDecl());
7140     Operators.suppressDiagnostics();
7141 
7142     for (LookupResult::iterator Oper = Operators.begin(),
7143                              OperEnd = Operators.end();
7144          Oper != OperEnd;
7145          ++Oper)
7146       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7147                          Args[0]->Classify(Context), Args.slice(1),
7148                          CandidateSet, /*SuppressUserConversions=*/false);
7149   }
7150 }
7151 
7152 /// AddBuiltinCandidate - Add a candidate for a built-in
7153 /// operator. ResultTy and ParamTys are the result and parameter types
7154 /// of the built-in candidate, respectively. Args and NumArgs are the
7155 /// arguments being passed to the candidate. IsAssignmentOperator
7156 /// should be true when this built-in candidate is an assignment
7157 /// operator. NumContextualBoolArguments is the number of arguments
7158 /// (at the beginning of the argument list) that will be contextually
7159 /// converted to bool.
7160 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7161                                OverloadCandidateSet& CandidateSet,
7162                                bool IsAssignmentOperator,
7163                                unsigned NumContextualBoolArguments) {
7164   // Overload resolution is always an unevaluated context.
7165   EnterExpressionEvaluationContext Unevaluated(
7166       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7167 
7168   // Add this candidate
7169   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7170   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7171   Candidate.Function = nullptr;
7172   Candidate.IsSurrogate = false;
7173   Candidate.IgnoreObjectArgument = false;
7174   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7175 
7176   // Determine the implicit conversion sequences for each of the
7177   // arguments.
7178   Candidate.Viable = true;
7179   Candidate.ExplicitCallArguments = Args.size();
7180   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7181     // C++ [over.match.oper]p4:
7182     //   For the built-in assignment operators, conversions of the
7183     //   left operand are restricted as follows:
7184     //     -- no temporaries are introduced to hold the left operand, and
7185     //     -- no user-defined conversions are applied to the left
7186     //        operand to achieve a type match with the left-most
7187     //        parameter of a built-in candidate.
7188     //
7189     // We block these conversions by turning off user-defined
7190     // conversions, since that is the only way that initialization of
7191     // a reference to a non-class type can occur from something that
7192     // is not of the same type.
7193     if (ArgIdx < NumContextualBoolArguments) {
7194       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7195              "Contextual conversion to bool requires bool type");
7196       Candidate.Conversions[ArgIdx]
7197         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7198     } else {
7199       Candidate.Conversions[ArgIdx]
7200         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7201                                 ArgIdx == 0 && IsAssignmentOperator,
7202                                 /*InOverloadResolution=*/false,
7203                                 /*AllowObjCWritebackConversion=*/
7204                                   getLangOpts().ObjCAutoRefCount);
7205     }
7206     if (Candidate.Conversions[ArgIdx].isBad()) {
7207       Candidate.Viable = false;
7208       Candidate.FailureKind = ovl_fail_bad_conversion;
7209       break;
7210     }
7211   }
7212 }
7213 
7214 namespace {
7215 
7216 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7217 /// candidate operator functions for built-in operators (C++
7218 /// [over.built]). The types are separated into pointer types and
7219 /// enumeration types.
7220 class BuiltinCandidateTypeSet  {
7221   /// TypeSet - A set of types.
7222   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7223                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7224 
7225   /// PointerTypes - The set of pointer types that will be used in the
7226   /// built-in candidates.
7227   TypeSet PointerTypes;
7228 
7229   /// MemberPointerTypes - The set of member pointer types that will be
7230   /// used in the built-in candidates.
7231   TypeSet MemberPointerTypes;
7232 
7233   /// EnumerationTypes - The set of enumeration types that will be
7234   /// used in the built-in candidates.
7235   TypeSet EnumerationTypes;
7236 
7237   /// \brief The set of vector types that will be used in the built-in
7238   /// candidates.
7239   TypeSet VectorTypes;
7240 
7241   /// \brief A flag indicating non-record types are viable candidates
7242   bool HasNonRecordTypes;
7243 
7244   /// \brief A flag indicating whether either arithmetic or enumeration types
7245   /// were present in the candidate set.
7246   bool HasArithmeticOrEnumeralTypes;
7247 
7248   /// \brief A flag indicating whether the nullptr type was present in the
7249   /// candidate set.
7250   bool HasNullPtrType;
7251 
7252   /// Sema - The semantic analysis instance where we are building the
7253   /// candidate type set.
7254   Sema &SemaRef;
7255 
7256   /// Context - The AST context in which we will build the type sets.
7257   ASTContext &Context;
7258 
7259   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7260                                                const Qualifiers &VisibleQuals);
7261   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7262 
7263 public:
7264   /// iterator - Iterates through the types that are part of the set.
7265   typedef TypeSet::iterator iterator;
7266 
7267   BuiltinCandidateTypeSet(Sema &SemaRef)
7268     : HasNonRecordTypes(false),
7269       HasArithmeticOrEnumeralTypes(false),
7270       HasNullPtrType(false),
7271       SemaRef(SemaRef),
7272       Context(SemaRef.Context) { }
7273 
7274   void AddTypesConvertedFrom(QualType Ty,
7275                              SourceLocation Loc,
7276                              bool AllowUserConversions,
7277                              bool AllowExplicitConversions,
7278                              const Qualifiers &VisibleTypeConversionsQuals);
7279 
7280   /// pointer_begin - First pointer type found;
7281   iterator pointer_begin() { return PointerTypes.begin(); }
7282 
7283   /// pointer_end - Past the last pointer type found;
7284   iterator pointer_end() { return PointerTypes.end(); }
7285 
7286   /// member_pointer_begin - First member pointer type found;
7287   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7288 
7289   /// member_pointer_end - Past the last member pointer type found;
7290   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7291 
7292   /// enumeration_begin - First enumeration type found;
7293   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7294 
7295   /// enumeration_end - Past the last enumeration type found;
7296   iterator enumeration_end() { return EnumerationTypes.end(); }
7297 
7298   iterator vector_begin() { return VectorTypes.begin(); }
7299   iterator vector_end() { return VectorTypes.end(); }
7300 
7301   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7302   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7303   bool hasNullPtrType() const { return HasNullPtrType; }
7304 };
7305 
7306 } // end anonymous namespace
7307 
7308 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7309 /// the set of pointer types along with any more-qualified variants of
7310 /// that type. For example, if @p Ty is "int const *", this routine
7311 /// will add "int const *", "int const volatile *", "int const
7312 /// restrict *", and "int const volatile restrict *" to the set of
7313 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7314 /// false otherwise.
7315 ///
7316 /// FIXME: what to do about extended qualifiers?
7317 bool
7318 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7319                                              const Qualifiers &VisibleQuals) {
7320 
7321   // Insert this type.
7322   if (!PointerTypes.insert(Ty))
7323     return false;
7324 
7325   QualType PointeeTy;
7326   const PointerType *PointerTy = Ty->getAs<PointerType>();
7327   bool buildObjCPtr = false;
7328   if (!PointerTy) {
7329     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7330     PointeeTy = PTy->getPointeeType();
7331     buildObjCPtr = true;
7332   } else {
7333     PointeeTy = PointerTy->getPointeeType();
7334   }
7335 
7336   // Don't add qualified variants of arrays. For one, they're not allowed
7337   // (the qualifier would sink to the element type), and for another, the
7338   // only overload situation where it matters is subscript or pointer +- int,
7339   // and those shouldn't have qualifier variants anyway.
7340   if (PointeeTy->isArrayType())
7341     return true;
7342 
7343   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7344   bool hasVolatile = VisibleQuals.hasVolatile();
7345   bool hasRestrict = VisibleQuals.hasRestrict();
7346 
7347   // Iterate through all strict supersets of BaseCVR.
7348   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7349     if ((CVR | BaseCVR) != CVR) continue;
7350     // Skip over volatile if no volatile found anywhere in the types.
7351     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7352 
7353     // Skip over restrict if no restrict found anywhere in the types, or if
7354     // the type cannot be restrict-qualified.
7355     if ((CVR & Qualifiers::Restrict) &&
7356         (!hasRestrict ||
7357          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7358       continue;
7359 
7360     // Build qualified pointee type.
7361     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7362 
7363     // Build qualified pointer type.
7364     QualType QPointerTy;
7365     if (!buildObjCPtr)
7366       QPointerTy = Context.getPointerType(QPointeeTy);
7367     else
7368       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7369 
7370     // Insert qualified pointer type.
7371     PointerTypes.insert(QPointerTy);
7372   }
7373 
7374   return true;
7375 }
7376 
7377 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7378 /// to the set of pointer types along with any more-qualified variants of
7379 /// that type. For example, if @p Ty is "int const *", this routine
7380 /// will add "int const *", "int const volatile *", "int const
7381 /// restrict *", and "int const volatile restrict *" to the set of
7382 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7383 /// false otherwise.
7384 ///
7385 /// FIXME: what to do about extended qualifiers?
7386 bool
7387 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7388     QualType Ty) {
7389   // Insert this type.
7390   if (!MemberPointerTypes.insert(Ty))
7391     return false;
7392 
7393   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7394   assert(PointerTy && "type was not a member pointer type!");
7395 
7396   QualType PointeeTy = PointerTy->getPointeeType();
7397   // Don't add qualified variants of arrays. For one, they're not allowed
7398   // (the qualifier would sink to the element type), and for another, the
7399   // only overload situation where it matters is subscript or pointer +- int,
7400   // and those shouldn't have qualifier variants anyway.
7401   if (PointeeTy->isArrayType())
7402     return true;
7403   const Type *ClassTy = PointerTy->getClass();
7404 
7405   // Iterate through all strict supersets of the pointee type's CVR
7406   // qualifiers.
7407   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7408   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7409     if ((CVR | BaseCVR) != CVR) continue;
7410 
7411     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7412     MemberPointerTypes.insert(
7413       Context.getMemberPointerType(QPointeeTy, ClassTy));
7414   }
7415 
7416   return true;
7417 }
7418 
7419 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7420 /// Ty can be implicit converted to the given set of @p Types. We're
7421 /// primarily interested in pointer types and enumeration types. We also
7422 /// take member pointer types, for the conditional operator.
7423 /// AllowUserConversions is true if we should look at the conversion
7424 /// functions of a class type, and AllowExplicitConversions if we
7425 /// should also include the explicit conversion functions of a class
7426 /// type.
7427 void
7428 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7429                                                SourceLocation Loc,
7430                                                bool AllowUserConversions,
7431                                                bool AllowExplicitConversions,
7432                                                const Qualifiers &VisibleQuals) {
7433   // Only deal with canonical types.
7434   Ty = Context.getCanonicalType(Ty);
7435 
7436   // Look through reference types; they aren't part of the type of an
7437   // expression for the purposes of conversions.
7438   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7439     Ty = RefTy->getPointeeType();
7440 
7441   // If we're dealing with an array type, decay to the pointer.
7442   if (Ty->isArrayType())
7443     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7444 
7445   // Otherwise, we don't care about qualifiers on the type.
7446   Ty = Ty.getLocalUnqualifiedType();
7447 
7448   // Flag if we ever add a non-record type.
7449   const RecordType *TyRec = Ty->getAs<RecordType>();
7450   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7451 
7452   // Flag if we encounter an arithmetic type.
7453   HasArithmeticOrEnumeralTypes =
7454     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7455 
7456   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7457     PointerTypes.insert(Ty);
7458   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7459     // Insert our type, and its more-qualified variants, into the set
7460     // of types.
7461     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7462       return;
7463   } else if (Ty->isMemberPointerType()) {
7464     // Member pointers are far easier, since the pointee can't be converted.
7465     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7466       return;
7467   } else if (Ty->isEnumeralType()) {
7468     HasArithmeticOrEnumeralTypes = true;
7469     EnumerationTypes.insert(Ty);
7470   } else if (Ty->isVectorType()) {
7471     // We treat vector types as arithmetic types in many contexts as an
7472     // extension.
7473     HasArithmeticOrEnumeralTypes = true;
7474     VectorTypes.insert(Ty);
7475   } else if (Ty->isNullPtrType()) {
7476     HasNullPtrType = true;
7477   } else if (AllowUserConversions && TyRec) {
7478     // No conversion functions in incomplete types.
7479     if (!SemaRef.isCompleteType(Loc, Ty))
7480       return;
7481 
7482     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7483     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7484       if (isa<UsingShadowDecl>(D))
7485         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7486 
7487       // Skip conversion function templates; they don't tell us anything
7488       // about which builtin types we can convert to.
7489       if (isa<FunctionTemplateDecl>(D))
7490         continue;
7491 
7492       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7493       if (AllowExplicitConversions || !Conv->isExplicit()) {
7494         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7495                               VisibleQuals);
7496       }
7497     }
7498   }
7499 }
7500 
7501 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7502 /// the volatile- and non-volatile-qualified assignment operators for the
7503 /// given type to the candidate set.
7504 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7505                                                    QualType T,
7506                                                    ArrayRef<Expr *> Args,
7507                                     OverloadCandidateSet &CandidateSet) {
7508   QualType ParamTypes[2];
7509 
7510   // T& operator=(T&, T)
7511   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7512   ParamTypes[1] = T;
7513   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7514                         /*IsAssignmentOperator=*/true);
7515 
7516   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7517     // volatile T& operator=(volatile T&, T)
7518     ParamTypes[0]
7519       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7520     ParamTypes[1] = T;
7521     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7522                           /*IsAssignmentOperator=*/true);
7523   }
7524 }
7525 
7526 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7527 /// if any, found in visible type conversion functions found in ArgExpr's type.
7528 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7529     Qualifiers VRQuals;
7530     const RecordType *TyRec;
7531     if (const MemberPointerType *RHSMPType =
7532         ArgExpr->getType()->getAs<MemberPointerType>())
7533       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7534     else
7535       TyRec = ArgExpr->getType()->getAs<RecordType>();
7536     if (!TyRec) {
7537       // Just to be safe, assume the worst case.
7538       VRQuals.addVolatile();
7539       VRQuals.addRestrict();
7540       return VRQuals;
7541     }
7542 
7543     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7544     if (!ClassDecl->hasDefinition())
7545       return VRQuals;
7546 
7547     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7548       if (isa<UsingShadowDecl>(D))
7549         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7550       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7551         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7552         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7553           CanTy = ResTypeRef->getPointeeType();
7554         // Need to go down the pointer/mempointer chain and add qualifiers
7555         // as see them.
7556         bool done = false;
7557         while (!done) {
7558           if (CanTy.isRestrictQualified())
7559             VRQuals.addRestrict();
7560           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7561             CanTy = ResTypePtr->getPointeeType();
7562           else if (const MemberPointerType *ResTypeMPtr =
7563                 CanTy->getAs<MemberPointerType>())
7564             CanTy = ResTypeMPtr->getPointeeType();
7565           else
7566             done = true;
7567           if (CanTy.isVolatileQualified())
7568             VRQuals.addVolatile();
7569           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7570             return VRQuals;
7571         }
7572       }
7573     }
7574     return VRQuals;
7575 }
7576 
7577 namespace {
7578 
7579 /// \brief Helper class to manage the addition of builtin operator overload
7580 /// candidates. It provides shared state and utility methods used throughout
7581 /// the process, as well as a helper method to add each group of builtin
7582 /// operator overloads from the standard to a candidate set.
7583 class BuiltinOperatorOverloadBuilder {
7584   // Common instance state available to all overload candidate addition methods.
7585   Sema &S;
7586   ArrayRef<Expr *> Args;
7587   Qualifiers VisibleTypeConversionsQuals;
7588   bool HasArithmeticOrEnumeralCandidateType;
7589   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7590   OverloadCandidateSet &CandidateSet;
7591 
7592   // Define some constants used to index and iterate over the arithemetic types
7593   // provided via the getArithmeticType() method below.
7594   // The "promoted arithmetic types" are the arithmetic
7595   // types are that preserved by promotion (C++ [over.built]p2).
7596   static const unsigned FirstIntegralType = 4;
7597   static const unsigned LastIntegralType = 21;
7598   static const unsigned FirstPromotedIntegralType = 4,
7599                         LastPromotedIntegralType = 12;
7600   static const unsigned FirstPromotedArithmeticType = 0,
7601                         LastPromotedArithmeticType = 12;
7602   static const unsigned NumArithmeticTypes = 21;
7603 
7604   /// \brief Get the canonical type for a given arithmetic type index.
7605   CanQualType getArithmeticType(unsigned index) {
7606     assert(index < NumArithmeticTypes);
7607     static CanQualType ASTContext::* const
7608       ArithmeticTypes[NumArithmeticTypes] = {
7609       // Start of promoted types.
7610       &ASTContext::FloatTy,
7611       &ASTContext::DoubleTy,
7612       &ASTContext::LongDoubleTy,
7613       &ASTContext::Float128Ty,
7614 
7615       // Start of integral types.
7616       &ASTContext::IntTy,
7617       &ASTContext::LongTy,
7618       &ASTContext::LongLongTy,
7619       &ASTContext::Int128Ty,
7620       &ASTContext::UnsignedIntTy,
7621       &ASTContext::UnsignedLongTy,
7622       &ASTContext::UnsignedLongLongTy,
7623       &ASTContext::UnsignedInt128Ty,
7624       // End of promoted types.
7625 
7626       &ASTContext::BoolTy,
7627       &ASTContext::CharTy,
7628       &ASTContext::WCharTy,
7629       &ASTContext::Char16Ty,
7630       &ASTContext::Char32Ty,
7631       &ASTContext::SignedCharTy,
7632       &ASTContext::ShortTy,
7633       &ASTContext::UnsignedCharTy,
7634       &ASTContext::UnsignedShortTy,
7635       // End of integral types.
7636       // FIXME: What about complex? What about half?
7637     };
7638     return S.Context.*ArithmeticTypes[index];
7639   }
7640 
7641   /// \brief Helper method to factor out the common pattern of adding overloads
7642   /// for '++' and '--' builtin operators.
7643   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7644                                            bool HasVolatile,
7645                                            bool HasRestrict) {
7646     QualType ParamTypes[2] = {
7647       S.Context.getLValueReferenceType(CandidateTy),
7648       S.Context.IntTy
7649     };
7650 
7651     // Non-volatile version.
7652     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7653 
7654     // Use a heuristic to reduce number of builtin candidates in the set:
7655     // add volatile version only if there are conversions to a volatile type.
7656     if (HasVolatile) {
7657       ParamTypes[0] =
7658         S.Context.getLValueReferenceType(
7659           S.Context.getVolatileType(CandidateTy));
7660       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7661     }
7662 
7663     // Add restrict version only if there are conversions to a restrict type
7664     // and our candidate type is a non-restrict-qualified pointer.
7665     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7666         !CandidateTy.isRestrictQualified()) {
7667       ParamTypes[0]
7668         = S.Context.getLValueReferenceType(
7669             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7670       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7671 
7672       if (HasVolatile) {
7673         ParamTypes[0]
7674           = S.Context.getLValueReferenceType(
7675               S.Context.getCVRQualifiedType(CandidateTy,
7676                                             (Qualifiers::Volatile |
7677                                              Qualifiers::Restrict)));
7678         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7679       }
7680     }
7681 
7682   }
7683 
7684 public:
7685   BuiltinOperatorOverloadBuilder(
7686     Sema &S, ArrayRef<Expr *> Args,
7687     Qualifiers VisibleTypeConversionsQuals,
7688     bool HasArithmeticOrEnumeralCandidateType,
7689     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7690     OverloadCandidateSet &CandidateSet)
7691     : S(S), Args(Args),
7692       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7693       HasArithmeticOrEnumeralCandidateType(
7694         HasArithmeticOrEnumeralCandidateType),
7695       CandidateTypes(CandidateTypes),
7696       CandidateSet(CandidateSet) {
7697     // Validate some of our static helper constants in debug builds.
7698     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7699            "Invalid first promoted integral type");
7700     assert(getArithmeticType(LastPromotedIntegralType - 1)
7701              == S.Context.UnsignedInt128Ty &&
7702            "Invalid last promoted integral type");
7703     assert(getArithmeticType(FirstPromotedArithmeticType)
7704              == S.Context.FloatTy &&
7705            "Invalid first promoted arithmetic type");
7706     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7707              == S.Context.UnsignedInt128Ty &&
7708            "Invalid last promoted arithmetic type");
7709   }
7710 
7711   // C++ [over.built]p3:
7712   //
7713   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7714   //   is either volatile or empty, there exist candidate operator
7715   //   functions of the form
7716   //
7717   //       VQ T&      operator++(VQ T&);
7718   //       T          operator++(VQ T&, int);
7719   //
7720   // C++ [over.built]p4:
7721   //
7722   //   For every pair (T, VQ), where T is an arithmetic type other
7723   //   than bool, and VQ is either volatile or empty, there exist
7724   //   candidate operator functions of the form
7725   //
7726   //       VQ T&      operator--(VQ T&);
7727   //       T          operator--(VQ T&, int);
7728   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7729     if (!HasArithmeticOrEnumeralCandidateType)
7730       return;
7731 
7732     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7733          Arith < NumArithmeticTypes; ++Arith) {
7734       addPlusPlusMinusMinusStyleOverloads(
7735         getArithmeticType(Arith),
7736         VisibleTypeConversionsQuals.hasVolatile(),
7737         VisibleTypeConversionsQuals.hasRestrict());
7738     }
7739   }
7740 
7741   // C++ [over.built]p5:
7742   //
7743   //   For every pair (T, VQ), where T is a cv-qualified or
7744   //   cv-unqualified object type, and VQ is either volatile or
7745   //   empty, there exist candidate operator functions of the form
7746   //
7747   //       T*VQ&      operator++(T*VQ&);
7748   //       T*VQ&      operator--(T*VQ&);
7749   //       T*         operator++(T*VQ&, int);
7750   //       T*         operator--(T*VQ&, int);
7751   void addPlusPlusMinusMinusPointerOverloads() {
7752     for (BuiltinCandidateTypeSet::iterator
7753               Ptr = CandidateTypes[0].pointer_begin(),
7754            PtrEnd = CandidateTypes[0].pointer_end();
7755          Ptr != PtrEnd; ++Ptr) {
7756       // Skip pointer types that aren't pointers to object types.
7757       if (!(*Ptr)->getPointeeType()->isObjectType())
7758         continue;
7759 
7760       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7761         (!(*Ptr).isVolatileQualified() &&
7762          VisibleTypeConversionsQuals.hasVolatile()),
7763         (!(*Ptr).isRestrictQualified() &&
7764          VisibleTypeConversionsQuals.hasRestrict()));
7765     }
7766   }
7767 
7768   // C++ [over.built]p6:
7769   //   For every cv-qualified or cv-unqualified object type T, there
7770   //   exist candidate operator functions of the form
7771   //
7772   //       T&         operator*(T*);
7773   //
7774   // C++ [over.built]p7:
7775   //   For every function type T that does not have cv-qualifiers or a
7776   //   ref-qualifier, there exist candidate operator functions of the form
7777   //       T&         operator*(T*);
7778   void addUnaryStarPointerOverloads() {
7779     for (BuiltinCandidateTypeSet::iterator
7780               Ptr = CandidateTypes[0].pointer_begin(),
7781            PtrEnd = CandidateTypes[0].pointer_end();
7782          Ptr != PtrEnd; ++Ptr) {
7783       QualType ParamTy = *Ptr;
7784       QualType PointeeTy = ParamTy->getPointeeType();
7785       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7786         continue;
7787 
7788       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7789         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7790           continue;
7791 
7792       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7793     }
7794   }
7795 
7796   // C++ [over.built]p9:
7797   //  For every promoted arithmetic type T, there exist candidate
7798   //  operator functions of the form
7799   //
7800   //       T         operator+(T);
7801   //       T         operator-(T);
7802   void addUnaryPlusOrMinusArithmeticOverloads() {
7803     if (!HasArithmeticOrEnumeralCandidateType)
7804       return;
7805 
7806     for (unsigned Arith = FirstPromotedArithmeticType;
7807          Arith < LastPromotedArithmeticType; ++Arith) {
7808       QualType ArithTy = getArithmeticType(Arith);
7809       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7810     }
7811 
7812     // Extension: We also add these operators for vector types.
7813     for (BuiltinCandidateTypeSet::iterator
7814               Vec = CandidateTypes[0].vector_begin(),
7815            VecEnd = CandidateTypes[0].vector_end();
7816          Vec != VecEnd; ++Vec) {
7817       QualType VecTy = *Vec;
7818       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7819     }
7820   }
7821 
7822   // C++ [over.built]p8:
7823   //   For every type T, there exist candidate operator functions of
7824   //   the form
7825   //
7826   //       T*         operator+(T*);
7827   void addUnaryPlusPointerOverloads() {
7828     for (BuiltinCandidateTypeSet::iterator
7829               Ptr = CandidateTypes[0].pointer_begin(),
7830            PtrEnd = CandidateTypes[0].pointer_end();
7831          Ptr != PtrEnd; ++Ptr) {
7832       QualType ParamTy = *Ptr;
7833       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7834     }
7835   }
7836 
7837   // C++ [over.built]p10:
7838   //   For every promoted integral type T, there exist candidate
7839   //   operator functions of the form
7840   //
7841   //        T         operator~(T);
7842   void addUnaryTildePromotedIntegralOverloads() {
7843     if (!HasArithmeticOrEnumeralCandidateType)
7844       return;
7845 
7846     for (unsigned Int = FirstPromotedIntegralType;
7847          Int < LastPromotedIntegralType; ++Int) {
7848       QualType IntTy = getArithmeticType(Int);
7849       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7850     }
7851 
7852     // Extension: We also add this operator for vector types.
7853     for (BuiltinCandidateTypeSet::iterator
7854               Vec = CandidateTypes[0].vector_begin(),
7855            VecEnd = CandidateTypes[0].vector_end();
7856          Vec != VecEnd; ++Vec) {
7857       QualType VecTy = *Vec;
7858       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7859     }
7860   }
7861 
7862   // C++ [over.match.oper]p16:
7863   //   For every pointer to member type T or type std::nullptr_t, there
7864   //   exist candidate operator functions of the form
7865   //
7866   //        bool operator==(T,T);
7867   //        bool operator!=(T,T);
7868   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7869     /// Set of (canonical) types that we've already handled.
7870     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7871 
7872     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7873       for (BuiltinCandidateTypeSet::iterator
7874                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7875              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7876            MemPtr != MemPtrEnd;
7877            ++MemPtr) {
7878         // Don't add the same builtin candidate twice.
7879         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7880           continue;
7881 
7882         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7883         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7884       }
7885 
7886       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7887         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7888         if (AddedTypes.insert(NullPtrTy).second) {
7889           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7890           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7891         }
7892       }
7893     }
7894   }
7895 
7896   // C++ [over.built]p15:
7897   //
7898   //   For every T, where T is an enumeration type or a pointer type,
7899   //   there exist candidate operator functions of the form
7900   //
7901   //        bool       operator<(T, T);
7902   //        bool       operator>(T, T);
7903   //        bool       operator<=(T, T);
7904   //        bool       operator>=(T, T);
7905   //        bool       operator==(T, T);
7906   //        bool       operator!=(T, T);
7907   void addRelationalPointerOrEnumeralOverloads() {
7908     // C++ [over.match.oper]p3:
7909     //   [...]the built-in candidates include all of the candidate operator
7910     //   functions defined in 13.6 that, compared to the given operator, [...]
7911     //   do not have the same parameter-type-list as any non-template non-member
7912     //   candidate.
7913     //
7914     // Note that in practice, this only affects enumeration types because there
7915     // aren't any built-in candidates of record type, and a user-defined operator
7916     // must have an operand of record or enumeration type. Also, the only other
7917     // overloaded operator with enumeration arguments, operator=,
7918     // cannot be overloaded for enumeration types, so this is the only place
7919     // where we must suppress candidates like this.
7920     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7921       UserDefinedBinaryOperators;
7922 
7923     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7924       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7925           CandidateTypes[ArgIdx].enumeration_end()) {
7926         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7927                                          CEnd = CandidateSet.end();
7928              C != CEnd; ++C) {
7929           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7930             continue;
7931 
7932           if (C->Function->isFunctionTemplateSpecialization())
7933             continue;
7934 
7935           QualType FirstParamType =
7936             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7937           QualType SecondParamType =
7938             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7939 
7940           // Skip if either parameter isn't of enumeral type.
7941           if (!FirstParamType->isEnumeralType() ||
7942               !SecondParamType->isEnumeralType())
7943             continue;
7944 
7945           // Add this operator to the set of known user-defined operators.
7946           UserDefinedBinaryOperators.insert(
7947             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7948                            S.Context.getCanonicalType(SecondParamType)));
7949         }
7950       }
7951     }
7952 
7953     /// Set of (canonical) types that we've already handled.
7954     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7955 
7956     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7957       for (BuiltinCandidateTypeSet::iterator
7958                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7959              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7960            Ptr != PtrEnd; ++Ptr) {
7961         // Don't add the same builtin candidate twice.
7962         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7963           continue;
7964 
7965         QualType ParamTypes[2] = { *Ptr, *Ptr };
7966         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7967       }
7968       for (BuiltinCandidateTypeSet::iterator
7969                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7970              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7971            Enum != EnumEnd; ++Enum) {
7972         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7973 
7974         // Don't add the same builtin candidate twice, or if a user defined
7975         // candidate exists.
7976         if (!AddedTypes.insert(CanonType).second ||
7977             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7978                                                             CanonType)))
7979           continue;
7980 
7981         QualType ParamTypes[2] = { *Enum, *Enum };
7982         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7983       }
7984     }
7985   }
7986 
7987   // C++ [over.built]p13:
7988   //
7989   //   For every cv-qualified or cv-unqualified object type T
7990   //   there exist candidate operator functions of the form
7991   //
7992   //      T*         operator+(T*, ptrdiff_t);
7993   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7994   //      T*         operator-(T*, ptrdiff_t);
7995   //      T*         operator+(ptrdiff_t, T*);
7996   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7997   //
7998   // C++ [over.built]p14:
7999   //
8000   //   For every T, where T is a pointer to object type, there
8001   //   exist candidate operator functions of the form
8002   //
8003   //      ptrdiff_t  operator-(T, T);
8004   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8005     /// Set of (canonical) types that we've already handled.
8006     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8007 
8008     for (int Arg = 0; Arg < 2; ++Arg) {
8009       QualType AsymmetricParamTypes[2] = {
8010         S.Context.getPointerDiffType(),
8011         S.Context.getPointerDiffType(),
8012       };
8013       for (BuiltinCandidateTypeSet::iterator
8014                 Ptr = CandidateTypes[Arg].pointer_begin(),
8015              PtrEnd = CandidateTypes[Arg].pointer_end();
8016            Ptr != PtrEnd; ++Ptr) {
8017         QualType PointeeTy = (*Ptr)->getPointeeType();
8018         if (!PointeeTy->isObjectType())
8019           continue;
8020 
8021         AsymmetricParamTypes[Arg] = *Ptr;
8022         if (Arg == 0 || Op == OO_Plus) {
8023           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8024           // T* operator+(ptrdiff_t, T*);
8025           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8026         }
8027         if (Op == OO_Minus) {
8028           // ptrdiff_t operator-(T, T);
8029           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8030             continue;
8031 
8032           QualType ParamTypes[2] = { *Ptr, *Ptr };
8033           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8034         }
8035       }
8036     }
8037   }
8038 
8039   // C++ [over.built]p12:
8040   //
8041   //   For every pair of promoted arithmetic types L and R, there
8042   //   exist candidate operator functions of the form
8043   //
8044   //        LR         operator*(L, R);
8045   //        LR         operator/(L, R);
8046   //        LR         operator+(L, R);
8047   //        LR         operator-(L, R);
8048   //        bool       operator<(L, R);
8049   //        bool       operator>(L, R);
8050   //        bool       operator<=(L, R);
8051   //        bool       operator>=(L, R);
8052   //        bool       operator==(L, R);
8053   //        bool       operator!=(L, R);
8054   //
8055   //   where LR is the result of the usual arithmetic conversions
8056   //   between types L and R.
8057   //
8058   // C++ [over.built]p24:
8059   //
8060   //   For every pair of promoted arithmetic types L and R, there exist
8061   //   candidate operator functions of the form
8062   //
8063   //        LR       operator?(bool, L, R);
8064   //
8065   //   where LR is the result of the usual arithmetic conversions
8066   //   between types L and R.
8067   // Our candidates ignore the first parameter.
8068   void addGenericBinaryArithmeticOverloads() {
8069     if (!HasArithmeticOrEnumeralCandidateType)
8070       return;
8071 
8072     for (unsigned Left = FirstPromotedArithmeticType;
8073          Left < LastPromotedArithmeticType; ++Left) {
8074       for (unsigned Right = FirstPromotedArithmeticType;
8075            Right < LastPromotedArithmeticType; ++Right) {
8076         QualType LandR[2] = { getArithmeticType(Left),
8077                               getArithmeticType(Right) };
8078         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8079       }
8080     }
8081 
8082     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8083     // conditional operator for vector types.
8084     for (BuiltinCandidateTypeSet::iterator
8085               Vec1 = CandidateTypes[0].vector_begin(),
8086            Vec1End = CandidateTypes[0].vector_end();
8087          Vec1 != Vec1End; ++Vec1) {
8088       for (BuiltinCandidateTypeSet::iterator
8089                 Vec2 = CandidateTypes[1].vector_begin(),
8090              Vec2End = CandidateTypes[1].vector_end();
8091            Vec2 != Vec2End; ++Vec2) {
8092         QualType LandR[2] = { *Vec1, *Vec2 };
8093         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8094       }
8095     }
8096   }
8097 
8098   // C++ [over.built]p17:
8099   //
8100   //   For every pair of promoted integral types L and R, there
8101   //   exist candidate operator functions of the form
8102   //
8103   //      LR         operator%(L, R);
8104   //      LR         operator&(L, R);
8105   //      LR         operator^(L, R);
8106   //      LR         operator|(L, R);
8107   //      L          operator<<(L, R);
8108   //      L          operator>>(L, R);
8109   //
8110   //   where LR is the result of the usual arithmetic conversions
8111   //   between types L and R.
8112   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8113     if (!HasArithmeticOrEnumeralCandidateType)
8114       return;
8115 
8116     for (unsigned Left = FirstPromotedIntegralType;
8117          Left < LastPromotedIntegralType; ++Left) {
8118       for (unsigned Right = FirstPromotedIntegralType;
8119            Right < LastPromotedIntegralType; ++Right) {
8120         QualType LandR[2] = { getArithmeticType(Left),
8121                               getArithmeticType(Right) };
8122         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8123       }
8124     }
8125   }
8126 
8127   // C++ [over.built]p20:
8128   //
8129   //   For every pair (T, VQ), where T is an enumeration or
8130   //   pointer to member type and VQ is either volatile or
8131   //   empty, there exist candidate operator functions of the form
8132   //
8133   //        VQ T&      operator=(VQ T&, T);
8134   void addAssignmentMemberPointerOrEnumeralOverloads() {
8135     /// Set of (canonical) types that we've already handled.
8136     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8137 
8138     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8139       for (BuiltinCandidateTypeSet::iterator
8140                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8141              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8142            Enum != EnumEnd; ++Enum) {
8143         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8144           continue;
8145 
8146         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8147       }
8148 
8149       for (BuiltinCandidateTypeSet::iterator
8150                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8151              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8152            MemPtr != MemPtrEnd; ++MemPtr) {
8153         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8154           continue;
8155 
8156         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8157       }
8158     }
8159   }
8160 
8161   // C++ [over.built]p19:
8162   //
8163   //   For every pair (T, VQ), where T is any type and VQ is either
8164   //   volatile or empty, there exist candidate operator functions
8165   //   of the form
8166   //
8167   //        T*VQ&      operator=(T*VQ&, T*);
8168   //
8169   // C++ [over.built]p21:
8170   //
8171   //   For every pair (T, VQ), where T is a cv-qualified or
8172   //   cv-unqualified object type and VQ is either volatile or
8173   //   empty, there exist candidate operator functions of the form
8174   //
8175   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8176   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8177   void addAssignmentPointerOverloads(bool isEqualOp) {
8178     /// Set of (canonical) types that we've already handled.
8179     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8180 
8181     for (BuiltinCandidateTypeSet::iterator
8182               Ptr = CandidateTypes[0].pointer_begin(),
8183            PtrEnd = CandidateTypes[0].pointer_end();
8184          Ptr != PtrEnd; ++Ptr) {
8185       // If this is operator=, keep track of the builtin candidates we added.
8186       if (isEqualOp)
8187         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8188       else if (!(*Ptr)->getPointeeType()->isObjectType())
8189         continue;
8190 
8191       // non-volatile version
8192       QualType ParamTypes[2] = {
8193         S.Context.getLValueReferenceType(*Ptr),
8194         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8195       };
8196       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8197                             /*IsAssigmentOperator=*/ isEqualOp);
8198 
8199       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8200                           VisibleTypeConversionsQuals.hasVolatile();
8201       if (NeedVolatile) {
8202         // volatile version
8203         ParamTypes[0] =
8204           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8205         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8206                               /*IsAssigmentOperator=*/isEqualOp);
8207       }
8208 
8209       if (!(*Ptr).isRestrictQualified() &&
8210           VisibleTypeConversionsQuals.hasRestrict()) {
8211         // restrict version
8212         ParamTypes[0]
8213           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8214         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8215                               /*IsAssigmentOperator=*/isEqualOp);
8216 
8217         if (NeedVolatile) {
8218           // volatile restrict version
8219           ParamTypes[0]
8220             = S.Context.getLValueReferenceType(
8221                 S.Context.getCVRQualifiedType(*Ptr,
8222                                               (Qualifiers::Volatile |
8223                                                Qualifiers::Restrict)));
8224           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8225                                 /*IsAssigmentOperator=*/isEqualOp);
8226         }
8227       }
8228     }
8229 
8230     if (isEqualOp) {
8231       for (BuiltinCandidateTypeSet::iterator
8232                 Ptr = CandidateTypes[1].pointer_begin(),
8233              PtrEnd = CandidateTypes[1].pointer_end();
8234            Ptr != PtrEnd; ++Ptr) {
8235         // Make sure we don't add the same candidate twice.
8236         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8237           continue;
8238 
8239         QualType ParamTypes[2] = {
8240           S.Context.getLValueReferenceType(*Ptr),
8241           *Ptr,
8242         };
8243 
8244         // non-volatile version
8245         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8246                               /*IsAssigmentOperator=*/true);
8247 
8248         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8249                            VisibleTypeConversionsQuals.hasVolatile();
8250         if (NeedVolatile) {
8251           // volatile version
8252           ParamTypes[0] =
8253             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8254           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8255                                 /*IsAssigmentOperator=*/true);
8256         }
8257 
8258         if (!(*Ptr).isRestrictQualified() &&
8259             VisibleTypeConversionsQuals.hasRestrict()) {
8260           // restrict version
8261           ParamTypes[0]
8262             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8263           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8264                                 /*IsAssigmentOperator=*/true);
8265 
8266           if (NeedVolatile) {
8267             // volatile restrict version
8268             ParamTypes[0]
8269               = S.Context.getLValueReferenceType(
8270                   S.Context.getCVRQualifiedType(*Ptr,
8271                                                 (Qualifiers::Volatile |
8272                                                  Qualifiers::Restrict)));
8273             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8274                                   /*IsAssigmentOperator=*/true);
8275           }
8276         }
8277       }
8278     }
8279   }
8280 
8281   // C++ [over.built]p18:
8282   //
8283   //   For every triple (L, VQ, R), where L is an arithmetic type,
8284   //   VQ is either volatile or empty, and R is a promoted
8285   //   arithmetic type, there exist candidate operator functions of
8286   //   the form
8287   //
8288   //        VQ L&      operator=(VQ L&, R);
8289   //        VQ L&      operator*=(VQ L&, R);
8290   //        VQ L&      operator/=(VQ L&, R);
8291   //        VQ L&      operator+=(VQ L&, R);
8292   //        VQ L&      operator-=(VQ L&, R);
8293   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8294     if (!HasArithmeticOrEnumeralCandidateType)
8295       return;
8296 
8297     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8298       for (unsigned Right = FirstPromotedArithmeticType;
8299            Right < LastPromotedArithmeticType; ++Right) {
8300         QualType ParamTypes[2];
8301         ParamTypes[1] = getArithmeticType(Right);
8302 
8303         // Add this built-in operator as a candidate (VQ is empty).
8304         ParamTypes[0] =
8305           S.Context.getLValueReferenceType(getArithmeticType(Left));
8306         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8307                               /*IsAssigmentOperator=*/isEqualOp);
8308 
8309         // Add this built-in operator as a candidate (VQ is 'volatile').
8310         if (VisibleTypeConversionsQuals.hasVolatile()) {
8311           ParamTypes[0] =
8312             S.Context.getVolatileType(getArithmeticType(Left));
8313           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8314           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8315                                 /*IsAssigmentOperator=*/isEqualOp);
8316         }
8317       }
8318     }
8319 
8320     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8321     for (BuiltinCandidateTypeSet::iterator
8322               Vec1 = CandidateTypes[0].vector_begin(),
8323            Vec1End = CandidateTypes[0].vector_end();
8324          Vec1 != Vec1End; ++Vec1) {
8325       for (BuiltinCandidateTypeSet::iterator
8326                 Vec2 = CandidateTypes[1].vector_begin(),
8327              Vec2End = CandidateTypes[1].vector_end();
8328            Vec2 != Vec2End; ++Vec2) {
8329         QualType ParamTypes[2];
8330         ParamTypes[1] = *Vec2;
8331         // Add this built-in operator as a candidate (VQ is empty).
8332         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8333         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8334                               /*IsAssigmentOperator=*/isEqualOp);
8335 
8336         // Add this built-in operator as a candidate (VQ is 'volatile').
8337         if (VisibleTypeConversionsQuals.hasVolatile()) {
8338           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8339           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8340           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8341                                 /*IsAssigmentOperator=*/isEqualOp);
8342         }
8343       }
8344     }
8345   }
8346 
8347   // C++ [over.built]p22:
8348   //
8349   //   For every triple (L, VQ, R), where L is an integral type, VQ
8350   //   is either volatile or empty, and R is a promoted integral
8351   //   type, there exist candidate operator functions of the form
8352   //
8353   //        VQ L&       operator%=(VQ L&, R);
8354   //        VQ L&       operator<<=(VQ L&, R);
8355   //        VQ L&       operator>>=(VQ L&, R);
8356   //        VQ L&       operator&=(VQ L&, R);
8357   //        VQ L&       operator^=(VQ L&, R);
8358   //        VQ L&       operator|=(VQ L&, R);
8359   void addAssignmentIntegralOverloads() {
8360     if (!HasArithmeticOrEnumeralCandidateType)
8361       return;
8362 
8363     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8364       for (unsigned Right = FirstPromotedIntegralType;
8365            Right < LastPromotedIntegralType; ++Right) {
8366         QualType ParamTypes[2];
8367         ParamTypes[1] = getArithmeticType(Right);
8368 
8369         // Add this built-in operator as a candidate (VQ is empty).
8370         ParamTypes[0] =
8371           S.Context.getLValueReferenceType(getArithmeticType(Left));
8372         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8373         if (VisibleTypeConversionsQuals.hasVolatile()) {
8374           // Add this built-in operator as a candidate (VQ is 'volatile').
8375           ParamTypes[0] = getArithmeticType(Left);
8376           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8377           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8378           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8379         }
8380       }
8381     }
8382   }
8383 
8384   // C++ [over.operator]p23:
8385   //
8386   //   There also exist candidate operator functions of the form
8387   //
8388   //        bool        operator!(bool);
8389   //        bool        operator&&(bool, bool);
8390   //        bool        operator||(bool, bool);
8391   void addExclaimOverload() {
8392     QualType ParamTy = S.Context.BoolTy;
8393     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8394                           /*IsAssignmentOperator=*/false,
8395                           /*NumContextualBoolArguments=*/1);
8396   }
8397   void addAmpAmpOrPipePipeOverload() {
8398     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8399     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8400                           /*IsAssignmentOperator=*/false,
8401                           /*NumContextualBoolArguments=*/2);
8402   }
8403 
8404   // C++ [over.built]p13:
8405   //
8406   //   For every cv-qualified or cv-unqualified object type T there
8407   //   exist candidate operator functions of the form
8408   //
8409   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8410   //        T&         operator[](T*, ptrdiff_t);
8411   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8412   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8413   //        T&         operator[](ptrdiff_t, T*);
8414   void addSubscriptOverloads() {
8415     for (BuiltinCandidateTypeSet::iterator
8416               Ptr = CandidateTypes[0].pointer_begin(),
8417            PtrEnd = CandidateTypes[0].pointer_end();
8418          Ptr != PtrEnd; ++Ptr) {
8419       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8420       QualType PointeeType = (*Ptr)->getPointeeType();
8421       if (!PointeeType->isObjectType())
8422         continue;
8423 
8424       // T& operator[](T*, ptrdiff_t)
8425       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8426     }
8427 
8428     for (BuiltinCandidateTypeSet::iterator
8429               Ptr = CandidateTypes[1].pointer_begin(),
8430            PtrEnd = CandidateTypes[1].pointer_end();
8431          Ptr != PtrEnd; ++Ptr) {
8432       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8433       QualType PointeeType = (*Ptr)->getPointeeType();
8434       if (!PointeeType->isObjectType())
8435         continue;
8436 
8437       // T& operator[](ptrdiff_t, T*)
8438       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8439     }
8440   }
8441 
8442   // C++ [over.built]p11:
8443   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8444   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8445   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8446   //    there exist candidate operator functions of the form
8447   //
8448   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8449   //
8450   //    where CV12 is the union of CV1 and CV2.
8451   void addArrowStarOverloads() {
8452     for (BuiltinCandidateTypeSet::iterator
8453              Ptr = CandidateTypes[0].pointer_begin(),
8454            PtrEnd = CandidateTypes[0].pointer_end();
8455          Ptr != PtrEnd; ++Ptr) {
8456       QualType C1Ty = (*Ptr);
8457       QualType C1;
8458       QualifierCollector Q1;
8459       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8460       if (!isa<RecordType>(C1))
8461         continue;
8462       // heuristic to reduce number of builtin candidates in the set.
8463       // Add volatile/restrict version only if there are conversions to a
8464       // volatile/restrict type.
8465       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8466         continue;
8467       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8468         continue;
8469       for (BuiltinCandidateTypeSet::iterator
8470                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8471              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8472            MemPtr != MemPtrEnd; ++MemPtr) {
8473         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8474         QualType C2 = QualType(mptr->getClass(), 0);
8475         C2 = C2.getUnqualifiedType();
8476         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8477           break;
8478         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8479         // build CV12 T&
8480         QualType T = mptr->getPointeeType();
8481         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8482             T.isVolatileQualified())
8483           continue;
8484         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8485             T.isRestrictQualified())
8486           continue;
8487         T = Q1.apply(S.Context, T);
8488         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8489       }
8490     }
8491   }
8492 
8493   // Note that we don't consider the first argument, since it has been
8494   // contextually converted to bool long ago. The candidates below are
8495   // therefore added as binary.
8496   //
8497   // C++ [over.built]p25:
8498   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8499   //   enumeration type, there exist candidate operator functions of the form
8500   //
8501   //        T        operator?(bool, T, T);
8502   //
8503   void addConditionalOperatorOverloads() {
8504     /// Set of (canonical) types that we've already handled.
8505     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8506 
8507     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8508       for (BuiltinCandidateTypeSet::iterator
8509                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8510              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8511            Ptr != PtrEnd; ++Ptr) {
8512         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8513           continue;
8514 
8515         QualType ParamTypes[2] = { *Ptr, *Ptr };
8516         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8517       }
8518 
8519       for (BuiltinCandidateTypeSet::iterator
8520                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8521              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8522            MemPtr != MemPtrEnd; ++MemPtr) {
8523         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8524           continue;
8525 
8526         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8527         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8528       }
8529 
8530       if (S.getLangOpts().CPlusPlus11) {
8531         for (BuiltinCandidateTypeSet::iterator
8532                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8533                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8534              Enum != EnumEnd; ++Enum) {
8535           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8536             continue;
8537 
8538           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8539             continue;
8540 
8541           QualType ParamTypes[2] = { *Enum, *Enum };
8542           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8543         }
8544       }
8545     }
8546   }
8547 };
8548 
8549 } // end anonymous namespace
8550 
8551 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8552 /// operator overloads to the candidate set (C++ [over.built]), based
8553 /// on the operator @p Op and the arguments given. For example, if the
8554 /// operator is a binary '+', this routine might add "int
8555 /// operator+(int, int)" to cover integer addition.
8556 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8557                                         SourceLocation OpLoc,
8558                                         ArrayRef<Expr *> Args,
8559                                         OverloadCandidateSet &CandidateSet) {
8560   // Find all of the types that the arguments can convert to, but only
8561   // if the operator we're looking at has built-in operator candidates
8562   // that make use of these types. Also record whether we encounter non-record
8563   // candidate types or either arithmetic or enumeral candidate types.
8564   Qualifiers VisibleTypeConversionsQuals;
8565   VisibleTypeConversionsQuals.addConst();
8566   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8567     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8568 
8569   bool HasNonRecordCandidateType = false;
8570   bool HasArithmeticOrEnumeralCandidateType = false;
8571   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8572   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8573     CandidateTypes.emplace_back(*this);
8574     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8575                                                  OpLoc,
8576                                                  true,
8577                                                  (Op == OO_Exclaim ||
8578                                                   Op == OO_AmpAmp ||
8579                                                   Op == OO_PipePipe),
8580                                                  VisibleTypeConversionsQuals);
8581     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8582         CandidateTypes[ArgIdx].hasNonRecordTypes();
8583     HasArithmeticOrEnumeralCandidateType =
8584         HasArithmeticOrEnumeralCandidateType ||
8585         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8586   }
8587 
8588   // Exit early when no non-record types have been added to the candidate set
8589   // for any of the arguments to the operator.
8590   //
8591   // We can't exit early for !, ||, or &&, since there we have always have
8592   // 'bool' overloads.
8593   if (!HasNonRecordCandidateType &&
8594       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8595     return;
8596 
8597   // Setup an object to manage the common state for building overloads.
8598   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8599                                            VisibleTypeConversionsQuals,
8600                                            HasArithmeticOrEnumeralCandidateType,
8601                                            CandidateTypes, CandidateSet);
8602 
8603   // Dispatch over the operation to add in only those overloads which apply.
8604   switch (Op) {
8605   case OO_None:
8606   case NUM_OVERLOADED_OPERATORS:
8607     llvm_unreachable("Expected an overloaded operator");
8608 
8609   case OO_New:
8610   case OO_Delete:
8611   case OO_Array_New:
8612   case OO_Array_Delete:
8613   case OO_Call:
8614     llvm_unreachable(
8615                     "Special operators don't use AddBuiltinOperatorCandidates");
8616 
8617   case OO_Comma:
8618   case OO_Arrow:
8619   case OO_Coawait:
8620     // C++ [over.match.oper]p3:
8621     //   -- For the operator ',', the unary operator '&', the
8622     //      operator '->', or the operator 'co_await', the
8623     //      built-in candidates set is empty.
8624     break;
8625 
8626   case OO_Plus: // '+' is either unary or binary
8627     if (Args.size() == 1)
8628       OpBuilder.addUnaryPlusPointerOverloads();
8629     // Fall through.
8630 
8631   case OO_Minus: // '-' is either unary or binary
8632     if (Args.size() == 1) {
8633       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8634     } else {
8635       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8636       OpBuilder.addGenericBinaryArithmeticOverloads();
8637     }
8638     break;
8639 
8640   case OO_Star: // '*' is either unary or binary
8641     if (Args.size() == 1)
8642       OpBuilder.addUnaryStarPointerOverloads();
8643     else
8644       OpBuilder.addGenericBinaryArithmeticOverloads();
8645     break;
8646 
8647   case OO_Slash:
8648     OpBuilder.addGenericBinaryArithmeticOverloads();
8649     break;
8650 
8651   case OO_PlusPlus:
8652   case OO_MinusMinus:
8653     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8654     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8655     break;
8656 
8657   case OO_EqualEqual:
8658   case OO_ExclaimEqual:
8659     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8660     // Fall through.
8661 
8662   case OO_Less:
8663   case OO_Greater:
8664   case OO_LessEqual:
8665   case OO_GreaterEqual:
8666     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8667     OpBuilder.addGenericBinaryArithmeticOverloads();
8668     break;
8669 
8670   case OO_Percent:
8671   case OO_Caret:
8672   case OO_Pipe:
8673   case OO_LessLess:
8674   case OO_GreaterGreater:
8675     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8676     break;
8677 
8678   case OO_Amp: // '&' is either unary or binary
8679     if (Args.size() == 1)
8680       // C++ [over.match.oper]p3:
8681       //   -- For the operator ',', the unary operator '&', or the
8682       //      operator '->', the built-in candidates set is empty.
8683       break;
8684 
8685     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8686     break;
8687 
8688   case OO_Tilde:
8689     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8690     break;
8691 
8692   case OO_Equal:
8693     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8694     // Fall through.
8695 
8696   case OO_PlusEqual:
8697   case OO_MinusEqual:
8698     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8699     // Fall through.
8700 
8701   case OO_StarEqual:
8702   case OO_SlashEqual:
8703     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8704     break;
8705 
8706   case OO_PercentEqual:
8707   case OO_LessLessEqual:
8708   case OO_GreaterGreaterEqual:
8709   case OO_AmpEqual:
8710   case OO_CaretEqual:
8711   case OO_PipeEqual:
8712     OpBuilder.addAssignmentIntegralOverloads();
8713     break;
8714 
8715   case OO_Exclaim:
8716     OpBuilder.addExclaimOverload();
8717     break;
8718 
8719   case OO_AmpAmp:
8720   case OO_PipePipe:
8721     OpBuilder.addAmpAmpOrPipePipeOverload();
8722     break;
8723 
8724   case OO_Subscript:
8725     OpBuilder.addSubscriptOverloads();
8726     break;
8727 
8728   case OO_ArrowStar:
8729     OpBuilder.addArrowStarOverloads();
8730     break;
8731 
8732   case OO_Conditional:
8733     OpBuilder.addConditionalOperatorOverloads();
8734     OpBuilder.addGenericBinaryArithmeticOverloads();
8735     break;
8736   }
8737 }
8738 
8739 /// \brief Add function candidates found via argument-dependent lookup
8740 /// to the set of overloading candidates.
8741 ///
8742 /// This routine performs argument-dependent name lookup based on the
8743 /// given function name (which may also be an operator name) and adds
8744 /// all of the overload candidates found by ADL to the overload
8745 /// candidate set (C++ [basic.lookup.argdep]).
8746 void
8747 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8748                                            SourceLocation Loc,
8749                                            ArrayRef<Expr *> Args,
8750                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8751                                            OverloadCandidateSet& CandidateSet,
8752                                            bool PartialOverloading) {
8753   ADLResult Fns;
8754 
8755   // FIXME: This approach for uniquing ADL results (and removing
8756   // redundant candidates from the set) relies on pointer-equality,
8757   // which means we need to key off the canonical decl.  However,
8758   // always going back to the canonical decl might not get us the
8759   // right set of default arguments.  What default arguments are
8760   // we supposed to consider on ADL candidates, anyway?
8761 
8762   // FIXME: Pass in the explicit template arguments?
8763   ArgumentDependentLookup(Name, Loc, Args, Fns);
8764 
8765   // Erase all of the candidates we already knew about.
8766   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8767                                    CandEnd = CandidateSet.end();
8768        Cand != CandEnd; ++Cand)
8769     if (Cand->Function) {
8770       Fns.erase(Cand->Function);
8771       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8772         Fns.erase(FunTmpl);
8773     }
8774 
8775   // For each of the ADL candidates we found, add it to the overload
8776   // set.
8777   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8778     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8779     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8780       if (ExplicitTemplateArgs)
8781         continue;
8782 
8783       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8784                            PartialOverloading);
8785     } else
8786       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8787                                    FoundDecl, ExplicitTemplateArgs,
8788                                    Args, CandidateSet, PartialOverloading);
8789   }
8790 }
8791 
8792 namespace {
8793 enum class Comparison { Equal, Better, Worse };
8794 }
8795 
8796 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8797 /// overload resolution.
8798 ///
8799 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8800 /// Cand1's first N enable_if attributes have precisely the same conditions as
8801 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8802 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8803 ///
8804 /// Note that you can have a pair of candidates such that Cand1's enable_if
8805 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8806 /// worse than Cand1's.
8807 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8808                                        const FunctionDecl *Cand2) {
8809   // Common case: One (or both) decls don't have enable_if attrs.
8810   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8811   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8812   if (!Cand1Attr || !Cand2Attr) {
8813     if (Cand1Attr == Cand2Attr)
8814       return Comparison::Equal;
8815     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8816   }
8817 
8818   // FIXME: The next several lines are just
8819   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8820   // instead of reverse order which is how they're stored in the AST.
8821   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8822   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8823 
8824   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8825   // has fewer enable_if attributes than Cand2.
8826   if (Cand1Attrs.size() < Cand2Attrs.size())
8827     return Comparison::Worse;
8828 
8829   auto Cand1I = Cand1Attrs.begin();
8830   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8831   for (auto &Cand2A : Cand2Attrs) {
8832     Cand1ID.clear();
8833     Cand2ID.clear();
8834 
8835     auto &Cand1A = *Cand1I++;
8836     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8837     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8838     if (Cand1ID != Cand2ID)
8839       return Comparison::Worse;
8840   }
8841 
8842   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8843 }
8844 
8845 /// isBetterOverloadCandidate - Determines whether the first overload
8846 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8847 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8848                                       const OverloadCandidate &Cand2,
8849                                       SourceLocation Loc,
8850                                       bool UserDefinedConversion) {
8851   // Define viable functions to be better candidates than non-viable
8852   // functions.
8853   if (!Cand2.Viable)
8854     return Cand1.Viable;
8855   else if (!Cand1.Viable)
8856     return false;
8857 
8858   // C++ [over.match.best]p1:
8859   //
8860   //   -- if F is a static member function, ICS1(F) is defined such
8861   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8862   //      any function G, and, symmetrically, ICS1(G) is neither
8863   //      better nor worse than ICS1(F).
8864   unsigned StartArg = 0;
8865   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8866     StartArg = 1;
8867 
8868   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8869     // We don't allow incompatible pointer conversions in C++.
8870     if (!S.getLangOpts().CPlusPlus)
8871       return ICS.isStandard() &&
8872              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8873 
8874     // The only ill-formed conversion we allow in C++ is the string literal to
8875     // char* conversion, which is only considered ill-formed after C++11.
8876     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8877            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8878   };
8879 
8880   // Define functions that don't require ill-formed conversions for a given
8881   // argument to be better candidates than functions that do.
8882   unsigned NumArgs = Cand1.Conversions.size();
8883   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8884   bool HasBetterConversion = false;
8885   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8886     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8887     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8888     if (Cand1Bad != Cand2Bad) {
8889       if (Cand1Bad)
8890         return false;
8891       HasBetterConversion = true;
8892     }
8893   }
8894 
8895   if (HasBetterConversion)
8896     return true;
8897 
8898   // C++ [over.match.best]p1:
8899   //   A viable function F1 is defined to be a better function than another
8900   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8901   //   conversion sequence than ICSi(F2), and then...
8902   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8903     switch (CompareImplicitConversionSequences(S, Loc,
8904                                                Cand1.Conversions[ArgIdx],
8905                                                Cand2.Conversions[ArgIdx])) {
8906     case ImplicitConversionSequence::Better:
8907       // Cand1 has a better conversion sequence.
8908       HasBetterConversion = true;
8909       break;
8910 
8911     case ImplicitConversionSequence::Worse:
8912       // Cand1 can't be better than Cand2.
8913       return false;
8914 
8915     case ImplicitConversionSequence::Indistinguishable:
8916       // Do nothing.
8917       break;
8918     }
8919   }
8920 
8921   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8922   //       ICSj(F2), or, if not that,
8923   if (HasBetterConversion)
8924     return true;
8925 
8926   //   -- the context is an initialization by user-defined conversion
8927   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8928   //      from the return type of F1 to the destination type (i.e.,
8929   //      the type of the entity being initialized) is a better
8930   //      conversion sequence than the standard conversion sequence
8931   //      from the return type of F2 to the destination type.
8932   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8933       isa<CXXConversionDecl>(Cand1.Function) &&
8934       isa<CXXConversionDecl>(Cand2.Function)) {
8935     // First check whether we prefer one of the conversion functions over the
8936     // other. This only distinguishes the results in non-standard, extension
8937     // cases such as the conversion from a lambda closure type to a function
8938     // pointer or block.
8939     ImplicitConversionSequence::CompareKind Result =
8940         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8941     if (Result == ImplicitConversionSequence::Indistinguishable)
8942       Result = CompareStandardConversionSequences(S, Loc,
8943                                                   Cand1.FinalConversion,
8944                                                   Cand2.FinalConversion);
8945 
8946     if (Result != ImplicitConversionSequence::Indistinguishable)
8947       return Result == ImplicitConversionSequence::Better;
8948 
8949     // FIXME: Compare kind of reference binding if conversion functions
8950     // convert to a reference type used in direct reference binding, per
8951     // C++14 [over.match.best]p1 section 2 bullet 3.
8952   }
8953 
8954   //    -- F1 is generated from a deduction-guide and F2 is not
8955   auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
8956   auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
8957   if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
8958     return Guide2->isImplicit();
8959 
8960   //    -- F1 is a non-template function and F2 is a function template
8961   //       specialization, or, if not that,
8962   bool Cand1IsSpecialization = Cand1.Function &&
8963                                Cand1.Function->getPrimaryTemplate();
8964   bool Cand2IsSpecialization = Cand2.Function &&
8965                                Cand2.Function->getPrimaryTemplate();
8966   if (Cand1IsSpecialization != Cand2IsSpecialization)
8967     return Cand2IsSpecialization;
8968 
8969   //   -- F1 and F2 are function template specializations, and the function
8970   //      template for F1 is more specialized than the template for F2
8971   //      according to the partial ordering rules described in 14.5.5.2, or,
8972   //      if not that,
8973   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8974     if (FunctionTemplateDecl *BetterTemplate
8975           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8976                                          Cand2.Function->getPrimaryTemplate(),
8977                                          Loc,
8978                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8979                                                              : TPOC_Call,
8980                                          Cand1.ExplicitCallArguments,
8981                                          Cand2.ExplicitCallArguments))
8982       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8983   }
8984 
8985   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8986   // A derived-class constructor beats an (inherited) base class constructor.
8987   bool Cand1IsInherited =
8988       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8989   bool Cand2IsInherited =
8990       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8991   if (Cand1IsInherited != Cand2IsInherited)
8992     return Cand2IsInherited;
8993   else if (Cand1IsInherited) {
8994     assert(Cand2IsInherited);
8995     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8996     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8997     if (Cand1Class->isDerivedFrom(Cand2Class))
8998       return true;
8999     if (Cand2Class->isDerivedFrom(Cand1Class))
9000       return false;
9001     // Inherited from sibling base classes: still ambiguous.
9002   }
9003 
9004   // Check for enable_if value-based overload resolution.
9005   if (Cand1.Function && Cand2.Function) {
9006     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9007     if (Cmp != Comparison::Equal)
9008       return Cmp == Comparison::Better;
9009   }
9010 
9011   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9012     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9013     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9014            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9015   }
9016 
9017   bool HasPS1 = Cand1.Function != nullptr &&
9018                 functionHasPassObjectSizeParams(Cand1.Function);
9019   bool HasPS2 = Cand2.Function != nullptr &&
9020                 functionHasPassObjectSizeParams(Cand2.Function);
9021   return HasPS1 != HasPS2 && HasPS1;
9022 }
9023 
9024 /// Determine whether two declarations are "equivalent" for the purposes of
9025 /// name lookup and overload resolution. This applies when the same internal/no
9026 /// linkage entity is defined by two modules (probably by textually including
9027 /// the same header). In such a case, we don't consider the declarations to
9028 /// declare the same entity, but we also don't want lookups with both
9029 /// declarations visible to be ambiguous in some cases (this happens when using
9030 /// a modularized libstdc++).
9031 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9032                                                   const NamedDecl *B) {
9033   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9034   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9035   if (!VA || !VB)
9036     return false;
9037 
9038   // The declarations must be declaring the same name as an internal linkage
9039   // entity in different modules.
9040   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9041           VB->getDeclContext()->getRedeclContext()) ||
9042       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9043           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9044       VA->isExternallyVisible() || VB->isExternallyVisible())
9045     return false;
9046 
9047   // Check that the declarations appear to be equivalent.
9048   //
9049   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9050   // For constants and functions, we should check the initializer or body is
9051   // the same. For non-constant variables, we shouldn't allow it at all.
9052   if (Context.hasSameType(VA->getType(), VB->getType()))
9053     return true;
9054 
9055   // Enum constants within unnamed enumerations will have different types, but
9056   // may still be similar enough to be interchangeable for our purposes.
9057   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9058     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9059       // Only handle anonymous enums. If the enumerations were named and
9060       // equivalent, they would have been merged to the same type.
9061       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9062       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9063       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9064           !Context.hasSameType(EnumA->getIntegerType(),
9065                                EnumB->getIntegerType()))
9066         return false;
9067       // Allow this only if the value is the same for both enumerators.
9068       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9069     }
9070   }
9071 
9072   // Nothing else is sufficiently similar.
9073   return false;
9074 }
9075 
9076 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9077     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9078   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9079 
9080   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9081   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9082       << !M << (M ? M->getFullModuleName() : "");
9083 
9084   for (auto *E : Equiv) {
9085     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9086     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9087         << !M << (M ? M->getFullModuleName() : "");
9088   }
9089 }
9090 
9091 /// \brief Computes the best viable function (C++ 13.3.3)
9092 /// within an overload candidate set.
9093 ///
9094 /// \param Loc The location of the function name (or operator symbol) for
9095 /// which overload resolution occurs.
9096 ///
9097 /// \param Best If overload resolution was successful or found a deleted
9098 /// function, \p Best points to the candidate function found.
9099 ///
9100 /// \returns The result of overload resolution.
9101 OverloadingResult
9102 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9103                                          iterator &Best,
9104                                          bool UserDefinedConversion) {
9105   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9106   std::transform(begin(), end(), std::back_inserter(Candidates),
9107                  [](OverloadCandidate &Cand) { return &Cand; });
9108 
9109   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9110   // are accepted by both clang and NVCC. However, during a particular
9111   // compilation mode only one call variant is viable. We need to
9112   // exclude non-viable overload candidates from consideration based
9113   // only on their host/device attributes. Specifically, if one
9114   // candidate call is WrongSide and the other is SameSide, we ignore
9115   // the WrongSide candidate.
9116   if (S.getLangOpts().CUDA) {
9117     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9118     bool ContainsSameSideCandidate =
9119         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9120           return Cand->Function &&
9121                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9122                      Sema::CFP_SameSide;
9123         });
9124     if (ContainsSameSideCandidate) {
9125       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9126         return Cand->Function &&
9127                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9128                    Sema::CFP_WrongSide;
9129       };
9130       llvm::erase_if(Candidates, IsWrongSideCandidate);
9131     }
9132   }
9133 
9134   // Find the best viable function.
9135   Best = end();
9136   for (auto *Cand : Candidates)
9137     if (Cand->Viable)
9138       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
9139                                                      UserDefinedConversion))
9140         Best = Cand;
9141 
9142   // If we didn't find any viable functions, abort.
9143   if (Best == end())
9144     return OR_No_Viable_Function;
9145 
9146   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9147 
9148   // Make sure that this function is better than every other viable
9149   // function. If not, we have an ambiguity.
9150   for (auto *Cand : Candidates) {
9151     if (Cand->Viable &&
9152         Cand != Best &&
9153         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
9154                                    UserDefinedConversion)) {
9155       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9156                                                    Cand->Function)) {
9157         EquivalentCands.push_back(Cand->Function);
9158         continue;
9159       }
9160 
9161       Best = end();
9162       return OR_Ambiguous;
9163     }
9164   }
9165 
9166   // Best is the best viable function.
9167   if (Best->Function &&
9168       (Best->Function->isDeleted() ||
9169        S.isFunctionConsideredUnavailable(Best->Function)))
9170     return OR_Deleted;
9171 
9172   if (!EquivalentCands.empty())
9173     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9174                                                     EquivalentCands);
9175 
9176   return OR_Success;
9177 }
9178 
9179 namespace {
9180 
9181 enum OverloadCandidateKind {
9182   oc_function,
9183   oc_method,
9184   oc_constructor,
9185   oc_function_template,
9186   oc_method_template,
9187   oc_constructor_template,
9188   oc_implicit_default_constructor,
9189   oc_implicit_copy_constructor,
9190   oc_implicit_move_constructor,
9191   oc_implicit_copy_assignment,
9192   oc_implicit_move_assignment,
9193   oc_inherited_constructor,
9194   oc_inherited_constructor_template
9195 };
9196 
9197 static OverloadCandidateKind
9198 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9199                           std::string &Description) {
9200   bool isTemplate = false;
9201 
9202   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9203     isTemplate = true;
9204     Description = S.getTemplateArgumentBindingsText(
9205       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9206   }
9207 
9208   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9209     if (!Ctor->isImplicit()) {
9210       if (isa<ConstructorUsingShadowDecl>(Found))
9211         return isTemplate ? oc_inherited_constructor_template
9212                           : oc_inherited_constructor;
9213       else
9214         return isTemplate ? oc_constructor_template : oc_constructor;
9215     }
9216 
9217     if (Ctor->isDefaultConstructor())
9218       return oc_implicit_default_constructor;
9219 
9220     if (Ctor->isMoveConstructor())
9221       return oc_implicit_move_constructor;
9222 
9223     assert(Ctor->isCopyConstructor() &&
9224            "unexpected sort of implicit constructor");
9225     return oc_implicit_copy_constructor;
9226   }
9227 
9228   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9229     // This actually gets spelled 'candidate function' for now, but
9230     // it doesn't hurt to split it out.
9231     if (!Meth->isImplicit())
9232       return isTemplate ? oc_method_template : oc_method;
9233 
9234     if (Meth->isMoveAssignmentOperator())
9235       return oc_implicit_move_assignment;
9236 
9237     if (Meth->isCopyAssignmentOperator())
9238       return oc_implicit_copy_assignment;
9239 
9240     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9241     return oc_method;
9242   }
9243 
9244   return isTemplate ? oc_function_template : oc_function;
9245 }
9246 
9247 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9248   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9249   // set.
9250   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9251     S.Diag(FoundDecl->getLocation(),
9252            diag::note_ovl_candidate_inherited_constructor)
9253       << Shadow->getNominatedBaseClass();
9254 }
9255 
9256 } // end anonymous namespace
9257 
9258 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9259                                     const FunctionDecl *FD) {
9260   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9261     bool AlwaysTrue;
9262     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9263       return false;
9264     if (!AlwaysTrue)
9265       return false;
9266   }
9267   return true;
9268 }
9269 
9270 /// \brief Returns true if we can take the address of the function.
9271 ///
9272 /// \param Complain - If true, we'll emit a diagnostic
9273 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9274 ///   we in overload resolution?
9275 /// \param Loc - The location of the statement we're complaining about. Ignored
9276 ///   if we're not complaining, or if we're in overload resolution.
9277 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9278                                               bool Complain,
9279                                               bool InOverloadResolution,
9280                                               SourceLocation Loc) {
9281   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9282     if (Complain) {
9283       if (InOverloadResolution)
9284         S.Diag(FD->getLocStart(),
9285                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9286       else
9287         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9288     }
9289     return false;
9290   }
9291 
9292   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9293     return P->hasAttr<PassObjectSizeAttr>();
9294   });
9295   if (I == FD->param_end())
9296     return true;
9297 
9298   if (Complain) {
9299     // Add one to ParamNo because it's user-facing
9300     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9301     if (InOverloadResolution)
9302       S.Diag(FD->getLocation(),
9303              diag::note_ovl_candidate_has_pass_object_size_params)
9304           << ParamNo;
9305     else
9306       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9307           << FD << ParamNo;
9308   }
9309   return false;
9310 }
9311 
9312 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9313                                                const FunctionDecl *FD) {
9314   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9315                                            /*InOverloadResolution=*/true,
9316                                            /*Loc=*/SourceLocation());
9317 }
9318 
9319 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9320                                              bool Complain,
9321                                              SourceLocation Loc) {
9322   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9323                                              /*InOverloadResolution=*/false,
9324                                              Loc);
9325 }
9326 
9327 // Notes the location of an overload candidate.
9328 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9329                                  QualType DestType, bool TakingAddress) {
9330   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9331     return;
9332 
9333   std::string FnDesc;
9334   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9335   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9336                              << (unsigned) K << Fn << FnDesc;
9337 
9338   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9339   Diag(Fn->getLocation(), PD);
9340   MaybeEmitInheritedConstructorNote(*this, Found);
9341 }
9342 
9343 // Notes the location of all overload candidates designated through
9344 // OverloadedExpr
9345 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9346                                      bool TakingAddress) {
9347   assert(OverloadedExpr->getType() == Context.OverloadTy);
9348 
9349   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9350   OverloadExpr *OvlExpr = Ovl.Expression;
9351 
9352   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9353                             IEnd = OvlExpr->decls_end();
9354        I != IEnd; ++I) {
9355     if (FunctionTemplateDecl *FunTmpl =
9356                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9357       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9358                             TakingAddress);
9359     } else if (FunctionDecl *Fun
9360                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9361       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9362     }
9363   }
9364 }
9365 
9366 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9367 /// "lead" diagnostic; it will be given two arguments, the source and
9368 /// target types of the conversion.
9369 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9370                                  Sema &S,
9371                                  SourceLocation CaretLoc,
9372                                  const PartialDiagnostic &PDiag) const {
9373   S.Diag(CaretLoc, PDiag)
9374     << Ambiguous.getFromType() << Ambiguous.getToType();
9375   // FIXME: The note limiting machinery is borrowed from
9376   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9377   // refactoring here.
9378   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9379   unsigned CandsShown = 0;
9380   AmbiguousConversionSequence::const_iterator I, E;
9381   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9382     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9383       break;
9384     ++CandsShown;
9385     S.NoteOverloadCandidate(I->first, I->second);
9386   }
9387   if (I != E)
9388     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9389 }
9390 
9391 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9392                                   unsigned I, bool TakingCandidateAddress) {
9393   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9394   assert(Conv.isBad());
9395   assert(Cand->Function && "for now, candidate must be a function");
9396   FunctionDecl *Fn = Cand->Function;
9397 
9398   // There's a conversion slot for the object argument if this is a
9399   // non-constructor method.  Note that 'I' corresponds the
9400   // conversion-slot index.
9401   bool isObjectArgument = false;
9402   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9403     if (I == 0)
9404       isObjectArgument = true;
9405     else
9406       I--;
9407   }
9408 
9409   std::string FnDesc;
9410   OverloadCandidateKind FnKind =
9411       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9412 
9413   Expr *FromExpr = Conv.Bad.FromExpr;
9414   QualType FromTy = Conv.Bad.getFromType();
9415   QualType ToTy = Conv.Bad.getToType();
9416 
9417   if (FromTy == S.Context.OverloadTy) {
9418     assert(FromExpr && "overload set argument came from implicit argument?");
9419     Expr *E = FromExpr->IgnoreParens();
9420     if (isa<UnaryOperator>(E))
9421       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9422     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9423 
9424     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9425       << (unsigned) FnKind << FnDesc
9426       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9427       << ToTy << Name << I+1;
9428     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9429     return;
9430   }
9431 
9432   // Do some hand-waving analysis to see if the non-viability is due
9433   // to a qualifier mismatch.
9434   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9435   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9436   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9437     CToTy = RT->getPointeeType();
9438   else {
9439     // TODO: detect and diagnose the full richness of const mismatches.
9440     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9441       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9442         CFromTy = FromPT->getPointeeType();
9443         CToTy = ToPT->getPointeeType();
9444       }
9445   }
9446 
9447   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9448       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9449     Qualifiers FromQs = CFromTy.getQualifiers();
9450     Qualifiers ToQs = CToTy.getQualifiers();
9451 
9452     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9453       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9454         << (unsigned) FnKind << FnDesc
9455         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9456         << FromTy
9457         << FromQs.getAddressSpaceAttributePrintValue()
9458         << ToQs.getAddressSpaceAttributePrintValue()
9459         << (unsigned) isObjectArgument << I+1;
9460       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9461       return;
9462     }
9463 
9464     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9465       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9466         << (unsigned) FnKind << FnDesc
9467         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9468         << FromTy
9469         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9470         << (unsigned) isObjectArgument << I+1;
9471       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9472       return;
9473     }
9474 
9475     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9476       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9477       << (unsigned) FnKind << FnDesc
9478       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9479       << FromTy
9480       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9481       << (unsigned) isObjectArgument << I+1;
9482       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9483       return;
9484     }
9485 
9486     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9487       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9488         << (unsigned) FnKind << FnDesc
9489         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9490         << FromTy << FromQs.hasUnaligned() << I+1;
9491       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9492       return;
9493     }
9494 
9495     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9496     assert(CVR && "unexpected qualifiers mismatch");
9497 
9498     if (isObjectArgument) {
9499       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9500         << (unsigned) FnKind << FnDesc
9501         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9502         << FromTy << (CVR - 1);
9503     } else {
9504       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9505         << (unsigned) FnKind << FnDesc
9506         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9507         << FromTy << (CVR - 1) << I+1;
9508     }
9509     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9510     return;
9511   }
9512 
9513   // Special diagnostic for failure to convert an initializer list, since
9514   // telling the user that it has type void is not useful.
9515   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9516     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9517       << (unsigned) FnKind << FnDesc
9518       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9519       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9520     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9521     return;
9522   }
9523 
9524   // Diagnose references or pointers to incomplete types differently,
9525   // since it's far from impossible that the incompleteness triggered
9526   // the failure.
9527   QualType TempFromTy = FromTy.getNonReferenceType();
9528   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9529     TempFromTy = PTy->getPointeeType();
9530   if (TempFromTy->isIncompleteType()) {
9531     // Emit the generic diagnostic and, optionally, add the hints to it.
9532     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9533       << (unsigned) FnKind << FnDesc
9534       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9535       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9536       << (unsigned) (Cand->Fix.Kind);
9537 
9538     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9539     return;
9540   }
9541 
9542   // Diagnose base -> derived pointer conversions.
9543   unsigned BaseToDerivedConversion = 0;
9544   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9545     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9546       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9547                                                FromPtrTy->getPointeeType()) &&
9548           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9549           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9550           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9551                           FromPtrTy->getPointeeType()))
9552         BaseToDerivedConversion = 1;
9553     }
9554   } else if (const ObjCObjectPointerType *FromPtrTy
9555                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9556     if (const ObjCObjectPointerType *ToPtrTy
9557                                         = ToTy->getAs<ObjCObjectPointerType>())
9558       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9559         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9560           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9561                                                 FromPtrTy->getPointeeType()) &&
9562               FromIface->isSuperClassOf(ToIface))
9563             BaseToDerivedConversion = 2;
9564   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9565     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9566         !FromTy->isIncompleteType() &&
9567         !ToRefTy->getPointeeType()->isIncompleteType() &&
9568         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9569       BaseToDerivedConversion = 3;
9570     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9571                ToTy.getNonReferenceType().getCanonicalType() ==
9572                FromTy.getNonReferenceType().getCanonicalType()) {
9573       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9574         << (unsigned) FnKind << FnDesc
9575         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9576         << (unsigned) isObjectArgument << I + 1;
9577       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9578       return;
9579     }
9580   }
9581 
9582   if (BaseToDerivedConversion) {
9583     S.Diag(Fn->getLocation(),
9584            diag::note_ovl_candidate_bad_base_to_derived_conv)
9585       << (unsigned) FnKind << FnDesc
9586       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9587       << (BaseToDerivedConversion - 1)
9588       << FromTy << ToTy << I+1;
9589     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9590     return;
9591   }
9592 
9593   if (isa<ObjCObjectPointerType>(CFromTy) &&
9594       isa<PointerType>(CToTy)) {
9595       Qualifiers FromQs = CFromTy.getQualifiers();
9596       Qualifiers ToQs = CToTy.getQualifiers();
9597       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9598         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9599         << (unsigned) FnKind << FnDesc
9600         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9601         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9602         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9603         return;
9604       }
9605   }
9606 
9607   if (TakingCandidateAddress &&
9608       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9609     return;
9610 
9611   // Emit the generic diagnostic and, optionally, add the hints to it.
9612   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9613   FDiag << (unsigned) FnKind << FnDesc
9614     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9615     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9616     << (unsigned) (Cand->Fix.Kind);
9617 
9618   // If we can fix the conversion, suggest the FixIts.
9619   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9620        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9621     FDiag << *HI;
9622   S.Diag(Fn->getLocation(), FDiag);
9623 
9624   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9625 }
9626 
9627 /// Additional arity mismatch diagnosis specific to a function overload
9628 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9629 /// over a candidate in any candidate set.
9630 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9631                                unsigned NumArgs) {
9632   FunctionDecl *Fn = Cand->Function;
9633   unsigned MinParams = Fn->getMinRequiredArguments();
9634 
9635   // With invalid overloaded operators, it's possible that we think we
9636   // have an arity mismatch when in fact it looks like we have the
9637   // right number of arguments, because only overloaded operators have
9638   // the weird behavior of overloading member and non-member functions.
9639   // Just don't report anything.
9640   if (Fn->isInvalidDecl() &&
9641       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9642     return true;
9643 
9644   if (NumArgs < MinParams) {
9645     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9646            (Cand->FailureKind == ovl_fail_bad_deduction &&
9647             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9648   } else {
9649     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9650            (Cand->FailureKind == ovl_fail_bad_deduction &&
9651             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9652   }
9653 
9654   return false;
9655 }
9656 
9657 /// General arity mismatch diagnosis over a candidate in a candidate set.
9658 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9659                                   unsigned NumFormalArgs) {
9660   assert(isa<FunctionDecl>(D) &&
9661       "The templated declaration should at least be a function"
9662       " when diagnosing bad template argument deduction due to too many"
9663       " or too few arguments");
9664 
9665   FunctionDecl *Fn = cast<FunctionDecl>(D);
9666 
9667   // TODO: treat calls to a missing default constructor as a special case
9668   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9669   unsigned MinParams = Fn->getMinRequiredArguments();
9670 
9671   // at least / at most / exactly
9672   unsigned mode, modeCount;
9673   if (NumFormalArgs < MinParams) {
9674     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9675         FnTy->isTemplateVariadic())
9676       mode = 0; // "at least"
9677     else
9678       mode = 2; // "exactly"
9679     modeCount = MinParams;
9680   } else {
9681     if (MinParams != FnTy->getNumParams())
9682       mode = 1; // "at most"
9683     else
9684       mode = 2; // "exactly"
9685     modeCount = FnTy->getNumParams();
9686   }
9687 
9688   std::string Description;
9689   OverloadCandidateKind FnKind =
9690       ClassifyOverloadCandidate(S, Found, Fn, Description);
9691 
9692   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9693     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9694       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9695       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9696   else
9697     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9698       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9699       << mode << modeCount << NumFormalArgs;
9700   MaybeEmitInheritedConstructorNote(S, Found);
9701 }
9702 
9703 /// Arity mismatch diagnosis specific to a function overload candidate.
9704 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9705                                   unsigned NumFormalArgs) {
9706   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9707     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9708 }
9709 
9710 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9711   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9712     return TD;
9713   llvm_unreachable("Unsupported: Getting the described template declaration"
9714                    " for bad deduction diagnosis");
9715 }
9716 
9717 /// Diagnose a failed template-argument deduction.
9718 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9719                                  DeductionFailureInfo &DeductionFailure,
9720                                  unsigned NumArgs,
9721                                  bool TakingCandidateAddress) {
9722   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9723   NamedDecl *ParamD;
9724   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9725   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9726   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9727   switch (DeductionFailure.Result) {
9728   case Sema::TDK_Success:
9729     llvm_unreachable("TDK_success while diagnosing bad deduction");
9730 
9731   case Sema::TDK_Incomplete: {
9732     assert(ParamD && "no parameter found for incomplete deduction result");
9733     S.Diag(Templated->getLocation(),
9734            diag::note_ovl_candidate_incomplete_deduction)
9735         << ParamD->getDeclName();
9736     MaybeEmitInheritedConstructorNote(S, Found);
9737     return;
9738   }
9739 
9740   case Sema::TDK_Underqualified: {
9741     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9742     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9743 
9744     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9745 
9746     // Param will have been canonicalized, but it should just be a
9747     // qualified version of ParamD, so move the qualifiers to that.
9748     QualifierCollector Qs;
9749     Qs.strip(Param);
9750     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9751     assert(S.Context.hasSameType(Param, NonCanonParam));
9752 
9753     // Arg has also been canonicalized, but there's nothing we can do
9754     // about that.  It also doesn't matter as much, because it won't
9755     // have any template parameters in it (because deduction isn't
9756     // done on dependent types).
9757     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9758 
9759     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9760         << ParamD->getDeclName() << Arg << NonCanonParam;
9761     MaybeEmitInheritedConstructorNote(S, Found);
9762     return;
9763   }
9764 
9765   case Sema::TDK_Inconsistent: {
9766     assert(ParamD && "no parameter found for inconsistent deduction result");
9767     int which = 0;
9768     if (isa<TemplateTypeParmDecl>(ParamD))
9769       which = 0;
9770     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9771       // Deduction might have failed because we deduced arguments of two
9772       // different types for a non-type template parameter.
9773       // FIXME: Use a different TDK value for this.
9774       QualType T1 =
9775           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9776       QualType T2 =
9777           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9778       if (!S.Context.hasSameType(T1, T2)) {
9779         S.Diag(Templated->getLocation(),
9780                diag::note_ovl_candidate_inconsistent_deduction_types)
9781           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9782           << *DeductionFailure.getSecondArg() << T2;
9783         MaybeEmitInheritedConstructorNote(S, Found);
9784         return;
9785       }
9786 
9787       which = 1;
9788     } else {
9789       which = 2;
9790     }
9791 
9792     S.Diag(Templated->getLocation(),
9793            diag::note_ovl_candidate_inconsistent_deduction)
9794         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9795         << *DeductionFailure.getSecondArg();
9796     MaybeEmitInheritedConstructorNote(S, Found);
9797     return;
9798   }
9799 
9800   case Sema::TDK_InvalidExplicitArguments:
9801     assert(ParamD && "no parameter found for invalid explicit arguments");
9802     if (ParamD->getDeclName())
9803       S.Diag(Templated->getLocation(),
9804              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9805           << ParamD->getDeclName();
9806     else {
9807       int index = 0;
9808       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9809         index = TTP->getIndex();
9810       else if (NonTypeTemplateParmDecl *NTTP
9811                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9812         index = NTTP->getIndex();
9813       else
9814         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9815       S.Diag(Templated->getLocation(),
9816              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9817           << (index + 1);
9818     }
9819     MaybeEmitInheritedConstructorNote(S, Found);
9820     return;
9821 
9822   case Sema::TDK_TooManyArguments:
9823   case Sema::TDK_TooFewArguments:
9824     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9825     return;
9826 
9827   case Sema::TDK_InstantiationDepth:
9828     S.Diag(Templated->getLocation(),
9829            diag::note_ovl_candidate_instantiation_depth);
9830     MaybeEmitInheritedConstructorNote(S, Found);
9831     return;
9832 
9833   case Sema::TDK_SubstitutionFailure: {
9834     // Format the template argument list into the argument string.
9835     SmallString<128> TemplateArgString;
9836     if (TemplateArgumentList *Args =
9837             DeductionFailure.getTemplateArgumentList()) {
9838       TemplateArgString = " ";
9839       TemplateArgString += S.getTemplateArgumentBindingsText(
9840           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9841     }
9842 
9843     // If this candidate was disabled by enable_if, say so.
9844     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9845     if (PDiag && PDiag->second.getDiagID() ==
9846           diag::err_typename_nested_not_found_enable_if) {
9847       // FIXME: Use the source range of the condition, and the fully-qualified
9848       //        name of the enable_if template. These are both present in PDiag.
9849       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9850         << "'enable_if'" << TemplateArgString;
9851       return;
9852     }
9853 
9854     // We found a specific requirement that disabled the enable_if.
9855     if (PDiag && PDiag->second.getDiagID() ==
9856         diag::err_typename_nested_not_found_requirement) {
9857       S.Diag(Templated->getLocation(),
9858              diag::note_ovl_candidate_disabled_by_requirement)
9859         << PDiag->second.getStringArg(0) << TemplateArgString;
9860       return;
9861     }
9862 
9863     // Format the SFINAE diagnostic into the argument string.
9864     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9865     //        formatted message in another diagnostic.
9866     SmallString<128> SFINAEArgString;
9867     SourceRange R;
9868     if (PDiag) {
9869       SFINAEArgString = ": ";
9870       R = SourceRange(PDiag->first, PDiag->first);
9871       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9872     }
9873 
9874     S.Diag(Templated->getLocation(),
9875            diag::note_ovl_candidate_substitution_failure)
9876         << TemplateArgString << SFINAEArgString << R;
9877     MaybeEmitInheritedConstructorNote(S, Found);
9878     return;
9879   }
9880 
9881   case Sema::TDK_DeducedMismatch:
9882   case Sema::TDK_DeducedMismatchNested: {
9883     // Format the template argument list into the argument string.
9884     SmallString<128> TemplateArgString;
9885     if (TemplateArgumentList *Args =
9886             DeductionFailure.getTemplateArgumentList()) {
9887       TemplateArgString = " ";
9888       TemplateArgString += S.getTemplateArgumentBindingsText(
9889           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9890     }
9891 
9892     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9893         << (*DeductionFailure.getCallArgIndex() + 1)
9894         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9895         << TemplateArgString
9896         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9897     break;
9898   }
9899 
9900   case Sema::TDK_NonDeducedMismatch: {
9901     // FIXME: Provide a source location to indicate what we couldn't match.
9902     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9903     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9904     if (FirstTA.getKind() == TemplateArgument::Template &&
9905         SecondTA.getKind() == TemplateArgument::Template) {
9906       TemplateName FirstTN = FirstTA.getAsTemplate();
9907       TemplateName SecondTN = SecondTA.getAsTemplate();
9908       if (FirstTN.getKind() == TemplateName::Template &&
9909           SecondTN.getKind() == TemplateName::Template) {
9910         if (FirstTN.getAsTemplateDecl()->getName() ==
9911             SecondTN.getAsTemplateDecl()->getName()) {
9912           // FIXME: This fixes a bad diagnostic where both templates are named
9913           // the same.  This particular case is a bit difficult since:
9914           // 1) It is passed as a string to the diagnostic printer.
9915           // 2) The diagnostic printer only attempts to find a better
9916           //    name for types, not decls.
9917           // Ideally, this should folded into the diagnostic printer.
9918           S.Diag(Templated->getLocation(),
9919                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9920               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9921           return;
9922         }
9923       }
9924     }
9925 
9926     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9927         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9928       return;
9929 
9930     // FIXME: For generic lambda parameters, check if the function is a lambda
9931     // call operator, and if so, emit a prettier and more informative
9932     // diagnostic that mentions 'auto' and lambda in addition to
9933     // (or instead of?) the canonical template type parameters.
9934     S.Diag(Templated->getLocation(),
9935            diag::note_ovl_candidate_non_deduced_mismatch)
9936         << FirstTA << SecondTA;
9937     return;
9938   }
9939   // TODO: diagnose these individually, then kill off
9940   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9941   case Sema::TDK_MiscellaneousDeductionFailure:
9942     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9943     MaybeEmitInheritedConstructorNote(S, Found);
9944     return;
9945   case Sema::TDK_CUDATargetMismatch:
9946     S.Diag(Templated->getLocation(),
9947            diag::note_cuda_ovl_candidate_target_mismatch);
9948     return;
9949   }
9950 }
9951 
9952 /// Diagnose a failed template-argument deduction, for function calls.
9953 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9954                                  unsigned NumArgs,
9955                                  bool TakingCandidateAddress) {
9956   unsigned TDK = Cand->DeductionFailure.Result;
9957   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9958     if (CheckArityMismatch(S, Cand, NumArgs))
9959       return;
9960   }
9961   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9962                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9963 }
9964 
9965 /// CUDA: diagnose an invalid call across targets.
9966 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9967   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9968   FunctionDecl *Callee = Cand->Function;
9969 
9970   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9971                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9972 
9973   std::string FnDesc;
9974   OverloadCandidateKind FnKind =
9975       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9976 
9977   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9978       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9979 
9980   // This could be an implicit constructor for which we could not infer the
9981   // target due to a collsion. Diagnose that case.
9982   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9983   if (Meth != nullptr && Meth->isImplicit()) {
9984     CXXRecordDecl *ParentClass = Meth->getParent();
9985     Sema::CXXSpecialMember CSM;
9986 
9987     switch (FnKind) {
9988     default:
9989       return;
9990     case oc_implicit_default_constructor:
9991       CSM = Sema::CXXDefaultConstructor;
9992       break;
9993     case oc_implicit_copy_constructor:
9994       CSM = Sema::CXXCopyConstructor;
9995       break;
9996     case oc_implicit_move_constructor:
9997       CSM = Sema::CXXMoveConstructor;
9998       break;
9999     case oc_implicit_copy_assignment:
10000       CSM = Sema::CXXCopyAssignment;
10001       break;
10002     case oc_implicit_move_assignment:
10003       CSM = Sema::CXXMoveAssignment;
10004       break;
10005     };
10006 
10007     bool ConstRHS = false;
10008     if (Meth->getNumParams()) {
10009       if (const ReferenceType *RT =
10010               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10011         ConstRHS = RT->getPointeeType().isConstQualified();
10012       }
10013     }
10014 
10015     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10016                                               /* ConstRHS */ ConstRHS,
10017                                               /* Diagnose */ true);
10018   }
10019 }
10020 
10021 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10022   FunctionDecl *Callee = Cand->Function;
10023   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10024 
10025   S.Diag(Callee->getLocation(),
10026          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10027       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10028 }
10029 
10030 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10031   FunctionDecl *Callee = Cand->Function;
10032 
10033   S.Diag(Callee->getLocation(),
10034          diag::note_ovl_candidate_disabled_by_extension);
10035 }
10036 
10037 /// Generates a 'note' diagnostic for an overload candidate.  We've
10038 /// already generated a primary error at the call site.
10039 ///
10040 /// It really does need to be a single diagnostic with its caret
10041 /// pointed at the candidate declaration.  Yes, this creates some
10042 /// major challenges of technical writing.  Yes, this makes pointing
10043 /// out problems with specific arguments quite awkward.  It's still
10044 /// better than generating twenty screens of text for every failed
10045 /// overload.
10046 ///
10047 /// It would be great to be able to express per-candidate problems
10048 /// more richly for those diagnostic clients that cared, but we'd
10049 /// still have to be just as careful with the default diagnostics.
10050 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10051                                   unsigned NumArgs,
10052                                   bool TakingCandidateAddress) {
10053   FunctionDecl *Fn = Cand->Function;
10054 
10055   // Note deleted candidates, but only if they're viable.
10056   if (Cand->Viable) {
10057     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10058       std::string FnDesc;
10059       OverloadCandidateKind FnKind =
10060         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10061 
10062       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10063         << FnKind << FnDesc
10064         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10065       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10066       return;
10067     }
10068 
10069     // We don't really have anything else to say about viable candidates.
10070     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10071     return;
10072   }
10073 
10074   switch (Cand->FailureKind) {
10075   case ovl_fail_too_many_arguments:
10076   case ovl_fail_too_few_arguments:
10077     return DiagnoseArityMismatch(S, Cand, NumArgs);
10078 
10079   case ovl_fail_bad_deduction:
10080     return DiagnoseBadDeduction(S, Cand, NumArgs,
10081                                 TakingCandidateAddress);
10082 
10083   case ovl_fail_illegal_constructor: {
10084     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10085       << (Fn->getPrimaryTemplate() ? 1 : 0);
10086     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10087     return;
10088   }
10089 
10090   case ovl_fail_trivial_conversion:
10091   case ovl_fail_bad_final_conversion:
10092   case ovl_fail_final_conversion_not_exact:
10093     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10094 
10095   case ovl_fail_bad_conversion: {
10096     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10097     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10098       if (Cand->Conversions[I].isBad())
10099         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10100 
10101     // FIXME: this currently happens when we're called from SemaInit
10102     // when user-conversion overload fails.  Figure out how to handle
10103     // those conditions and diagnose them well.
10104     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10105   }
10106 
10107   case ovl_fail_bad_target:
10108     return DiagnoseBadTarget(S, Cand);
10109 
10110   case ovl_fail_enable_if:
10111     return DiagnoseFailedEnableIfAttr(S, Cand);
10112 
10113   case ovl_fail_ext_disabled:
10114     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10115 
10116   case ovl_fail_inhctor_slice:
10117     // It's generally not interesting to note copy/move constructors here.
10118     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10119       return;
10120     S.Diag(Fn->getLocation(),
10121            diag::note_ovl_candidate_inherited_constructor_slice)
10122       << (Fn->getPrimaryTemplate() ? 1 : 0)
10123       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10124     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10125     return;
10126 
10127   case ovl_fail_addr_not_available: {
10128     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10129     (void)Available;
10130     assert(!Available);
10131     break;
10132   }
10133   }
10134 }
10135 
10136 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10137   // Desugar the type of the surrogate down to a function type,
10138   // retaining as many typedefs as possible while still showing
10139   // the function type (and, therefore, its parameter types).
10140   QualType FnType = Cand->Surrogate->getConversionType();
10141   bool isLValueReference = false;
10142   bool isRValueReference = false;
10143   bool isPointer = false;
10144   if (const LValueReferenceType *FnTypeRef =
10145         FnType->getAs<LValueReferenceType>()) {
10146     FnType = FnTypeRef->getPointeeType();
10147     isLValueReference = true;
10148   } else if (const RValueReferenceType *FnTypeRef =
10149                FnType->getAs<RValueReferenceType>()) {
10150     FnType = FnTypeRef->getPointeeType();
10151     isRValueReference = true;
10152   }
10153   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10154     FnType = FnTypePtr->getPointeeType();
10155     isPointer = true;
10156   }
10157   // Desugar down to a function type.
10158   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10159   // Reconstruct the pointer/reference as appropriate.
10160   if (isPointer) FnType = S.Context.getPointerType(FnType);
10161   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10162   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10163 
10164   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10165     << FnType;
10166 }
10167 
10168 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10169                                          SourceLocation OpLoc,
10170                                          OverloadCandidate *Cand) {
10171   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10172   std::string TypeStr("operator");
10173   TypeStr += Opc;
10174   TypeStr += "(";
10175   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10176   if (Cand->Conversions.size() == 1) {
10177     TypeStr += ")";
10178     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10179   } else {
10180     TypeStr += ", ";
10181     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10182     TypeStr += ")";
10183     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10184   }
10185 }
10186 
10187 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10188                                          OverloadCandidate *Cand) {
10189   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10190     if (ICS.isBad()) break; // all meaningless after first invalid
10191     if (!ICS.isAmbiguous()) continue;
10192 
10193     ICS.DiagnoseAmbiguousConversion(
10194         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10195   }
10196 }
10197 
10198 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10199   if (Cand->Function)
10200     return Cand->Function->getLocation();
10201   if (Cand->IsSurrogate)
10202     return Cand->Surrogate->getLocation();
10203   return SourceLocation();
10204 }
10205 
10206 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10207   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10208   case Sema::TDK_Success:
10209   case Sema::TDK_NonDependentConversionFailure:
10210     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10211 
10212   case Sema::TDK_Invalid:
10213   case Sema::TDK_Incomplete:
10214     return 1;
10215 
10216   case Sema::TDK_Underqualified:
10217   case Sema::TDK_Inconsistent:
10218     return 2;
10219 
10220   case Sema::TDK_SubstitutionFailure:
10221   case Sema::TDK_DeducedMismatch:
10222   case Sema::TDK_DeducedMismatchNested:
10223   case Sema::TDK_NonDeducedMismatch:
10224   case Sema::TDK_MiscellaneousDeductionFailure:
10225   case Sema::TDK_CUDATargetMismatch:
10226     return 3;
10227 
10228   case Sema::TDK_InstantiationDepth:
10229     return 4;
10230 
10231   case Sema::TDK_InvalidExplicitArguments:
10232     return 5;
10233 
10234   case Sema::TDK_TooManyArguments:
10235   case Sema::TDK_TooFewArguments:
10236     return 6;
10237   }
10238   llvm_unreachable("Unhandled deduction result");
10239 }
10240 
10241 namespace {
10242 struct CompareOverloadCandidatesForDisplay {
10243   Sema &S;
10244   SourceLocation Loc;
10245   size_t NumArgs;
10246 
10247   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10248       : S(S), NumArgs(nArgs) {}
10249 
10250   bool operator()(const OverloadCandidate *L,
10251                   const OverloadCandidate *R) {
10252     // Fast-path this check.
10253     if (L == R) return false;
10254 
10255     // Order first by viability.
10256     if (L->Viable) {
10257       if (!R->Viable) return true;
10258 
10259       // TODO: introduce a tri-valued comparison for overload
10260       // candidates.  Would be more worthwhile if we had a sort
10261       // that could exploit it.
10262       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10263       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10264     } else if (R->Viable)
10265       return false;
10266 
10267     assert(L->Viable == R->Viable);
10268 
10269     // Criteria by which we can sort non-viable candidates:
10270     if (!L->Viable) {
10271       // 1. Arity mismatches come after other candidates.
10272       if (L->FailureKind == ovl_fail_too_many_arguments ||
10273           L->FailureKind == ovl_fail_too_few_arguments) {
10274         if (R->FailureKind == ovl_fail_too_many_arguments ||
10275             R->FailureKind == ovl_fail_too_few_arguments) {
10276           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10277           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10278           if (LDist == RDist) {
10279             if (L->FailureKind == R->FailureKind)
10280               // Sort non-surrogates before surrogates.
10281               return !L->IsSurrogate && R->IsSurrogate;
10282             // Sort candidates requiring fewer parameters than there were
10283             // arguments given after candidates requiring more parameters
10284             // than there were arguments given.
10285             return L->FailureKind == ovl_fail_too_many_arguments;
10286           }
10287           return LDist < RDist;
10288         }
10289         return false;
10290       }
10291       if (R->FailureKind == ovl_fail_too_many_arguments ||
10292           R->FailureKind == ovl_fail_too_few_arguments)
10293         return true;
10294 
10295       // 2. Bad conversions come first and are ordered by the number
10296       // of bad conversions and quality of good conversions.
10297       if (L->FailureKind == ovl_fail_bad_conversion) {
10298         if (R->FailureKind != ovl_fail_bad_conversion)
10299           return true;
10300 
10301         // The conversion that can be fixed with a smaller number of changes,
10302         // comes first.
10303         unsigned numLFixes = L->Fix.NumConversionsFixed;
10304         unsigned numRFixes = R->Fix.NumConversionsFixed;
10305         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10306         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10307         if (numLFixes != numRFixes) {
10308           return numLFixes < numRFixes;
10309         }
10310 
10311         // If there's any ordering between the defined conversions...
10312         // FIXME: this might not be transitive.
10313         assert(L->Conversions.size() == R->Conversions.size());
10314 
10315         int leftBetter = 0;
10316         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10317         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10318           switch (CompareImplicitConversionSequences(S, Loc,
10319                                                      L->Conversions[I],
10320                                                      R->Conversions[I])) {
10321           case ImplicitConversionSequence::Better:
10322             leftBetter++;
10323             break;
10324 
10325           case ImplicitConversionSequence::Worse:
10326             leftBetter--;
10327             break;
10328 
10329           case ImplicitConversionSequence::Indistinguishable:
10330             break;
10331           }
10332         }
10333         if (leftBetter > 0) return true;
10334         if (leftBetter < 0) return false;
10335 
10336       } else if (R->FailureKind == ovl_fail_bad_conversion)
10337         return false;
10338 
10339       if (L->FailureKind == ovl_fail_bad_deduction) {
10340         if (R->FailureKind != ovl_fail_bad_deduction)
10341           return true;
10342 
10343         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10344           return RankDeductionFailure(L->DeductionFailure)
10345                < RankDeductionFailure(R->DeductionFailure);
10346       } else if (R->FailureKind == ovl_fail_bad_deduction)
10347         return false;
10348 
10349       // TODO: others?
10350     }
10351 
10352     // Sort everything else by location.
10353     SourceLocation LLoc = GetLocationForCandidate(L);
10354     SourceLocation RLoc = GetLocationForCandidate(R);
10355 
10356     // Put candidates without locations (e.g. builtins) at the end.
10357     if (LLoc.isInvalid()) return false;
10358     if (RLoc.isInvalid()) return true;
10359 
10360     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10361   }
10362 };
10363 }
10364 
10365 /// CompleteNonViableCandidate - Normally, overload resolution only
10366 /// computes up to the first bad conversion. Produces the FixIt set if
10367 /// possible.
10368 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10369                                        ArrayRef<Expr *> Args) {
10370   assert(!Cand->Viable);
10371 
10372   // Don't do anything on failures other than bad conversion.
10373   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10374 
10375   // We only want the FixIts if all the arguments can be corrected.
10376   bool Unfixable = false;
10377   // Use a implicit copy initialization to check conversion fixes.
10378   Cand->Fix.setConversionChecker(TryCopyInitialization);
10379 
10380   // Attempt to fix the bad conversion.
10381   unsigned ConvCount = Cand->Conversions.size();
10382   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10383        ++ConvIdx) {
10384     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10385     if (Cand->Conversions[ConvIdx].isInitialized() &&
10386         Cand->Conversions[ConvIdx].isBad()) {
10387       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10388       break;
10389     }
10390   }
10391 
10392   // FIXME: this should probably be preserved from the overload
10393   // operation somehow.
10394   bool SuppressUserConversions = false;
10395 
10396   unsigned ConvIdx = 0;
10397   ArrayRef<QualType> ParamTypes;
10398 
10399   if (Cand->IsSurrogate) {
10400     QualType ConvType
10401       = Cand->Surrogate->getConversionType().getNonReferenceType();
10402     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10403       ConvType = ConvPtrType->getPointeeType();
10404     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10405     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10406     ConvIdx = 1;
10407   } else if (Cand->Function) {
10408     ParamTypes =
10409         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10410     if (isa<CXXMethodDecl>(Cand->Function) &&
10411         !isa<CXXConstructorDecl>(Cand->Function)) {
10412       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10413       ConvIdx = 1;
10414     }
10415   } else {
10416     // Builtin operator.
10417     assert(ConvCount <= 3);
10418     ParamTypes = Cand->BuiltinParamTypes;
10419   }
10420 
10421   // Fill in the rest of the conversions.
10422   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10423     if (Cand->Conversions[ConvIdx].isInitialized()) {
10424       // We've already checked this conversion.
10425     } else if (ArgIdx < ParamTypes.size()) {
10426       if (ParamTypes[ArgIdx]->isDependentType())
10427         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10428             Args[ArgIdx]->getType());
10429       else {
10430         Cand->Conversions[ConvIdx] =
10431             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10432                                   SuppressUserConversions,
10433                                   /*InOverloadResolution=*/true,
10434                                   /*AllowObjCWritebackConversion=*/
10435                                   S.getLangOpts().ObjCAutoRefCount);
10436         // Store the FixIt in the candidate if it exists.
10437         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10438           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10439       }
10440     } else
10441       Cand->Conversions[ConvIdx].setEllipsis();
10442   }
10443 }
10444 
10445 /// PrintOverloadCandidates - When overload resolution fails, prints
10446 /// diagnostic messages containing the candidates in the candidate
10447 /// set.
10448 void OverloadCandidateSet::NoteCandidates(
10449     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10450     StringRef Opc, SourceLocation OpLoc,
10451     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10452   // Sort the candidates by viability and position.  Sorting directly would
10453   // be prohibitive, so we make a set of pointers and sort those.
10454   SmallVector<OverloadCandidate*, 32> Cands;
10455   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10456   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10457     if (!Filter(*Cand))
10458       continue;
10459     if (Cand->Viable)
10460       Cands.push_back(Cand);
10461     else if (OCD == OCD_AllCandidates) {
10462       CompleteNonViableCandidate(S, Cand, Args);
10463       if (Cand->Function || Cand->IsSurrogate)
10464         Cands.push_back(Cand);
10465       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10466       // want to list every possible builtin candidate.
10467     }
10468   }
10469 
10470   std::sort(Cands.begin(), Cands.end(),
10471             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10472 
10473   bool ReportedAmbiguousConversions = false;
10474 
10475   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10476   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10477   unsigned CandsShown = 0;
10478   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10479     OverloadCandidate *Cand = *I;
10480 
10481     // Set an arbitrary limit on the number of candidate functions we'll spam
10482     // the user with.  FIXME: This limit should depend on details of the
10483     // candidate list.
10484     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10485       break;
10486     }
10487     ++CandsShown;
10488 
10489     if (Cand->Function)
10490       NoteFunctionCandidate(S, Cand, Args.size(),
10491                             /*TakingCandidateAddress=*/false);
10492     else if (Cand->IsSurrogate)
10493       NoteSurrogateCandidate(S, Cand);
10494     else {
10495       assert(Cand->Viable &&
10496              "Non-viable built-in candidates are not added to Cands.");
10497       // Generally we only see ambiguities including viable builtin
10498       // operators if overload resolution got screwed up by an
10499       // ambiguous user-defined conversion.
10500       //
10501       // FIXME: It's quite possible for different conversions to see
10502       // different ambiguities, though.
10503       if (!ReportedAmbiguousConversions) {
10504         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10505         ReportedAmbiguousConversions = true;
10506       }
10507 
10508       // If this is a viable builtin, print it.
10509       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10510     }
10511   }
10512 
10513   if (I != E)
10514     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10515 }
10516 
10517 static SourceLocation
10518 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10519   return Cand->Specialization ? Cand->Specialization->getLocation()
10520                               : SourceLocation();
10521 }
10522 
10523 namespace {
10524 struct CompareTemplateSpecCandidatesForDisplay {
10525   Sema &S;
10526   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10527 
10528   bool operator()(const TemplateSpecCandidate *L,
10529                   const TemplateSpecCandidate *R) {
10530     // Fast-path this check.
10531     if (L == R)
10532       return false;
10533 
10534     // Assuming that both candidates are not matches...
10535 
10536     // Sort by the ranking of deduction failures.
10537     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10538       return RankDeductionFailure(L->DeductionFailure) <
10539              RankDeductionFailure(R->DeductionFailure);
10540 
10541     // Sort everything else by location.
10542     SourceLocation LLoc = GetLocationForCandidate(L);
10543     SourceLocation RLoc = GetLocationForCandidate(R);
10544 
10545     // Put candidates without locations (e.g. builtins) at the end.
10546     if (LLoc.isInvalid())
10547       return false;
10548     if (RLoc.isInvalid())
10549       return true;
10550 
10551     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10552   }
10553 };
10554 }
10555 
10556 /// Diagnose a template argument deduction failure.
10557 /// We are treating these failures as overload failures due to bad
10558 /// deductions.
10559 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10560                                                  bool ForTakingAddress) {
10561   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10562                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10563 }
10564 
10565 void TemplateSpecCandidateSet::destroyCandidates() {
10566   for (iterator i = begin(), e = end(); i != e; ++i) {
10567     i->DeductionFailure.Destroy();
10568   }
10569 }
10570 
10571 void TemplateSpecCandidateSet::clear() {
10572   destroyCandidates();
10573   Candidates.clear();
10574 }
10575 
10576 /// NoteCandidates - When no template specialization match is found, prints
10577 /// diagnostic messages containing the non-matching specializations that form
10578 /// the candidate set.
10579 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10580 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10581 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10582   // Sort the candidates by position (assuming no candidate is a match).
10583   // Sorting directly would be prohibitive, so we make a set of pointers
10584   // and sort those.
10585   SmallVector<TemplateSpecCandidate *, 32> Cands;
10586   Cands.reserve(size());
10587   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10588     if (Cand->Specialization)
10589       Cands.push_back(Cand);
10590     // Otherwise, this is a non-matching builtin candidate.  We do not,
10591     // in general, want to list every possible builtin candidate.
10592   }
10593 
10594   std::sort(Cands.begin(), Cands.end(),
10595             CompareTemplateSpecCandidatesForDisplay(S));
10596 
10597   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10598   // for generalization purposes (?).
10599   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10600 
10601   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10602   unsigned CandsShown = 0;
10603   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10604     TemplateSpecCandidate *Cand = *I;
10605 
10606     // Set an arbitrary limit on the number of candidates we'll spam
10607     // the user with.  FIXME: This limit should depend on details of the
10608     // candidate list.
10609     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10610       break;
10611     ++CandsShown;
10612 
10613     assert(Cand->Specialization &&
10614            "Non-matching built-in candidates are not added to Cands.");
10615     Cand->NoteDeductionFailure(S, ForTakingAddress);
10616   }
10617 
10618   if (I != E)
10619     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10620 }
10621 
10622 // [PossiblyAFunctionType]  -->   [Return]
10623 // NonFunctionType --> NonFunctionType
10624 // R (A) --> R(A)
10625 // R (*)(A) --> R (A)
10626 // R (&)(A) --> R (A)
10627 // R (S::*)(A) --> R (A)
10628 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10629   QualType Ret = PossiblyAFunctionType;
10630   if (const PointerType *ToTypePtr =
10631     PossiblyAFunctionType->getAs<PointerType>())
10632     Ret = ToTypePtr->getPointeeType();
10633   else if (const ReferenceType *ToTypeRef =
10634     PossiblyAFunctionType->getAs<ReferenceType>())
10635     Ret = ToTypeRef->getPointeeType();
10636   else if (const MemberPointerType *MemTypePtr =
10637     PossiblyAFunctionType->getAs<MemberPointerType>())
10638     Ret = MemTypePtr->getPointeeType();
10639   Ret =
10640     Context.getCanonicalType(Ret).getUnqualifiedType();
10641   return Ret;
10642 }
10643 
10644 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10645                                  bool Complain = true) {
10646   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10647       S.DeduceReturnType(FD, Loc, Complain))
10648     return true;
10649 
10650   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10651   if (S.getLangOpts().CPlusPlus1z &&
10652       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10653       !S.ResolveExceptionSpec(Loc, FPT))
10654     return true;
10655 
10656   return false;
10657 }
10658 
10659 namespace {
10660 // A helper class to help with address of function resolution
10661 // - allows us to avoid passing around all those ugly parameters
10662 class AddressOfFunctionResolver {
10663   Sema& S;
10664   Expr* SourceExpr;
10665   const QualType& TargetType;
10666   QualType TargetFunctionType; // Extracted function type from target type
10667 
10668   bool Complain;
10669   //DeclAccessPair& ResultFunctionAccessPair;
10670   ASTContext& Context;
10671 
10672   bool TargetTypeIsNonStaticMemberFunction;
10673   bool FoundNonTemplateFunction;
10674   bool StaticMemberFunctionFromBoundPointer;
10675   bool HasComplained;
10676 
10677   OverloadExpr::FindResult OvlExprInfo;
10678   OverloadExpr *OvlExpr;
10679   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10680   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10681   TemplateSpecCandidateSet FailedCandidates;
10682 
10683 public:
10684   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10685                             const QualType &TargetType, bool Complain)
10686       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10687         Complain(Complain), Context(S.getASTContext()),
10688         TargetTypeIsNonStaticMemberFunction(
10689             !!TargetType->getAs<MemberPointerType>()),
10690         FoundNonTemplateFunction(false),
10691         StaticMemberFunctionFromBoundPointer(false),
10692         HasComplained(false),
10693         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10694         OvlExpr(OvlExprInfo.Expression),
10695         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10696     ExtractUnqualifiedFunctionTypeFromTargetType();
10697 
10698     if (TargetFunctionType->isFunctionType()) {
10699       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10700         if (!UME->isImplicitAccess() &&
10701             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10702           StaticMemberFunctionFromBoundPointer = true;
10703     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10704       DeclAccessPair dap;
10705       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10706               OvlExpr, false, &dap)) {
10707         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10708           if (!Method->isStatic()) {
10709             // If the target type is a non-function type and the function found
10710             // is a non-static member function, pretend as if that was the
10711             // target, it's the only possible type to end up with.
10712             TargetTypeIsNonStaticMemberFunction = true;
10713 
10714             // And skip adding the function if its not in the proper form.
10715             // We'll diagnose this due to an empty set of functions.
10716             if (!OvlExprInfo.HasFormOfMemberPointer)
10717               return;
10718           }
10719 
10720         Matches.push_back(std::make_pair(dap, Fn));
10721       }
10722       return;
10723     }
10724 
10725     if (OvlExpr->hasExplicitTemplateArgs())
10726       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10727 
10728     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10729       // C++ [over.over]p4:
10730       //   If more than one function is selected, [...]
10731       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10732         if (FoundNonTemplateFunction)
10733           EliminateAllTemplateMatches();
10734         else
10735           EliminateAllExceptMostSpecializedTemplate();
10736       }
10737     }
10738 
10739     if (S.getLangOpts().CUDA && Matches.size() > 1)
10740       EliminateSuboptimalCudaMatches();
10741   }
10742 
10743   bool hasComplained() const { return HasComplained; }
10744 
10745 private:
10746   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10747     QualType Discard;
10748     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10749            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10750   }
10751 
10752   /// \return true if A is considered a better overload candidate for the
10753   /// desired type than B.
10754   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10755     // If A doesn't have exactly the correct type, we don't want to classify it
10756     // as "better" than anything else. This way, the user is required to
10757     // disambiguate for us if there are multiple candidates and no exact match.
10758     return candidateHasExactlyCorrectType(A) &&
10759            (!candidateHasExactlyCorrectType(B) ||
10760             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10761   }
10762 
10763   /// \return true if we were able to eliminate all but one overload candidate,
10764   /// false otherwise.
10765   bool eliminiateSuboptimalOverloadCandidates() {
10766     // Same algorithm as overload resolution -- one pass to pick the "best",
10767     // another pass to be sure that nothing is better than the best.
10768     auto Best = Matches.begin();
10769     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10770       if (isBetterCandidate(I->second, Best->second))
10771         Best = I;
10772 
10773     const FunctionDecl *BestFn = Best->second;
10774     auto IsBestOrInferiorToBest = [this, BestFn](
10775         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10776       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10777     };
10778 
10779     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10780     // option, so we can potentially give the user a better error
10781     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10782       return false;
10783     Matches[0] = *Best;
10784     Matches.resize(1);
10785     return true;
10786   }
10787 
10788   bool isTargetTypeAFunction() const {
10789     return TargetFunctionType->isFunctionType();
10790   }
10791 
10792   // [ToType]     [Return]
10793 
10794   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10795   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10796   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10797   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10798     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10799   }
10800 
10801   // return true if any matching specializations were found
10802   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10803                                    const DeclAccessPair& CurAccessFunPair) {
10804     if (CXXMethodDecl *Method
10805               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10806       // Skip non-static function templates when converting to pointer, and
10807       // static when converting to member pointer.
10808       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10809         return false;
10810     }
10811     else if (TargetTypeIsNonStaticMemberFunction)
10812       return false;
10813 
10814     // C++ [over.over]p2:
10815     //   If the name is a function template, template argument deduction is
10816     //   done (14.8.2.2), and if the argument deduction succeeds, the
10817     //   resulting template argument list is used to generate a single
10818     //   function template specialization, which is added to the set of
10819     //   overloaded functions considered.
10820     FunctionDecl *Specialization = nullptr;
10821     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10822     if (Sema::TemplateDeductionResult Result
10823           = S.DeduceTemplateArguments(FunctionTemplate,
10824                                       &OvlExplicitTemplateArgs,
10825                                       TargetFunctionType, Specialization,
10826                                       Info, /*IsAddressOfFunction*/true)) {
10827       // Make a note of the failed deduction for diagnostics.
10828       FailedCandidates.addCandidate()
10829           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10830                MakeDeductionFailureInfo(Context, Result, Info));
10831       return false;
10832     }
10833 
10834     // Template argument deduction ensures that we have an exact match or
10835     // compatible pointer-to-function arguments that would be adjusted by ICS.
10836     // This function template specicalization works.
10837     assert(S.isSameOrCompatibleFunctionType(
10838               Context.getCanonicalType(Specialization->getType()),
10839               Context.getCanonicalType(TargetFunctionType)));
10840 
10841     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10842       return false;
10843 
10844     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10845     return true;
10846   }
10847 
10848   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10849                                       const DeclAccessPair& CurAccessFunPair) {
10850     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10851       // Skip non-static functions when converting to pointer, and static
10852       // when converting to member pointer.
10853       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10854         return false;
10855     }
10856     else if (TargetTypeIsNonStaticMemberFunction)
10857       return false;
10858 
10859     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10860       if (S.getLangOpts().CUDA)
10861         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10862           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10863             return false;
10864 
10865       // If any candidate has a placeholder return type, trigger its deduction
10866       // now.
10867       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10868                                Complain)) {
10869         HasComplained |= Complain;
10870         return false;
10871       }
10872 
10873       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10874         return false;
10875 
10876       // If we're in C, we need to support types that aren't exactly identical.
10877       if (!S.getLangOpts().CPlusPlus ||
10878           candidateHasExactlyCorrectType(FunDecl)) {
10879         Matches.push_back(std::make_pair(
10880             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10881         FoundNonTemplateFunction = true;
10882         return true;
10883       }
10884     }
10885 
10886     return false;
10887   }
10888 
10889   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10890     bool Ret = false;
10891 
10892     // If the overload expression doesn't have the form of a pointer to
10893     // member, don't try to convert it to a pointer-to-member type.
10894     if (IsInvalidFormOfPointerToMemberFunction())
10895       return false;
10896 
10897     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10898                                E = OvlExpr->decls_end();
10899          I != E; ++I) {
10900       // Look through any using declarations to find the underlying function.
10901       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10902 
10903       // C++ [over.over]p3:
10904       //   Non-member functions and static member functions match
10905       //   targets of type "pointer-to-function" or "reference-to-function."
10906       //   Nonstatic member functions match targets of
10907       //   type "pointer-to-member-function."
10908       // Note that according to DR 247, the containing class does not matter.
10909       if (FunctionTemplateDecl *FunctionTemplate
10910                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10911         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10912           Ret = true;
10913       }
10914       // If we have explicit template arguments supplied, skip non-templates.
10915       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10916                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10917         Ret = true;
10918     }
10919     assert(Ret || Matches.empty());
10920     return Ret;
10921   }
10922 
10923   void EliminateAllExceptMostSpecializedTemplate() {
10924     //   [...] and any given function template specialization F1 is
10925     //   eliminated if the set contains a second function template
10926     //   specialization whose function template is more specialized
10927     //   than the function template of F1 according to the partial
10928     //   ordering rules of 14.5.5.2.
10929 
10930     // The algorithm specified above is quadratic. We instead use a
10931     // two-pass algorithm (similar to the one used to identify the
10932     // best viable function in an overload set) that identifies the
10933     // best function template (if it exists).
10934 
10935     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10936     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10937       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10938 
10939     // TODO: It looks like FailedCandidates does not serve much purpose
10940     // here, since the no_viable diagnostic has index 0.
10941     UnresolvedSetIterator Result = S.getMostSpecialized(
10942         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10943         SourceExpr->getLocStart(), S.PDiag(),
10944         S.PDiag(diag::err_addr_ovl_ambiguous)
10945           << Matches[0].second->getDeclName(),
10946         S.PDiag(diag::note_ovl_candidate)
10947           << (unsigned)oc_function_template,
10948         Complain, TargetFunctionType);
10949 
10950     if (Result != MatchesCopy.end()) {
10951       // Make it the first and only element
10952       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10953       Matches[0].second = cast<FunctionDecl>(*Result);
10954       Matches.resize(1);
10955     } else
10956       HasComplained |= Complain;
10957   }
10958 
10959   void EliminateAllTemplateMatches() {
10960     //   [...] any function template specializations in the set are
10961     //   eliminated if the set also contains a non-template function, [...]
10962     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10963       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10964         ++I;
10965       else {
10966         Matches[I] = Matches[--N];
10967         Matches.resize(N);
10968       }
10969     }
10970   }
10971 
10972   void EliminateSuboptimalCudaMatches() {
10973     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10974   }
10975 
10976 public:
10977   void ComplainNoMatchesFound() const {
10978     assert(Matches.empty());
10979     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10980         << OvlExpr->getName() << TargetFunctionType
10981         << OvlExpr->getSourceRange();
10982     if (FailedCandidates.empty())
10983       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10984                                   /*TakingAddress=*/true);
10985     else {
10986       // We have some deduction failure messages. Use them to diagnose
10987       // the function templates, and diagnose the non-template candidates
10988       // normally.
10989       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10990                                  IEnd = OvlExpr->decls_end();
10991            I != IEnd; ++I)
10992         if (FunctionDecl *Fun =
10993                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10994           if (!functionHasPassObjectSizeParams(Fun))
10995             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10996                                     /*TakingAddress=*/true);
10997       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10998     }
10999   }
11000 
11001   bool IsInvalidFormOfPointerToMemberFunction() const {
11002     return TargetTypeIsNonStaticMemberFunction &&
11003       !OvlExprInfo.HasFormOfMemberPointer;
11004   }
11005 
11006   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11007       // TODO: Should we condition this on whether any functions might
11008       // have matched, or is it more appropriate to do that in callers?
11009       // TODO: a fixit wouldn't hurt.
11010       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11011         << TargetType << OvlExpr->getSourceRange();
11012   }
11013 
11014   bool IsStaticMemberFunctionFromBoundPointer() const {
11015     return StaticMemberFunctionFromBoundPointer;
11016   }
11017 
11018   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11019     S.Diag(OvlExpr->getLocStart(),
11020            diag::err_invalid_form_pointer_member_function)
11021       << OvlExpr->getSourceRange();
11022   }
11023 
11024   void ComplainOfInvalidConversion() const {
11025     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11026       << OvlExpr->getName() << TargetType;
11027   }
11028 
11029   void ComplainMultipleMatchesFound() const {
11030     assert(Matches.size() > 1);
11031     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11032       << OvlExpr->getName()
11033       << OvlExpr->getSourceRange();
11034     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11035                                 /*TakingAddress=*/true);
11036   }
11037 
11038   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11039 
11040   int getNumMatches() const { return Matches.size(); }
11041 
11042   FunctionDecl* getMatchingFunctionDecl() const {
11043     if (Matches.size() != 1) return nullptr;
11044     return Matches[0].second;
11045   }
11046 
11047   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11048     if (Matches.size() != 1) return nullptr;
11049     return &Matches[0].first;
11050   }
11051 };
11052 }
11053 
11054 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11055 /// an overloaded function (C++ [over.over]), where @p From is an
11056 /// expression with overloaded function type and @p ToType is the type
11057 /// we're trying to resolve to. For example:
11058 ///
11059 /// @code
11060 /// int f(double);
11061 /// int f(int);
11062 ///
11063 /// int (*pfd)(double) = f; // selects f(double)
11064 /// @endcode
11065 ///
11066 /// This routine returns the resulting FunctionDecl if it could be
11067 /// resolved, and NULL otherwise. When @p Complain is true, this
11068 /// routine will emit diagnostics if there is an error.
11069 FunctionDecl *
11070 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11071                                          QualType TargetType,
11072                                          bool Complain,
11073                                          DeclAccessPair &FoundResult,
11074                                          bool *pHadMultipleCandidates) {
11075   assert(AddressOfExpr->getType() == Context.OverloadTy);
11076 
11077   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11078                                      Complain);
11079   int NumMatches = Resolver.getNumMatches();
11080   FunctionDecl *Fn = nullptr;
11081   bool ShouldComplain = Complain && !Resolver.hasComplained();
11082   if (NumMatches == 0 && ShouldComplain) {
11083     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11084       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11085     else
11086       Resolver.ComplainNoMatchesFound();
11087   }
11088   else if (NumMatches > 1 && ShouldComplain)
11089     Resolver.ComplainMultipleMatchesFound();
11090   else if (NumMatches == 1) {
11091     Fn = Resolver.getMatchingFunctionDecl();
11092     assert(Fn);
11093     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11094       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11095     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11096     if (Complain) {
11097       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11098         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11099       else
11100         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11101     }
11102   }
11103 
11104   if (pHadMultipleCandidates)
11105     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11106   return Fn;
11107 }
11108 
11109 /// \brief Given an expression that refers to an overloaded function, try to
11110 /// resolve that function to a single function that can have its address taken.
11111 /// This will modify `Pair` iff it returns non-null.
11112 ///
11113 /// This routine can only realistically succeed if all but one candidates in the
11114 /// overload set for SrcExpr cannot have their addresses taken.
11115 FunctionDecl *
11116 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11117                                                   DeclAccessPair &Pair) {
11118   OverloadExpr::FindResult R = OverloadExpr::find(E);
11119   OverloadExpr *Ovl = R.Expression;
11120   FunctionDecl *Result = nullptr;
11121   DeclAccessPair DAP;
11122   // Don't use the AddressOfResolver because we're specifically looking for
11123   // cases where we have one overload candidate that lacks
11124   // enable_if/pass_object_size/...
11125   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11126     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11127     if (!FD)
11128       return nullptr;
11129 
11130     if (!checkAddressOfFunctionIsAvailable(FD))
11131       continue;
11132 
11133     // We have more than one result; quit.
11134     if (Result)
11135       return nullptr;
11136     DAP = I.getPair();
11137     Result = FD;
11138   }
11139 
11140   if (Result)
11141     Pair = DAP;
11142   return Result;
11143 }
11144 
11145 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11146 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11147 /// will perform access checks, diagnose the use of the resultant decl, and, if
11148 /// requested, potentially perform a function-to-pointer decay.
11149 ///
11150 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11151 /// Otherwise, returns true. This may emit diagnostics and return true.
11152 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11153     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11154   Expr *E = SrcExpr.get();
11155   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11156 
11157   DeclAccessPair DAP;
11158   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11159   if (!Found)
11160     return false;
11161 
11162   // Emitting multiple diagnostics for a function that is both inaccessible and
11163   // unavailable is consistent with our behavior elsewhere. So, always check
11164   // for both.
11165   DiagnoseUseOfDecl(Found, E->getExprLoc());
11166   CheckAddressOfMemberAccess(E, DAP);
11167   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11168   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11169     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11170   else
11171     SrcExpr = Fixed;
11172   return true;
11173 }
11174 
11175 /// \brief Given an expression that refers to an overloaded function, try to
11176 /// resolve that overloaded function expression down to a single function.
11177 ///
11178 /// This routine can only resolve template-ids that refer to a single function
11179 /// template, where that template-id refers to a single template whose template
11180 /// arguments are either provided by the template-id or have defaults,
11181 /// as described in C++0x [temp.arg.explicit]p3.
11182 ///
11183 /// If no template-ids are found, no diagnostics are emitted and NULL is
11184 /// returned.
11185 FunctionDecl *
11186 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11187                                                   bool Complain,
11188                                                   DeclAccessPair *FoundResult) {
11189   // C++ [over.over]p1:
11190   //   [...] [Note: any redundant set of parentheses surrounding the
11191   //   overloaded function name is ignored (5.1). ]
11192   // C++ [over.over]p1:
11193   //   [...] The overloaded function name can be preceded by the &
11194   //   operator.
11195 
11196   // If we didn't actually find any template-ids, we're done.
11197   if (!ovl->hasExplicitTemplateArgs())
11198     return nullptr;
11199 
11200   TemplateArgumentListInfo ExplicitTemplateArgs;
11201   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11202   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11203 
11204   // Look through all of the overloaded functions, searching for one
11205   // whose type matches exactly.
11206   FunctionDecl *Matched = nullptr;
11207   for (UnresolvedSetIterator I = ovl->decls_begin(),
11208          E = ovl->decls_end(); I != E; ++I) {
11209     // C++0x [temp.arg.explicit]p3:
11210     //   [...] In contexts where deduction is done and fails, or in contexts
11211     //   where deduction is not done, if a template argument list is
11212     //   specified and it, along with any default template arguments,
11213     //   identifies a single function template specialization, then the
11214     //   template-id is an lvalue for the function template specialization.
11215     FunctionTemplateDecl *FunctionTemplate
11216       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11217 
11218     // C++ [over.over]p2:
11219     //   If the name is a function template, template argument deduction is
11220     //   done (14.8.2.2), and if the argument deduction succeeds, the
11221     //   resulting template argument list is used to generate a single
11222     //   function template specialization, which is added to the set of
11223     //   overloaded functions considered.
11224     FunctionDecl *Specialization = nullptr;
11225     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11226     if (TemplateDeductionResult Result
11227           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11228                                     Specialization, Info,
11229                                     /*IsAddressOfFunction*/true)) {
11230       // Make a note of the failed deduction for diagnostics.
11231       // TODO: Actually use the failed-deduction info?
11232       FailedCandidates.addCandidate()
11233           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11234                MakeDeductionFailureInfo(Context, Result, Info));
11235       continue;
11236     }
11237 
11238     assert(Specialization && "no specialization and no error?");
11239 
11240     // Multiple matches; we can't resolve to a single declaration.
11241     if (Matched) {
11242       if (Complain) {
11243         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11244           << ovl->getName();
11245         NoteAllOverloadCandidates(ovl);
11246       }
11247       return nullptr;
11248     }
11249 
11250     Matched = Specialization;
11251     if (FoundResult) *FoundResult = I.getPair();
11252   }
11253 
11254   if (Matched &&
11255       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11256     return nullptr;
11257 
11258   return Matched;
11259 }
11260 
11261 
11262 
11263 
11264 // Resolve and fix an overloaded expression that can be resolved
11265 // because it identifies a single function template specialization.
11266 //
11267 // Last three arguments should only be supplied if Complain = true
11268 //
11269 // Return true if it was logically possible to so resolve the
11270 // expression, regardless of whether or not it succeeded.  Always
11271 // returns true if 'complain' is set.
11272 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11273                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11274                       bool complain, SourceRange OpRangeForComplaining,
11275                                            QualType DestTypeForComplaining,
11276                                             unsigned DiagIDForComplaining) {
11277   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11278 
11279   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11280 
11281   DeclAccessPair found;
11282   ExprResult SingleFunctionExpression;
11283   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11284                            ovl.Expression, /*complain*/ false, &found)) {
11285     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11286       SrcExpr = ExprError();
11287       return true;
11288     }
11289 
11290     // It is only correct to resolve to an instance method if we're
11291     // resolving a form that's permitted to be a pointer to member.
11292     // Otherwise we'll end up making a bound member expression, which
11293     // is illegal in all the contexts we resolve like this.
11294     if (!ovl.HasFormOfMemberPointer &&
11295         isa<CXXMethodDecl>(fn) &&
11296         cast<CXXMethodDecl>(fn)->isInstance()) {
11297       if (!complain) return false;
11298 
11299       Diag(ovl.Expression->getExprLoc(),
11300            diag::err_bound_member_function)
11301         << 0 << ovl.Expression->getSourceRange();
11302 
11303       // TODO: I believe we only end up here if there's a mix of
11304       // static and non-static candidates (otherwise the expression
11305       // would have 'bound member' type, not 'overload' type).
11306       // Ideally we would note which candidate was chosen and why
11307       // the static candidates were rejected.
11308       SrcExpr = ExprError();
11309       return true;
11310     }
11311 
11312     // Fix the expression to refer to 'fn'.
11313     SingleFunctionExpression =
11314         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11315 
11316     // If desired, do function-to-pointer decay.
11317     if (doFunctionPointerConverion) {
11318       SingleFunctionExpression =
11319         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11320       if (SingleFunctionExpression.isInvalid()) {
11321         SrcExpr = ExprError();
11322         return true;
11323       }
11324     }
11325   }
11326 
11327   if (!SingleFunctionExpression.isUsable()) {
11328     if (complain) {
11329       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11330         << ovl.Expression->getName()
11331         << DestTypeForComplaining
11332         << OpRangeForComplaining
11333         << ovl.Expression->getQualifierLoc().getSourceRange();
11334       NoteAllOverloadCandidates(SrcExpr.get());
11335 
11336       SrcExpr = ExprError();
11337       return true;
11338     }
11339 
11340     return false;
11341   }
11342 
11343   SrcExpr = SingleFunctionExpression;
11344   return true;
11345 }
11346 
11347 /// \brief Add a single candidate to the overload set.
11348 static void AddOverloadedCallCandidate(Sema &S,
11349                                        DeclAccessPair FoundDecl,
11350                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11351                                        ArrayRef<Expr *> Args,
11352                                        OverloadCandidateSet &CandidateSet,
11353                                        bool PartialOverloading,
11354                                        bool KnownValid) {
11355   NamedDecl *Callee = FoundDecl.getDecl();
11356   if (isa<UsingShadowDecl>(Callee))
11357     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11358 
11359   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11360     if (ExplicitTemplateArgs) {
11361       assert(!KnownValid && "Explicit template arguments?");
11362       return;
11363     }
11364     // Prevent ill-formed function decls to be added as overload candidates.
11365     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11366       return;
11367 
11368     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11369                            /*SuppressUsedConversions=*/false,
11370                            PartialOverloading);
11371     return;
11372   }
11373 
11374   if (FunctionTemplateDecl *FuncTemplate
11375       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11376     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11377                                    ExplicitTemplateArgs, Args, CandidateSet,
11378                                    /*SuppressUsedConversions=*/false,
11379                                    PartialOverloading);
11380     return;
11381   }
11382 
11383   assert(!KnownValid && "unhandled case in overloaded call candidate");
11384 }
11385 
11386 /// \brief Add the overload candidates named by callee and/or found by argument
11387 /// dependent lookup to the given overload set.
11388 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11389                                        ArrayRef<Expr *> Args,
11390                                        OverloadCandidateSet &CandidateSet,
11391                                        bool PartialOverloading) {
11392 
11393 #ifndef NDEBUG
11394   // Verify that ArgumentDependentLookup is consistent with the rules
11395   // in C++0x [basic.lookup.argdep]p3:
11396   //
11397   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11398   //   and let Y be the lookup set produced by argument dependent
11399   //   lookup (defined as follows). If X contains
11400   //
11401   //     -- a declaration of a class member, or
11402   //
11403   //     -- a block-scope function declaration that is not a
11404   //        using-declaration, or
11405   //
11406   //     -- a declaration that is neither a function or a function
11407   //        template
11408   //
11409   //   then Y is empty.
11410 
11411   if (ULE->requiresADL()) {
11412     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11413            E = ULE->decls_end(); I != E; ++I) {
11414       assert(!(*I)->getDeclContext()->isRecord());
11415       assert(isa<UsingShadowDecl>(*I) ||
11416              !(*I)->getDeclContext()->isFunctionOrMethod());
11417       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11418     }
11419   }
11420 #endif
11421 
11422   // It would be nice to avoid this copy.
11423   TemplateArgumentListInfo TABuffer;
11424   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11425   if (ULE->hasExplicitTemplateArgs()) {
11426     ULE->copyTemplateArgumentsInto(TABuffer);
11427     ExplicitTemplateArgs = &TABuffer;
11428   }
11429 
11430   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11431          E = ULE->decls_end(); I != E; ++I)
11432     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11433                                CandidateSet, PartialOverloading,
11434                                /*KnownValid*/ true);
11435 
11436   if (ULE->requiresADL())
11437     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11438                                          Args, ExplicitTemplateArgs,
11439                                          CandidateSet, PartialOverloading);
11440 }
11441 
11442 /// Determine whether a declaration with the specified name could be moved into
11443 /// a different namespace.
11444 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11445   switch (Name.getCXXOverloadedOperator()) {
11446   case OO_New: case OO_Array_New:
11447   case OO_Delete: case OO_Array_Delete:
11448     return false;
11449 
11450   default:
11451     return true;
11452   }
11453 }
11454 
11455 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11456 /// template, where the non-dependent name was declared after the template
11457 /// was defined. This is common in code written for a compilers which do not
11458 /// correctly implement two-stage name lookup.
11459 ///
11460 /// Returns true if a viable candidate was found and a diagnostic was issued.
11461 static bool
11462 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11463                        const CXXScopeSpec &SS, LookupResult &R,
11464                        OverloadCandidateSet::CandidateSetKind CSK,
11465                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11466                        ArrayRef<Expr *> Args,
11467                        bool *DoDiagnoseEmptyLookup = nullptr) {
11468   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11469     return false;
11470 
11471   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11472     if (DC->isTransparentContext())
11473       continue;
11474 
11475     SemaRef.LookupQualifiedName(R, DC);
11476 
11477     if (!R.empty()) {
11478       R.suppressDiagnostics();
11479 
11480       if (isa<CXXRecordDecl>(DC)) {
11481         // Don't diagnose names we find in classes; we get much better
11482         // diagnostics for these from DiagnoseEmptyLookup.
11483         R.clear();
11484         if (DoDiagnoseEmptyLookup)
11485           *DoDiagnoseEmptyLookup = true;
11486         return false;
11487       }
11488 
11489       OverloadCandidateSet Candidates(FnLoc, CSK);
11490       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11491         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11492                                    ExplicitTemplateArgs, Args,
11493                                    Candidates, false, /*KnownValid*/ false);
11494 
11495       OverloadCandidateSet::iterator Best;
11496       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11497         // No viable functions. Don't bother the user with notes for functions
11498         // which don't work and shouldn't be found anyway.
11499         R.clear();
11500         return false;
11501       }
11502 
11503       // Find the namespaces where ADL would have looked, and suggest
11504       // declaring the function there instead.
11505       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11506       Sema::AssociatedClassSet AssociatedClasses;
11507       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11508                                                  AssociatedNamespaces,
11509                                                  AssociatedClasses);
11510       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11511       if (canBeDeclaredInNamespace(R.getLookupName())) {
11512         DeclContext *Std = SemaRef.getStdNamespace();
11513         for (Sema::AssociatedNamespaceSet::iterator
11514                it = AssociatedNamespaces.begin(),
11515                end = AssociatedNamespaces.end(); it != end; ++it) {
11516           // Never suggest declaring a function within namespace 'std'.
11517           if (Std && Std->Encloses(*it))
11518             continue;
11519 
11520           // Never suggest declaring a function within a namespace with a
11521           // reserved name, like __gnu_cxx.
11522           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11523           if (NS &&
11524               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11525             continue;
11526 
11527           SuggestedNamespaces.insert(*it);
11528         }
11529       }
11530 
11531       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11532         << R.getLookupName();
11533       if (SuggestedNamespaces.empty()) {
11534         SemaRef.Diag(Best->Function->getLocation(),
11535                      diag::note_not_found_by_two_phase_lookup)
11536           << R.getLookupName() << 0;
11537       } else if (SuggestedNamespaces.size() == 1) {
11538         SemaRef.Diag(Best->Function->getLocation(),
11539                      diag::note_not_found_by_two_phase_lookup)
11540           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11541       } else {
11542         // FIXME: It would be useful to list the associated namespaces here,
11543         // but the diagnostics infrastructure doesn't provide a way to produce
11544         // a localized representation of a list of items.
11545         SemaRef.Diag(Best->Function->getLocation(),
11546                      diag::note_not_found_by_two_phase_lookup)
11547           << R.getLookupName() << 2;
11548       }
11549 
11550       // Try to recover by calling this function.
11551       return true;
11552     }
11553 
11554     R.clear();
11555   }
11556 
11557   return false;
11558 }
11559 
11560 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11561 /// template, where the non-dependent operator was declared after the template
11562 /// was defined.
11563 ///
11564 /// Returns true if a viable candidate was found and a diagnostic was issued.
11565 static bool
11566 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11567                                SourceLocation OpLoc,
11568                                ArrayRef<Expr *> Args) {
11569   DeclarationName OpName =
11570     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11571   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11572   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11573                                 OverloadCandidateSet::CSK_Operator,
11574                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11575 }
11576 
11577 namespace {
11578 class BuildRecoveryCallExprRAII {
11579   Sema &SemaRef;
11580 public:
11581   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11582     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11583     SemaRef.IsBuildingRecoveryCallExpr = true;
11584   }
11585 
11586   ~BuildRecoveryCallExprRAII() {
11587     SemaRef.IsBuildingRecoveryCallExpr = false;
11588   }
11589 };
11590 
11591 }
11592 
11593 static std::unique_ptr<CorrectionCandidateCallback>
11594 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11595               bool HasTemplateArgs, bool AllowTypoCorrection) {
11596   if (!AllowTypoCorrection)
11597     return llvm::make_unique<NoTypoCorrectionCCC>();
11598   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11599                                                   HasTemplateArgs, ME);
11600 }
11601 
11602 /// Attempts to recover from a call where no functions were found.
11603 ///
11604 /// Returns true if new candidates were found.
11605 static ExprResult
11606 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11607                       UnresolvedLookupExpr *ULE,
11608                       SourceLocation LParenLoc,
11609                       MutableArrayRef<Expr *> Args,
11610                       SourceLocation RParenLoc,
11611                       bool EmptyLookup, bool AllowTypoCorrection) {
11612   // Do not try to recover if it is already building a recovery call.
11613   // This stops infinite loops for template instantiations like
11614   //
11615   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11616   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11617   //
11618   if (SemaRef.IsBuildingRecoveryCallExpr)
11619     return ExprError();
11620   BuildRecoveryCallExprRAII RCE(SemaRef);
11621 
11622   CXXScopeSpec SS;
11623   SS.Adopt(ULE->getQualifierLoc());
11624   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11625 
11626   TemplateArgumentListInfo TABuffer;
11627   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11628   if (ULE->hasExplicitTemplateArgs()) {
11629     ULE->copyTemplateArgumentsInto(TABuffer);
11630     ExplicitTemplateArgs = &TABuffer;
11631   }
11632 
11633   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11634                  Sema::LookupOrdinaryName);
11635   bool DoDiagnoseEmptyLookup = EmptyLookup;
11636   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11637                               OverloadCandidateSet::CSK_Normal,
11638                               ExplicitTemplateArgs, Args,
11639                               &DoDiagnoseEmptyLookup) &&
11640     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11641         S, SS, R,
11642         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11643                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11644         ExplicitTemplateArgs, Args)))
11645     return ExprError();
11646 
11647   assert(!R.empty() && "lookup results empty despite recovery");
11648 
11649   // If recovery created an ambiguity, just bail out.
11650   if (R.isAmbiguous()) {
11651     R.suppressDiagnostics();
11652     return ExprError();
11653   }
11654 
11655   // Build an implicit member call if appropriate.  Just drop the
11656   // casts and such from the call, we don't really care.
11657   ExprResult NewFn = ExprError();
11658   if ((*R.begin())->isCXXClassMember())
11659     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11660                                                     ExplicitTemplateArgs, S);
11661   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11662     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11663                                         ExplicitTemplateArgs);
11664   else
11665     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11666 
11667   if (NewFn.isInvalid())
11668     return ExprError();
11669 
11670   // This shouldn't cause an infinite loop because we're giving it
11671   // an expression with viable lookup results, which should never
11672   // end up here.
11673   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11674                                MultiExprArg(Args.data(), Args.size()),
11675                                RParenLoc);
11676 }
11677 
11678 /// \brief Constructs and populates an OverloadedCandidateSet from
11679 /// the given function.
11680 /// \returns true when an the ExprResult output parameter has been set.
11681 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11682                                   UnresolvedLookupExpr *ULE,
11683                                   MultiExprArg Args,
11684                                   SourceLocation RParenLoc,
11685                                   OverloadCandidateSet *CandidateSet,
11686                                   ExprResult *Result) {
11687 #ifndef NDEBUG
11688   if (ULE->requiresADL()) {
11689     // To do ADL, we must have found an unqualified name.
11690     assert(!ULE->getQualifier() && "qualified name with ADL");
11691 
11692     // We don't perform ADL for implicit declarations of builtins.
11693     // Verify that this was correctly set up.
11694     FunctionDecl *F;
11695     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11696         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11697         F->getBuiltinID() && F->isImplicit())
11698       llvm_unreachable("performing ADL for builtin");
11699 
11700     // We don't perform ADL in C.
11701     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11702   }
11703 #endif
11704 
11705   UnbridgedCastsSet UnbridgedCasts;
11706   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11707     *Result = ExprError();
11708     return true;
11709   }
11710 
11711   // Add the functions denoted by the callee to the set of candidate
11712   // functions, including those from argument-dependent lookup.
11713   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11714 
11715   if (getLangOpts().MSVCCompat &&
11716       CurContext->isDependentContext() && !isSFINAEContext() &&
11717       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11718 
11719     OverloadCandidateSet::iterator Best;
11720     if (CandidateSet->empty() ||
11721         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11722             OR_No_Viable_Function) {
11723       // In Microsoft mode, if we are inside a template class member function then
11724       // create a type dependent CallExpr. The goal is to postpone name lookup
11725       // to instantiation time to be able to search into type dependent base
11726       // classes.
11727       CallExpr *CE = new (Context) CallExpr(
11728           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11729       CE->setTypeDependent(true);
11730       CE->setValueDependent(true);
11731       CE->setInstantiationDependent(true);
11732       *Result = CE;
11733       return true;
11734     }
11735   }
11736 
11737   if (CandidateSet->empty())
11738     return false;
11739 
11740   UnbridgedCasts.restore();
11741   return false;
11742 }
11743 
11744 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11745 /// the completed call expression. If overload resolution fails, emits
11746 /// diagnostics and returns ExprError()
11747 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11748                                            UnresolvedLookupExpr *ULE,
11749                                            SourceLocation LParenLoc,
11750                                            MultiExprArg Args,
11751                                            SourceLocation RParenLoc,
11752                                            Expr *ExecConfig,
11753                                            OverloadCandidateSet *CandidateSet,
11754                                            OverloadCandidateSet::iterator *Best,
11755                                            OverloadingResult OverloadResult,
11756                                            bool AllowTypoCorrection) {
11757   if (CandidateSet->empty())
11758     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11759                                  RParenLoc, /*EmptyLookup=*/true,
11760                                  AllowTypoCorrection);
11761 
11762   switch (OverloadResult) {
11763   case OR_Success: {
11764     FunctionDecl *FDecl = (*Best)->Function;
11765     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11766     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11767       return ExprError();
11768     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11769     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11770                                          ExecConfig);
11771   }
11772 
11773   case OR_No_Viable_Function: {
11774     // Try to recover by looking for viable functions which the user might
11775     // have meant to call.
11776     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11777                                                 Args, RParenLoc,
11778                                                 /*EmptyLookup=*/false,
11779                                                 AllowTypoCorrection);
11780     if (!Recovery.isInvalid())
11781       return Recovery;
11782 
11783     // If the user passes in a function that we can't take the address of, we
11784     // generally end up emitting really bad error messages. Here, we attempt to
11785     // emit better ones.
11786     for (const Expr *Arg : Args) {
11787       if (!Arg->getType()->isFunctionType())
11788         continue;
11789       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11790         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11791         if (FD &&
11792             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11793                                                        Arg->getExprLoc()))
11794           return ExprError();
11795       }
11796     }
11797 
11798     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11799         << ULE->getName() << Fn->getSourceRange();
11800     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11801     break;
11802   }
11803 
11804   case OR_Ambiguous:
11805     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11806       << ULE->getName() << Fn->getSourceRange();
11807     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11808     break;
11809 
11810   case OR_Deleted: {
11811     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11812       << (*Best)->Function->isDeleted()
11813       << ULE->getName()
11814       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11815       << Fn->getSourceRange();
11816     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11817 
11818     // We emitted an error for the unvailable/deleted function call but keep
11819     // the call in the AST.
11820     FunctionDecl *FDecl = (*Best)->Function;
11821     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11822     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11823                                          ExecConfig);
11824   }
11825   }
11826 
11827   // Overload resolution failed.
11828   return ExprError();
11829 }
11830 
11831 static void markUnaddressableCandidatesUnviable(Sema &S,
11832                                                 OverloadCandidateSet &CS) {
11833   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11834     if (I->Viable &&
11835         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11836       I->Viable = false;
11837       I->FailureKind = ovl_fail_addr_not_available;
11838     }
11839   }
11840 }
11841 
11842 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11843 /// (which eventually refers to the declaration Func) and the call
11844 /// arguments Args/NumArgs, attempt to resolve the function call down
11845 /// to a specific function. If overload resolution succeeds, returns
11846 /// the call expression produced by overload resolution.
11847 /// Otherwise, emits diagnostics and returns ExprError.
11848 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11849                                          UnresolvedLookupExpr *ULE,
11850                                          SourceLocation LParenLoc,
11851                                          MultiExprArg Args,
11852                                          SourceLocation RParenLoc,
11853                                          Expr *ExecConfig,
11854                                          bool AllowTypoCorrection,
11855                                          bool CalleesAddressIsTaken) {
11856   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11857                                     OverloadCandidateSet::CSK_Normal);
11858   ExprResult result;
11859 
11860   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11861                              &result))
11862     return result;
11863 
11864   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11865   // functions that aren't addressible are considered unviable.
11866   if (CalleesAddressIsTaken)
11867     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11868 
11869   OverloadCandidateSet::iterator Best;
11870   OverloadingResult OverloadResult =
11871       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11872 
11873   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11874                                   RParenLoc, ExecConfig, &CandidateSet,
11875                                   &Best, OverloadResult,
11876                                   AllowTypoCorrection);
11877 }
11878 
11879 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11880   return Functions.size() > 1 ||
11881     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11882 }
11883 
11884 /// \brief Create a unary operation that may resolve to an overloaded
11885 /// operator.
11886 ///
11887 /// \param OpLoc The location of the operator itself (e.g., '*').
11888 ///
11889 /// \param Opc The UnaryOperatorKind that describes this operator.
11890 ///
11891 /// \param Fns The set of non-member functions that will be
11892 /// considered by overload resolution. The caller needs to build this
11893 /// set based on the context using, e.g.,
11894 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11895 /// set should not contain any member functions; those will be added
11896 /// by CreateOverloadedUnaryOp().
11897 ///
11898 /// \param Input The input argument.
11899 ExprResult
11900 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11901                               const UnresolvedSetImpl &Fns,
11902                               Expr *Input) {
11903   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11904   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11905   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11906   // TODO: provide better source location info.
11907   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11908 
11909   if (checkPlaceholderForOverload(*this, Input))
11910     return ExprError();
11911 
11912   Expr *Args[2] = { Input, nullptr };
11913   unsigned NumArgs = 1;
11914 
11915   // For post-increment and post-decrement, add the implicit '0' as
11916   // the second argument, so that we know this is a post-increment or
11917   // post-decrement.
11918   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11919     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11920     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11921                                      SourceLocation());
11922     NumArgs = 2;
11923   }
11924 
11925   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11926 
11927   if (Input->isTypeDependent()) {
11928     if (Fns.empty())
11929       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11930                                          VK_RValue, OK_Ordinary, OpLoc);
11931 
11932     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11933     UnresolvedLookupExpr *Fn
11934       = UnresolvedLookupExpr::Create(Context, NamingClass,
11935                                      NestedNameSpecifierLoc(), OpNameInfo,
11936                                      /*ADL*/ true, IsOverloaded(Fns),
11937                                      Fns.begin(), Fns.end());
11938     return new (Context)
11939         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11940                             VK_RValue, OpLoc, FPOptions());
11941   }
11942 
11943   // Build an empty overload set.
11944   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11945 
11946   // Add the candidates from the given function set.
11947   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11948 
11949   // Add operator candidates that are member functions.
11950   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11951 
11952   // Add candidates from ADL.
11953   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11954                                        /*ExplicitTemplateArgs*/nullptr,
11955                                        CandidateSet);
11956 
11957   // Add builtin operator candidates.
11958   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11959 
11960   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11961 
11962   // Perform overload resolution.
11963   OverloadCandidateSet::iterator Best;
11964   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11965   case OR_Success: {
11966     // We found a built-in operator or an overloaded operator.
11967     FunctionDecl *FnDecl = Best->Function;
11968 
11969     if (FnDecl) {
11970       Expr *Base = nullptr;
11971       // We matched an overloaded operator. Build a call to that
11972       // operator.
11973 
11974       // Convert the arguments.
11975       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11976         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11977 
11978         ExprResult InputRes =
11979           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11980                                               Best->FoundDecl, Method);
11981         if (InputRes.isInvalid())
11982           return ExprError();
11983         Base = Input = InputRes.get();
11984       } else {
11985         // Convert the arguments.
11986         ExprResult InputInit
11987           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11988                                                       Context,
11989                                                       FnDecl->getParamDecl(0)),
11990                                       SourceLocation(),
11991                                       Input);
11992         if (InputInit.isInvalid())
11993           return ExprError();
11994         Input = InputInit.get();
11995       }
11996 
11997       // Build the actual expression node.
11998       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11999                                                 Base, HadMultipleCandidates,
12000                                                 OpLoc);
12001       if (FnExpr.isInvalid())
12002         return ExprError();
12003 
12004       // Determine the result type.
12005       QualType ResultTy = FnDecl->getReturnType();
12006       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12007       ResultTy = ResultTy.getNonLValueExprType(Context);
12008 
12009       Args[0] = Input;
12010       CallExpr *TheCall =
12011         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12012                                           ResultTy, VK, OpLoc, FPOptions());
12013 
12014       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12015         return ExprError();
12016 
12017       if (CheckFunctionCall(FnDecl, TheCall,
12018                             FnDecl->getType()->castAs<FunctionProtoType>()))
12019         return ExprError();
12020 
12021       return MaybeBindToTemporary(TheCall);
12022     } else {
12023       // We matched a built-in operator. Convert the arguments, then
12024       // break out so that we will build the appropriate built-in
12025       // operator node.
12026       ExprResult InputRes = PerformImplicitConversion(
12027           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12028       if (InputRes.isInvalid())
12029         return ExprError();
12030       Input = InputRes.get();
12031       break;
12032     }
12033   }
12034 
12035   case OR_No_Viable_Function:
12036     // This is an erroneous use of an operator which can be overloaded by
12037     // a non-member function. Check for non-member operators which were
12038     // defined too late to be candidates.
12039     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12040       // FIXME: Recover by calling the found function.
12041       return ExprError();
12042 
12043     // No viable function; fall through to handling this as a
12044     // built-in operator, which will produce an error message for us.
12045     break;
12046 
12047   case OR_Ambiguous:
12048     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12049         << UnaryOperator::getOpcodeStr(Opc)
12050         << Input->getType()
12051         << Input->getSourceRange();
12052     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12053                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12054     return ExprError();
12055 
12056   case OR_Deleted:
12057     Diag(OpLoc, diag::err_ovl_deleted_oper)
12058       << Best->Function->isDeleted()
12059       << UnaryOperator::getOpcodeStr(Opc)
12060       << getDeletedOrUnavailableSuffix(Best->Function)
12061       << Input->getSourceRange();
12062     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12063                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12064     return ExprError();
12065   }
12066 
12067   // Either we found no viable overloaded operator or we matched a
12068   // built-in operator. In either case, fall through to trying to
12069   // build a built-in operation.
12070   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12071 }
12072 
12073 /// \brief Create a binary operation that may resolve to an overloaded
12074 /// operator.
12075 ///
12076 /// \param OpLoc The location of the operator itself (e.g., '+').
12077 ///
12078 /// \param Opc The BinaryOperatorKind that describes this operator.
12079 ///
12080 /// \param Fns The set of non-member functions that will be
12081 /// considered by overload resolution. The caller needs to build this
12082 /// set based on the context using, e.g.,
12083 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12084 /// set should not contain any member functions; those will be added
12085 /// by CreateOverloadedBinOp().
12086 ///
12087 /// \param LHS Left-hand argument.
12088 /// \param RHS Right-hand argument.
12089 ExprResult
12090 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12091                             BinaryOperatorKind Opc,
12092                             const UnresolvedSetImpl &Fns,
12093                             Expr *LHS, Expr *RHS) {
12094   Expr *Args[2] = { LHS, RHS };
12095   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12096 
12097   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12098   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12099 
12100   // If either side is type-dependent, create an appropriate dependent
12101   // expression.
12102   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12103     if (Fns.empty()) {
12104       // If there are no functions to store, just build a dependent
12105       // BinaryOperator or CompoundAssignment.
12106       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12107         return new (Context) BinaryOperator(
12108             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12109             OpLoc, FPFeatures);
12110 
12111       return new (Context) CompoundAssignOperator(
12112           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12113           Context.DependentTy, Context.DependentTy, OpLoc,
12114           FPFeatures);
12115     }
12116 
12117     // FIXME: save results of ADL from here?
12118     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12119     // TODO: provide better source location info in DNLoc component.
12120     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12121     UnresolvedLookupExpr *Fn
12122       = UnresolvedLookupExpr::Create(Context, NamingClass,
12123                                      NestedNameSpecifierLoc(), OpNameInfo,
12124                                      /*ADL*/ true, IsOverloaded(Fns),
12125                                      Fns.begin(), Fns.end());
12126     return new (Context)
12127         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12128                             VK_RValue, OpLoc, FPFeatures);
12129   }
12130 
12131   // Always do placeholder-like conversions on the RHS.
12132   if (checkPlaceholderForOverload(*this, Args[1]))
12133     return ExprError();
12134 
12135   // Do placeholder-like conversion on the LHS; note that we should
12136   // not get here with a PseudoObject LHS.
12137   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12138   if (checkPlaceholderForOverload(*this, Args[0]))
12139     return ExprError();
12140 
12141   // If this is the assignment operator, we only perform overload resolution
12142   // if the left-hand side is a class or enumeration type. This is actually
12143   // a hack. The standard requires that we do overload resolution between the
12144   // various built-in candidates, but as DR507 points out, this can lead to
12145   // problems. So we do it this way, which pretty much follows what GCC does.
12146   // Note that we go the traditional code path for compound assignment forms.
12147   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12148     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12149 
12150   // If this is the .* operator, which is not overloadable, just
12151   // create a built-in binary operator.
12152   if (Opc == BO_PtrMemD)
12153     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12154 
12155   // Build an empty overload set.
12156   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12157 
12158   // Add the candidates from the given function set.
12159   AddFunctionCandidates(Fns, Args, CandidateSet);
12160 
12161   // Add operator candidates that are member functions.
12162   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12163 
12164   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12165   // performed for an assignment operator (nor for operator[] nor operator->,
12166   // which don't get here).
12167   if (Opc != BO_Assign)
12168     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12169                                          /*ExplicitTemplateArgs*/ nullptr,
12170                                          CandidateSet);
12171 
12172   // Add builtin operator candidates.
12173   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12174 
12175   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12176 
12177   // Perform overload resolution.
12178   OverloadCandidateSet::iterator Best;
12179   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12180     case OR_Success: {
12181       // We found a built-in operator or an overloaded operator.
12182       FunctionDecl *FnDecl = Best->Function;
12183 
12184       if (FnDecl) {
12185         Expr *Base = nullptr;
12186         // We matched an overloaded operator. Build a call to that
12187         // operator.
12188 
12189         // Convert the arguments.
12190         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12191           // Best->Access is only meaningful for class members.
12192           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12193 
12194           ExprResult Arg1 =
12195             PerformCopyInitialization(
12196               InitializedEntity::InitializeParameter(Context,
12197                                                      FnDecl->getParamDecl(0)),
12198               SourceLocation(), Args[1]);
12199           if (Arg1.isInvalid())
12200             return ExprError();
12201 
12202           ExprResult Arg0 =
12203             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12204                                                 Best->FoundDecl, Method);
12205           if (Arg0.isInvalid())
12206             return ExprError();
12207           Base = Args[0] = Arg0.getAs<Expr>();
12208           Args[1] = RHS = Arg1.getAs<Expr>();
12209         } else {
12210           // Convert the arguments.
12211           ExprResult Arg0 = PerformCopyInitialization(
12212             InitializedEntity::InitializeParameter(Context,
12213                                                    FnDecl->getParamDecl(0)),
12214             SourceLocation(), Args[0]);
12215           if (Arg0.isInvalid())
12216             return ExprError();
12217 
12218           ExprResult Arg1 =
12219             PerformCopyInitialization(
12220               InitializedEntity::InitializeParameter(Context,
12221                                                      FnDecl->getParamDecl(1)),
12222               SourceLocation(), Args[1]);
12223           if (Arg1.isInvalid())
12224             return ExprError();
12225           Args[0] = LHS = Arg0.getAs<Expr>();
12226           Args[1] = RHS = Arg1.getAs<Expr>();
12227         }
12228 
12229         // Build the actual expression node.
12230         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12231                                                   Best->FoundDecl, Base,
12232                                                   HadMultipleCandidates, OpLoc);
12233         if (FnExpr.isInvalid())
12234           return ExprError();
12235 
12236         // Determine the result type.
12237         QualType ResultTy = FnDecl->getReturnType();
12238         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12239         ResultTy = ResultTy.getNonLValueExprType(Context);
12240 
12241         CXXOperatorCallExpr *TheCall =
12242           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12243                                             Args, ResultTy, VK, OpLoc,
12244                                             FPFeatures);
12245 
12246         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12247                                 FnDecl))
12248           return ExprError();
12249 
12250         ArrayRef<const Expr *> ArgsArray(Args, 2);
12251         const Expr *ImplicitThis = nullptr;
12252         // Cut off the implicit 'this'.
12253         if (isa<CXXMethodDecl>(FnDecl)) {
12254           ImplicitThis = ArgsArray[0];
12255           ArgsArray = ArgsArray.slice(1);
12256         }
12257 
12258         // Check for a self move.
12259         if (Op == OO_Equal)
12260           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12261 
12262         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12263                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12264                   VariadicDoesNotApply);
12265 
12266         return MaybeBindToTemporary(TheCall);
12267       } else {
12268         // We matched a built-in operator. Convert the arguments, then
12269         // break out so that we will build the appropriate built-in
12270         // operator node.
12271         ExprResult ArgsRes0 =
12272             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12273                                       Best->Conversions[0], AA_Passing);
12274         if (ArgsRes0.isInvalid())
12275           return ExprError();
12276         Args[0] = ArgsRes0.get();
12277 
12278         ExprResult ArgsRes1 =
12279             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12280                                       Best->Conversions[1], AA_Passing);
12281         if (ArgsRes1.isInvalid())
12282           return ExprError();
12283         Args[1] = ArgsRes1.get();
12284         break;
12285       }
12286     }
12287 
12288     case OR_No_Viable_Function: {
12289       // C++ [over.match.oper]p9:
12290       //   If the operator is the operator , [...] and there are no
12291       //   viable functions, then the operator is assumed to be the
12292       //   built-in operator and interpreted according to clause 5.
12293       if (Opc == BO_Comma)
12294         break;
12295 
12296       // For class as left operand for assignment or compound assigment
12297       // operator do not fall through to handling in built-in, but report that
12298       // no overloaded assignment operator found
12299       ExprResult Result = ExprError();
12300       if (Args[0]->getType()->isRecordType() &&
12301           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12302         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12303              << BinaryOperator::getOpcodeStr(Opc)
12304              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12305         if (Args[0]->getType()->isIncompleteType()) {
12306           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12307             << Args[0]->getType()
12308             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12309         }
12310       } else {
12311         // This is an erroneous use of an operator which can be overloaded by
12312         // a non-member function. Check for non-member operators which were
12313         // defined too late to be candidates.
12314         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12315           // FIXME: Recover by calling the found function.
12316           return ExprError();
12317 
12318         // No viable function; try to create a built-in operation, which will
12319         // produce an error. Then, show the non-viable candidates.
12320         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12321       }
12322       assert(Result.isInvalid() &&
12323              "C++ binary operator overloading is missing candidates!");
12324       if (Result.isInvalid())
12325         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12326                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12327       return Result;
12328     }
12329 
12330     case OR_Ambiguous:
12331       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12332           << BinaryOperator::getOpcodeStr(Opc)
12333           << Args[0]->getType() << Args[1]->getType()
12334           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12335       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12336                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12337       return ExprError();
12338 
12339     case OR_Deleted:
12340       if (isImplicitlyDeleted(Best->Function)) {
12341         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12342         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12343           << Context.getRecordType(Method->getParent())
12344           << getSpecialMember(Method);
12345 
12346         // The user probably meant to call this special member. Just
12347         // explain why it's deleted.
12348         NoteDeletedFunction(Method);
12349         return ExprError();
12350       } else {
12351         Diag(OpLoc, diag::err_ovl_deleted_oper)
12352           << Best->Function->isDeleted()
12353           << BinaryOperator::getOpcodeStr(Opc)
12354           << getDeletedOrUnavailableSuffix(Best->Function)
12355           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12356       }
12357       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12358                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12359       return ExprError();
12360   }
12361 
12362   // We matched a built-in operator; build it.
12363   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12364 }
12365 
12366 ExprResult
12367 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12368                                          SourceLocation RLoc,
12369                                          Expr *Base, Expr *Idx) {
12370   Expr *Args[2] = { Base, Idx };
12371   DeclarationName OpName =
12372       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12373 
12374   // If either side is type-dependent, create an appropriate dependent
12375   // expression.
12376   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12377 
12378     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12379     // CHECKME: no 'operator' keyword?
12380     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12381     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12382     UnresolvedLookupExpr *Fn
12383       = UnresolvedLookupExpr::Create(Context, NamingClass,
12384                                      NestedNameSpecifierLoc(), OpNameInfo,
12385                                      /*ADL*/ true, /*Overloaded*/ false,
12386                                      UnresolvedSetIterator(),
12387                                      UnresolvedSetIterator());
12388     // Can't add any actual overloads yet
12389 
12390     return new (Context)
12391         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12392                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12393   }
12394 
12395   // Handle placeholders on both operands.
12396   if (checkPlaceholderForOverload(*this, Args[0]))
12397     return ExprError();
12398   if (checkPlaceholderForOverload(*this, Args[1]))
12399     return ExprError();
12400 
12401   // Build an empty overload set.
12402   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12403 
12404   // Subscript can only be overloaded as a member function.
12405 
12406   // Add operator candidates that are member functions.
12407   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12408 
12409   // Add builtin operator candidates.
12410   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12411 
12412   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12413 
12414   // Perform overload resolution.
12415   OverloadCandidateSet::iterator Best;
12416   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12417     case OR_Success: {
12418       // We found a built-in operator or an overloaded operator.
12419       FunctionDecl *FnDecl = Best->Function;
12420 
12421       if (FnDecl) {
12422         // We matched an overloaded operator. Build a call to that
12423         // operator.
12424 
12425         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12426 
12427         // Convert the arguments.
12428         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12429         ExprResult Arg0 =
12430           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12431                                               Best->FoundDecl, Method);
12432         if (Arg0.isInvalid())
12433           return ExprError();
12434         Args[0] = Arg0.get();
12435 
12436         // Convert the arguments.
12437         ExprResult InputInit
12438           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12439                                                       Context,
12440                                                       FnDecl->getParamDecl(0)),
12441                                       SourceLocation(),
12442                                       Args[1]);
12443         if (InputInit.isInvalid())
12444           return ExprError();
12445 
12446         Args[1] = InputInit.getAs<Expr>();
12447 
12448         // Build the actual expression node.
12449         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12450         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12451         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12452                                                   Best->FoundDecl,
12453                                                   Base,
12454                                                   HadMultipleCandidates,
12455                                                   OpLocInfo.getLoc(),
12456                                                   OpLocInfo.getInfo());
12457         if (FnExpr.isInvalid())
12458           return ExprError();
12459 
12460         // Determine the result type
12461         QualType ResultTy = FnDecl->getReturnType();
12462         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12463         ResultTy = ResultTy.getNonLValueExprType(Context);
12464 
12465         CXXOperatorCallExpr *TheCall =
12466           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12467                                             FnExpr.get(), Args,
12468                                             ResultTy, VK, RLoc,
12469                                             FPOptions());
12470 
12471         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12472           return ExprError();
12473 
12474         if (CheckFunctionCall(Method, TheCall,
12475                               Method->getType()->castAs<FunctionProtoType>()))
12476           return ExprError();
12477 
12478         return MaybeBindToTemporary(TheCall);
12479       } else {
12480         // We matched a built-in operator. Convert the arguments, then
12481         // break out so that we will build the appropriate built-in
12482         // operator node.
12483         ExprResult ArgsRes0 =
12484             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12485                                       Best->Conversions[0], AA_Passing);
12486         if (ArgsRes0.isInvalid())
12487           return ExprError();
12488         Args[0] = ArgsRes0.get();
12489 
12490         ExprResult ArgsRes1 =
12491             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12492                                       Best->Conversions[1], AA_Passing);
12493         if (ArgsRes1.isInvalid())
12494           return ExprError();
12495         Args[1] = ArgsRes1.get();
12496 
12497         break;
12498       }
12499     }
12500 
12501     case OR_No_Viable_Function: {
12502       if (CandidateSet.empty())
12503         Diag(LLoc, diag::err_ovl_no_oper)
12504           << Args[0]->getType() << /*subscript*/ 0
12505           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12506       else
12507         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12508           << Args[0]->getType()
12509           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12510       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12511                                   "[]", LLoc);
12512       return ExprError();
12513     }
12514 
12515     case OR_Ambiguous:
12516       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12517           << "[]"
12518           << Args[0]->getType() << Args[1]->getType()
12519           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12520       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12521                                   "[]", LLoc);
12522       return ExprError();
12523 
12524     case OR_Deleted:
12525       Diag(LLoc, diag::err_ovl_deleted_oper)
12526         << Best->Function->isDeleted() << "[]"
12527         << getDeletedOrUnavailableSuffix(Best->Function)
12528         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12529       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12530                                   "[]", LLoc);
12531       return ExprError();
12532     }
12533 
12534   // We matched a built-in operator; build it.
12535   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12536 }
12537 
12538 /// BuildCallToMemberFunction - Build a call to a member
12539 /// function. MemExpr is the expression that refers to the member
12540 /// function (and includes the object parameter), Args/NumArgs are the
12541 /// arguments to the function call (not including the object
12542 /// parameter). The caller needs to validate that the member
12543 /// expression refers to a non-static member function or an overloaded
12544 /// member function.
12545 ExprResult
12546 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12547                                 SourceLocation LParenLoc,
12548                                 MultiExprArg Args,
12549                                 SourceLocation RParenLoc) {
12550   assert(MemExprE->getType() == Context.BoundMemberTy ||
12551          MemExprE->getType() == Context.OverloadTy);
12552 
12553   // Dig out the member expression. This holds both the object
12554   // argument and the member function we're referring to.
12555   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12556 
12557   // Determine whether this is a call to a pointer-to-member function.
12558   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12559     assert(op->getType() == Context.BoundMemberTy);
12560     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12561 
12562     QualType fnType =
12563       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12564 
12565     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12566     QualType resultType = proto->getCallResultType(Context);
12567     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12568 
12569     // Check that the object type isn't more qualified than the
12570     // member function we're calling.
12571     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12572 
12573     QualType objectType = op->getLHS()->getType();
12574     if (op->getOpcode() == BO_PtrMemI)
12575       objectType = objectType->castAs<PointerType>()->getPointeeType();
12576     Qualifiers objectQuals = objectType.getQualifiers();
12577 
12578     Qualifiers difference = objectQuals - funcQuals;
12579     difference.removeObjCGCAttr();
12580     difference.removeAddressSpace();
12581     if (difference) {
12582       std::string qualsString = difference.getAsString();
12583       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12584         << fnType.getUnqualifiedType()
12585         << qualsString
12586         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12587     }
12588 
12589     CXXMemberCallExpr *call
12590       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12591                                         resultType, valueKind, RParenLoc);
12592 
12593     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12594                             call, nullptr))
12595       return ExprError();
12596 
12597     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12598       return ExprError();
12599 
12600     if (CheckOtherCall(call, proto))
12601       return ExprError();
12602 
12603     return MaybeBindToTemporary(call);
12604   }
12605 
12606   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12607     return new (Context)
12608         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12609 
12610   UnbridgedCastsSet UnbridgedCasts;
12611   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12612     return ExprError();
12613 
12614   MemberExpr *MemExpr;
12615   CXXMethodDecl *Method = nullptr;
12616   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12617   NestedNameSpecifier *Qualifier = nullptr;
12618   if (isa<MemberExpr>(NakedMemExpr)) {
12619     MemExpr = cast<MemberExpr>(NakedMemExpr);
12620     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12621     FoundDecl = MemExpr->getFoundDecl();
12622     Qualifier = MemExpr->getQualifier();
12623     UnbridgedCasts.restore();
12624   } else {
12625     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12626     Qualifier = UnresExpr->getQualifier();
12627 
12628     QualType ObjectType = UnresExpr->getBaseType();
12629     Expr::Classification ObjectClassification
12630       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12631                             : UnresExpr->getBase()->Classify(Context);
12632 
12633     // Add overload candidates
12634     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12635                                       OverloadCandidateSet::CSK_Normal);
12636 
12637     // FIXME: avoid copy.
12638     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12639     if (UnresExpr->hasExplicitTemplateArgs()) {
12640       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12641       TemplateArgs = &TemplateArgsBuffer;
12642     }
12643 
12644     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12645            E = UnresExpr->decls_end(); I != E; ++I) {
12646 
12647       NamedDecl *Func = *I;
12648       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12649       if (isa<UsingShadowDecl>(Func))
12650         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12651 
12652 
12653       // Microsoft supports direct constructor calls.
12654       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12655         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12656                              Args, CandidateSet);
12657       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12658         // If explicit template arguments were provided, we can't call a
12659         // non-template member function.
12660         if (TemplateArgs)
12661           continue;
12662 
12663         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12664                            ObjectClassification, Args, CandidateSet,
12665                            /*SuppressUserConversions=*/false);
12666       } else {
12667         AddMethodTemplateCandidate(
12668             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12669             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12670             /*SuppressUsedConversions=*/false);
12671       }
12672     }
12673 
12674     DeclarationName DeclName = UnresExpr->getMemberName();
12675 
12676     UnbridgedCasts.restore();
12677 
12678     OverloadCandidateSet::iterator Best;
12679     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12680                                             Best)) {
12681     case OR_Success:
12682       Method = cast<CXXMethodDecl>(Best->Function);
12683       FoundDecl = Best->FoundDecl;
12684       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12685       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12686         return ExprError();
12687       // If FoundDecl is different from Method (such as if one is a template
12688       // and the other a specialization), make sure DiagnoseUseOfDecl is
12689       // called on both.
12690       // FIXME: This would be more comprehensively addressed by modifying
12691       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12692       // being used.
12693       if (Method != FoundDecl.getDecl() &&
12694                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12695         return ExprError();
12696       break;
12697 
12698     case OR_No_Viable_Function:
12699       Diag(UnresExpr->getMemberLoc(),
12700            diag::err_ovl_no_viable_member_function_in_call)
12701         << DeclName << MemExprE->getSourceRange();
12702       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12703       // FIXME: Leaking incoming expressions!
12704       return ExprError();
12705 
12706     case OR_Ambiguous:
12707       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12708         << DeclName << MemExprE->getSourceRange();
12709       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12710       // FIXME: Leaking incoming expressions!
12711       return ExprError();
12712 
12713     case OR_Deleted:
12714       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12715         << Best->Function->isDeleted()
12716         << DeclName
12717         << getDeletedOrUnavailableSuffix(Best->Function)
12718         << MemExprE->getSourceRange();
12719       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12720       // FIXME: Leaking incoming expressions!
12721       return ExprError();
12722     }
12723 
12724     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12725 
12726     // If overload resolution picked a static member, build a
12727     // non-member call based on that function.
12728     if (Method->isStatic()) {
12729       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12730                                    RParenLoc);
12731     }
12732 
12733     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12734   }
12735 
12736   QualType ResultType = Method->getReturnType();
12737   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12738   ResultType = ResultType.getNonLValueExprType(Context);
12739 
12740   assert(Method && "Member call to something that isn't a method?");
12741   CXXMemberCallExpr *TheCall =
12742     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12743                                     ResultType, VK, RParenLoc);
12744 
12745   // Check for a valid return type.
12746   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12747                           TheCall, Method))
12748     return ExprError();
12749 
12750   // Convert the object argument (for a non-static member function call).
12751   // We only need to do this if there was actually an overload; otherwise
12752   // it was done at lookup.
12753   if (!Method->isStatic()) {
12754     ExprResult ObjectArg =
12755       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12756                                           FoundDecl, Method);
12757     if (ObjectArg.isInvalid())
12758       return ExprError();
12759     MemExpr->setBase(ObjectArg.get());
12760   }
12761 
12762   // Convert the rest of the arguments
12763   const FunctionProtoType *Proto =
12764     Method->getType()->getAs<FunctionProtoType>();
12765   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12766                               RParenLoc))
12767     return ExprError();
12768 
12769   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12770 
12771   if (CheckFunctionCall(Method, TheCall, Proto))
12772     return ExprError();
12773 
12774   // In the case the method to call was not selected by the overloading
12775   // resolution process, we still need to handle the enable_if attribute. Do
12776   // that here, so it will not hide previous -- and more relevant -- errors.
12777   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12778     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12779       Diag(MemE->getMemberLoc(),
12780            diag::err_ovl_no_viable_member_function_in_call)
12781           << Method << Method->getSourceRange();
12782       Diag(Method->getLocation(),
12783            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12784           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12785       return ExprError();
12786     }
12787   }
12788 
12789   if ((isa<CXXConstructorDecl>(CurContext) ||
12790        isa<CXXDestructorDecl>(CurContext)) &&
12791       TheCall->getMethodDecl()->isPure()) {
12792     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12793 
12794     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12795         MemExpr->performsVirtualDispatch(getLangOpts())) {
12796       Diag(MemExpr->getLocStart(),
12797            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12798         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12799         << MD->getParent()->getDeclName();
12800 
12801       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12802       if (getLangOpts().AppleKext)
12803         Diag(MemExpr->getLocStart(),
12804              diag::note_pure_qualified_call_kext)
12805              << MD->getParent()->getDeclName()
12806              << MD->getDeclName();
12807     }
12808   }
12809 
12810   if (CXXDestructorDecl *DD =
12811           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12812     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12813     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12814     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12815                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12816                          MemExpr->getMemberLoc());
12817   }
12818 
12819   return MaybeBindToTemporary(TheCall);
12820 }
12821 
12822 /// BuildCallToObjectOfClassType - Build a call to an object of class
12823 /// type (C++ [over.call.object]), which can end up invoking an
12824 /// overloaded function call operator (@c operator()) or performing a
12825 /// user-defined conversion on the object argument.
12826 ExprResult
12827 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12828                                    SourceLocation LParenLoc,
12829                                    MultiExprArg Args,
12830                                    SourceLocation RParenLoc) {
12831   if (checkPlaceholderForOverload(*this, Obj))
12832     return ExprError();
12833   ExprResult Object = Obj;
12834 
12835   UnbridgedCastsSet UnbridgedCasts;
12836   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12837     return ExprError();
12838 
12839   assert(Object.get()->getType()->isRecordType() &&
12840          "Requires object type argument");
12841   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12842 
12843   // C++ [over.call.object]p1:
12844   //  If the primary-expression E in the function call syntax
12845   //  evaluates to a class object of type "cv T", then the set of
12846   //  candidate functions includes at least the function call
12847   //  operators of T. The function call operators of T are obtained by
12848   //  ordinary lookup of the name operator() in the context of
12849   //  (E).operator().
12850   OverloadCandidateSet CandidateSet(LParenLoc,
12851                                     OverloadCandidateSet::CSK_Operator);
12852   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12853 
12854   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12855                           diag::err_incomplete_object_call, Object.get()))
12856     return true;
12857 
12858   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12859   LookupQualifiedName(R, Record->getDecl());
12860   R.suppressDiagnostics();
12861 
12862   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12863        Oper != OperEnd; ++Oper) {
12864     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12865                        Object.get()->Classify(Context), Args, CandidateSet,
12866                        /*SuppressUserConversions=*/false);
12867   }
12868 
12869   // C++ [over.call.object]p2:
12870   //   In addition, for each (non-explicit in C++0x) conversion function
12871   //   declared in T of the form
12872   //
12873   //        operator conversion-type-id () cv-qualifier;
12874   //
12875   //   where cv-qualifier is the same cv-qualification as, or a
12876   //   greater cv-qualification than, cv, and where conversion-type-id
12877   //   denotes the type "pointer to function of (P1,...,Pn) returning
12878   //   R", or the type "reference to pointer to function of
12879   //   (P1,...,Pn) returning R", or the type "reference to function
12880   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12881   //   is also considered as a candidate function. Similarly,
12882   //   surrogate call functions are added to the set of candidate
12883   //   functions for each conversion function declared in an
12884   //   accessible base class provided the function is not hidden
12885   //   within T by another intervening declaration.
12886   const auto &Conversions =
12887       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12888   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12889     NamedDecl *D = *I;
12890     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12891     if (isa<UsingShadowDecl>(D))
12892       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12893 
12894     // Skip over templated conversion functions; they aren't
12895     // surrogates.
12896     if (isa<FunctionTemplateDecl>(D))
12897       continue;
12898 
12899     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12900     if (!Conv->isExplicit()) {
12901       // Strip the reference type (if any) and then the pointer type (if
12902       // any) to get down to what might be a function type.
12903       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12904       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12905         ConvType = ConvPtrType->getPointeeType();
12906 
12907       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12908       {
12909         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12910                               Object.get(), Args, CandidateSet);
12911       }
12912     }
12913   }
12914 
12915   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12916 
12917   // Perform overload resolution.
12918   OverloadCandidateSet::iterator Best;
12919   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12920                              Best)) {
12921   case OR_Success:
12922     // Overload resolution succeeded; we'll build the appropriate call
12923     // below.
12924     break;
12925 
12926   case OR_No_Viable_Function:
12927     if (CandidateSet.empty())
12928       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12929         << Object.get()->getType() << /*call*/ 1
12930         << Object.get()->getSourceRange();
12931     else
12932       Diag(Object.get()->getLocStart(),
12933            diag::err_ovl_no_viable_object_call)
12934         << Object.get()->getType() << Object.get()->getSourceRange();
12935     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12936     break;
12937 
12938   case OR_Ambiguous:
12939     Diag(Object.get()->getLocStart(),
12940          diag::err_ovl_ambiguous_object_call)
12941       << Object.get()->getType() << Object.get()->getSourceRange();
12942     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12943     break;
12944 
12945   case OR_Deleted:
12946     Diag(Object.get()->getLocStart(),
12947          diag::err_ovl_deleted_object_call)
12948       << Best->Function->isDeleted()
12949       << Object.get()->getType()
12950       << getDeletedOrUnavailableSuffix(Best->Function)
12951       << Object.get()->getSourceRange();
12952     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12953     break;
12954   }
12955 
12956   if (Best == CandidateSet.end())
12957     return true;
12958 
12959   UnbridgedCasts.restore();
12960 
12961   if (Best->Function == nullptr) {
12962     // Since there is no function declaration, this is one of the
12963     // surrogate candidates. Dig out the conversion function.
12964     CXXConversionDecl *Conv
12965       = cast<CXXConversionDecl>(
12966                          Best->Conversions[0].UserDefined.ConversionFunction);
12967 
12968     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12969                               Best->FoundDecl);
12970     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12971       return ExprError();
12972     assert(Conv == Best->FoundDecl.getDecl() &&
12973              "Found Decl & conversion-to-functionptr should be same, right?!");
12974     // We selected one of the surrogate functions that converts the
12975     // object parameter to a function pointer. Perform the conversion
12976     // on the object argument, then let ActOnCallExpr finish the job.
12977 
12978     // Create an implicit member expr to refer to the conversion operator.
12979     // and then call it.
12980     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12981                                              Conv, HadMultipleCandidates);
12982     if (Call.isInvalid())
12983       return ExprError();
12984     // Record usage of conversion in an implicit cast.
12985     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12986                                     CK_UserDefinedConversion, Call.get(),
12987                                     nullptr, VK_RValue);
12988 
12989     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12990   }
12991 
12992   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12993 
12994   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12995   // that calls this method, using Object for the implicit object
12996   // parameter and passing along the remaining arguments.
12997   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12998 
12999   // An error diagnostic has already been printed when parsing the declaration.
13000   if (Method->isInvalidDecl())
13001     return ExprError();
13002 
13003   const FunctionProtoType *Proto =
13004     Method->getType()->getAs<FunctionProtoType>();
13005 
13006   unsigned NumParams = Proto->getNumParams();
13007 
13008   DeclarationNameInfo OpLocInfo(
13009                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13010   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13011   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13012                                            Obj, HadMultipleCandidates,
13013                                            OpLocInfo.getLoc(),
13014                                            OpLocInfo.getInfo());
13015   if (NewFn.isInvalid())
13016     return true;
13017 
13018   // Build the full argument list for the method call (the implicit object
13019   // parameter is placed at the beginning of the list).
13020   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13021   MethodArgs[0] = Object.get();
13022   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13023 
13024   // Once we've built TheCall, all of the expressions are properly
13025   // owned.
13026   QualType ResultTy = Method->getReturnType();
13027   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13028   ResultTy = ResultTy.getNonLValueExprType(Context);
13029 
13030   CXXOperatorCallExpr *TheCall = new (Context)
13031       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13032                           VK, RParenLoc, FPOptions());
13033 
13034   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13035     return true;
13036 
13037   // We may have default arguments. If so, we need to allocate more
13038   // slots in the call for them.
13039   if (Args.size() < NumParams)
13040     TheCall->setNumArgs(Context, NumParams + 1);
13041 
13042   bool IsError = false;
13043 
13044   // Initialize the implicit object parameter.
13045   ExprResult ObjRes =
13046     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13047                                         Best->FoundDecl, Method);
13048   if (ObjRes.isInvalid())
13049     IsError = true;
13050   else
13051     Object = ObjRes;
13052   TheCall->setArg(0, Object.get());
13053 
13054   // Check the argument types.
13055   for (unsigned i = 0; i != NumParams; i++) {
13056     Expr *Arg;
13057     if (i < Args.size()) {
13058       Arg = Args[i];
13059 
13060       // Pass the argument.
13061 
13062       ExprResult InputInit
13063         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13064                                                     Context,
13065                                                     Method->getParamDecl(i)),
13066                                     SourceLocation(), Arg);
13067 
13068       IsError |= InputInit.isInvalid();
13069       Arg = InputInit.getAs<Expr>();
13070     } else {
13071       ExprResult DefArg
13072         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13073       if (DefArg.isInvalid()) {
13074         IsError = true;
13075         break;
13076       }
13077 
13078       Arg = DefArg.getAs<Expr>();
13079     }
13080 
13081     TheCall->setArg(i + 1, Arg);
13082   }
13083 
13084   // If this is a variadic call, handle args passed through "...".
13085   if (Proto->isVariadic()) {
13086     // Promote the arguments (C99 6.5.2.2p7).
13087     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13088       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13089                                                         nullptr);
13090       IsError |= Arg.isInvalid();
13091       TheCall->setArg(i + 1, Arg.get());
13092     }
13093   }
13094 
13095   if (IsError) return true;
13096 
13097   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13098 
13099   if (CheckFunctionCall(Method, TheCall, Proto))
13100     return true;
13101 
13102   return MaybeBindToTemporary(TheCall);
13103 }
13104 
13105 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13106 ///  (if one exists), where @c Base is an expression of class type and
13107 /// @c Member is the name of the member we're trying to find.
13108 ExprResult
13109 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13110                                bool *NoArrowOperatorFound) {
13111   assert(Base->getType()->isRecordType() &&
13112          "left-hand side must have class type");
13113 
13114   if (checkPlaceholderForOverload(*this, Base))
13115     return ExprError();
13116 
13117   SourceLocation Loc = Base->getExprLoc();
13118 
13119   // C++ [over.ref]p1:
13120   //
13121   //   [...] An expression x->m is interpreted as (x.operator->())->m
13122   //   for a class object x of type T if T::operator->() exists and if
13123   //   the operator is selected as the best match function by the
13124   //   overload resolution mechanism (13.3).
13125   DeclarationName OpName =
13126     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13127   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13128   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13129 
13130   if (RequireCompleteType(Loc, Base->getType(),
13131                           diag::err_typecheck_incomplete_tag, Base))
13132     return ExprError();
13133 
13134   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13135   LookupQualifiedName(R, BaseRecord->getDecl());
13136   R.suppressDiagnostics();
13137 
13138   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13139        Oper != OperEnd; ++Oper) {
13140     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13141                        None, CandidateSet, /*SuppressUserConversions=*/false);
13142   }
13143 
13144   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13145 
13146   // Perform overload resolution.
13147   OverloadCandidateSet::iterator Best;
13148   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13149   case OR_Success:
13150     // Overload resolution succeeded; we'll build the call below.
13151     break;
13152 
13153   case OR_No_Viable_Function:
13154     if (CandidateSet.empty()) {
13155       QualType BaseType = Base->getType();
13156       if (NoArrowOperatorFound) {
13157         // Report this specific error to the caller instead of emitting a
13158         // diagnostic, as requested.
13159         *NoArrowOperatorFound = true;
13160         return ExprError();
13161       }
13162       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13163         << BaseType << Base->getSourceRange();
13164       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13165         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13166           << FixItHint::CreateReplacement(OpLoc, ".");
13167       }
13168     } else
13169       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13170         << "operator->" << Base->getSourceRange();
13171     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13172     return ExprError();
13173 
13174   case OR_Ambiguous:
13175     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13176       << "->" << Base->getType() << Base->getSourceRange();
13177     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13178     return ExprError();
13179 
13180   case OR_Deleted:
13181     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13182       << Best->Function->isDeleted()
13183       << "->"
13184       << getDeletedOrUnavailableSuffix(Best->Function)
13185       << Base->getSourceRange();
13186     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13187     return ExprError();
13188   }
13189 
13190   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13191 
13192   // Convert the object parameter.
13193   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13194   ExprResult BaseResult =
13195     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13196                                         Best->FoundDecl, Method);
13197   if (BaseResult.isInvalid())
13198     return ExprError();
13199   Base = BaseResult.get();
13200 
13201   // Build the operator call.
13202   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13203                                             Base, HadMultipleCandidates, OpLoc);
13204   if (FnExpr.isInvalid())
13205     return ExprError();
13206 
13207   QualType ResultTy = Method->getReturnType();
13208   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13209   ResultTy = ResultTy.getNonLValueExprType(Context);
13210   CXXOperatorCallExpr *TheCall =
13211     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13212                                       Base, ResultTy, VK, OpLoc, FPOptions());
13213 
13214   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13215     return ExprError();
13216 
13217   if (CheckFunctionCall(Method, TheCall,
13218                         Method->getType()->castAs<FunctionProtoType>()))
13219     return ExprError();
13220 
13221   return MaybeBindToTemporary(TheCall);
13222 }
13223 
13224 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13225 /// a literal operator described by the provided lookup results.
13226 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13227                                           DeclarationNameInfo &SuffixInfo,
13228                                           ArrayRef<Expr*> Args,
13229                                           SourceLocation LitEndLoc,
13230                                        TemplateArgumentListInfo *TemplateArgs) {
13231   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13232 
13233   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13234                                     OverloadCandidateSet::CSK_Normal);
13235   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13236                         /*SuppressUserConversions=*/true);
13237 
13238   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13239 
13240   // Perform overload resolution. This will usually be trivial, but might need
13241   // to perform substitutions for a literal operator template.
13242   OverloadCandidateSet::iterator Best;
13243   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13244   case OR_Success:
13245   case OR_Deleted:
13246     break;
13247 
13248   case OR_No_Viable_Function:
13249     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13250       << R.getLookupName();
13251     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13252     return ExprError();
13253 
13254   case OR_Ambiguous:
13255     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13256     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13257     return ExprError();
13258   }
13259 
13260   FunctionDecl *FD = Best->Function;
13261   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13262                                         nullptr, HadMultipleCandidates,
13263                                         SuffixInfo.getLoc(),
13264                                         SuffixInfo.getInfo());
13265   if (Fn.isInvalid())
13266     return true;
13267 
13268   // Check the argument types. This should almost always be a no-op, except
13269   // that array-to-pointer decay is applied to string literals.
13270   Expr *ConvArgs[2];
13271   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13272     ExprResult InputInit = PerformCopyInitialization(
13273       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13274       SourceLocation(), Args[ArgIdx]);
13275     if (InputInit.isInvalid())
13276       return true;
13277     ConvArgs[ArgIdx] = InputInit.get();
13278   }
13279 
13280   QualType ResultTy = FD->getReturnType();
13281   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13282   ResultTy = ResultTy.getNonLValueExprType(Context);
13283 
13284   UserDefinedLiteral *UDL =
13285     new (Context) UserDefinedLiteral(Context, Fn.get(),
13286                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13287                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13288 
13289   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13290     return ExprError();
13291 
13292   if (CheckFunctionCall(FD, UDL, nullptr))
13293     return ExprError();
13294 
13295   return MaybeBindToTemporary(UDL);
13296 }
13297 
13298 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13299 /// given LookupResult is non-empty, it is assumed to describe a member which
13300 /// will be invoked. Otherwise, the function will be found via argument
13301 /// dependent lookup.
13302 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13303 /// otherwise CallExpr is set to ExprError() and some non-success value
13304 /// is returned.
13305 Sema::ForRangeStatus
13306 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13307                                 SourceLocation RangeLoc,
13308                                 const DeclarationNameInfo &NameInfo,
13309                                 LookupResult &MemberLookup,
13310                                 OverloadCandidateSet *CandidateSet,
13311                                 Expr *Range, ExprResult *CallExpr) {
13312   Scope *S = nullptr;
13313 
13314   CandidateSet->clear();
13315   if (!MemberLookup.empty()) {
13316     ExprResult MemberRef =
13317         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13318                                  /*IsPtr=*/false, CXXScopeSpec(),
13319                                  /*TemplateKWLoc=*/SourceLocation(),
13320                                  /*FirstQualifierInScope=*/nullptr,
13321                                  MemberLookup,
13322                                  /*TemplateArgs=*/nullptr, S);
13323     if (MemberRef.isInvalid()) {
13324       *CallExpr = ExprError();
13325       return FRS_DiagnosticIssued;
13326     }
13327     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13328     if (CallExpr->isInvalid()) {
13329       *CallExpr = ExprError();
13330       return FRS_DiagnosticIssued;
13331     }
13332   } else {
13333     UnresolvedSet<0> FoundNames;
13334     UnresolvedLookupExpr *Fn =
13335       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13336                                    NestedNameSpecifierLoc(), NameInfo,
13337                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13338                                    FoundNames.begin(), FoundNames.end());
13339 
13340     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13341                                                     CandidateSet, CallExpr);
13342     if (CandidateSet->empty() || CandidateSetError) {
13343       *CallExpr = ExprError();
13344       return FRS_NoViableFunction;
13345     }
13346     OverloadCandidateSet::iterator Best;
13347     OverloadingResult OverloadResult =
13348         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13349 
13350     if (OverloadResult == OR_No_Viable_Function) {
13351       *CallExpr = ExprError();
13352       return FRS_NoViableFunction;
13353     }
13354     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13355                                          Loc, nullptr, CandidateSet, &Best,
13356                                          OverloadResult,
13357                                          /*AllowTypoCorrection=*/false);
13358     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13359       *CallExpr = ExprError();
13360       return FRS_DiagnosticIssued;
13361     }
13362   }
13363   return FRS_Success;
13364 }
13365 
13366 
13367 /// FixOverloadedFunctionReference - E is an expression that refers to
13368 /// a C++ overloaded function (possibly with some parentheses and
13369 /// perhaps a '&' around it). We have resolved the overloaded function
13370 /// to the function declaration Fn, so patch up the expression E to
13371 /// refer (possibly indirectly) to Fn. Returns the new expr.
13372 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13373                                            FunctionDecl *Fn) {
13374   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13375     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13376                                                    Found, Fn);
13377     if (SubExpr == PE->getSubExpr())
13378       return PE;
13379 
13380     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13381   }
13382 
13383   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13384     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13385                                                    Found, Fn);
13386     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13387                                SubExpr->getType()) &&
13388            "Implicit cast type cannot be determined from overload");
13389     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13390     if (SubExpr == ICE->getSubExpr())
13391       return ICE;
13392 
13393     return ImplicitCastExpr::Create(Context, ICE->getType(),
13394                                     ICE->getCastKind(),
13395                                     SubExpr, nullptr,
13396                                     ICE->getValueKind());
13397   }
13398 
13399   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13400     if (!GSE->isResultDependent()) {
13401       Expr *SubExpr =
13402           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13403       if (SubExpr == GSE->getResultExpr())
13404         return GSE;
13405 
13406       // Replace the resulting type information before rebuilding the generic
13407       // selection expression.
13408       ArrayRef<Expr *> A = GSE->getAssocExprs();
13409       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13410       unsigned ResultIdx = GSE->getResultIndex();
13411       AssocExprs[ResultIdx] = SubExpr;
13412 
13413       return new (Context) GenericSelectionExpr(
13414           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13415           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13416           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13417           ResultIdx);
13418     }
13419     // Rather than fall through to the unreachable, return the original generic
13420     // selection expression.
13421     return GSE;
13422   }
13423 
13424   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13425     assert(UnOp->getOpcode() == UO_AddrOf &&
13426            "Can only take the address of an overloaded function");
13427     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13428       if (Method->isStatic()) {
13429         // Do nothing: static member functions aren't any different
13430         // from non-member functions.
13431       } else {
13432         // Fix the subexpression, which really has to be an
13433         // UnresolvedLookupExpr holding an overloaded member function
13434         // or template.
13435         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13436                                                        Found, Fn);
13437         if (SubExpr == UnOp->getSubExpr())
13438           return UnOp;
13439 
13440         assert(isa<DeclRefExpr>(SubExpr)
13441                && "fixed to something other than a decl ref");
13442         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13443                && "fixed to a member ref with no nested name qualifier");
13444 
13445         // We have taken the address of a pointer to member
13446         // function. Perform the computation here so that we get the
13447         // appropriate pointer to member type.
13448         QualType ClassType
13449           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13450         QualType MemPtrType
13451           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13452         // Under the MS ABI, lock down the inheritance model now.
13453         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13454           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13455 
13456         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13457                                            VK_RValue, OK_Ordinary,
13458                                            UnOp->getOperatorLoc());
13459       }
13460     }
13461     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13462                                                    Found, Fn);
13463     if (SubExpr == UnOp->getSubExpr())
13464       return UnOp;
13465 
13466     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13467                                      Context.getPointerType(SubExpr->getType()),
13468                                        VK_RValue, OK_Ordinary,
13469                                        UnOp->getOperatorLoc());
13470   }
13471 
13472   // C++ [except.spec]p17:
13473   //   An exception-specification is considered to be needed when:
13474   //   - in an expression the function is the unique lookup result or the
13475   //     selected member of a set of overloaded functions
13476   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13477     ResolveExceptionSpec(E->getExprLoc(), FPT);
13478 
13479   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13480     // FIXME: avoid copy.
13481     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13482     if (ULE->hasExplicitTemplateArgs()) {
13483       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13484       TemplateArgs = &TemplateArgsBuffer;
13485     }
13486 
13487     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13488                                            ULE->getQualifierLoc(),
13489                                            ULE->getTemplateKeywordLoc(),
13490                                            Fn,
13491                                            /*enclosing*/ false, // FIXME?
13492                                            ULE->getNameLoc(),
13493                                            Fn->getType(),
13494                                            VK_LValue,
13495                                            Found.getDecl(),
13496                                            TemplateArgs);
13497     MarkDeclRefReferenced(DRE);
13498     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13499     return DRE;
13500   }
13501 
13502   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13503     // FIXME: avoid copy.
13504     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13505     if (MemExpr->hasExplicitTemplateArgs()) {
13506       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13507       TemplateArgs = &TemplateArgsBuffer;
13508     }
13509 
13510     Expr *Base;
13511 
13512     // If we're filling in a static method where we used to have an
13513     // implicit member access, rewrite to a simple decl ref.
13514     if (MemExpr->isImplicitAccess()) {
13515       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13516         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13517                                                MemExpr->getQualifierLoc(),
13518                                                MemExpr->getTemplateKeywordLoc(),
13519                                                Fn,
13520                                                /*enclosing*/ false,
13521                                                MemExpr->getMemberLoc(),
13522                                                Fn->getType(),
13523                                                VK_LValue,
13524                                                Found.getDecl(),
13525                                                TemplateArgs);
13526         MarkDeclRefReferenced(DRE);
13527         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13528         return DRE;
13529       } else {
13530         SourceLocation Loc = MemExpr->getMemberLoc();
13531         if (MemExpr->getQualifier())
13532           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13533         CheckCXXThisCapture(Loc);
13534         Base = new (Context) CXXThisExpr(Loc,
13535                                          MemExpr->getBaseType(),
13536                                          /*isImplicit=*/true);
13537       }
13538     } else
13539       Base = MemExpr->getBase();
13540 
13541     ExprValueKind valueKind;
13542     QualType type;
13543     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13544       valueKind = VK_LValue;
13545       type = Fn->getType();
13546     } else {
13547       valueKind = VK_RValue;
13548       type = Context.BoundMemberTy;
13549     }
13550 
13551     MemberExpr *ME = MemberExpr::Create(
13552         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13553         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13554         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13555         OK_Ordinary);
13556     ME->setHadMultipleCandidates(true);
13557     MarkMemberReferenced(ME);
13558     return ME;
13559   }
13560 
13561   llvm_unreachable("Invalid reference to overloaded function");
13562 }
13563 
13564 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13565                                                 DeclAccessPair Found,
13566                                                 FunctionDecl *Fn) {
13567   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13568 }
13569