1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
64                                                  VK_LValue, Loc, LocInfo);
65   if (HadMultipleCandidates)
66     DRE->setHadMultipleCandidates(true);
67 
68   S.MarkDeclRefReferenced(DRE);
69   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
70                              CK_FunctionToPointerDecay);
71 }
72 
73 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
74                                  bool InOverloadResolution,
75                                  StandardConversionSequence &SCS,
76                                  bool CStyle,
77                                  bool AllowObjCWritebackConversion);
78 
79 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
80                                                  QualType &ToType,
81                                                  bool InOverloadResolution,
82                                                  StandardConversionSequence &SCS,
83                                                  bool CStyle);
84 static OverloadingResult
85 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
86                         UserDefinedConversionSequence& User,
87                         OverloadCandidateSet& Conversions,
88                         bool AllowExplicit,
89                         bool AllowObjCConversionOnExplicit);
90 
91 
92 static ImplicitConversionSequence::CompareKind
93 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
94                                    const StandardConversionSequence& SCS1,
95                                    const StandardConversionSequence& SCS2);
96 
97 static ImplicitConversionSequence::CompareKind
98 CompareQualificationConversions(Sema &S,
99                                 const StandardConversionSequence& SCS1,
100                                 const StandardConversionSequence& SCS2);
101 
102 static ImplicitConversionSequence::CompareKind
103 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
104                                 const StandardConversionSequence& SCS1,
105                                 const StandardConversionSequence& SCS2);
106 
107 /// GetConversionRank - Retrieve the implicit conversion rank
108 /// corresponding to the given implicit conversion kind.
109 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
110   static const ImplicitConversionRank
111     Rank[(int)ICK_Num_Conversion_Kinds] = {
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Promotion,
119     ICR_Promotion,
120     ICR_Promotion,
121     ICR_Conversion,
122     ICR_Conversion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Complex_Real_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Writeback_Conversion,
136     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
137                      // it was omitted by the patch that added
138                      // ICK_Zero_Event_Conversion
139     ICR_C_Conversion
140   };
141   return Rank[(int)Kind];
142 }
143 
144 /// GetImplicitConversionName - Return the name of this kind of
145 /// implicit conversion.
146 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
147   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
148     "No conversion",
149     "Lvalue-to-rvalue",
150     "Array-to-pointer",
151     "Function-to-pointer",
152     "Noreturn adjustment",
153     "Qualification",
154     "Integral promotion",
155     "Floating point promotion",
156     "Complex promotion",
157     "Integral conversion",
158     "Floating conversion",
159     "Complex conversion",
160     "Floating-integral conversion",
161     "Pointer conversion",
162     "Pointer-to-member conversion",
163     "Boolean conversion",
164     "Compatible-types conversion",
165     "Derived-to-base conversion",
166     "Vector conversion",
167     "Vector splat",
168     "Complex-real conversion",
169     "Block Pointer conversion",
170     "Transparent Union Conversion",
171     "Writeback conversion",
172     "OpenCL Zero Event Conversion",
173     "C specific type conversion"
174   };
175   return Name[Kind];
176 }
177 
178 /// StandardConversionSequence - Set the standard conversion
179 /// sequence to the identity conversion.
180 void StandardConversionSequence::setAsIdentityConversion() {
181   First = ICK_Identity;
182   Second = ICK_Identity;
183   Third = ICK_Identity;
184   DeprecatedStringLiteralToCharPtr = false;
185   QualificationIncludesObjCLifetime = false;
186   ReferenceBinding = false;
187   DirectBinding = false;
188   IsLvalueReference = true;
189   BindsToFunctionLvalue = false;
190   BindsToRvalue = false;
191   BindsImplicitObjectArgumentWithoutRefQualifier = false;
192   ObjCLifetimeConversionBinding = false;
193   CopyConstructor = nullptr;
194 }
195 
196 /// getRank - Retrieve the rank of this standard conversion sequence
197 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
198 /// implicit conversions.
199 ImplicitConversionRank StandardConversionSequence::getRank() const {
200   ImplicitConversionRank Rank = ICR_Exact_Match;
201   if  (GetConversionRank(First) > Rank)
202     Rank = GetConversionRank(First);
203   if  (GetConversionRank(Second) > Rank)
204     Rank = GetConversionRank(Second);
205   if  (GetConversionRank(Third) > Rank)
206     Rank = GetConversionRank(Third);
207   return Rank;
208 }
209 
210 /// isPointerConversionToBool - Determines whether this conversion is
211 /// a conversion of a pointer or pointer-to-member to bool. This is
212 /// used as part of the ranking of standard conversion sequences
213 /// (C++ 13.3.3.2p4).
214 bool StandardConversionSequence::isPointerConversionToBool() const {
215   // Note that FromType has not necessarily been transformed by the
216   // array-to-pointer or function-to-pointer implicit conversions, so
217   // check for their presence as well as checking whether FromType is
218   // a pointer.
219   if (getToType(1)->isBooleanType() &&
220       (getFromType()->isPointerType() ||
221        getFromType()->isObjCObjectPointerType() ||
222        getFromType()->isBlockPointerType() ||
223        getFromType()->isNullPtrType() ||
224        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
225     return true;
226 
227   return false;
228 }
229 
230 /// isPointerConversionToVoidPointer - Determines whether this
231 /// conversion is a conversion of a pointer to a void pointer. This is
232 /// used as part of the ranking of standard conversion sequences (C++
233 /// 13.3.3.2p4).
234 bool
235 StandardConversionSequence::
236 isPointerConversionToVoidPointer(ASTContext& Context) const {
237   QualType FromType = getFromType();
238   QualType ToType = getToType(1);
239 
240   // Note that FromType has not necessarily been transformed by the
241   // array-to-pointer implicit conversion, so check for its presence
242   // and redo the conversion to get a pointer.
243   if (First == ICK_Array_To_Pointer)
244     FromType = Context.getArrayDecayedType(FromType);
245 
246   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
247     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
248       return ToPtrType->getPointeeType()->isVoidType();
249 
250   return false;
251 }
252 
253 /// Skip any implicit casts which could be either part of a narrowing conversion
254 /// or after one in an implicit conversion.
255 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
256   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
257     switch (ICE->getCastKind()) {
258     case CK_NoOp:
259     case CK_IntegralCast:
260     case CK_IntegralToBoolean:
261     case CK_IntegralToFloating:
262     case CK_BooleanToSignedIntegral:
263     case CK_FloatingToIntegral:
264     case CK_FloatingToBoolean:
265     case CK_FloatingCast:
266       Converted = ICE->getSubExpr();
267       continue;
268 
269     default:
270       return Converted;
271     }
272   }
273 
274   return Converted;
275 }
276 
277 /// Check if this standard conversion sequence represents a narrowing
278 /// conversion, according to C++11 [dcl.init.list]p7.
279 ///
280 /// \param Ctx  The AST context.
281 /// \param Converted  The result of applying this standard conversion sequence.
282 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
283 ///        value of the expression prior to the narrowing conversion.
284 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
285 ///        type of the expression prior to the narrowing conversion.
286 NarrowingKind
287 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
288                                              const Expr *Converted,
289                                              APValue &ConstantValue,
290                                              QualType &ConstantType) const {
291   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
292 
293   // C++11 [dcl.init.list]p7:
294   //   A narrowing conversion is an implicit conversion ...
295   QualType FromType = getToType(0);
296   QualType ToType = getToType(1);
297 
298   // A conversion to an enumeration type is narrowing if the conversion to
299   // the underlying type is narrowing. This only arises for expressions of
300   // the form 'Enum{init}'.
301   if (auto *ET = ToType->getAs<EnumType>())
302     ToType = ET->getDecl()->getIntegerType();
303 
304   switch (Second) {
305   // 'bool' is an integral type; dispatch to the right place to handle it.
306   case ICK_Boolean_Conversion:
307     if (FromType->isRealFloatingType())
308       goto FloatingIntegralConversion;
309     if (FromType->isIntegralOrUnscopedEnumerationType())
310       goto IntegralConversion;
311     // Boolean conversions can be from pointers and pointers to members
312     // [conv.bool], and those aren't considered narrowing conversions.
313     return NK_Not_Narrowing;
314 
315   // -- from a floating-point type to an integer type, or
316   //
317   // -- from an integer type or unscoped enumeration type to a floating-point
318   //    type, except where the source is a constant expression and the actual
319   //    value after conversion will fit into the target type and will produce
320   //    the original value when converted back to the original type, or
321   case ICK_Floating_Integral:
322   FloatingIntegralConversion:
323     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
324       return NK_Type_Narrowing;
325     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
326       llvm::APSInt IntConstantValue;
327       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
328       if (Initializer &&
329           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
330         // Convert the integer to the floating type.
331         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
332         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
333                                 llvm::APFloat::rmNearestTiesToEven);
334         // And back.
335         llvm::APSInt ConvertedValue = IntConstantValue;
336         bool ignored;
337         Result.convertToInteger(ConvertedValue,
338                                 llvm::APFloat::rmTowardZero, &ignored);
339         // If the resulting value is different, this was a narrowing conversion.
340         if (IntConstantValue != ConvertedValue) {
341           ConstantValue = APValue(IntConstantValue);
342           ConstantType = Initializer->getType();
343           return NK_Constant_Narrowing;
344         }
345       } else {
346         // Variables are always narrowings.
347         return NK_Variable_Narrowing;
348       }
349     }
350     return NK_Not_Narrowing;
351 
352   // -- from long double to double or float, or from double to float, except
353   //    where the source is a constant expression and the actual value after
354   //    conversion is within the range of values that can be represented (even
355   //    if it cannot be represented exactly), or
356   case ICK_Floating_Conversion:
357     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
358         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
359       // FromType is larger than ToType.
360       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
361       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
362         // Constant!
363         assert(ConstantValue.isFloat());
364         llvm::APFloat FloatVal = ConstantValue.getFloat();
365         // Convert the source value into the target type.
366         bool ignored;
367         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
368           Ctx.getFloatTypeSemantics(ToType),
369           llvm::APFloat::rmNearestTiesToEven, &ignored);
370         // If there was no overflow, the source value is within the range of
371         // values that can be represented.
372         if (ConvertStatus & llvm::APFloat::opOverflow) {
373           ConstantType = Initializer->getType();
374           return NK_Constant_Narrowing;
375         }
376       } else {
377         return NK_Variable_Narrowing;
378       }
379     }
380     return NK_Not_Narrowing;
381 
382   // -- from an integer type or unscoped enumeration type to an integer type
383   //    that cannot represent all the values of the original type, except where
384   //    the source is a constant expression and the actual value after
385   //    conversion will fit into the target type and will produce the original
386   //    value when converted back to the original type.
387   case ICK_Integral_Conversion:
388   IntegralConversion: {
389     assert(FromType->isIntegralOrUnscopedEnumerationType());
390     assert(ToType->isIntegralOrUnscopedEnumerationType());
391     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
392     const unsigned FromWidth = Ctx.getIntWidth(FromType);
393     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
394     const unsigned ToWidth = Ctx.getIntWidth(ToType);
395 
396     if (FromWidth > ToWidth ||
397         (FromWidth == ToWidth && FromSigned != ToSigned) ||
398         (FromSigned && !ToSigned)) {
399       // Not all values of FromType can be represented in ToType.
400       llvm::APSInt InitializerValue;
401       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
402       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
403         // Such conversions on variables are always narrowing.
404         return NK_Variable_Narrowing;
405       }
406       bool Narrowing = false;
407       if (FromWidth < ToWidth) {
408         // Negative -> unsigned is narrowing. Otherwise, more bits is never
409         // narrowing.
410         if (InitializerValue.isSigned() && InitializerValue.isNegative())
411           Narrowing = true;
412       } else {
413         // Add a bit to the InitializerValue so we don't have to worry about
414         // signed vs. unsigned comparisons.
415         InitializerValue = InitializerValue.extend(
416           InitializerValue.getBitWidth() + 1);
417         // Convert the initializer to and from the target width and signed-ness.
418         llvm::APSInt ConvertedValue = InitializerValue;
419         ConvertedValue = ConvertedValue.trunc(ToWidth);
420         ConvertedValue.setIsSigned(ToSigned);
421         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
422         ConvertedValue.setIsSigned(InitializerValue.isSigned());
423         // If the result is different, this was a narrowing conversion.
424         if (ConvertedValue != InitializerValue)
425           Narrowing = true;
426       }
427       if (Narrowing) {
428         ConstantType = Initializer->getType();
429         ConstantValue = APValue(InitializerValue);
430         return NK_Constant_Narrowing;
431       }
432     }
433     return NK_Not_Narrowing;
434   }
435 
436   default:
437     // Other kinds of conversions are not narrowings.
438     return NK_Not_Narrowing;
439   }
440 }
441 
442 /// dump - Print this standard conversion sequence to standard
443 /// error. Useful for debugging overloading issues.
444 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
445   raw_ostream &OS = llvm::errs();
446   bool PrintedSomething = false;
447   if (First != ICK_Identity) {
448     OS << GetImplicitConversionName(First);
449     PrintedSomething = true;
450   }
451 
452   if (Second != ICK_Identity) {
453     if (PrintedSomething) {
454       OS << " -> ";
455     }
456     OS << GetImplicitConversionName(Second);
457 
458     if (CopyConstructor) {
459       OS << " (by copy constructor)";
460     } else if (DirectBinding) {
461       OS << " (direct reference binding)";
462     } else if (ReferenceBinding) {
463       OS << " (reference binding)";
464     }
465     PrintedSomething = true;
466   }
467 
468   if (Third != ICK_Identity) {
469     if (PrintedSomething) {
470       OS << " -> ";
471     }
472     OS << GetImplicitConversionName(Third);
473     PrintedSomething = true;
474   }
475 
476   if (!PrintedSomething) {
477     OS << "No conversions required";
478   }
479 }
480 
481 /// dump - Print this user-defined conversion sequence to standard
482 /// error. Useful for debugging overloading issues.
483 void UserDefinedConversionSequence::dump() const {
484   raw_ostream &OS = llvm::errs();
485   if (Before.First || Before.Second || Before.Third) {
486     Before.dump();
487     OS << " -> ";
488   }
489   if (ConversionFunction)
490     OS << '\'' << *ConversionFunction << '\'';
491   else
492     OS << "aggregate initialization";
493   if (After.First || After.Second || After.Third) {
494     OS << " -> ";
495     After.dump();
496   }
497 }
498 
499 /// dump - Print this implicit conversion sequence to standard
500 /// error. Useful for debugging overloading issues.
501 void ImplicitConversionSequence::dump() const {
502   raw_ostream &OS = llvm::errs();
503   if (isStdInitializerListElement())
504     OS << "Worst std::initializer_list element conversion: ";
505   switch (ConversionKind) {
506   case StandardConversion:
507     OS << "Standard conversion: ";
508     Standard.dump();
509     break;
510   case UserDefinedConversion:
511     OS << "User-defined conversion: ";
512     UserDefined.dump();
513     break;
514   case EllipsisConversion:
515     OS << "Ellipsis conversion";
516     break;
517   case AmbiguousConversion:
518     OS << "Ambiguous conversion";
519     break;
520   case BadConversion:
521     OS << "Bad conversion";
522     break;
523   }
524 
525   OS << "\n";
526 }
527 
528 void AmbiguousConversionSequence::construct() {
529   new (&conversions()) ConversionSet();
530 }
531 
532 void AmbiguousConversionSequence::destruct() {
533   conversions().~ConversionSet();
534 }
535 
536 void
537 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
538   FromTypePtr = O.FromTypePtr;
539   ToTypePtr = O.ToTypePtr;
540   new (&conversions()) ConversionSet(O.conversions());
541 }
542 
543 namespace {
544   // Structure used by DeductionFailureInfo to store
545   // template argument information.
546   struct DFIArguments {
547     TemplateArgument FirstArg;
548     TemplateArgument SecondArg;
549   };
550   // Structure used by DeductionFailureInfo to store
551   // template parameter and template argument information.
552   struct DFIParamWithArguments : DFIArguments {
553     TemplateParameter Param;
554   };
555   // Structure used by DeductionFailureInfo to store template argument
556   // information and the index of the problematic call argument.
557   struct DFIDeducedMismatchArgs : DFIArguments {
558     TemplateArgumentList *TemplateArgs;
559     unsigned CallArgIndex;
560   };
561 }
562 
563 /// \brief Convert from Sema's representation of template deduction information
564 /// to the form used in overload-candidate information.
565 DeductionFailureInfo
566 clang::MakeDeductionFailureInfo(ASTContext &Context,
567                                 Sema::TemplateDeductionResult TDK,
568                                 TemplateDeductionInfo &Info) {
569   DeductionFailureInfo Result;
570   Result.Result = static_cast<unsigned>(TDK);
571   Result.HasDiagnostic = false;
572   switch (TDK) {
573   case Sema::TDK_Success:
574   case Sema::TDK_Invalid:
575   case Sema::TDK_InstantiationDepth:
576   case Sema::TDK_TooManyArguments:
577   case Sema::TDK_TooFewArguments:
578   case Sema::TDK_MiscellaneousDeductionFailure:
579     Result.Data = nullptr;
580     break;
581 
582   case Sema::TDK_Incomplete:
583   case Sema::TDK_InvalidExplicitArguments:
584     Result.Data = Info.Param.getOpaqueValue();
585     break;
586 
587   case Sema::TDK_DeducedMismatch: {
588     // FIXME: Should allocate from normal heap so that we can free this later.
589     auto *Saved = new (Context) DFIDeducedMismatchArgs;
590     Saved->FirstArg = Info.FirstArg;
591     Saved->SecondArg = Info.SecondArg;
592     Saved->TemplateArgs = Info.take();
593     Saved->CallArgIndex = Info.CallArgIndex;
594     Result.Data = Saved;
595     break;
596   }
597 
598   case Sema::TDK_NonDeducedMismatch: {
599     // FIXME: Should allocate from normal heap so that we can free this later.
600     DFIArguments *Saved = new (Context) DFIArguments;
601     Saved->FirstArg = Info.FirstArg;
602     Saved->SecondArg = Info.SecondArg;
603     Result.Data = Saved;
604     break;
605   }
606 
607   case Sema::TDK_Inconsistent:
608   case Sema::TDK_Underqualified: {
609     // FIXME: Should allocate from normal heap so that we can free this later.
610     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
611     Saved->Param = Info.Param;
612     Saved->FirstArg = Info.FirstArg;
613     Saved->SecondArg = Info.SecondArg;
614     Result.Data = Saved;
615     break;
616   }
617 
618   case Sema::TDK_SubstitutionFailure:
619     Result.Data = Info.take();
620     if (Info.hasSFINAEDiagnostic()) {
621       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
622           SourceLocation(), PartialDiagnostic::NullDiagnostic());
623       Info.takeSFINAEDiagnostic(*Diag);
624       Result.HasDiagnostic = true;
625     }
626     break;
627 
628   case Sema::TDK_FailedOverloadResolution:
629     Result.Data = Info.Expression;
630     break;
631   }
632 
633   return Result;
634 }
635 
636 void DeductionFailureInfo::Destroy() {
637   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
638   case Sema::TDK_Success:
639   case Sema::TDK_Invalid:
640   case Sema::TDK_InstantiationDepth:
641   case Sema::TDK_Incomplete:
642   case Sema::TDK_TooManyArguments:
643   case Sema::TDK_TooFewArguments:
644   case Sema::TDK_InvalidExplicitArguments:
645   case Sema::TDK_FailedOverloadResolution:
646     break;
647 
648   case Sema::TDK_Inconsistent:
649   case Sema::TDK_Underqualified:
650   case Sema::TDK_DeducedMismatch:
651   case Sema::TDK_NonDeducedMismatch:
652     // FIXME: Destroy the data?
653     Data = nullptr;
654     break;
655 
656   case Sema::TDK_SubstitutionFailure:
657     // FIXME: Destroy the template argument list?
658     Data = nullptr;
659     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
660       Diag->~PartialDiagnosticAt();
661       HasDiagnostic = false;
662     }
663     break;
664 
665   // Unhandled
666   case Sema::TDK_MiscellaneousDeductionFailure:
667     break;
668   }
669 }
670 
671 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
672   if (HasDiagnostic)
673     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
674   return nullptr;
675 }
676 
677 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
678   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
679   case Sema::TDK_Success:
680   case Sema::TDK_Invalid:
681   case Sema::TDK_InstantiationDepth:
682   case Sema::TDK_TooManyArguments:
683   case Sema::TDK_TooFewArguments:
684   case Sema::TDK_SubstitutionFailure:
685   case Sema::TDK_DeducedMismatch:
686   case Sema::TDK_NonDeducedMismatch:
687   case Sema::TDK_FailedOverloadResolution:
688     return TemplateParameter();
689 
690   case Sema::TDK_Incomplete:
691   case Sema::TDK_InvalidExplicitArguments:
692     return TemplateParameter::getFromOpaqueValue(Data);
693 
694   case Sema::TDK_Inconsistent:
695   case Sema::TDK_Underqualified:
696     return static_cast<DFIParamWithArguments*>(Data)->Param;
697 
698   // Unhandled
699   case Sema::TDK_MiscellaneousDeductionFailure:
700     break;
701   }
702 
703   return TemplateParameter();
704 }
705 
706 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
707   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708   case Sema::TDK_Success:
709   case Sema::TDK_Invalid:
710   case Sema::TDK_InstantiationDepth:
711   case Sema::TDK_TooManyArguments:
712   case Sema::TDK_TooFewArguments:
713   case Sema::TDK_Incomplete:
714   case Sema::TDK_InvalidExplicitArguments:
715   case Sema::TDK_Inconsistent:
716   case Sema::TDK_Underqualified:
717   case Sema::TDK_NonDeducedMismatch:
718   case Sema::TDK_FailedOverloadResolution:
719     return nullptr;
720 
721   case Sema::TDK_DeducedMismatch:
722     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
723 
724   case Sema::TDK_SubstitutionFailure:
725     return static_cast<TemplateArgumentList*>(Data);
726 
727   // Unhandled
728   case Sema::TDK_MiscellaneousDeductionFailure:
729     break;
730   }
731 
732   return nullptr;
733 }
734 
735 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
736   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
737   case Sema::TDK_Success:
738   case Sema::TDK_Invalid:
739   case Sema::TDK_InstantiationDepth:
740   case Sema::TDK_Incomplete:
741   case Sema::TDK_TooManyArguments:
742   case Sema::TDK_TooFewArguments:
743   case Sema::TDK_InvalidExplicitArguments:
744   case Sema::TDK_SubstitutionFailure:
745   case Sema::TDK_FailedOverloadResolution:
746     return nullptr;
747 
748   case Sema::TDK_Inconsistent:
749   case Sema::TDK_Underqualified:
750   case Sema::TDK_DeducedMismatch:
751   case Sema::TDK_NonDeducedMismatch:
752     return &static_cast<DFIArguments*>(Data)->FirstArg;
753 
754   // Unhandled
755   case Sema::TDK_MiscellaneousDeductionFailure:
756     break;
757   }
758 
759   return nullptr;
760 }
761 
762 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
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_FailedOverloadResolution:
773     return nullptr;
774 
775   case Sema::TDK_Inconsistent:
776   case Sema::TDK_Underqualified:
777   case Sema::TDK_DeducedMismatch:
778   case Sema::TDK_NonDeducedMismatch:
779     return &static_cast<DFIArguments*>(Data)->SecondArg;
780 
781   // Unhandled
782   case Sema::TDK_MiscellaneousDeductionFailure:
783     break;
784   }
785 
786   return nullptr;
787 }
788 
789 Expr *DeductionFailureInfo::getExpr() {
790   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
791         Sema::TDK_FailedOverloadResolution)
792     return static_cast<Expr*>(Data);
793 
794   return nullptr;
795 }
796 
797 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
798   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
799         Sema::TDK_DeducedMismatch)
800     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
801 
802   return llvm::None;
803 }
804 
805 void OverloadCandidateSet::destroyCandidates() {
806   for (iterator i = begin(), e = end(); i != e; ++i) {
807     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
808       i->Conversions[ii].~ImplicitConversionSequence();
809     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
810       i->DeductionFailure.Destroy();
811   }
812 }
813 
814 void OverloadCandidateSet::clear() {
815   destroyCandidates();
816   NumInlineSequences = 0;
817   Candidates.clear();
818   Functions.clear();
819 }
820 
821 namespace {
822   class UnbridgedCastsSet {
823     struct Entry {
824       Expr **Addr;
825       Expr *Saved;
826     };
827     SmallVector<Entry, 2> Entries;
828 
829   public:
830     void save(Sema &S, Expr *&E) {
831       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
832       Entry entry = { &E, E };
833       Entries.push_back(entry);
834       E = S.stripARCUnbridgedCast(E);
835     }
836 
837     void restore() {
838       for (SmallVectorImpl<Entry>::iterator
839              i = Entries.begin(), e = Entries.end(); i != e; ++i)
840         *i->Addr = i->Saved;
841     }
842   };
843 }
844 
845 /// checkPlaceholderForOverload - Do any interesting placeholder-like
846 /// preprocessing on the given expression.
847 ///
848 /// \param unbridgedCasts a collection to which to add unbridged casts;
849 ///   without this, they will be immediately diagnosed as errors
850 ///
851 /// Return true on unrecoverable error.
852 static bool
853 checkPlaceholderForOverload(Sema &S, Expr *&E,
854                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
855   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
856     // We can't handle overloaded expressions here because overload
857     // resolution might reasonably tweak them.
858     if (placeholder->getKind() == BuiltinType::Overload) return false;
859 
860     // If the context potentially accepts unbridged ARC casts, strip
861     // the unbridged cast and add it to the collection for later restoration.
862     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
863         unbridgedCasts) {
864       unbridgedCasts->save(S, E);
865       return false;
866     }
867 
868     // Go ahead and check everything else.
869     ExprResult result = S.CheckPlaceholderExpr(E);
870     if (result.isInvalid())
871       return true;
872 
873     E = result.get();
874     return false;
875   }
876 
877   // Nothing to do.
878   return false;
879 }
880 
881 /// checkArgPlaceholdersForOverload - Check a set of call operands for
882 /// placeholders.
883 static bool checkArgPlaceholdersForOverload(Sema &S,
884                                             MultiExprArg Args,
885                                             UnbridgedCastsSet &unbridged) {
886   for (unsigned i = 0, e = Args.size(); i != e; ++i)
887     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
888       return true;
889 
890   return false;
891 }
892 
893 // IsOverload - Determine whether the given New declaration is an
894 // overload of the declarations in Old. This routine returns false if
895 // New and Old cannot be overloaded, e.g., if New has the same
896 // signature as some function in Old (C++ 1.3.10) or if the Old
897 // declarations aren't functions (or function templates) at all. When
898 // it does return false, MatchedDecl will point to the decl that New
899 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
900 // top of the underlying declaration.
901 //
902 // Example: Given the following input:
903 //
904 //   void f(int, float); // #1
905 //   void f(int, int); // #2
906 //   int f(int, int); // #3
907 //
908 // When we process #1, there is no previous declaration of "f",
909 // so IsOverload will not be used.
910 //
911 // When we process #2, Old contains only the FunctionDecl for #1.  By
912 // comparing the parameter types, we see that #1 and #2 are overloaded
913 // (since they have different signatures), so this routine returns
914 // false; MatchedDecl is unchanged.
915 //
916 // When we process #3, Old is an overload set containing #1 and #2. We
917 // compare the signatures of #3 to #1 (they're overloaded, so we do
918 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
919 // identical (return types of functions are not part of the
920 // signature), IsOverload returns false and MatchedDecl will be set to
921 // point to the FunctionDecl for #2.
922 //
923 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
924 // into a class by a using declaration.  The rules for whether to hide
925 // shadow declarations ignore some properties which otherwise figure
926 // into a function template's signature.
927 Sema::OverloadKind
928 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
929                     NamedDecl *&Match, bool NewIsUsingDecl) {
930   for (LookupResult::iterator I = Old.begin(), E = Old.end();
931          I != E; ++I) {
932     NamedDecl *OldD = *I;
933 
934     bool OldIsUsingDecl = false;
935     if (isa<UsingShadowDecl>(OldD)) {
936       OldIsUsingDecl = true;
937 
938       // We can always introduce two using declarations into the same
939       // context, even if they have identical signatures.
940       if (NewIsUsingDecl) continue;
941 
942       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
943     }
944 
945     // A using-declaration does not conflict with another declaration
946     // if one of them is hidden.
947     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
948       continue;
949 
950     // If either declaration was introduced by a using declaration,
951     // we'll need to use slightly different rules for matching.
952     // Essentially, these rules are the normal rules, except that
953     // function templates hide function templates with different
954     // return types or template parameter lists.
955     bool UseMemberUsingDeclRules =
956       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
957       !New->getFriendObjectKind();
958 
959     if (FunctionDecl *OldF = OldD->getAsFunction()) {
960       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
961         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
962           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
963           continue;
964         }
965 
966         if (!isa<FunctionTemplateDecl>(OldD) &&
967             !shouldLinkPossiblyHiddenDecl(*I, New))
968           continue;
969 
970         Match = *I;
971         return Ovl_Match;
972       }
973     } else if (isa<UsingDecl>(OldD)) {
974       // We can overload with these, which can show up when doing
975       // redeclaration checks for UsingDecls.
976       assert(Old.getLookupKind() == LookupUsingDeclName);
977     } else if (isa<TagDecl>(OldD)) {
978       // We can always overload with tags by hiding them.
979     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
980       // Optimistically assume that an unresolved using decl will
981       // overload; if it doesn't, we'll have to diagnose during
982       // template instantiation.
983     } else {
984       // (C++ 13p1):
985       //   Only function declarations can be overloaded; object and type
986       //   declarations cannot be overloaded.
987       Match = *I;
988       return Ovl_NonFunction;
989     }
990   }
991 
992   return Ovl_Overload;
993 }
994 
995 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
996                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
997   // C++ [basic.start.main]p2: This function shall not be overloaded.
998   if (New->isMain())
999     return false;
1000 
1001   // MSVCRT user defined entry points cannot be overloaded.
1002   if (New->isMSVCRTEntryPoint())
1003     return false;
1004 
1005   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1006   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1007 
1008   // C++ [temp.fct]p2:
1009   //   A function template can be overloaded with other function templates
1010   //   and with normal (non-template) functions.
1011   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1012     return true;
1013 
1014   // Is the function New an overload of the function Old?
1015   QualType OldQType = Context.getCanonicalType(Old->getType());
1016   QualType NewQType = Context.getCanonicalType(New->getType());
1017 
1018   // Compare the signatures (C++ 1.3.10) of the two functions to
1019   // determine whether they are overloads. If we find any mismatch
1020   // in the signature, they are overloads.
1021 
1022   // If either of these functions is a K&R-style function (no
1023   // prototype), then we consider them to have matching signatures.
1024   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1025       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1026     return false;
1027 
1028   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1029   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1030 
1031   // The signature of a function includes the types of its
1032   // parameters (C++ 1.3.10), which includes the presence or absence
1033   // of the ellipsis; see C++ DR 357).
1034   if (OldQType != NewQType &&
1035       (OldType->getNumParams() != NewType->getNumParams() ||
1036        OldType->isVariadic() != NewType->isVariadic() ||
1037        !FunctionParamTypesAreEqual(OldType, NewType)))
1038     return true;
1039 
1040   // C++ [temp.over.link]p4:
1041   //   The signature of a function template consists of its function
1042   //   signature, its return type and its template parameter list. The names
1043   //   of the template parameters are significant only for establishing the
1044   //   relationship between the template parameters and the rest of the
1045   //   signature.
1046   //
1047   // We check the return type and template parameter lists for function
1048   // templates first; the remaining checks follow.
1049   //
1050   // However, we don't consider either of these when deciding whether
1051   // a member introduced by a shadow declaration is hidden.
1052   if (!UseMemberUsingDeclRules && NewTemplate &&
1053       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1054                                        OldTemplate->getTemplateParameters(),
1055                                        false, TPL_TemplateMatch) ||
1056        OldType->getReturnType() != NewType->getReturnType()))
1057     return true;
1058 
1059   // If the function is a class member, its signature includes the
1060   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1061   //
1062   // As part of this, also check whether one of the member functions
1063   // is static, in which case they are not overloads (C++
1064   // 13.1p2). While not part of the definition of the signature,
1065   // this check is important to determine whether these functions
1066   // can be overloaded.
1067   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1068   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1069   if (OldMethod && NewMethod &&
1070       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1071     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1072       if (!UseMemberUsingDeclRules &&
1073           (OldMethod->getRefQualifier() == RQ_None ||
1074            NewMethod->getRefQualifier() == RQ_None)) {
1075         // C++0x [over.load]p2:
1076         //   - Member function declarations with the same name and the same
1077         //     parameter-type-list as well as member function template
1078         //     declarations with the same name, the same parameter-type-list, and
1079         //     the same template parameter lists cannot be overloaded if any of
1080         //     them, but not all, have a ref-qualifier (8.3.5).
1081         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1082           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1083         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1084       }
1085       return true;
1086     }
1087 
1088     // We may not have applied the implicit const for a constexpr member
1089     // function yet (because we haven't yet resolved whether this is a static
1090     // or non-static member function). Add it now, on the assumption that this
1091     // is a redeclaration of OldMethod.
1092     unsigned OldQuals = OldMethod->getTypeQualifiers();
1093     unsigned NewQuals = NewMethod->getTypeQualifiers();
1094     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1095         !isa<CXXConstructorDecl>(NewMethod))
1096       NewQuals |= Qualifiers::Const;
1097 
1098     // We do not allow overloading based off of '__restrict'.
1099     OldQuals &= ~Qualifiers::Restrict;
1100     NewQuals &= ~Qualifiers::Restrict;
1101     if (OldQuals != NewQuals)
1102       return true;
1103   }
1104 
1105   // Though pass_object_size is placed on parameters and takes an argument, we
1106   // consider it to be a function-level modifier for the sake of function
1107   // identity. Either the function has one or more parameters with
1108   // pass_object_size or it doesn't.
1109   if (functionHasPassObjectSizeParams(New) !=
1110       functionHasPassObjectSizeParams(Old))
1111     return true;
1112 
1113   // enable_if attributes are an order-sensitive part of the signature.
1114   for (specific_attr_iterator<EnableIfAttr>
1115          NewI = New->specific_attr_begin<EnableIfAttr>(),
1116          NewE = New->specific_attr_end<EnableIfAttr>(),
1117          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1118          OldE = Old->specific_attr_end<EnableIfAttr>();
1119        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1120     if (NewI == NewE || OldI == OldE)
1121       return true;
1122     llvm::FoldingSetNodeID NewID, OldID;
1123     NewI->getCond()->Profile(NewID, Context, true);
1124     OldI->getCond()->Profile(OldID, Context, true);
1125     if (NewID != OldID)
1126       return true;
1127   }
1128 
1129   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1130     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1131                        OldTarget = IdentifyCUDATarget(Old);
1132     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1133       return false;
1134 
1135     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1136 
1137     // Don't allow mixing of HD with other kinds. This guarantees that
1138     // we have only one viable function with this signature on any
1139     // side of CUDA compilation .
1140     // __global__ functions can't be overloaded based on attribute
1141     // difference because, like HD, they also exist on both sides.
1142     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1143         (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1144       return false;
1145 
1146     // Allow overloading of functions with same signature, but
1147     // different CUDA target attributes.
1148     return NewTarget != OldTarget;
1149   }
1150 
1151   // The signatures match; this is not an overload.
1152   return false;
1153 }
1154 
1155 /// \brief Checks availability of the function depending on the current
1156 /// function context. Inside an unavailable function, unavailability is ignored.
1157 ///
1158 /// \returns true if \arg FD is unavailable and current context is inside
1159 /// an available function, false otherwise.
1160 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1161   if (!FD->isUnavailable())
1162     return false;
1163 
1164   // Walk up the context of the caller.
1165   Decl *C = cast<Decl>(CurContext);
1166   do {
1167     if (C->isUnavailable())
1168       return false;
1169   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1170   return true;
1171 }
1172 
1173 /// \brief Tries a user-defined conversion from From to ToType.
1174 ///
1175 /// Produces an implicit conversion sequence for when a standard conversion
1176 /// is not an option. See TryImplicitConversion for more information.
1177 static ImplicitConversionSequence
1178 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1179                          bool SuppressUserConversions,
1180                          bool AllowExplicit,
1181                          bool InOverloadResolution,
1182                          bool CStyle,
1183                          bool AllowObjCWritebackConversion,
1184                          bool AllowObjCConversionOnExplicit) {
1185   ImplicitConversionSequence ICS;
1186 
1187   if (SuppressUserConversions) {
1188     // We're not in the case above, so there is no conversion that
1189     // we can perform.
1190     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1191     return ICS;
1192   }
1193 
1194   // Attempt user-defined conversion.
1195   OverloadCandidateSet Conversions(From->getExprLoc(),
1196                                    OverloadCandidateSet::CSK_Normal);
1197   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1198                                   Conversions, AllowExplicit,
1199                                   AllowObjCConversionOnExplicit)) {
1200   case OR_Success:
1201   case OR_Deleted:
1202     ICS.setUserDefined();
1203     // C++ [over.ics.user]p4:
1204     //   A conversion of an expression of class type to the same class
1205     //   type is given Exact Match rank, and a conversion of an
1206     //   expression of class type to a base class of that type is
1207     //   given Conversion rank, in spite of the fact that a copy
1208     //   constructor (i.e., a user-defined conversion function) is
1209     //   called for those cases.
1210     if (CXXConstructorDecl *Constructor
1211           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1212       QualType FromCanon
1213         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1214       QualType ToCanon
1215         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1216       if (Constructor->isCopyConstructor() &&
1217           (FromCanon == ToCanon ||
1218            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1219         // Turn this into a "standard" conversion sequence, so that it
1220         // gets ranked with standard conversion sequences.
1221         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1222         ICS.setStandard();
1223         ICS.Standard.setAsIdentityConversion();
1224         ICS.Standard.setFromType(From->getType());
1225         ICS.Standard.setAllToTypes(ToType);
1226         ICS.Standard.CopyConstructor = Constructor;
1227         ICS.Standard.FoundCopyConstructor = Found;
1228         if (ToCanon != FromCanon)
1229           ICS.Standard.Second = ICK_Derived_To_Base;
1230       }
1231     }
1232     break;
1233 
1234   case OR_Ambiguous:
1235     ICS.setAmbiguous();
1236     ICS.Ambiguous.setFromType(From->getType());
1237     ICS.Ambiguous.setToType(ToType);
1238     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1239          Cand != Conversions.end(); ++Cand)
1240       if (Cand->Viable)
1241         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1242     break;
1243 
1244     // Fall through.
1245   case OR_No_Viable_Function:
1246     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1247     break;
1248   }
1249 
1250   return ICS;
1251 }
1252 
1253 /// TryImplicitConversion - Attempt to perform an implicit conversion
1254 /// from the given expression (Expr) to the given type (ToType). This
1255 /// function returns an implicit conversion sequence that can be used
1256 /// to perform the initialization. Given
1257 ///
1258 ///   void f(float f);
1259 ///   void g(int i) { f(i); }
1260 ///
1261 /// this routine would produce an implicit conversion sequence to
1262 /// describe the initialization of f from i, which will be a standard
1263 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1264 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1265 //
1266 /// Note that this routine only determines how the conversion can be
1267 /// performed; it does not actually perform the conversion. As such,
1268 /// it will not produce any diagnostics if no conversion is available,
1269 /// but will instead return an implicit conversion sequence of kind
1270 /// "BadConversion".
1271 ///
1272 /// If @p SuppressUserConversions, then user-defined conversions are
1273 /// not permitted.
1274 /// If @p AllowExplicit, then explicit user-defined conversions are
1275 /// permitted.
1276 ///
1277 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1278 /// writeback conversion, which allows __autoreleasing id* parameters to
1279 /// be initialized with __strong id* or __weak id* arguments.
1280 static ImplicitConversionSequence
1281 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1282                       bool SuppressUserConversions,
1283                       bool AllowExplicit,
1284                       bool InOverloadResolution,
1285                       bool CStyle,
1286                       bool AllowObjCWritebackConversion,
1287                       bool AllowObjCConversionOnExplicit) {
1288   ImplicitConversionSequence ICS;
1289   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1290                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1291     ICS.setStandard();
1292     return ICS;
1293   }
1294 
1295   if (!S.getLangOpts().CPlusPlus) {
1296     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1297     return ICS;
1298   }
1299 
1300   // C++ [over.ics.user]p4:
1301   //   A conversion of an expression of class type to the same class
1302   //   type is given Exact Match rank, and a conversion of an
1303   //   expression of class type to a base class of that type is
1304   //   given Conversion rank, in spite of the fact that a copy/move
1305   //   constructor (i.e., a user-defined conversion function) is
1306   //   called for those cases.
1307   QualType FromType = From->getType();
1308   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1309       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1310        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1311     ICS.setStandard();
1312     ICS.Standard.setAsIdentityConversion();
1313     ICS.Standard.setFromType(FromType);
1314     ICS.Standard.setAllToTypes(ToType);
1315 
1316     // We don't actually check at this point whether there is a valid
1317     // copy/move constructor, since overloading just assumes that it
1318     // exists. When we actually perform initialization, we'll find the
1319     // appropriate constructor to copy the returned object, if needed.
1320     ICS.Standard.CopyConstructor = nullptr;
1321 
1322     // Determine whether this is considered a derived-to-base conversion.
1323     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1324       ICS.Standard.Second = ICK_Derived_To_Base;
1325 
1326     return ICS;
1327   }
1328 
1329   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1330                                   AllowExplicit, InOverloadResolution, CStyle,
1331                                   AllowObjCWritebackConversion,
1332                                   AllowObjCConversionOnExplicit);
1333 }
1334 
1335 ImplicitConversionSequence
1336 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1337                             bool SuppressUserConversions,
1338                             bool AllowExplicit,
1339                             bool InOverloadResolution,
1340                             bool CStyle,
1341                             bool AllowObjCWritebackConversion) {
1342   return ::TryImplicitConversion(*this, From, ToType,
1343                                  SuppressUserConversions, AllowExplicit,
1344                                  InOverloadResolution, CStyle,
1345                                  AllowObjCWritebackConversion,
1346                                  /*AllowObjCConversionOnExplicit=*/false);
1347 }
1348 
1349 /// PerformImplicitConversion - Perform an implicit conversion of the
1350 /// expression From to the type ToType. Returns the
1351 /// converted expression. Flavor is the kind of conversion we're
1352 /// performing, used in the error message. If @p AllowExplicit,
1353 /// explicit user-defined conversions are permitted.
1354 ExprResult
1355 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1356                                 AssignmentAction Action, bool AllowExplicit) {
1357   ImplicitConversionSequence ICS;
1358   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1359 }
1360 
1361 ExprResult
1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1363                                 AssignmentAction Action, bool AllowExplicit,
1364                                 ImplicitConversionSequence& ICS) {
1365   if (checkPlaceholderForOverload(*this, From))
1366     return ExprError();
1367 
1368   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1369   bool AllowObjCWritebackConversion
1370     = getLangOpts().ObjCAutoRefCount &&
1371       (Action == AA_Passing || Action == AA_Sending);
1372   if (getLangOpts().ObjC1)
1373     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1374                                       ToType, From->getType(), From);
1375   ICS = ::TryImplicitConversion(*this, From, ToType,
1376                                 /*SuppressUserConversions=*/false,
1377                                 AllowExplicit,
1378                                 /*InOverloadResolution=*/false,
1379                                 /*CStyle=*/false,
1380                                 AllowObjCWritebackConversion,
1381                                 /*AllowObjCConversionOnExplicit=*/false);
1382   return PerformImplicitConversion(From, ToType, ICS, Action);
1383 }
1384 
1385 /// \brief Determine whether the conversion from FromType to ToType is a valid
1386 /// conversion that strips "noreturn" off the nested function type.
1387 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1388                                 QualType &ResultTy) {
1389   if (Context.hasSameUnqualifiedType(FromType, ToType))
1390     return false;
1391 
1392   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1393   // where F adds one of the following at most once:
1394   //   - a pointer
1395   //   - a member pointer
1396   //   - a block pointer
1397   CanQualType CanTo = Context.getCanonicalType(ToType);
1398   CanQualType CanFrom = Context.getCanonicalType(FromType);
1399   Type::TypeClass TyClass = CanTo->getTypeClass();
1400   if (TyClass != CanFrom->getTypeClass()) return false;
1401   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1402     if (TyClass == Type::Pointer) {
1403       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1404       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1405     } else if (TyClass == Type::BlockPointer) {
1406       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1407       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1408     } else if (TyClass == Type::MemberPointer) {
1409       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1410       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1411     } else {
1412       return false;
1413     }
1414 
1415     TyClass = CanTo->getTypeClass();
1416     if (TyClass != CanFrom->getTypeClass()) return false;
1417     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1418       return false;
1419   }
1420 
1421   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1422   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1423   if (!EInfo.getNoReturn()) return false;
1424 
1425   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1426   assert(QualType(FromFn, 0).isCanonical());
1427   if (QualType(FromFn, 0) != CanTo) return false;
1428 
1429   ResultTy = ToType;
1430   return true;
1431 }
1432 
1433 /// \brief Determine whether the conversion from FromType to ToType is a valid
1434 /// vector conversion.
1435 ///
1436 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1437 /// conversion.
1438 static bool IsVectorConversion(Sema &S, QualType FromType,
1439                                QualType ToType, ImplicitConversionKind &ICK) {
1440   // We need at least one of these types to be a vector type to have a vector
1441   // conversion.
1442   if (!ToType->isVectorType() && !FromType->isVectorType())
1443     return false;
1444 
1445   // Identical types require no conversions.
1446   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1447     return false;
1448 
1449   // There are no conversions between extended vector types, only identity.
1450   if (ToType->isExtVectorType()) {
1451     // There are no conversions between extended vector types other than the
1452     // identity conversion.
1453     if (FromType->isExtVectorType())
1454       return false;
1455 
1456     // Vector splat from any arithmetic type to a vector.
1457     if (FromType->isArithmeticType()) {
1458       ICK = ICK_Vector_Splat;
1459       return true;
1460     }
1461   }
1462 
1463   // We can perform the conversion between vector types in the following cases:
1464   // 1)vector types are equivalent AltiVec and GCC vector types
1465   // 2)lax vector conversions are permitted and the vector types are of the
1466   //   same size
1467   if (ToType->isVectorType() && FromType->isVectorType()) {
1468     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1469         S.isLaxVectorConversion(FromType, ToType)) {
1470       ICK = ICK_Vector_Conversion;
1471       return true;
1472     }
1473   }
1474 
1475   return false;
1476 }
1477 
1478 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1479                                 bool InOverloadResolution,
1480                                 StandardConversionSequence &SCS,
1481                                 bool CStyle);
1482 
1483 /// IsStandardConversion - Determines whether there is a standard
1484 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1485 /// expression From to the type ToType. Standard conversion sequences
1486 /// only consider non-class types; for conversions that involve class
1487 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1488 /// contain the standard conversion sequence required to perform this
1489 /// conversion and this routine will return true. Otherwise, this
1490 /// routine will return false and the value of SCS is unspecified.
1491 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1492                                  bool InOverloadResolution,
1493                                  StandardConversionSequence &SCS,
1494                                  bool CStyle,
1495                                  bool AllowObjCWritebackConversion) {
1496   QualType FromType = From->getType();
1497 
1498   // Standard conversions (C++ [conv])
1499   SCS.setAsIdentityConversion();
1500   SCS.IncompatibleObjC = false;
1501   SCS.setFromType(FromType);
1502   SCS.CopyConstructor = nullptr;
1503 
1504   // There are no standard conversions for class types in C++, so
1505   // abort early. When overloading in C, however, we do permit them.
1506   if (S.getLangOpts().CPlusPlus &&
1507       (FromType->isRecordType() || ToType->isRecordType()))
1508     return false;
1509 
1510   // The first conversion can be an lvalue-to-rvalue conversion,
1511   // array-to-pointer conversion, or function-to-pointer conversion
1512   // (C++ 4p1).
1513 
1514   if (FromType == S.Context.OverloadTy) {
1515     DeclAccessPair AccessPair;
1516     if (FunctionDecl *Fn
1517           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1518                                                  AccessPair)) {
1519       // We were able to resolve the address of the overloaded function,
1520       // so we can convert to the type of that function.
1521       FromType = Fn->getType();
1522       SCS.setFromType(FromType);
1523 
1524       // we can sometimes resolve &foo<int> regardless of ToType, so check
1525       // if the type matches (identity) or we are converting to bool
1526       if (!S.Context.hasSameUnqualifiedType(
1527                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1528         QualType resultTy;
1529         // if the function type matches except for [[noreturn]], it's ok
1530         if (!S.IsNoReturnConversion(FromType,
1531               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1532           // otherwise, only a boolean conversion is standard
1533           if (!ToType->isBooleanType())
1534             return false;
1535       }
1536 
1537       // Check if the "from" expression is taking the address of an overloaded
1538       // function and recompute the FromType accordingly. Take advantage of the
1539       // fact that non-static member functions *must* have such an address-of
1540       // expression.
1541       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1542       if (Method && !Method->isStatic()) {
1543         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1544                "Non-unary operator on non-static member address");
1545         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1546                == UO_AddrOf &&
1547                "Non-address-of operator on non-static member address");
1548         const Type *ClassType
1549           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1550         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1551       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1552         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1553                UO_AddrOf &&
1554                "Non-address-of operator for overloaded function expression");
1555         FromType = S.Context.getPointerType(FromType);
1556       }
1557 
1558       // Check that we've computed the proper type after overload resolution.
1559       assert(S.Context.hasSameType(
1560         FromType,
1561         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1562     } else {
1563       return false;
1564     }
1565   }
1566   // Lvalue-to-rvalue conversion (C++11 4.1):
1567   //   A glvalue (3.10) of a non-function, non-array type T can
1568   //   be converted to a prvalue.
1569   bool argIsLValue = From->isGLValue();
1570   if (argIsLValue &&
1571       !FromType->isFunctionType() && !FromType->isArrayType() &&
1572       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1573     SCS.First = ICK_Lvalue_To_Rvalue;
1574 
1575     // C11 6.3.2.1p2:
1576     //   ... if the lvalue has atomic type, the value has the non-atomic version
1577     //   of the type of the lvalue ...
1578     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1579       FromType = Atomic->getValueType();
1580 
1581     // If T is a non-class type, the type of the rvalue is the
1582     // cv-unqualified version of T. Otherwise, the type of the rvalue
1583     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1584     // just strip the qualifiers because they don't matter.
1585     FromType = FromType.getUnqualifiedType();
1586   } else if (FromType->isArrayType()) {
1587     // Array-to-pointer conversion (C++ 4.2)
1588     SCS.First = ICK_Array_To_Pointer;
1589 
1590     // An lvalue or rvalue of type "array of N T" or "array of unknown
1591     // bound of T" can be converted to an rvalue of type "pointer to
1592     // T" (C++ 4.2p1).
1593     FromType = S.Context.getArrayDecayedType(FromType);
1594 
1595     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1596       // This conversion is deprecated in C++03 (D.4)
1597       SCS.DeprecatedStringLiteralToCharPtr = true;
1598 
1599       // For the purpose of ranking in overload resolution
1600       // (13.3.3.1.1), this conversion is considered an
1601       // array-to-pointer conversion followed by a qualification
1602       // conversion (4.4). (C++ 4.2p2)
1603       SCS.Second = ICK_Identity;
1604       SCS.Third = ICK_Qualification;
1605       SCS.QualificationIncludesObjCLifetime = false;
1606       SCS.setAllToTypes(FromType);
1607       return true;
1608     }
1609   } else if (FromType->isFunctionType() && argIsLValue) {
1610     // Function-to-pointer conversion (C++ 4.3).
1611     SCS.First = ICK_Function_To_Pointer;
1612 
1613     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1614       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1615         if (!S.checkAddressOfFunctionIsAvailable(FD))
1616           return false;
1617 
1618     // An lvalue of function type T can be converted to an rvalue of
1619     // type "pointer to T." The result is a pointer to the
1620     // function. (C++ 4.3p1).
1621     FromType = S.Context.getPointerType(FromType);
1622   } else {
1623     // We don't require any conversions for the first step.
1624     SCS.First = ICK_Identity;
1625   }
1626   SCS.setToType(0, FromType);
1627 
1628   // The second conversion can be an integral promotion, floating
1629   // point promotion, integral conversion, floating point conversion,
1630   // floating-integral conversion, pointer conversion,
1631   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1632   // For overloading in C, this can also be a "compatible-type"
1633   // conversion.
1634   bool IncompatibleObjC = false;
1635   ImplicitConversionKind SecondICK = ICK_Identity;
1636   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1637     // The unqualified versions of the types are the same: there's no
1638     // conversion to do.
1639     SCS.Second = ICK_Identity;
1640   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1641     // Integral promotion (C++ 4.5).
1642     SCS.Second = ICK_Integral_Promotion;
1643     FromType = ToType.getUnqualifiedType();
1644   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1645     // Floating point promotion (C++ 4.6).
1646     SCS.Second = ICK_Floating_Promotion;
1647     FromType = ToType.getUnqualifiedType();
1648   } else if (S.IsComplexPromotion(FromType, ToType)) {
1649     // Complex promotion (Clang extension)
1650     SCS.Second = ICK_Complex_Promotion;
1651     FromType = ToType.getUnqualifiedType();
1652   } else if (ToType->isBooleanType() &&
1653              (FromType->isArithmeticType() ||
1654               FromType->isAnyPointerType() ||
1655               FromType->isBlockPointerType() ||
1656               FromType->isMemberPointerType() ||
1657               FromType->isNullPtrType())) {
1658     // Boolean conversions (C++ 4.12).
1659     SCS.Second = ICK_Boolean_Conversion;
1660     FromType = S.Context.BoolTy;
1661   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1662              ToType->isIntegralType(S.Context)) {
1663     // Integral conversions (C++ 4.7).
1664     SCS.Second = ICK_Integral_Conversion;
1665     FromType = ToType.getUnqualifiedType();
1666   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1667     // Complex conversions (C99 6.3.1.6)
1668     SCS.Second = ICK_Complex_Conversion;
1669     FromType = ToType.getUnqualifiedType();
1670   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1671              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1672     // Complex-real conversions (C99 6.3.1.7)
1673     SCS.Second = ICK_Complex_Real;
1674     FromType = ToType.getUnqualifiedType();
1675   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1676     // FIXME: disable conversions between long double and __float128 if
1677     // their representation is different until there is back end support
1678     // We of course allow this conversion if long double is really double.
1679     if (&S.Context.getFloatTypeSemantics(FromType) !=
1680         &S.Context.getFloatTypeSemantics(ToType)) {
1681       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1682                                     ToType == S.Context.LongDoubleTy) ||
1683                                    (FromType == S.Context.LongDoubleTy &&
1684                                     ToType == S.Context.Float128Ty));
1685       if (Float128AndLongDouble &&
1686           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1687            &llvm::APFloat::IEEEdouble))
1688         return false;
1689     }
1690     // Floating point conversions (C++ 4.8).
1691     SCS.Second = ICK_Floating_Conversion;
1692     FromType = ToType.getUnqualifiedType();
1693   } else if ((FromType->isRealFloatingType() &&
1694               ToType->isIntegralType(S.Context)) ||
1695              (FromType->isIntegralOrUnscopedEnumerationType() &&
1696               ToType->isRealFloatingType())) {
1697     // Floating-integral conversions (C++ 4.9).
1698     SCS.Second = ICK_Floating_Integral;
1699     FromType = ToType.getUnqualifiedType();
1700   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1701     SCS.Second = ICK_Block_Pointer_Conversion;
1702   } else if (AllowObjCWritebackConversion &&
1703              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1704     SCS.Second = ICK_Writeback_Conversion;
1705   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1706                                    FromType, IncompatibleObjC)) {
1707     // Pointer conversions (C++ 4.10).
1708     SCS.Second = ICK_Pointer_Conversion;
1709     SCS.IncompatibleObjC = IncompatibleObjC;
1710     FromType = FromType.getUnqualifiedType();
1711   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1712                                          InOverloadResolution, FromType)) {
1713     // Pointer to member conversions (4.11).
1714     SCS.Second = ICK_Pointer_Member;
1715   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1716     SCS.Second = SecondICK;
1717     FromType = ToType.getUnqualifiedType();
1718   } else if (!S.getLangOpts().CPlusPlus &&
1719              S.Context.typesAreCompatible(ToType, FromType)) {
1720     // Compatible conversions (Clang extension for C function overloading)
1721     SCS.Second = ICK_Compatible_Conversion;
1722     FromType = ToType.getUnqualifiedType();
1723   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1724     // Treat a conversion that strips "noreturn" as an identity conversion.
1725     SCS.Second = ICK_NoReturn_Adjustment;
1726   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1727                                              InOverloadResolution,
1728                                              SCS, CStyle)) {
1729     SCS.Second = ICK_TransparentUnionConversion;
1730     FromType = ToType;
1731   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1732                                  CStyle)) {
1733     // tryAtomicConversion has updated the standard conversion sequence
1734     // appropriately.
1735     return true;
1736   } else if (ToType->isEventT() &&
1737              From->isIntegerConstantExpr(S.getASTContext()) &&
1738              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1739     SCS.Second = ICK_Zero_Event_Conversion;
1740     FromType = ToType;
1741   } else {
1742     // No second conversion required.
1743     SCS.Second = ICK_Identity;
1744   }
1745   SCS.setToType(1, FromType);
1746 
1747   QualType CanonFrom;
1748   QualType CanonTo;
1749   // The third conversion can be a qualification conversion (C++ 4p1).
1750   bool ObjCLifetimeConversion;
1751   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1752                                   ObjCLifetimeConversion)) {
1753     SCS.Third = ICK_Qualification;
1754     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1755     FromType = ToType;
1756     CanonFrom = S.Context.getCanonicalType(FromType);
1757     CanonTo = S.Context.getCanonicalType(ToType);
1758   } else {
1759     // No conversion required
1760     SCS.Third = ICK_Identity;
1761 
1762     // C++ [over.best.ics]p6:
1763     //   [...] Any difference in top-level cv-qualification is
1764     //   subsumed by the initialization itself and does not constitute
1765     //   a conversion. [...]
1766     CanonFrom = S.Context.getCanonicalType(FromType);
1767     CanonTo = S.Context.getCanonicalType(ToType);
1768     if (CanonFrom.getLocalUnqualifiedType()
1769                                        == CanonTo.getLocalUnqualifiedType() &&
1770         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1771       FromType = ToType;
1772       CanonFrom = CanonTo;
1773     }
1774   }
1775   SCS.setToType(2, FromType);
1776 
1777   if (CanonFrom == CanonTo)
1778     return true;
1779 
1780   // If we have not converted the argument type to the parameter type,
1781   // this is a bad conversion sequence, unless we're resolving an overload in C.
1782   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1783     return false;
1784 
1785   ExprResult ER = ExprResult{From};
1786   auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1787                                                  /*Diagnose=*/false,
1788                                                  /*DiagnoseCFAudited=*/false,
1789                                                  /*ConvertRHS=*/false);
1790   if (Conv != Sema::Compatible)
1791     return false;
1792 
1793   SCS.setAllToTypes(ToType);
1794   // We need to set all three because we want this conversion to rank terribly,
1795   // and we don't know what conversions it may overlap with.
1796   SCS.First = ICK_C_Only_Conversion;
1797   SCS.Second = ICK_C_Only_Conversion;
1798   SCS.Third = ICK_C_Only_Conversion;
1799   return true;
1800 }
1801 
1802 static bool
1803 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1804                                      QualType &ToType,
1805                                      bool InOverloadResolution,
1806                                      StandardConversionSequence &SCS,
1807                                      bool CStyle) {
1808 
1809   const RecordType *UT = ToType->getAsUnionType();
1810   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1811     return false;
1812   // The field to initialize within the transparent union.
1813   RecordDecl *UD = UT->getDecl();
1814   // It's compatible if the expression matches any of the fields.
1815   for (const auto *it : UD->fields()) {
1816     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1817                              CStyle, /*ObjCWritebackConversion=*/false)) {
1818       ToType = it->getType();
1819       return true;
1820     }
1821   }
1822   return false;
1823 }
1824 
1825 /// IsIntegralPromotion - Determines whether the conversion from the
1826 /// expression From (whose potentially-adjusted type is FromType) to
1827 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1828 /// sets PromotedType to the promoted type.
1829 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1830   const BuiltinType *To = ToType->getAs<BuiltinType>();
1831   // All integers are built-in.
1832   if (!To) {
1833     return false;
1834   }
1835 
1836   // An rvalue of type char, signed char, unsigned char, short int, or
1837   // unsigned short int can be converted to an rvalue of type int if
1838   // int can represent all the values of the source type; otherwise,
1839   // the source rvalue can be converted to an rvalue of type unsigned
1840   // int (C++ 4.5p1).
1841   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1842       !FromType->isEnumeralType()) {
1843     if (// We can promote any signed, promotable integer type to an int
1844         (FromType->isSignedIntegerType() ||
1845          // We can promote any unsigned integer type whose size is
1846          // less than int to an int.
1847          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1848       return To->getKind() == BuiltinType::Int;
1849     }
1850 
1851     return To->getKind() == BuiltinType::UInt;
1852   }
1853 
1854   // C++11 [conv.prom]p3:
1855   //   A prvalue of an unscoped enumeration type whose underlying type is not
1856   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1857   //   following types that can represent all the values of the enumeration
1858   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1859   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1860   //   long long int. If none of the types in that list can represent all the
1861   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1862   //   type can be converted to an rvalue a prvalue of the extended integer type
1863   //   with lowest integer conversion rank (4.13) greater than the rank of long
1864   //   long in which all the values of the enumeration can be represented. If
1865   //   there are two such extended types, the signed one is chosen.
1866   // C++11 [conv.prom]p4:
1867   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1868   //   can be converted to a prvalue of its underlying type. Moreover, if
1869   //   integral promotion can be applied to its underlying type, a prvalue of an
1870   //   unscoped enumeration type whose underlying type is fixed can also be
1871   //   converted to a prvalue of the promoted underlying type.
1872   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1873     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1874     // provided for a scoped enumeration.
1875     if (FromEnumType->getDecl()->isScoped())
1876       return false;
1877 
1878     // We can perform an integral promotion to the underlying type of the enum,
1879     // even if that's not the promoted type. Note that the check for promoting
1880     // the underlying type is based on the type alone, and does not consider
1881     // the bitfield-ness of the actual source expression.
1882     if (FromEnumType->getDecl()->isFixed()) {
1883       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1884       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1885              IsIntegralPromotion(nullptr, Underlying, ToType);
1886     }
1887 
1888     // We have already pre-calculated the promotion type, so this is trivial.
1889     if (ToType->isIntegerType() &&
1890         isCompleteType(From->getLocStart(), FromType))
1891       return Context.hasSameUnqualifiedType(
1892           ToType, FromEnumType->getDecl()->getPromotionType());
1893   }
1894 
1895   // C++0x [conv.prom]p2:
1896   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1897   //   to an rvalue a prvalue of the first of the following types that can
1898   //   represent all the values of its underlying type: int, unsigned int,
1899   //   long int, unsigned long int, long long int, or unsigned long long int.
1900   //   If none of the types in that list can represent all the values of its
1901   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1902   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1903   //   type.
1904   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1905       ToType->isIntegerType()) {
1906     // Determine whether the type we're converting from is signed or
1907     // unsigned.
1908     bool FromIsSigned = FromType->isSignedIntegerType();
1909     uint64_t FromSize = Context.getTypeSize(FromType);
1910 
1911     // The types we'll try to promote to, in the appropriate
1912     // order. Try each of these types.
1913     QualType PromoteTypes[6] = {
1914       Context.IntTy, Context.UnsignedIntTy,
1915       Context.LongTy, Context.UnsignedLongTy ,
1916       Context.LongLongTy, Context.UnsignedLongLongTy
1917     };
1918     for (int Idx = 0; Idx < 6; ++Idx) {
1919       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1920       if (FromSize < ToSize ||
1921           (FromSize == ToSize &&
1922            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1923         // We found the type that we can promote to. If this is the
1924         // type we wanted, we have a promotion. Otherwise, no
1925         // promotion.
1926         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1927       }
1928     }
1929   }
1930 
1931   // An rvalue for an integral bit-field (9.6) can be converted to an
1932   // rvalue of type int if int can represent all the values of the
1933   // bit-field; otherwise, it can be converted to unsigned int if
1934   // unsigned int can represent all the values of the bit-field. If
1935   // the bit-field is larger yet, no integral promotion applies to
1936   // it. If the bit-field has an enumerated type, it is treated as any
1937   // other value of that type for promotion purposes (C++ 4.5p3).
1938   // FIXME: We should delay checking of bit-fields until we actually perform the
1939   // conversion.
1940   if (From) {
1941     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1942       llvm::APSInt BitWidth;
1943       if (FromType->isIntegralType(Context) &&
1944           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1945         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1946         ToSize = Context.getTypeSize(ToType);
1947 
1948         // Are we promoting to an int from a bitfield that fits in an int?
1949         if (BitWidth < ToSize ||
1950             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1951           return To->getKind() == BuiltinType::Int;
1952         }
1953 
1954         // Are we promoting to an unsigned int from an unsigned bitfield
1955         // that fits into an unsigned int?
1956         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1957           return To->getKind() == BuiltinType::UInt;
1958         }
1959 
1960         return false;
1961       }
1962     }
1963   }
1964 
1965   // An rvalue of type bool can be converted to an rvalue of type int,
1966   // with false becoming zero and true becoming one (C++ 4.5p4).
1967   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1968     return true;
1969   }
1970 
1971   return false;
1972 }
1973 
1974 /// IsFloatingPointPromotion - Determines whether the conversion from
1975 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1976 /// returns true and sets PromotedType to the promoted type.
1977 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1978   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1979     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1980       /// An rvalue of type float can be converted to an rvalue of type
1981       /// double. (C++ 4.6p1).
1982       if (FromBuiltin->getKind() == BuiltinType::Float &&
1983           ToBuiltin->getKind() == BuiltinType::Double)
1984         return true;
1985 
1986       // C99 6.3.1.5p1:
1987       //   When a float is promoted to double or long double, or a
1988       //   double is promoted to long double [...].
1989       if (!getLangOpts().CPlusPlus &&
1990           (FromBuiltin->getKind() == BuiltinType::Float ||
1991            FromBuiltin->getKind() == BuiltinType::Double) &&
1992           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
1993            ToBuiltin->getKind() == BuiltinType::Float128))
1994         return true;
1995 
1996       // Half can be promoted to float.
1997       if (!getLangOpts().NativeHalfType &&
1998            FromBuiltin->getKind() == BuiltinType::Half &&
1999           ToBuiltin->getKind() == BuiltinType::Float)
2000         return true;
2001     }
2002 
2003   return false;
2004 }
2005 
2006 /// \brief Determine if a conversion is a complex promotion.
2007 ///
2008 /// A complex promotion is defined as a complex -> complex conversion
2009 /// where the conversion between the underlying real types is a
2010 /// floating-point or integral promotion.
2011 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2012   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2013   if (!FromComplex)
2014     return false;
2015 
2016   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2017   if (!ToComplex)
2018     return false;
2019 
2020   return IsFloatingPointPromotion(FromComplex->getElementType(),
2021                                   ToComplex->getElementType()) ||
2022     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2023                         ToComplex->getElementType());
2024 }
2025 
2026 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2027 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2028 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2029 /// if non-empty, will be a pointer to ToType that may or may not have
2030 /// the right set of qualifiers on its pointee.
2031 ///
2032 static QualType
2033 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2034                                    QualType ToPointee, QualType ToType,
2035                                    ASTContext &Context,
2036                                    bool StripObjCLifetime = false) {
2037   assert((FromPtr->getTypeClass() == Type::Pointer ||
2038           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2039          "Invalid similarly-qualified pointer type");
2040 
2041   /// Conversions to 'id' subsume cv-qualifier conversions.
2042   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2043     return ToType.getUnqualifiedType();
2044 
2045   QualType CanonFromPointee
2046     = Context.getCanonicalType(FromPtr->getPointeeType());
2047   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2048   Qualifiers Quals = CanonFromPointee.getQualifiers();
2049 
2050   if (StripObjCLifetime)
2051     Quals.removeObjCLifetime();
2052 
2053   // Exact qualifier match -> return the pointer type we're converting to.
2054   if (CanonToPointee.getLocalQualifiers() == Quals) {
2055     // ToType is exactly what we need. Return it.
2056     if (!ToType.isNull())
2057       return ToType.getUnqualifiedType();
2058 
2059     // Build a pointer to ToPointee. It has the right qualifiers
2060     // already.
2061     if (isa<ObjCObjectPointerType>(ToType))
2062       return Context.getObjCObjectPointerType(ToPointee);
2063     return Context.getPointerType(ToPointee);
2064   }
2065 
2066   // Just build a canonical type that has the right qualifiers.
2067   QualType QualifiedCanonToPointee
2068     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2069 
2070   if (isa<ObjCObjectPointerType>(ToType))
2071     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2072   return Context.getPointerType(QualifiedCanonToPointee);
2073 }
2074 
2075 static bool isNullPointerConstantForConversion(Expr *Expr,
2076                                                bool InOverloadResolution,
2077                                                ASTContext &Context) {
2078   // Handle value-dependent integral null pointer constants correctly.
2079   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2080   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2081       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2082     return !InOverloadResolution;
2083 
2084   return Expr->isNullPointerConstant(Context,
2085                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2086                                         : Expr::NPC_ValueDependentIsNull);
2087 }
2088 
2089 /// IsPointerConversion - Determines whether the conversion of the
2090 /// expression From, which has the (possibly adjusted) type FromType,
2091 /// can be converted to the type ToType via a pointer conversion (C++
2092 /// 4.10). If so, returns true and places the converted type (that
2093 /// might differ from ToType in its cv-qualifiers at some level) into
2094 /// ConvertedType.
2095 ///
2096 /// This routine also supports conversions to and from block pointers
2097 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2098 /// pointers to interfaces. FIXME: Once we've determined the
2099 /// appropriate overloading rules for Objective-C, we may want to
2100 /// split the Objective-C checks into a different routine; however,
2101 /// GCC seems to consider all of these conversions to be pointer
2102 /// conversions, so for now they live here. IncompatibleObjC will be
2103 /// set if the conversion is an allowed Objective-C conversion that
2104 /// should result in a warning.
2105 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2106                                bool InOverloadResolution,
2107                                QualType& ConvertedType,
2108                                bool &IncompatibleObjC) {
2109   IncompatibleObjC = false;
2110   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2111                               IncompatibleObjC))
2112     return true;
2113 
2114   // Conversion from a null pointer constant to any Objective-C pointer type.
2115   if (ToType->isObjCObjectPointerType() &&
2116       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2117     ConvertedType = ToType;
2118     return true;
2119   }
2120 
2121   // Blocks: Block pointers can be converted to void*.
2122   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2123       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2124     ConvertedType = ToType;
2125     return true;
2126   }
2127   // Blocks: A null pointer constant can be converted to a block
2128   // pointer type.
2129   if (ToType->isBlockPointerType() &&
2130       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2131     ConvertedType = ToType;
2132     return true;
2133   }
2134 
2135   // If the left-hand-side is nullptr_t, the right side can be a null
2136   // pointer constant.
2137   if (ToType->isNullPtrType() &&
2138       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2139     ConvertedType = ToType;
2140     return true;
2141   }
2142 
2143   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2144   if (!ToTypePtr)
2145     return false;
2146 
2147   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2148   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2149     ConvertedType = ToType;
2150     return true;
2151   }
2152 
2153   // Beyond this point, both types need to be pointers
2154   // , including objective-c pointers.
2155   QualType ToPointeeType = ToTypePtr->getPointeeType();
2156   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2157       !getLangOpts().ObjCAutoRefCount) {
2158     ConvertedType = BuildSimilarlyQualifiedPointerType(
2159                                       FromType->getAs<ObjCObjectPointerType>(),
2160                                                        ToPointeeType,
2161                                                        ToType, Context);
2162     return true;
2163   }
2164   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2165   if (!FromTypePtr)
2166     return false;
2167 
2168   QualType FromPointeeType = FromTypePtr->getPointeeType();
2169 
2170   // If the unqualified pointee types are the same, this can't be a
2171   // pointer conversion, so don't do all of the work below.
2172   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2173     return false;
2174 
2175   // An rvalue of type "pointer to cv T," where T is an object type,
2176   // can be converted to an rvalue of type "pointer to cv void" (C++
2177   // 4.10p2).
2178   if (FromPointeeType->isIncompleteOrObjectType() &&
2179       ToPointeeType->isVoidType()) {
2180     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2181                                                        ToPointeeType,
2182                                                        ToType, Context,
2183                                                    /*StripObjCLifetime=*/true);
2184     return true;
2185   }
2186 
2187   // MSVC allows implicit function to void* type conversion.
2188   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2189       ToPointeeType->isVoidType()) {
2190     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2191                                                        ToPointeeType,
2192                                                        ToType, Context);
2193     return true;
2194   }
2195 
2196   // When we're overloading in C, we allow a special kind of pointer
2197   // conversion for compatible-but-not-identical pointee types.
2198   if (!getLangOpts().CPlusPlus &&
2199       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2200     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2201                                                        ToPointeeType,
2202                                                        ToType, Context);
2203     return true;
2204   }
2205 
2206   // C++ [conv.ptr]p3:
2207   //
2208   //   An rvalue of type "pointer to cv D," where D is a class type,
2209   //   can be converted to an rvalue of type "pointer to cv B," where
2210   //   B is a base class (clause 10) of D. If B is an inaccessible
2211   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2212   //   necessitates this conversion is ill-formed. The result of the
2213   //   conversion is a pointer to the base class sub-object of the
2214   //   derived class object. The null pointer value is converted to
2215   //   the null pointer value of the destination type.
2216   //
2217   // Note that we do not check for ambiguity or inaccessibility
2218   // here. That is handled by CheckPointerConversion.
2219   if (getLangOpts().CPlusPlus &&
2220       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2221       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2222       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2223     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2224                                                        ToPointeeType,
2225                                                        ToType, Context);
2226     return true;
2227   }
2228 
2229   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2230       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2231     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2232                                                        ToPointeeType,
2233                                                        ToType, Context);
2234     return true;
2235   }
2236 
2237   return false;
2238 }
2239 
2240 /// \brief Adopt the given qualifiers for the given type.
2241 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2242   Qualifiers TQs = T.getQualifiers();
2243 
2244   // Check whether qualifiers already match.
2245   if (TQs == Qs)
2246     return T;
2247 
2248   if (Qs.compatiblyIncludes(TQs))
2249     return Context.getQualifiedType(T, Qs);
2250 
2251   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2252 }
2253 
2254 /// isObjCPointerConversion - Determines whether this is an
2255 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2256 /// with the same arguments and return values.
2257 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2258                                    QualType& ConvertedType,
2259                                    bool &IncompatibleObjC) {
2260   if (!getLangOpts().ObjC1)
2261     return false;
2262 
2263   // The set of qualifiers on the type we're converting from.
2264   Qualifiers FromQualifiers = FromType.getQualifiers();
2265 
2266   // First, we handle all conversions on ObjC object pointer types.
2267   const ObjCObjectPointerType* ToObjCPtr =
2268     ToType->getAs<ObjCObjectPointerType>();
2269   const ObjCObjectPointerType *FromObjCPtr =
2270     FromType->getAs<ObjCObjectPointerType>();
2271 
2272   if (ToObjCPtr && FromObjCPtr) {
2273     // If the pointee types are the same (ignoring qualifications),
2274     // then this is not a pointer conversion.
2275     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2276                                        FromObjCPtr->getPointeeType()))
2277       return false;
2278 
2279     // Conversion between Objective-C pointers.
2280     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2281       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2282       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2283       if (getLangOpts().CPlusPlus && LHS && RHS &&
2284           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2285                                                 FromObjCPtr->getPointeeType()))
2286         return false;
2287       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2288                                                    ToObjCPtr->getPointeeType(),
2289                                                          ToType, Context);
2290       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2291       return true;
2292     }
2293 
2294     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2295       // Okay: this is some kind of implicit downcast of Objective-C
2296       // interfaces, which is permitted. However, we're going to
2297       // complain about it.
2298       IncompatibleObjC = true;
2299       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2300                                                    ToObjCPtr->getPointeeType(),
2301                                                          ToType, Context);
2302       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2303       return true;
2304     }
2305   }
2306   // Beyond this point, both types need to be C pointers or block pointers.
2307   QualType ToPointeeType;
2308   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2309     ToPointeeType = ToCPtr->getPointeeType();
2310   else if (const BlockPointerType *ToBlockPtr =
2311             ToType->getAs<BlockPointerType>()) {
2312     // Objective C++: We're able to convert from a pointer to any object
2313     // to a block pointer type.
2314     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2315       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2316       return true;
2317     }
2318     ToPointeeType = ToBlockPtr->getPointeeType();
2319   }
2320   else if (FromType->getAs<BlockPointerType>() &&
2321            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2322     // Objective C++: We're able to convert from a block pointer type to a
2323     // pointer to any object.
2324     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2325     return true;
2326   }
2327   else
2328     return false;
2329 
2330   QualType FromPointeeType;
2331   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2332     FromPointeeType = FromCPtr->getPointeeType();
2333   else if (const BlockPointerType *FromBlockPtr =
2334            FromType->getAs<BlockPointerType>())
2335     FromPointeeType = FromBlockPtr->getPointeeType();
2336   else
2337     return false;
2338 
2339   // If we have pointers to pointers, recursively check whether this
2340   // is an Objective-C conversion.
2341   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2342       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2343                               IncompatibleObjC)) {
2344     // We always complain about this conversion.
2345     IncompatibleObjC = true;
2346     ConvertedType = Context.getPointerType(ConvertedType);
2347     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2348     return true;
2349   }
2350   // Allow conversion of pointee being objective-c pointer to another one;
2351   // as in I* to id.
2352   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2353       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2354       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2355                               IncompatibleObjC)) {
2356 
2357     ConvertedType = Context.getPointerType(ConvertedType);
2358     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2359     return true;
2360   }
2361 
2362   // If we have pointers to functions or blocks, check whether the only
2363   // differences in the argument and result types are in Objective-C
2364   // pointer conversions. If so, we permit the conversion (but
2365   // complain about it).
2366   const FunctionProtoType *FromFunctionType
2367     = FromPointeeType->getAs<FunctionProtoType>();
2368   const FunctionProtoType *ToFunctionType
2369     = ToPointeeType->getAs<FunctionProtoType>();
2370   if (FromFunctionType && ToFunctionType) {
2371     // If the function types are exactly the same, this isn't an
2372     // Objective-C pointer conversion.
2373     if (Context.getCanonicalType(FromPointeeType)
2374           == Context.getCanonicalType(ToPointeeType))
2375       return false;
2376 
2377     // Perform the quick checks that will tell us whether these
2378     // function types are obviously different.
2379     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2380         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2381         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2382       return false;
2383 
2384     bool HasObjCConversion = false;
2385     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2386         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2387       // Okay, the types match exactly. Nothing to do.
2388     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2389                                        ToFunctionType->getReturnType(),
2390                                        ConvertedType, IncompatibleObjC)) {
2391       // Okay, we have an Objective-C pointer conversion.
2392       HasObjCConversion = true;
2393     } else {
2394       // Function types are too different. Abort.
2395       return false;
2396     }
2397 
2398     // Check argument types.
2399     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2400          ArgIdx != NumArgs; ++ArgIdx) {
2401       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2402       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2403       if (Context.getCanonicalType(FromArgType)
2404             == Context.getCanonicalType(ToArgType)) {
2405         // Okay, the types match exactly. Nothing to do.
2406       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2407                                          ConvertedType, IncompatibleObjC)) {
2408         // Okay, we have an Objective-C pointer conversion.
2409         HasObjCConversion = true;
2410       } else {
2411         // Argument types are too different. Abort.
2412         return false;
2413       }
2414     }
2415 
2416     if (HasObjCConversion) {
2417       // We had an Objective-C conversion. Allow this pointer
2418       // conversion, but complain about it.
2419       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2420       IncompatibleObjC = true;
2421       return true;
2422     }
2423   }
2424 
2425   return false;
2426 }
2427 
2428 /// \brief Determine whether this is an Objective-C writeback conversion,
2429 /// used for parameter passing when performing automatic reference counting.
2430 ///
2431 /// \param FromType The type we're converting form.
2432 ///
2433 /// \param ToType The type we're converting to.
2434 ///
2435 /// \param ConvertedType The type that will be produced after applying
2436 /// this conversion.
2437 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2438                                      QualType &ConvertedType) {
2439   if (!getLangOpts().ObjCAutoRefCount ||
2440       Context.hasSameUnqualifiedType(FromType, ToType))
2441     return false;
2442 
2443   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2444   QualType ToPointee;
2445   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2446     ToPointee = ToPointer->getPointeeType();
2447   else
2448     return false;
2449 
2450   Qualifiers ToQuals = ToPointee.getQualifiers();
2451   if (!ToPointee->isObjCLifetimeType() ||
2452       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2453       !ToQuals.withoutObjCLifetime().empty())
2454     return false;
2455 
2456   // Argument must be a pointer to __strong to __weak.
2457   QualType FromPointee;
2458   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2459     FromPointee = FromPointer->getPointeeType();
2460   else
2461     return false;
2462 
2463   Qualifiers FromQuals = FromPointee.getQualifiers();
2464   if (!FromPointee->isObjCLifetimeType() ||
2465       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2466        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2467     return false;
2468 
2469   // Make sure that we have compatible qualifiers.
2470   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2471   if (!ToQuals.compatiblyIncludes(FromQuals))
2472     return false;
2473 
2474   // Remove qualifiers from the pointee type we're converting from; they
2475   // aren't used in the compatibility check belong, and we'll be adding back
2476   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2477   FromPointee = FromPointee.getUnqualifiedType();
2478 
2479   // The unqualified form of the pointee types must be compatible.
2480   ToPointee = ToPointee.getUnqualifiedType();
2481   bool IncompatibleObjC;
2482   if (Context.typesAreCompatible(FromPointee, ToPointee))
2483     FromPointee = ToPointee;
2484   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2485                                     IncompatibleObjC))
2486     return false;
2487 
2488   /// \brief Construct the type we're converting to, which is a pointer to
2489   /// __autoreleasing pointee.
2490   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2491   ConvertedType = Context.getPointerType(FromPointee);
2492   return true;
2493 }
2494 
2495 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2496                                     QualType& ConvertedType) {
2497   QualType ToPointeeType;
2498   if (const BlockPointerType *ToBlockPtr =
2499         ToType->getAs<BlockPointerType>())
2500     ToPointeeType = ToBlockPtr->getPointeeType();
2501   else
2502     return false;
2503 
2504   QualType FromPointeeType;
2505   if (const BlockPointerType *FromBlockPtr =
2506       FromType->getAs<BlockPointerType>())
2507     FromPointeeType = FromBlockPtr->getPointeeType();
2508   else
2509     return false;
2510   // We have pointer to blocks, check whether the only
2511   // differences in the argument and result types are in Objective-C
2512   // pointer conversions. If so, we permit the conversion.
2513 
2514   const FunctionProtoType *FromFunctionType
2515     = FromPointeeType->getAs<FunctionProtoType>();
2516   const FunctionProtoType *ToFunctionType
2517     = ToPointeeType->getAs<FunctionProtoType>();
2518 
2519   if (!FromFunctionType || !ToFunctionType)
2520     return false;
2521 
2522   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2523     return true;
2524 
2525   // Perform the quick checks that will tell us whether these
2526   // function types are obviously different.
2527   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2528       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2529     return false;
2530 
2531   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2532   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2533   if (FromEInfo != ToEInfo)
2534     return false;
2535 
2536   bool IncompatibleObjC = false;
2537   if (Context.hasSameType(FromFunctionType->getReturnType(),
2538                           ToFunctionType->getReturnType())) {
2539     // Okay, the types match exactly. Nothing to do.
2540   } else {
2541     QualType RHS = FromFunctionType->getReturnType();
2542     QualType LHS = ToFunctionType->getReturnType();
2543     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2544         !RHS.hasQualifiers() && LHS.hasQualifiers())
2545        LHS = LHS.getUnqualifiedType();
2546 
2547      if (Context.hasSameType(RHS,LHS)) {
2548        // OK exact match.
2549      } else if (isObjCPointerConversion(RHS, LHS,
2550                                         ConvertedType, IncompatibleObjC)) {
2551      if (IncompatibleObjC)
2552        return false;
2553      // Okay, we have an Objective-C pointer conversion.
2554      }
2555      else
2556        return false;
2557    }
2558 
2559    // Check argument types.
2560    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2561         ArgIdx != NumArgs; ++ArgIdx) {
2562      IncompatibleObjC = false;
2563      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2564      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2565      if (Context.hasSameType(FromArgType, ToArgType)) {
2566        // Okay, the types match exactly. Nothing to do.
2567      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2568                                         ConvertedType, IncompatibleObjC)) {
2569        if (IncompatibleObjC)
2570          return false;
2571        // Okay, we have an Objective-C pointer conversion.
2572      } else
2573        // Argument types are too different. Abort.
2574        return false;
2575    }
2576    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2577                                                         ToFunctionType))
2578      return false;
2579 
2580    ConvertedType = ToType;
2581    return true;
2582 }
2583 
2584 enum {
2585   ft_default,
2586   ft_different_class,
2587   ft_parameter_arity,
2588   ft_parameter_mismatch,
2589   ft_return_type,
2590   ft_qualifer_mismatch
2591 };
2592 
2593 /// Attempts to get the FunctionProtoType from a Type. Handles
2594 /// MemberFunctionPointers properly.
2595 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2596   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2597     return FPT;
2598 
2599   if (auto *MPT = FromType->getAs<MemberPointerType>())
2600     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2601 
2602   return nullptr;
2603 }
2604 
2605 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2606 /// function types.  Catches different number of parameter, mismatch in
2607 /// parameter types, and different return types.
2608 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2609                                       QualType FromType, QualType ToType) {
2610   // If either type is not valid, include no extra info.
2611   if (FromType.isNull() || ToType.isNull()) {
2612     PDiag << ft_default;
2613     return;
2614   }
2615 
2616   // Get the function type from the pointers.
2617   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2618     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2619                             *ToMember = ToType->getAs<MemberPointerType>();
2620     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2621       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2622             << QualType(FromMember->getClass(), 0);
2623       return;
2624     }
2625     FromType = FromMember->getPointeeType();
2626     ToType = ToMember->getPointeeType();
2627   }
2628 
2629   if (FromType->isPointerType())
2630     FromType = FromType->getPointeeType();
2631   if (ToType->isPointerType())
2632     ToType = ToType->getPointeeType();
2633 
2634   // Remove references.
2635   FromType = FromType.getNonReferenceType();
2636   ToType = ToType.getNonReferenceType();
2637 
2638   // Don't print extra info for non-specialized template functions.
2639   if (FromType->isInstantiationDependentType() &&
2640       !FromType->getAs<TemplateSpecializationType>()) {
2641     PDiag << ft_default;
2642     return;
2643   }
2644 
2645   // No extra info for same types.
2646   if (Context.hasSameType(FromType, ToType)) {
2647     PDiag << ft_default;
2648     return;
2649   }
2650 
2651   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2652                           *ToFunction = tryGetFunctionProtoType(ToType);
2653 
2654   // Both types need to be function types.
2655   if (!FromFunction || !ToFunction) {
2656     PDiag << ft_default;
2657     return;
2658   }
2659 
2660   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2661     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2662           << FromFunction->getNumParams();
2663     return;
2664   }
2665 
2666   // Handle different parameter types.
2667   unsigned ArgPos;
2668   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2669     PDiag << ft_parameter_mismatch << ArgPos + 1
2670           << ToFunction->getParamType(ArgPos)
2671           << FromFunction->getParamType(ArgPos);
2672     return;
2673   }
2674 
2675   // Handle different return type.
2676   if (!Context.hasSameType(FromFunction->getReturnType(),
2677                            ToFunction->getReturnType())) {
2678     PDiag << ft_return_type << ToFunction->getReturnType()
2679           << FromFunction->getReturnType();
2680     return;
2681   }
2682 
2683   unsigned FromQuals = FromFunction->getTypeQuals(),
2684            ToQuals = ToFunction->getTypeQuals();
2685   if (FromQuals != ToQuals) {
2686     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2687     return;
2688   }
2689 
2690   // Unable to find a difference, so add no extra info.
2691   PDiag << ft_default;
2692 }
2693 
2694 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2695 /// for equality of their argument types. Caller has already checked that
2696 /// they have same number of arguments.  If the parameters are different,
2697 /// ArgPos will have the parameter index of the first different parameter.
2698 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2699                                       const FunctionProtoType *NewType,
2700                                       unsigned *ArgPos) {
2701   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2702                                               N = NewType->param_type_begin(),
2703                                               E = OldType->param_type_end();
2704        O && (O != E); ++O, ++N) {
2705     if (!Context.hasSameType(O->getUnqualifiedType(),
2706                              N->getUnqualifiedType())) {
2707       if (ArgPos)
2708         *ArgPos = O - OldType->param_type_begin();
2709       return false;
2710     }
2711   }
2712   return true;
2713 }
2714 
2715 /// CheckPointerConversion - Check the pointer conversion from the
2716 /// expression From to the type ToType. This routine checks for
2717 /// ambiguous or inaccessible derived-to-base pointer
2718 /// conversions for which IsPointerConversion has already returned
2719 /// true. It returns true and produces a diagnostic if there was an
2720 /// error, or returns false otherwise.
2721 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2722                                   CastKind &Kind,
2723                                   CXXCastPath& BasePath,
2724                                   bool IgnoreBaseAccess,
2725                                   bool Diagnose) {
2726   QualType FromType = From->getType();
2727   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2728 
2729   Kind = CK_BitCast;
2730 
2731   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2732       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2733           Expr::NPCK_ZeroExpression) {
2734     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2735       DiagRuntimeBehavior(From->getExprLoc(), From,
2736                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2737                             << ToType << From->getSourceRange());
2738     else if (!isUnevaluatedContext())
2739       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2740         << ToType << From->getSourceRange();
2741   }
2742   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2743     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2744       QualType FromPointeeType = FromPtrType->getPointeeType(),
2745                ToPointeeType   = ToPtrType->getPointeeType();
2746 
2747       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2748           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2749         // We must have a derived-to-base conversion. Check an
2750         // ambiguous or inaccessible conversion.
2751         unsigned InaccessibleID = 0;
2752         unsigned AmbigiousID = 0;
2753         if (Diagnose) {
2754           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2755           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2756         }
2757         if (CheckDerivedToBaseConversion(
2758                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2759                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2760                 &BasePath, IgnoreBaseAccess))
2761           return true;
2762 
2763         // The conversion was successful.
2764         Kind = CK_DerivedToBase;
2765       }
2766 
2767       if (Diagnose && !IsCStyleOrFunctionalCast &&
2768           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2769         assert(getLangOpts().MSVCCompat &&
2770                "this should only be possible with MSVCCompat!");
2771         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2772             << From->getSourceRange();
2773       }
2774     }
2775   } else if (const ObjCObjectPointerType *ToPtrType =
2776                ToType->getAs<ObjCObjectPointerType>()) {
2777     if (const ObjCObjectPointerType *FromPtrType =
2778           FromType->getAs<ObjCObjectPointerType>()) {
2779       // Objective-C++ conversions are always okay.
2780       // FIXME: We should have a different class of conversions for the
2781       // Objective-C++ implicit conversions.
2782       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2783         return false;
2784     } else if (FromType->isBlockPointerType()) {
2785       Kind = CK_BlockPointerToObjCPointerCast;
2786     } else {
2787       Kind = CK_CPointerToObjCPointerCast;
2788     }
2789   } else if (ToType->isBlockPointerType()) {
2790     if (!FromType->isBlockPointerType())
2791       Kind = CK_AnyPointerToBlockPointerCast;
2792   }
2793 
2794   // We shouldn't fall into this case unless it's valid for other
2795   // reasons.
2796   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2797     Kind = CK_NullToPointer;
2798 
2799   return false;
2800 }
2801 
2802 /// IsMemberPointerConversion - Determines whether the conversion of the
2803 /// expression From, which has the (possibly adjusted) type FromType, can be
2804 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2805 /// If so, returns true and places the converted type (that might differ from
2806 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2807 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2808                                      QualType ToType,
2809                                      bool InOverloadResolution,
2810                                      QualType &ConvertedType) {
2811   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2812   if (!ToTypePtr)
2813     return false;
2814 
2815   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2816   if (From->isNullPointerConstant(Context,
2817                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2818                                         : Expr::NPC_ValueDependentIsNull)) {
2819     ConvertedType = ToType;
2820     return true;
2821   }
2822 
2823   // Otherwise, both types have to be member pointers.
2824   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2825   if (!FromTypePtr)
2826     return false;
2827 
2828   // A pointer to member of B can be converted to a pointer to member of D,
2829   // where D is derived from B (C++ 4.11p2).
2830   QualType FromClass(FromTypePtr->getClass(), 0);
2831   QualType ToClass(ToTypePtr->getClass(), 0);
2832 
2833   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2834       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2835     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2836                                                  ToClass.getTypePtr());
2837     return true;
2838   }
2839 
2840   return false;
2841 }
2842 
2843 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2844 /// expression From to the type ToType. This routine checks for ambiguous or
2845 /// virtual or inaccessible base-to-derived member pointer conversions
2846 /// for which IsMemberPointerConversion has already returned true. It returns
2847 /// true and produces a diagnostic if there was an error, or returns false
2848 /// otherwise.
2849 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2850                                         CastKind &Kind,
2851                                         CXXCastPath &BasePath,
2852                                         bool IgnoreBaseAccess) {
2853   QualType FromType = From->getType();
2854   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2855   if (!FromPtrType) {
2856     // This must be a null pointer to member pointer conversion
2857     assert(From->isNullPointerConstant(Context,
2858                                        Expr::NPC_ValueDependentIsNull) &&
2859            "Expr must be null pointer constant!");
2860     Kind = CK_NullToMemberPointer;
2861     return false;
2862   }
2863 
2864   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2865   assert(ToPtrType && "No member pointer cast has a target type "
2866                       "that is not a member pointer.");
2867 
2868   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2869   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2870 
2871   // FIXME: What about dependent types?
2872   assert(FromClass->isRecordType() && "Pointer into non-class.");
2873   assert(ToClass->isRecordType() && "Pointer into non-class.");
2874 
2875   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2876                      /*DetectVirtual=*/true);
2877   bool DerivationOkay =
2878       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2879   assert(DerivationOkay &&
2880          "Should not have been called if derivation isn't OK.");
2881   (void)DerivationOkay;
2882 
2883   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2884                                   getUnqualifiedType())) {
2885     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2886     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2887       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2888     return true;
2889   }
2890 
2891   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2892     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2893       << FromClass << ToClass << QualType(VBase, 0)
2894       << From->getSourceRange();
2895     return true;
2896   }
2897 
2898   if (!IgnoreBaseAccess)
2899     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2900                          Paths.front(),
2901                          diag::err_downcast_from_inaccessible_base);
2902 
2903   // Must be a base to derived member conversion.
2904   BuildBasePathArray(Paths, BasePath);
2905   Kind = CK_BaseToDerivedMemberPointer;
2906   return false;
2907 }
2908 
2909 /// Determine whether the lifetime conversion between the two given
2910 /// qualifiers sets is nontrivial.
2911 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2912                                                Qualifiers ToQuals) {
2913   // Converting anything to const __unsafe_unretained is trivial.
2914   if (ToQuals.hasConst() &&
2915       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2916     return false;
2917 
2918   return true;
2919 }
2920 
2921 /// IsQualificationConversion - Determines whether the conversion from
2922 /// an rvalue of type FromType to ToType is a qualification conversion
2923 /// (C++ 4.4).
2924 ///
2925 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2926 /// when the qualification conversion involves a change in the Objective-C
2927 /// object lifetime.
2928 bool
2929 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2930                                 bool CStyle, bool &ObjCLifetimeConversion) {
2931   FromType = Context.getCanonicalType(FromType);
2932   ToType = Context.getCanonicalType(ToType);
2933   ObjCLifetimeConversion = false;
2934 
2935   // If FromType and ToType are the same type, this is not a
2936   // qualification conversion.
2937   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2938     return false;
2939 
2940   // (C++ 4.4p4):
2941   //   A conversion can add cv-qualifiers at levels other than the first
2942   //   in multi-level pointers, subject to the following rules: [...]
2943   bool PreviousToQualsIncludeConst = true;
2944   bool UnwrappedAnyPointer = false;
2945   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2946     // Within each iteration of the loop, we check the qualifiers to
2947     // determine if this still looks like a qualification
2948     // conversion. Then, if all is well, we unwrap one more level of
2949     // pointers or pointers-to-members and do it all again
2950     // until there are no more pointers or pointers-to-members left to
2951     // unwrap.
2952     UnwrappedAnyPointer = true;
2953 
2954     Qualifiers FromQuals = FromType.getQualifiers();
2955     Qualifiers ToQuals = ToType.getQualifiers();
2956 
2957     // Ignore __unaligned qualifier if this type is void.
2958     if (ToType.getUnqualifiedType()->isVoidType())
2959       FromQuals.removeUnaligned();
2960 
2961     // Objective-C ARC:
2962     //   Check Objective-C lifetime conversions.
2963     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2964         UnwrappedAnyPointer) {
2965       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2966         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2967           ObjCLifetimeConversion = true;
2968         FromQuals.removeObjCLifetime();
2969         ToQuals.removeObjCLifetime();
2970       } else {
2971         // Qualification conversions cannot cast between different
2972         // Objective-C lifetime qualifiers.
2973         return false;
2974       }
2975     }
2976 
2977     // Allow addition/removal of GC attributes but not changing GC attributes.
2978     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2979         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2980       FromQuals.removeObjCGCAttr();
2981       ToQuals.removeObjCGCAttr();
2982     }
2983 
2984     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2985     //      2,j, and similarly for volatile.
2986     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2987       return false;
2988 
2989     //   -- if the cv 1,j and cv 2,j are different, then const is in
2990     //      every cv for 0 < k < j.
2991     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2992         && !PreviousToQualsIncludeConst)
2993       return false;
2994 
2995     // Keep track of whether all prior cv-qualifiers in the "to" type
2996     // include const.
2997     PreviousToQualsIncludeConst
2998       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2999   }
3000 
3001   // We are left with FromType and ToType being the pointee types
3002   // after unwrapping the original FromType and ToType the same number
3003   // of types. If we unwrapped any pointers, and if FromType and
3004   // ToType have the same unqualified type (since we checked
3005   // qualifiers above), then this is a qualification conversion.
3006   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3007 }
3008 
3009 /// \brief - Determine whether this is a conversion from a scalar type to an
3010 /// atomic type.
3011 ///
3012 /// If successful, updates \c SCS's second and third steps in the conversion
3013 /// sequence to finish the conversion.
3014 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3015                                 bool InOverloadResolution,
3016                                 StandardConversionSequence &SCS,
3017                                 bool CStyle) {
3018   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3019   if (!ToAtomic)
3020     return false;
3021 
3022   StandardConversionSequence InnerSCS;
3023   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3024                             InOverloadResolution, InnerSCS,
3025                             CStyle, /*AllowObjCWritebackConversion=*/false))
3026     return false;
3027 
3028   SCS.Second = InnerSCS.Second;
3029   SCS.setToType(1, InnerSCS.getToType(1));
3030   SCS.Third = InnerSCS.Third;
3031   SCS.QualificationIncludesObjCLifetime
3032     = InnerSCS.QualificationIncludesObjCLifetime;
3033   SCS.setToType(2, InnerSCS.getToType(2));
3034   return true;
3035 }
3036 
3037 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3038                                               CXXConstructorDecl *Constructor,
3039                                               QualType Type) {
3040   const FunctionProtoType *CtorType =
3041       Constructor->getType()->getAs<FunctionProtoType>();
3042   if (CtorType->getNumParams() > 0) {
3043     QualType FirstArg = CtorType->getParamType(0);
3044     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3045       return true;
3046   }
3047   return false;
3048 }
3049 
3050 static OverloadingResult
3051 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3052                                        CXXRecordDecl *To,
3053                                        UserDefinedConversionSequence &User,
3054                                        OverloadCandidateSet &CandidateSet,
3055                                        bool AllowExplicit) {
3056   for (auto *D : S.LookupConstructors(To)) {
3057     auto Info = getConstructorInfo(D);
3058     if (!Info)
3059       continue;
3060 
3061     bool Usable = !Info.Constructor->isInvalidDecl() &&
3062                   S.isInitListConstructor(Info.Constructor) &&
3063                   (AllowExplicit || !Info.Constructor->isExplicit());
3064     if (Usable) {
3065       // If the first argument is (a reference to) the target type,
3066       // suppress conversions.
3067       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3068           S.Context, Info.Constructor, ToType);
3069       if (Info.ConstructorTmpl)
3070         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3071                                        /*ExplicitArgs*/ nullptr, From,
3072                                        CandidateSet, SuppressUserConversions);
3073       else
3074         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3075                                CandidateSet, SuppressUserConversions);
3076     }
3077   }
3078 
3079   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3080 
3081   OverloadCandidateSet::iterator Best;
3082   switch (auto Result =
3083             CandidateSet.BestViableFunction(S, From->getLocStart(),
3084                                             Best, true)) {
3085   case OR_Deleted:
3086   case OR_Success: {
3087     // Record the standard conversion we used and the conversion function.
3088     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3089     QualType ThisType = Constructor->getThisType(S.Context);
3090     // Initializer lists don't have conversions as such.
3091     User.Before.setAsIdentityConversion();
3092     User.HadMultipleCandidates = HadMultipleCandidates;
3093     User.ConversionFunction = Constructor;
3094     User.FoundConversionFunction = Best->FoundDecl;
3095     User.After.setAsIdentityConversion();
3096     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3097     User.After.setAllToTypes(ToType);
3098     return Result;
3099   }
3100 
3101   case OR_No_Viable_Function:
3102     return OR_No_Viable_Function;
3103   case OR_Ambiguous:
3104     return OR_Ambiguous;
3105   }
3106 
3107   llvm_unreachable("Invalid OverloadResult!");
3108 }
3109 
3110 /// Determines whether there is a user-defined conversion sequence
3111 /// (C++ [over.ics.user]) that converts expression From to the type
3112 /// ToType. If such a conversion exists, User will contain the
3113 /// user-defined conversion sequence that performs such a conversion
3114 /// and this routine will return true. Otherwise, this routine returns
3115 /// false and User is unspecified.
3116 ///
3117 /// \param AllowExplicit  true if the conversion should consider C++0x
3118 /// "explicit" conversion functions as well as non-explicit conversion
3119 /// functions (C++0x [class.conv.fct]p2).
3120 ///
3121 /// \param AllowObjCConversionOnExplicit true if the conversion should
3122 /// allow an extra Objective-C pointer conversion on uses of explicit
3123 /// constructors. Requires \c AllowExplicit to also be set.
3124 static OverloadingResult
3125 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3126                         UserDefinedConversionSequence &User,
3127                         OverloadCandidateSet &CandidateSet,
3128                         bool AllowExplicit,
3129                         bool AllowObjCConversionOnExplicit) {
3130   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3131 
3132   // Whether we will only visit constructors.
3133   bool ConstructorsOnly = false;
3134 
3135   // If the type we are conversion to is a class type, enumerate its
3136   // constructors.
3137   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3138     // C++ [over.match.ctor]p1:
3139     //   When objects of class type are direct-initialized (8.5), or
3140     //   copy-initialized from an expression of the same or a
3141     //   derived class type (8.5), overload resolution selects the
3142     //   constructor. [...] For copy-initialization, the candidate
3143     //   functions are all the converting constructors (12.3.1) of
3144     //   that class. The argument list is the expression-list within
3145     //   the parentheses of the initializer.
3146     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3147         (From->getType()->getAs<RecordType>() &&
3148          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3149       ConstructorsOnly = true;
3150 
3151     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3152       // We're not going to find any constructors.
3153     } else if (CXXRecordDecl *ToRecordDecl
3154                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3155 
3156       Expr **Args = &From;
3157       unsigned NumArgs = 1;
3158       bool ListInitializing = false;
3159       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3160         // But first, see if there is an init-list-constructor that will work.
3161         OverloadingResult Result = IsInitializerListConstructorConversion(
3162             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3163         if (Result != OR_No_Viable_Function)
3164           return Result;
3165         // Never mind.
3166         CandidateSet.clear();
3167 
3168         // If we're list-initializing, we pass the individual elements as
3169         // arguments, not the entire list.
3170         Args = InitList->getInits();
3171         NumArgs = InitList->getNumInits();
3172         ListInitializing = true;
3173       }
3174 
3175       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3176         auto Info = getConstructorInfo(D);
3177         if (!Info)
3178           continue;
3179 
3180         bool Usable = !Info.Constructor->isInvalidDecl();
3181         if (ListInitializing)
3182           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3183         else
3184           Usable = Usable &&
3185                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3186         if (Usable) {
3187           bool SuppressUserConversions = !ConstructorsOnly;
3188           if (SuppressUserConversions && ListInitializing) {
3189             SuppressUserConversions = false;
3190             if (NumArgs == 1) {
3191               // If the first argument is (a reference to) the target type,
3192               // suppress conversions.
3193               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3194                   S.Context, Info.Constructor, ToType);
3195             }
3196           }
3197           if (Info.ConstructorTmpl)
3198             S.AddTemplateOverloadCandidate(
3199                 Info.ConstructorTmpl, Info.FoundDecl,
3200                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3201                 CandidateSet, SuppressUserConversions);
3202           else
3203             // Allow one user-defined conversion when user specifies a
3204             // From->ToType conversion via an static cast (c-style, etc).
3205             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3206                                    llvm::makeArrayRef(Args, NumArgs),
3207                                    CandidateSet, SuppressUserConversions);
3208         }
3209       }
3210     }
3211   }
3212 
3213   // Enumerate conversion functions, if we're allowed to.
3214   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3215   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3216     // No conversion functions from incomplete types.
3217   } else if (const RecordType *FromRecordType
3218                                    = From->getType()->getAs<RecordType>()) {
3219     if (CXXRecordDecl *FromRecordDecl
3220          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3221       // Add all of the conversion functions as candidates.
3222       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3223       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3224         DeclAccessPair FoundDecl = I.getPair();
3225         NamedDecl *D = FoundDecl.getDecl();
3226         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3227         if (isa<UsingShadowDecl>(D))
3228           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3229 
3230         CXXConversionDecl *Conv;
3231         FunctionTemplateDecl *ConvTemplate;
3232         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3233           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3234         else
3235           Conv = cast<CXXConversionDecl>(D);
3236 
3237         if (AllowExplicit || !Conv->isExplicit()) {
3238           if (ConvTemplate)
3239             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3240                                              ActingContext, From, ToType,
3241                                              CandidateSet,
3242                                              AllowObjCConversionOnExplicit);
3243           else
3244             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3245                                      From, ToType, CandidateSet,
3246                                      AllowObjCConversionOnExplicit);
3247         }
3248       }
3249     }
3250   }
3251 
3252   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3253 
3254   OverloadCandidateSet::iterator Best;
3255   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3256                                                         Best, true)) {
3257   case OR_Success:
3258   case OR_Deleted:
3259     // Record the standard conversion we used and the conversion function.
3260     if (CXXConstructorDecl *Constructor
3261           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3262       // C++ [over.ics.user]p1:
3263       //   If the user-defined conversion is specified by a
3264       //   constructor (12.3.1), the initial standard conversion
3265       //   sequence converts the source type to the type required by
3266       //   the argument of the constructor.
3267       //
3268       QualType ThisType = Constructor->getThisType(S.Context);
3269       if (isa<InitListExpr>(From)) {
3270         // Initializer lists don't have conversions as such.
3271         User.Before.setAsIdentityConversion();
3272       } else {
3273         if (Best->Conversions[0].isEllipsis())
3274           User.EllipsisConversion = true;
3275         else {
3276           User.Before = Best->Conversions[0].Standard;
3277           User.EllipsisConversion = false;
3278         }
3279       }
3280       User.HadMultipleCandidates = HadMultipleCandidates;
3281       User.ConversionFunction = Constructor;
3282       User.FoundConversionFunction = Best->FoundDecl;
3283       User.After.setAsIdentityConversion();
3284       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3285       User.After.setAllToTypes(ToType);
3286       return Result;
3287     }
3288     if (CXXConversionDecl *Conversion
3289                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3290       // C++ [over.ics.user]p1:
3291       //
3292       //   [...] If the user-defined conversion is specified by a
3293       //   conversion function (12.3.2), the initial standard
3294       //   conversion sequence converts the source type to the
3295       //   implicit object parameter of the conversion function.
3296       User.Before = Best->Conversions[0].Standard;
3297       User.HadMultipleCandidates = HadMultipleCandidates;
3298       User.ConversionFunction = Conversion;
3299       User.FoundConversionFunction = Best->FoundDecl;
3300       User.EllipsisConversion = false;
3301 
3302       // C++ [over.ics.user]p2:
3303       //   The second standard conversion sequence converts the
3304       //   result of the user-defined conversion to the target type
3305       //   for the sequence. Since an implicit conversion sequence
3306       //   is an initialization, the special rules for
3307       //   initialization by user-defined conversion apply when
3308       //   selecting the best user-defined conversion for a
3309       //   user-defined conversion sequence (see 13.3.3 and
3310       //   13.3.3.1).
3311       User.After = Best->FinalConversion;
3312       return Result;
3313     }
3314     llvm_unreachable("Not a constructor or conversion function?");
3315 
3316   case OR_No_Viable_Function:
3317     return OR_No_Viable_Function;
3318 
3319   case OR_Ambiguous:
3320     return OR_Ambiguous;
3321   }
3322 
3323   llvm_unreachable("Invalid OverloadResult!");
3324 }
3325 
3326 bool
3327 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3328   ImplicitConversionSequence ICS;
3329   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3330                                     OverloadCandidateSet::CSK_Normal);
3331   OverloadingResult OvResult =
3332     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3333                             CandidateSet, false, false);
3334   if (OvResult == OR_Ambiguous)
3335     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3336         << From->getType() << ToType << From->getSourceRange();
3337   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3338     if (!RequireCompleteType(From->getLocStart(), ToType,
3339                              diag::err_typecheck_nonviable_condition_incomplete,
3340                              From->getType(), From->getSourceRange()))
3341       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3342           << false << From->getType() << From->getSourceRange() << ToType;
3343   } else
3344     return false;
3345   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3346   return true;
3347 }
3348 
3349 /// \brief Compare the user-defined conversion functions or constructors
3350 /// of two user-defined conversion sequences to determine whether any ordering
3351 /// is possible.
3352 static ImplicitConversionSequence::CompareKind
3353 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3354                            FunctionDecl *Function2) {
3355   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3356     return ImplicitConversionSequence::Indistinguishable;
3357 
3358   // Objective-C++:
3359   //   If both conversion functions are implicitly-declared conversions from
3360   //   a lambda closure type to a function pointer and a block pointer,
3361   //   respectively, always prefer the conversion to a function pointer,
3362   //   because the function pointer is more lightweight and is more likely
3363   //   to keep code working.
3364   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3365   if (!Conv1)
3366     return ImplicitConversionSequence::Indistinguishable;
3367 
3368   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3369   if (!Conv2)
3370     return ImplicitConversionSequence::Indistinguishable;
3371 
3372   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3373     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3374     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3375     if (Block1 != Block2)
3376       return Block1 ? ImplicitConversionSequence::Worse
3377                     : ImplicitConversionSequence::Better;
3378   }
3379 
3380   return ImplicitConversionSequence::Indistinguishable;
3381 }
3382 
3383 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3384     const ImplicitConversionSequence &ICS) {
3385   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3386          (ICS.isUserDefined() &&
3387           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3388 }
3389 
3390 /// CompareImplicitConversionSequences - Compare two implicit
3391 /// conversion sequences to determine whether one is better than the
3392 /// other or if they are indistinguishable (C++ 13.3.3.2).
3393 static ImplicitConversionSequence::CompareKind
3394 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3395                                    const ImplicitConversionSequence& ICS1,
3396                                    const ImplicitConversionSequence& ICS2)
3397 {
3398   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3399   // conversion sequences (as defined in 13.3.3.1)
3400   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3401   //      conversion sequence than a user-defined conversion sequence or
3402   //      an ellipsis conversion sequence, and
3403   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3404   //      conversion sequence than an ellipsis conversion sequence
3405   //      (13.3.3.1.3).
3406   //
3407   // C++0x [over.best.ics]p10:
3408   //   For the purpose of ranking implicit conversion sequences as
3409   //   described in 13.3.3.2, the ambiguous conversion sequence is
3410   //   treated as a user-defined sequence that is indistinguishable
3411   //   from any other user-defined conversion sequence.
3412 
3413   // String literal to 'char *' conversion has been deprecated in C++03. It has
3414   // been removed from C++11. We still accept this conversion, if it happens at
3415   // the best viable function. Otherwise, this conversion is considered worse
3416   // than ellipsis conversion. Consider this as an extension; this is not in the
3417   // standard. For example:
3418   //
3419   // int &f(...);    // #1
3420   // void f(char*);  // #2
3421   // void g() { int &r = f("foo"); }
3422   //
3423   // In C++03, we pick #2 as the best viable function.
3424   // In C++11, we pick #1 as the best viable function, because ellipsis
3425   // conversion is better than string-literal to char* conversion (since there
3426   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3427   // convert arguments, #2 would be the best viable function in C++11.
3428   // If the best viable function has this conversion, a warning will be issued
3429   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3430 
3431   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3432       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3433       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3434     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3435                ? ImplicitConversionSequence::Worse
3436                : ImplicitConversionSequence::Better;
3437 
3438   if (ICS1.getKindRank() < ICS2.getKindRank())
3439     return ImplicitConversionSequence::Better;
3440   if (ICS2.getKindRank() < ICS1.getKindRank())
3441     return ImplicitConversionSequence::Worse;
3442 
3443   // The following checks require both conversion sequences to be of
3444   // the same kind.
3445   if (ICS1.getKind() != ICS2.getKind())
3446     return ImplicitConversionSequence::Indistinguishable;
3447 
3448   ImplicitConversionSequence::CompareKind Result =
3449       ImplicitConversionSequence::Indistinguishable;
3450 
3451   // Two implicit conversion sequences of the same form are
3452   // indistinguishable conversion sequences unless one of the
3453   // following rules apply: (C++ 13.3.3.2p3):
3454 
3455   // List-initialization sequence L1 is a better conversion sequence than
3456   // list-initialization sequence L2 if:
3457   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3458   //   if not that,
3459   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3460   //   and N1 is smaller than N2.,
3461   // even if one of the other rules in this paragraph would otherwise apply.
3462   if (!ICS1.isBad()) {
3463     if (ICS1.isStdInitializerListElement() &&
3464         !ICS2.isStdInitializerListElement())
3465       return ImplicitConversionSequence::Better;
3466     if (!ICS1.isStdInitializerListElement() &&
3467         ICS2.isStdInitializerListElement())
3468       return ImplicitConversionSequence::Worse;
3469   }
3470 
3471   if (ICS1.isStandard())
3472     // Standard conversion sequence S1 is a better conversion sequence than
3473     // standard conversion sequence S2 if [...]
3474     Result = CompareStandardConversionSequences(S, Loc,
3475                                                 ICS1.Standard, ICS2.Standard);
3476   else if (ICS1.isUserDefined()) {
3477     // User-defined conversion sequence U1 is a better conversion
3478     // sequence than another user-defined conversion sequence U2 if
3479     // they contain the same user-defined conversion function or
3480     // constructor and if the second standard conversion sequence of
3481     // U1 is better than the second standard conversion sequence of
3482     // U2 (C++ 13.3.3.2p3).
3483     if (ICS1.UserDefined.ConversionFunction ==
3484           ICS2.UserDefined.ConversionFunction)
3485       Result = CompareStandardConversionSequences(S, Loc,
3486                                                   ICS1.UserDefined.After,
3487                                                   ICS2.UserDefined.After);
3488     else
3489       Result = compareConversionFunctions(S,
3490                                           ICS1.UserDefined.ConversionFunction,
3491                                           ICS2.UserDefined.ConversionFunction);
3492   }
3493 
3494   return Result;
3495 }
3496 
3497 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3498   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3499     Qualifiers Quals;
3500     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3501     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3502   }
3503 
3504   return Context.hasSameUnqualifiedType(T1, T2);
3505 }
3506 
3507 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3508 // determine if one is a proper subset of the other.
3509 static ImplicitConversionSequence::CompareKind
3510 compareStandardConversionSubsets(ASTContext &Context,
3511                                  const StandardConversionSequence& SCS1,
3512                                  const StandardConversionSequence& SCS2) {
3513   ImplicitConversionSequence::CompareKind Result
3514     = ImplicitConversionSequence::Indistinguishable;
3515 
3516   // the identity conversion sequence is considered to be a subsequence of
3517   // any non-identity conversion sequence
3518   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3519     return ImplicitConversionSequence::Better;
3520   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3521     return ImplicitConversionSequence::Worse;
3522 
3523   if (SCS1.Second != SCS2.Second) {
3524     if (SCS1.Second == ICK_Identity)
3525       Result = ImplicitConversionSequence::Better;
3526     else if (SCS2.Second == ICK_Identity)
3527       Result = ImplicitConversionSequence::Worse;
3528     else
3529       return ImplicitConversionSequence::Indistinguishable;
3530   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3531     return ImplicitConversionSequence::Indistinguishable;
3532 
3533   if (SCS1.Third == SCS2.Third) {
3534     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3535                              : ImplicitConversionSequence::Indistinguishable;
3536   }
3537 
3538   if (SCS1.Third == ICK_Identity)
3539     return Result == ImplicitConversionSequence::Worse
3540              ? ImplicitConversionSequence::Indistinguishable
3541              : ImplicitConversionSequence::Better;
3542 
3543   if (SCS2.Third == ICK_Identity)
3544     return Result == ImplicitConversionSequence::Better
3545              ? ImplicitConversionSequence::Indistinguishable
3546              : ImplicitConversionSequence::Worse;
3547 
3548   return ImplicitConversionSequence::Indistinguishable;
3549 }
3550 
3551 /// \brief Determine whether one of the given reference bindings is better
3552 /// than the other based on what kind of bindings they are.
3553 static bool
3554 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3555                              const StandardConversionSequence &SCS2) {
3556   // C++0x [over.ics.rank]p3b4:
3557   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3558   //      implicit object parameter of a non-static member function declared
3559   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3560   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3561   //      lvalue reference to a function lvalue and S2 binds an rvalue
3562   //      reference*.
3563   //
3564   // FIXME: Rvalue references. We're going rogue with the above edits,
3565   // because the semantics in the current C++0x working paper (N3225 at the
3566   // time of this writing) break the standard definition of std::forward
3567   // and std::reference_wrapper when dealing with references to functions.
3568   // Proposed wording changes submitted to CWG for consideration.
3569   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3570       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3571     return false;
3572 
3573   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3574           SCS2.IsLvalueReference) ||
3575          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3576           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3577 }
3578 
3579 /// CompareStandardConversionSequences - Compare two standard
3580 /// conversion sequences to determine whether one is better than the
3581 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3582 static ImplicitConversionSequence::CompareKind
3583 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3584                                    const StandardConversionSequence& SCS1,
3585                                    const StandardConversionSequence& SCS2)
3586 {
3587   // Standard conversion sequence S1 is a better conversion sequence
3588   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3589 
3590   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3591   //     sequences in the canonical form defined by 13.3.3.1.1,
3592   //     excluding any Lvalue Transformation; the identity conversion
3593   //     sequence is considered to be a subsequence of any
3594   //     non-identity conversion sequence) or, if not that,
3595   if (ImplicitConversionSequence::CompareKind CK
3596         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3597     return CK;
3598 
3599   //  -- the rank of S1 is better than the rank of S2 (by the rules
3600   //     defined below), or, if not that,
3601   ImplicitConversionRank Rank1 = SCS1.getRank();
3602   ImplicitConversionRank Rank2 = SCS2.getRank();
3603   if (Rank1 < Rank2)
3604     return ImplicitConversionSequence::Better;
3605   else if (Rank2 < Rank1)
3606     return ImplicitConversionSequence::Worse;
3607 
3608   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3609   // are indistinguishable unless one of the following rules
3610   // applies:
3611 
3612   //   A conversion that is not a conversion of a pointer, or
3613   //   pointer to member, to bool is better than another conversion
3614   //   that is such a conversion.
3615   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3616     return SCS2.isPointerConversionToBool()
3617              ? ImplicitConversionSequence::Better
3618              : ImplicitConversionSequence::Worse;
3619 
3620   // C++ [over.ics.rank]p4b2:
3621   //
3622   //   If class B is derived directly or indirectly from class A,
3623   //   conversion of B* to A* is better than conversion of B* to
3624   //   void*, and conversion of A* to void* is better than conversion
3625   //   of B* to void*.
3626   bool SCS1ConvertsToVoid
3627     = SCS1.isPointerConversionToVoidPointer(S.Context);
3628   bool SCS2ConvertsToVoid
3629     = SCS2.isPointerConversionToVoidPointer(S.Context);
3630   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3631     // Exactly one of the conversion sequences is a conversion to
3632     // a void pointer; it's the worse conversion.
3633     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3634                               : ImplicitConversionSequence::Worse;
3635   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3636     // Neither conversion sequence converts to a void pointer; compare
3637     // their derived-to-base conversions.
3638     if (ImplicitConversionSequence::CompareKind DerivedCK
3639           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3640       return DerivedCK;
3641   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3642              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3643     // Both conversion sequences are conversions to void
3644     // pointers. Compare the source types to determine if there's an
3645     // inheritance relationship in their sources.
3646     QualType FromType1 = SCS1.getFromType();
3647     QualType FromType2 = SCS2.getFromType();
3648 
3649     // Adjust the types we're converting from via the array-to-pointer
3650     // conversion, if we need to.
3651     if (SCS1.First == ICK_Array_To_Pointer)
3652       FromType1 = S.Context.getArrayDecayedType(FromType1);
3653     if (SCS2.First == ICK_Array_To_Pointer)
3654       FromType2 = S.Context.getArrayDecayedType(FromType2);
3655 
3656     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3657     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3658 
3659     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3660       return ImplicitConversionSequence::Better;
3661     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3662       return ImplicitConversionSequence::Worse;
3663 
3664     // Objective-C++: If one interface is more specific than the
3665     // other, it is the better one.
3666     const ObjCObjectPointerType* FromObjCPtr1
3667       = FromType1->getAs<ObjCObjectPointerType>();
3668     const ObjCObjectPointerType* FromObjCPtr2
3669       = FromType2->getAs<ObjCObjectPointerType>();
3670     if (FromObjCPtr1 && FromObjCPtr2) {
3671       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3672                                                           FromObjCPtr2);
3673       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3674                                                            FromObjCPtr1);
3675       if (AssignLeft != AssignRight) {
3676         return AssignLeft? ImplicitConversionSequence::Better
3677                          : ImplicitConversionSequence::Worse;
3678       }
3679     }
3680   }
3681 
3682   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3683   // bullet 3).
3684   if (ImplicitConversionSequence::CompareKind QualCK
3685         = CompareQualificationConversions(S, SCS1, SCS2))
3686     return QualCK;
3687 
3688   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3689     // Check for a better reference binding based on the kind of bindings.
3690     if (isBetterReferenceBindingKind(SCS1, SCS2))
3691       return ImplicitConversionSequence::Better;
3692     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3693       return ImplicitConversionSequence::Worse;
3694 
3695     // C++ [over.ics.rank]p3b4:
3696     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3697     //      which the references refer are the same type except for
3698     //      top-level cv-qualifiers, and the type to which the reference
3699     //      initialized by S2 refers is more cv-qualified than the type
3700     //      to which the reference initialized by S1 refers.
3701     QualType T1 = SCS1.getToType(2);
3702     QualType T2 = SCS2.getToType(2);
3703     T1 = S.Context.getCanonicalType(T1);
3704     T2 = S.Context.getCanonicalType(T2);
3705     Qualifiers T1Quals, T2Quals;
3706     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3707     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3708     if (UnqualT1 == UnqualT2) {
3709       // Objective-C++ ARC: If the references refer to objects with different
3710       // lifetimes, prefer bindings that don't change lifetime.
3711       if (SCS1.ObjCLifetimeConversionBinding !=
3712                                           SCS2.ObjCLifetimeConversionBinding) {
3713         return SCS1.ObjCLifetimeConversionBinding
3714                                            ? ImplicitConversionSequence::Worse
3715                                            : ImplicitConversionSequence::Better;
3716       }
3717 
3718       // If the type is an array type, promote the element qualifiers to the
3719       // type for comparison.
3720       if (isa<ArrayType>(T1) && T1Quals)
3721         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3722       if (isa<ArrayType>(T2) && T2Quals)
3723         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3724       if (T2.isMoreQualifiedThan(T1))
3725         return ImplicitConversionSequence::Better;
3726       else if (T1.isMoreQualifiedThan(T2))
3727         return ImplicitConversionSequence::Worse;
3728     }
3729   }
3730 
3731   // In Microsoft mode, prefer an integral conversion to a
3732   // floating-to-integral conversion if the integral conversion
3733   // is between types of the same size.
3734   // For example:
3735   // void f(float);
3736   // void f(int);
3737   // int main {
3738   //    long a;
3739   //    f(a);
3740   // }
3741   // Here, MSVC will call f(int) instead of generating a compile error
3742   // as clang will do in standard mode.
3743   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3744       SCS2.Second == ICK_Floating_Integral &&
3745       S.Context.getTypeSize(SCS1.getFromType()) ==
3746           S.Context.getTypeSize(SCS1.getToType(2)))
3747     return ImplicitConversionSequence::Better;
3748 
3749   return ImplicitConversionSequence::Indistinguishable;
3750 }
3751 
3752 /// CompareQualificationConversions - Compares two standard conversion
3753 /// sequences to determine whether they can be ranked based on their
3754 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3755 static ImplicitConversionSequence::CompareKind
3756 CompareQualificationConversions(Sema &S,
3757                                 const StandardConversionSequence& SCS1,
3758                                 const StandardConversionSequence& SCS2) {
3759   // C++ 13.3.3.2p3:
3760   //  -- S1 and S2 differ only in their qualification conversion and
3761   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3762   //     cv-qualification signature of type T1 is a proper subset of
3763   //     the cv-qualification signature of type T2, and S1 is not the
3764   //     deprecated string literal array-to-pointer conversion (4.2).
3765   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3766       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3767     return ImplicitConversionSequence::Indistinguishable;
3768 
3769   // FIXME: the example in the standard doesn't use a qualification
3770   // conversion (!)
3771   QualType T1 = SCS1.getToType(2);
3772   QualType T2 = SCS2.getToType(2);
3773   T1 = S.Context.getCanonicalType(T1);
3774   T2 = S.Context.getCanonicalType(T2);
3775   Qualifiers T1Quals, T2Quals;
3776   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3777   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3778 
3779   // If the types are the same, we won't learn anything by unwrapped
3780   // them.
3781   if (UnqualT1 == UnqualT2)
3782     return ImplicitConversionSequence::Indistinguishable;
3783 
3784   // If the type is an array type, promote the element qualifiers to the type
3785   // for comparison.
3786   if (isa<ArrayType>(T1) && T1Quals)
3787     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3788   if (isa<ArrayType>(T2) && T2Quals)
3789     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3790 
3791   ImplicitConversionSequence::CompareKind Result
3792     = ImplicitConversionSequence::Indistinguishable;
3793 
3794   // Objective-C++ ARC:
3795   //   Prefer qualification conversions not involving a change in lifetime
3796   //   to qualification conversions that do not change lifetime.
3797   if (SCS1.QualificationIncludesObjCLifetime !=
3798                                       SCS2.QualificationIncludesObjCLifetime) {
3799     Result = SCS1.QualificationIncludesObjCLifetime
3800                ? ImplicitConversionSequence::Worse
3801                : ImplicitConversionSequence::Better;
3802   }
3803 
3804   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3805     // Within each iteration of the loop, we check the qualifiers to
3806     // determine if this still looks like a qualification
3807     // conversion. Then, if all is well, we unwrap one more level of
3808     // pointers or pointers-to-members and do it all again
3809     // until there are no more pointers or pointers-to-members left
3810     // to unwrap. This essentially mimics what
3811     // IsQualificationConversion does, but here we're checking for a
3812     // strict subset of qualifiers.
3813     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3814       // The qualifiers are the same, so this doesn't tell us anything
3815       // about how the sequences rank.
3816       ;
3817     else if (T2.isMoreQualifiedThan(T1)) {
3818       // T1 has fewer qualifiers, so it could be the better sequence.
3819       if (Result == ImplicitConversionSequence::Worse)
3820         // Neither has qualifiers that are a subset of the other's
3821         // qualifiers.
3822         return ImplicitConversionSequence::Indistinguishable;
3823 
3824       Result = ImplicitConversionSequence::Better;
3825     } else if (T1.isMoreQualifiedThan(T2)) {
3826       // T2 has fewer qualifiers, so it could be the better sequence.
3827       if (Result == ImplicitConversionSequence::Better)
3828         // Neither has qualifiers that are a subset of the other's
3829         // qualifiers.
3830         return ImplicitConversionSequence::Indistinguishable;
3831 
3832       Result = ImplicitConversionSequence::Worse;
3833     } else {
3834       // Qualifiers are disjoint.
3835       return ImplicitConversionSequence::Indistinguishable;
3836     }
3837 
3838     // If the types after this point are equivalent, we're done.
3839     if (S.Context.hasSameUnqualifiedType(T1, T2))
3840       break;
3841   }
3842 
3843   // Check that the winning standard conversion sequence isn't using
3844   // the deprecated string literal array to pointer conversion.
3845   switch (Result) {
3846   case ImplicitConversionSequence::Better:
3847     if (SCS1.DeprecatedStringLiteralToCharPtr)
3848       Result = ImplicitConversionSequence::Indistinguishable;
3849     break;
3850 
3851   case ImplicitConversionSequence::Indistinguishable:
3852     break;
3853 
3854   case ImplicitConversionSequence::Worse:
3855     if (SCS2.DeprecatedStringLiteralToCharPtr)
3856       Result = ImplicitConversionSequence::Indistinguishable;
3857     break;
3858   }
3859 
3860   return Result;
3861 }
3862 
3863 /// CompareDerivedToBaseConversions - Compares two standard conversion
3864 /// sequences to determine whether they can be ranked based on their
3865 /// various kinds of derived-to-base conversions (C++
3866 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3867 /// conversions between Objective-C interface types.
3868 static ImplicitConversionSequence::CompareKind
3869 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3870                                 const StandardConversionSequence& SCS1,
3871                                 const StandardConversionSequence& SCS2) {
3872   QualType FromType1 = SCS1.getFromType();
3873   QualType ToType1 = SCS1.getToType(1);
3874   QualType FromType2 = SCS2.getFromType();
3875   QualType ToType2 = SCS2.getToType(1);
3876 
3877   // Adjust the types we're converting from via the array-to-pointer
3878   // conversion, if we need to.
3879   if (SCS1.First == ICK_Array_To_Pointer)
3880     FromType1 = S.Context.getArrayDecayedType(FromType1);
3881   if (SCS2.First == ICK_Array_To_Pointer)
3882     FromType2 = S.Context.getArrayDecayedType(FromType2);
3883 
3884   // Canonicalize all of the types.
3885   FromType1 = S.Context.getCanonicalType(FromType1);
3886   ToType1 = S.Context.getCanonicalType(ToType1);
3887   FromType2 = S.Context.getCanonicalType(FromType2);
3888   ToType2 = S.Context.getCanonicalType(ToType2);
3889 
3890   // C++ [over.ics.rank]p4b3:
3891   //
3892   //   If class B is derived directly or indirectly from class A and
3893   //   class C is derived directly or indirectly from B,
3894   //
3895   // Compare based on pointer conversions.
3896   if (SCS1.Second == ICK_Pointer_Conversion &&
3897       SCS2.Second == ICK_Pointer_Conversion &&
3898       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3899       FromType1->isPointerType() && FromType2->isPointerType() &&
3900       ToType1->isPointerType() && ToType2->isPointerType()) {
3901     QualType FromPointee1
3902       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3903     QualType ToPointee1
3904       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3905     QualType FromPointee2
3906       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3907     QualType ToPointee2
3908       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3909 
3910     //   -- conversion of C* to B* is better than conversion of C* to A*,
3911     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3912       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3913         return ImplicitConversionSequence::Better;
3914       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3915         return ImplicitConversionSequence::Worse;
3916     }
3917 
3918     //   -- conversion of B* to A* is better than conversion of C* to A*,
3919     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3920       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3921         return ImplicitConversionSequence::Better;
3922       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3923         return ImplicitConversionSequence::Worse;
3924     }
3925   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3926              SCS2.Second == ICK_Pointer_Conversion) {
3927     const ObjCObjectPointerType *FromPtr1
3928       = FromType1->getAs<ObjCObjectPointerType>();
3929     const ObjCObjectPointerType *FromPtr2
3930       = FromType2->getAs<ObjCObjectPointerType>();
3931     const ObjCObjectPointerType *ToPtr1
3932       = ToType1->getAs<ObjCObjectPointerType>();
3933     const ObjCObjectPointerType *ToPtr2
3934       = ToType2->getAs<ObjCObjectPointerType>();
3935 
3936     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3937       // Apply the same conversion ranking rules for Objective-C pointer types
3938       // that we do for C++ pointers to class types. However, we employ the
3939       // Objective-C pseudo-subtyping relationship used for assignment of
3940       // Objective-C pointer types.
3941       bool FromAssignLeft
3942         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3943       bool FromAssignRight
3944         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3945       bool ToAssignLeft
3946         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3947       bool ToAssignRight
3948         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3949 
3950       // A conversion to an a non-id object pointer type or qualified 'id'
3951       // type is better than a conversion to 'id'.
3952       if (ToPtr1->isObjCIdType() &&
3953           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3954         return ImplicitConversionSequence::Worse;
3955       if (ToPtr2->isObjCIdType() &&
3956           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3957         return ImplicitConversionSequence::Better;
3958 
3959       // A conversion to a non-id object pointer type is better than a
3960       // conversion to a qualified 'id' type
3961       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3962         return ImplicitConversionSequence::Worse;
3963       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3964         return ImplicitConversionSequence::Better;
3965 
3966       // A conversion to an a non-Class object pointer type or qualified 'Class'
3967       // type is better than a conversion to 'Class'.
3968       if (ToPtr1->isObjCClassType() &&
3969           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3970         return ImplicitConversionSequence::Worse;
3971       if (ToPtr2->isObjCClassType() &&
3972           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3973         return ImplicitConversionSequence::Better;
3974 
3975       // A conversion to a non-Class object pointer type is better than a
3976       // conversion to a qualified 'Class' type.
3977       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3978         return ImplicitConversionSequence::Worse;
3979       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3980         return ImplicitConversionSequence::Better;
3981 
3982       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3983       if (S.Context.hasSameType(FromType1, FromType2) &&
3984           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3985           (ToAssignLeft != ToAssignRight))
3986         return ToAssignLeft? ImplicitConversionSequence::Worse
3987                            : ImplicitConversionSequence::Better;
3988 
3989       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3990       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3991           (FromAssignLeft != FromAssignRight))
3992         return FromAssignLeft? ImplicitConversionSequence::Better
3993         : ImplicitConversionSequence::Worse;
3994     }
3995   }
3996 
3997   // Ranking of member-pointer types.
3998   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3999       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4000       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4001     const MemberPointerType * FromMemPointer1 =
4002                                         FromType1->getAs<MemberPointerType>();
4003     const MemberPointerType * ToMemPointer1 =
4004                                           ToType1->getAs<MemberPointerType>();
4005     const MemberPointerType * FromMemPointer2 =
4006                                           FromType2->getAs<MemberPointerType>();
4007     const MemberPointerType * ToMemPointer2 =
4008                                           ToType2->getAs<MemberPointerType>();
4009     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4010     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4011     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4012     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4013     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4014     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4015     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4016     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4017     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4018     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4019       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4020         return ImplicitConversionSequence::Worse;
4021       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4022         return ImplicitConversionSequence::Better;
4023     }
4024     // conversion of B::* to C::* is better than conversion of A::* to C::*
4025     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4026       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4027         return ImplicitConversionSequence::Better;
4028       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4029         return ImplicitConversionSequence::Worse;
4030     }
4031   }
4032 
4033   if (SCS1.Second == ICK_Derived_To_Base) {
4034     //   -- conversion of C to B is better than conversion of C to A,
4035     //   -- binding of an expression of type C to a reference of type
4036     //      B& is better than binding an expression of type C to a
4037     //      reference of type A&,
4038     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4039         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4040       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4041         return ImplicitConversionSequence::Better;
4042       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4043         return ImplicitConversionSequence::Worse;
4044     }
4045 
4046     //   -- conversion of B to A is better than conversion of C to A.
4047     //   -- binding of an expression of type B to a reference of type
4048     //      A& is better than binding an expression of type C to a
4049     //      reference of type A&,
4050     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4051         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4052       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4053         return ImplicitConversionSequence::Better;
4054       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4055         return ImplicitConversionSequence::Worse;
4056     }
4057   }
4058 
4059   return ImplicitConversionSequence::Indistinguishable;
4060 }
4061 
4062 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4063 /// C++ class.
4064 static bool isTypeValid(QualType T) {
4065   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4066     return !Record->isInvalidDecl();
4067 
4068   return true;
4069 }
4070 
4071 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4072 /// determine whether they are reference-related,
4073 /// reference-compatible, reference-compatible with added
4074 /// qualification, or incompatible, for use in C++ initialization by
4075 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4076 /// type, and the first type (T1) is the pointee type of the reference
4077 /// type being initialized.
4078 Sema::ReferenceCompareResult
4079 Sema::CompareReferenceRelationship(SourceLocation Loc,
4080                                    QualType OrigT1, QualType OrigT2,
4081                                    bool &DerivedToBase,
4082                                    bool &ObjCConversion,
4083                                    bool &ObjCLifetimeConversion) {
4084   assert(!OrigT1->isReferenceType() &&
4085     "T1 must be the pointee type of the reference type");
4086   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4087 
4088   QualType T1 = Context.getCanonicalType(OrigT1);
4089   QualType T2 = Context.getCanonicalType(OrigT2);
4090   Qualifiers T1Quals, T2Quals;
4091   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4092   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4093 
4094   // C++ [dcl.init.ref]p4:
4095   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4096   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4097   //   T1 is a base class of T2.
4098   DerivedToBase = false;
4099   ObjCConversion = false;
4100   ObjCLifetimeConversion = false;
4101   if (UnqualT1 == UnqualT2) {
4102     // Nothing to do.
4103   } else if (isCompleteType(Loc, OrigT2) &&
4104              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4105              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4106     DerivedToBase = true;
4107   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4108            UnqualT2->isObjCObjectOrInterfaceType() &&
4109            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4110     ObjCConversion = true;
4111   else
4112     return Ref_Incompatible;
4113 
4114   // At this point, we know that T1 and T2 are reference-related (at
4115   // least).
4116 
4117   // If the type is an array type, promote the element qualifiers to the type
4118   // for comparison.
4119   if (isa<ArrayType>(T1) && T1Quals)
4120     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4121   if (isa<ArrayType>(T2) && T2Quals)
4122     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4123 
4124   // C++ [dcl.init.ref]p4:
4125   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4126   //   reference-related to T2 and cv1 is the same cv-qualification
4127   //   as, or greater cv-qualification than, cv2. For purposes of
4128   //   overload resolution, cases for which cv1 is greater
4129   //   cv-qualification than cv2 are identified as
4130   //   reference-compatible with added qualification (see 13.3.3.2).
4131   //
4132   // Note that we also require equivalence of Objective-C GC and address-space
4133   // qualifiers when performing these computations, so that e.g., an int in
4134   // address space 1 is not reference-compatible with an int in address
4135   // space 2.
4136   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4137       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4138     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4139       ObjCLifetimeConversion = true;
4140 
4141     T1Quals.removeObjCLifetime();
4142     T2Quals.removeObjCLifetime();
4143   }
4144 
4145   // MS compiler ignores __unaligned qualifier for references; do the same.
4146   T1Quals.removeUnaligned();
4147   T2Quals.removeUnaligned();
4148 
4149   if (T1Quals == T2Quals)
4150     return Ref_Compatible;
4151   else if (T1Quals.compatiblyIncludes(T2Quals))
4152     return Ref_Compatible_With_Added_Qualification;
4153   else
4154     return Ref_Related;
4155 }
4156 
4157 /// \brief Look for a user-defined conversion to an value reference-compatible
4158 ///        with DeclType. Return true if something definite is found.
4159 static bool
4160 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4161                          QualType DeclType, SourceLocation DeclLoc,
4162                          Expr *Init, QualType T2, bool AllowRvalues,
4163                          bool AllowExplicit) {
4164   assert(T2->isRecordType() && "Can only find conversions of record types.");
4165   CXXRecordDecl *T2RecordDecl
4166     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4167 
4168   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4169   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4170   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4171     NamedDecl *D = *I;
4172     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4173     if (isa<UsingShadowDecl>(D))
4174       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4175 
4176     FunctionTemplateDecl *ConvTemplate
4177       = dyn_cast<FunctionTemplateDecl>(D);
4178     CXXConversionDecl *Conv;
4179     if (ConvTemplate)
4180       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4181     else
4182       Conv = cast<CXXConversionDecl>(D);
4183 
4184     // If this is an explicit conversion, and we're not allowed to consider
4185     // explicit conversions, skip it.
4186     if (!AllowExplicit && Conv->isExplicit())
4187       continue;
4188 
4189     if (AllowRvalues) {
4190       bool DerivedToBase = false;
4191       bool ObjCConversion = false;
4192       bool ObjCLifetimeConversion = false;
4193 
4194       // If we are initializing an rvalue reference, don't permit conversion
4195       // functions that return lvalues.
4196       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4197         const ReferenceType *RefType
4198           = Conv->getConversionType()->getAs<LValueReferenceType>();
4199         if (RefType && !RefType->getPointeeType()->isFunctionType())
4200           continue;
4201       }
4202 
4203       if (!ConvTemplate &&
4204           S.CompareReferenceRelationship(
4205             DeclLoc,
4206             Conv->getConversionType().getNonReferenceType()
4207               .getUnqualifiedType(),
4208             DeclType.getNonReferenceType().getUnqualifiedType(),
4209             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4210           Sema::Ref_Incompatible)
4211         continue;
4212     } else {
4213       // If the conversion function doesn't return a reference type,
4214       // it can't be considered for this conversion. An rvalue reference
4215       // is only acceptable if its referencee is a function type.
4216 
4217       const ReferenceType *RefType =
4218         Conv->getConversionType()->getAs<ReferenceType>();
4219       if (!RefType ||
4220           (!RefType->isLValueReferenceType() &&
4221            !RefType->getPointeeType()->isFunctionType()))
4222         continue;
4223     }
4224 
4225     if (ConvTemplate)
4226       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4227                                        Init, DeclType, CandidateSet,
4228                                        /*AllowObjCConversionOnExplicit=*/false);
4229     else
4230       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4231                                DeclType, CandidateSet,
4232                                /*AllowObjCConversionOnExplicit=*/false);
4233   }
4234 
4235   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4236 
4237   OverloadCandidateSet::iterator Best;
4238   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4239   case OR_Success:
4240     // C++ [over.ics.ref]p1:
4241     //
4242     //   [...] If the parameter binds directly to the result of
4243     //   applying a conversion function to the argument
4244     //   expression, the implicit conversion sequence is a
4245     //   user-defined conversion sequence (13.3.3.1.2), with the
4246     //   second standard conversion sequence either an identity
4247     //   conversion or, if the conversion function returns an
4248     //   entity of a type that is a derived class of the parameter
4249     //   type, a derived-to-base Conversion.
4250     if (!Best->FinalConversion.DirectBinding)
4251       return false;
4252 
4253     ICS.setUserDefined();
4254     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4255     ICS.UserDefined.After = Best->FinalConversion;
4256     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4257     ICS.UserDefined.ConversionFunction = Best->Function;
4258     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4259     ICS.UserDefined.EllipsisConversion = false;
4260     assert(ICS.UserDefined.After.ReferenceBinding &&
4261            ICS.UserDefined.After.DirectBinding &&
4262            "Expected a direct reference binding!");
4263     return true;
4264 
4265   case OR_Ambiguous:
4266     ICS.setAmbiguous();
4267     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4268          Cand != CandidateSet.end(); ++Cand)
4269       if (Cand->Viable)
4270         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4271     return true;
4272 
4273   case OR_No_Viable_Function:
4274   case OR_Deleted:
4275     // There was no suitable conversion, or we found a deleted
4276     // conversion; continue with other checks.
4277     return false;
4278   }
4279 
4280   llvm_unreachable("Invalid OverloadResult!");
4281 }
4282 
4283 /// \brief Compute an implicit conversion sequence for reference
4284 /// initialization.
4285 static ImplicitConversionSequence
4286 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4287                  SourceLocation DeclLoc,
4288                  bool SuppressUserConversions,
4289                  bool AllowExplicit) {
4290   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4291 
4292   // Most paths end in a failed conversion.
4293   ImplicitConversionSequence ICS;
4294   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4295 
4296   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4297   QualType T2 = Init->getType();
4298 
4299   // If the initializer is the address of an overloaded function, try
4300   // to resolve the overloaded function. If all goes well, T2 is the
4301   // type of the resulting function.
4302   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4303     DeclAccessPair Found;
4304     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4305                                                                 false, Found))
4306       T2 = Fn->getType();
4307   }
4308 
4309   // Compute some basic properties of the types and the initializer.
4310   bool isRValRef = DeclType->isRValueReferenceType();
4311   bool DerivedToBase = false;
4312   bool ObjCConversion = false;
4313   bool ObjCLifetimeConversion = false;
4314   Expr::Classification InitCategory = Init->Classify(S.Context);
4315   Sema::ReferenceCompareResult RefRelationship
4316     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4317                                      ObjCConversion, ObjCLifetimeConversion);
4318 
4319 
4320   // C++0x [dcl.init.ref]p5:
4321   //   A reference to type "cv1 T1" is initialized by an expression
4322   //   of type "cv2 T2" as follows:
4323 
4324   //     -- If reference is an lvalue reference and the initializer expression
4325   if (!isRValRef) {
4326     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4327     //        reference-compatible with "cv2 T2," or
4328     //
4329     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4330     if (InitCategory.isLValue() &&
4331         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4332       // C++ [over.ics.ref]p1:
4333       //   When a parameter of reference type binds directly (8.5.3)
4334       //   to an argument expression, the implicit conversion sequence
4335       //   is the identity conversion, unless the argument expression
4336       //   has a type that is a derived class of the parameter type,
4337       //   in which case the implicit conversion sequence is a
4338       //   derived-to-base Conversion (13.3.3.1).
4339       ICS.setStandard();
4340       ICS.Standard.First = ICK_Identity;
4341       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4342                          : ObjCConversion? ICK_Compatible_Conversion
4343                          : ICK_Identity;
4344       ICS.Standard.Third = ICK_Identity;
4345       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4346       ICS.Standard.setToType(0, T2);
4347       ICS.Standard.setToType(1, T1);
4348       ICS.Standard.setToType(2, T1);
4349       ICS.Standard.ReferenceBinding = true;
4350       ICS.Standard.DirectBinding = true;
4351       ICS.Standard.IsLvalueReference = !isRValRef;
4352       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4353       ICS.Standard.BindsToRvalue = false;
4354       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4355       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4356       ICS.Standard.CopyConstructor = nullptr;
4357       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4358 
4359       // Nothing more to do: the inaccessibility/ambiguity check for
4360       // derived-to-base conversions is suppressed when we're
4361       // computing the implicit conversion sequence (C++
4362       // [over.best.ics]p2).
4363       return ICS;
4364     }
4365 
4366     //       -- has a class type (i.e., T2 is a class type), where T1 is
4367     //          not reference-related to T2, and can be implicitly
4368     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4369     //          is reference-compatible with "cv3 T3" 92) (this
4370     //          conversion is selected by enumerating the applicable
4371     //          conversion functions (13.3.1.6) and choosing the best
4372     //          one through overload resolution (13.3)),
4373     if (!SuppressUserConversions && T2->isRecordType() &&
4374         S.isCompleteType(DeclLoc, T2) &&
4375         RefRelationship == Sema::Ref_Incompatible) {
4376       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4377                                    Init, T2, /*AllowRvalues=*/false,
4378                                    AllowExplicit))
4379         return ICS;
4380     }
4381   }
4382 
4383   //     -- Otherwise, the reference shall be an lvalue reference to a
4384   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4385   //        shall be an rvalue reference.
4386   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4387     return ICS;
4388 
4389   //       -- If the initializer expression
4390   //
4391   //            -- is an xvalue, class prvalue, array prvalue or function
4392   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4393   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4394       (InitCategory.isXValue() ||
4395       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4396       (InitCategory.isLValue() && T2->isFunctionType()))) {
4397     ICS.setStandard();
4398     ICS.Standard.First = ICK_Identity;
4399     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4400                       : ObjCConversion? ICK_Compatible_Conversion
4401                       : ICK_Identity;
4402     ICS.Standard.Third = ICK_Identity;
4403     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4404     ICS.Standard.setToType(0, T2);
4405     ICS.Standard.setToType(1, T1);
4406     ICS.Standard.setToType(2, T1);
4407     ICS.Standard.ReferenceBinding = true;
4408     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4409     // binding unless we're binding to a class prvalue.
4410     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4411     // allow the use of rvalue references in C++98/03 for the benefit of
4412     // standard library implementors; therefore, we need the xvalue check here.
4413     ICS.Standard.DirectBinding =
4414       S.getLangOpts().CPlusPlus11 ||
4415       !(InitCategory.isPRValue() || T2->isRecordType());
4416     ICS.Standard.IsLvalueReference = !isRValRef;
4417     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4418     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4419     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4420     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4421     ICS.Standard.CopyConstructor = nullptr;
4422     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4423     return ICS;
4424   }
4425 
4426   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4427   //               reference-related to T2, and can be implicitly converted to
4428   //               an xvalue, class prvalue, or function lvalue of type
4429   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4430   //               "cv3 T3",
4431   //
4432   //          then the reference is bound to the value of the initializer
4433   //          expression in the first case and to the result of the conversion
4434   //          in the second case (or, in either case, to an appropriate base
4435   //          class subobject).
4436   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4437       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4438       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4439                                Init, T2, /*AllowRvalues=*/true,
4440                                AllowExplicit)) {
4441     // In the second case, if the reference is an rvalue reference
4442     // and the second standard conversion sequence of the
4443     // user-defined conversion sequence includes an lvalue-to-rvalue
4444     // conversion, the program is ill-formed.
4445     if (ICS.isUserDefined() && isRValRef &&
4446         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4447       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4448 
4449     return ICS;
4450   }
4451 
4452   // A temporary of function type cannot be created; don't even try.
4453   if (T1->isFunctionType())
4454     return ICS;
4455 
4456   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4457   //          initialized from the initializer expression using the
4458   //          rules for a non-reference copy initialization (8.5). The
4459   //          reference is then bound to the temporary. If T1 is
4460   //          reference-related to T2, cv1 must be the same
4461   //          cv-qualification as, or greater cv-qualification than,
4462   //          cv2; otherwise, the program is ill-formed.
4463   if (RefRelationship == Sema::Ref_Related) {
4464     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4465     // we would be reference-compatible or reference-compatible with
4466     // added qualification. But that wasn't the case, so the reference
4467     // initialization fails.
4468     //
4469     // Note that we only want to check address spaces and cvr-qualifiers here.
4470     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4471     Qualifiers T1Quals = T1.getQualifiers();
4472     Qualifiers T2Quals = T2.getQualifiers();
4473     T1Quals.removeObjCGCAttr();
4474     T1Quals.removeObjCLifetime();
4475     T2Quals.removeObjCGCAttr();
4476     T2Quals.removeObjCLifetime();
4477     // MS compiler ignores __unaligned qualifier for references; do the same.
4478     T1Quals.removeUnaligned();
4479     T2Quals.removeUnaligned();
4480     if (!T1Quals.compatiblyIncludes(T2Quals))
4481       return ICS;
4482   }
4483 
4484   // If at least one of the types is a class type, the types are not
4485   // related, and we aren't allowed any user conversions, the
4486   // reference binding fails. This case is important for breaking
4487   // recursion, since TryImplicitConversion below will attempt to
4488   // create a temporary through the use of a copy constructor.
4489   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4490       (T1->isRecordType() || T2->isRecordType()))
4491     return ICS;
4492 
4493   // If T1 is reference-related to T2 and the reference is an rvalue
4494   // reference, the initializer expression shall not be an lvalue.
4495   if (RefRelationship >= Sema::Ref_Related &&
4496       isRValRef && Init->Classify(S.Context).isLValue())
4497     return ICS;
4498 
4499   // C++ [over.ics.ref]p2:
4500   //   When a parameter of reference type is not bound directly to
4501   //   an argument expression, the conversion sequence is the one
4502   //   required to convert the argument expression to the
4503   //   underlying type of the reference according to
4504   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4505   //   to copy-initializing a temporary of the underlying type with
4506   //   the argument expression. Any difference in top-level
4507   //   cv-qualification is subsumed by the initialization itself
4508   //   and does not constitute a conversion.
4509   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4510                               /*AllowExplicit=*/false,
4511                               /*InOverloadResolution=*/false,
4512                               /*CStyle=*/false,
4513                               /*AllowObjCWritebackConversion=*/false,
4514                               /*AllowObjCConversionOnExplicit=*/false);
4515 
4516   // Of course, that's still a reference binding.
4517   if (ICS.isStandard()) {
4518     ICS.Standard.ReferenceBinding = true;
4519     ICS.Standard.IsLvalueReference = !isRValRef;
4520     ICS.Standard.BindsToFunctionLvalue = false;
4521     ICS.Standard.BindsToRvalue = true;
4522     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4523     ICS.Standard.ObjCLifetimeConversionBinding = false;
4524   } else if (ICS.isUserDefined()) {
4525     const ReferenceType *LValRefType =
4526         ICS.UserDefined.ConversionFunction->getReturnType()
4527             ->getAs<LValueReferenceType>();
4528 
4529     // C++ [over.ics.ref]p3:
4530     //   Except for an implicit object parameter, for which see 13.3.1, a
4531     //   standard conversion sequence cannot be formed if it requires [...]
4532     //   binding an rvalue reference to an lvalue other than a function
4533     //   lvalue.
4534     // Note that the function case is not possible here.
4535     if (DeclType->isRValueReferenceType() && LValRefType) {
4536       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4537       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4538       // reference to an rvalue!
4539       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4540       return ICS;
4541     }
4542 
4543     ICS.UserDefined.After.ReferenceBinding = true;
4544     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4545     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4546     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4547     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4548     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4549   }
4550 
4551   return ICS;
4552 }
4553 
4554 static ImplicitConversionSequence
4555 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4556                       bool SuppressUserConversions,
4557                       bool InOverloadResolution,
4558                       bool AllowObjCWritebackConversion,
4559                       bool AllowExplicit = false);
4560 
4561 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4562 /// initializer list From.
4563 static ImplicitConversionSequence
4564 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4565                   bool SuppressUserConversions,
4566                   bool InOverloadResolution,
4567                   bool AllowObjCWritebackConversion) {
4568   // C++11 [over.ics.list]p1:
4569   //   When an argument is an initializer list, it is not an expression and
4570   //   special rules apply for converting it to a parameter type.
4571 
4572   ImplicitConversionSequence Result;
4573   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4574 
4575   // We need a complete type for what follows. Incomplete types can never be
4576   // initialized from init lists.
4577   if (!S.isCompleteType(From->getLocStart(), ToType))
4578     return Result;
4579 
4580   // Per DR1467:
4581   //   If the parameter type is a class X and the initializer list has a single
4582   //   element of type cv U, where U is X or a class derived from X, the
4583   //   implicit conversion sequence is the one required to convert the element
4584   //   to the parameter type.
4585   //
4586   //   Otherwise, if the parameter type is a character array [... ]
4587   //   and the initializer list has a single element that is an
4588   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4589   //   implicit conversion sequence is the identity conversion.
4590   if (From->getNumInits() == 1) {
4591     if (ToType->isRecordType()) {
4592       QualType InitType = From->getInit(0)->getType();
4593       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4594           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4595         return TryCopyInitialization(S, From->getInit(0), ToType,
4596                                      SuppressUserConversions,
4597                                      InOverloadResolution,
4598                                      AllowObjCWritebackConversion);
4599     }
4600     // FIXME: Check the other conditions here: array of character type,
4601     // initializer is a string literal.
4602     if (ToType->isArrayType()) {
4603       InitializedEntity Entity =
4604         InitializedEntity::InitializeParameter(S.Context, ToType,
4605                                                /*Consumed=*/false);
4606       if (S.CanPerformCopyInitialization(Entity, From)) {
4607         Result.setStandard();
4608         Result.Standard.setAsIdentityConversion();
4609         Result.Standard.setFromType(ToType);
4610         Result.Standard.setAllToTypes(ToType);
4611         return Result;
4612       }
4613     }
4614   }
4615 
4616   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4617   // C++11 [over.ics.list]p2:
4618   //   If the parameter type is std::initializer_list<X> or "array of X" and
4619   //   all the elements can be implicitly converted to X, the implicit
4620   //   conversion sequence is the worst conversion necessary to convert an
4621   //   element of the list to X.
4622   //
4623   // C++14 [over.ics.list]p3:
4624   //   Otherwise, if the parameter type is "array of N X", if the initializer
4625   //   list has exactly N elements or if it has fewer than N elements and X is
4626   //   default-constructible, and if all the elements of the initializer list
4627   //   can be implicitly converted to X, the implicit conversion sequence is
4628   //   the worst conversion necessary to convert an element of the list to X.
4629   //
4630   // FIXME: We're missing a lot of these checks.
4631   bool toStdInitializerList = false;
4632   QualType X;
4633   if (ToType->isArrayType())
4634     X = S.Context.getAsArrayType(ToType)->getElementType();
4635   else
4636     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4637   if (!X.isNull()) {
4638     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4639       Expr *Init = From->getInit(i);
4640       ImplicitConversionSequence ICS =
4641           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4642                                 InOverloadResolution,
4643                                 AllowObjCWritebackConversion);
4644       // If a single element isn't convertible, fail.
4645       if (ICS.isBad()) {
4646         Result = ICS;
4647         break;
4648       }
4649       // Otherwise, look for the worst conversion.
4650       if (Result.isBad() ||
4651           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4652                                              Result) ==
4653               ImplicitConversionSequence::Worse)
4654         Result = ICS;
4655     }
4656 
4657     // For an empty list, we won't have computed any conversion sequence.
4658     // Introduce the identity conversion sequence.
4659     if (From->getNumInits() == 0) {
4660       Result.setStandard();
4661       Result.Standard.setAsIdentityConversion();
4662       Result.Standard.setFromType(ToType);
4663       Result.Standard.setAllToTypes(ToType);
4664     }
4665 
4666     Result.setStdInitializerListElement(toStdInitializerList);
4667     return Result;
4668   }
4669 
4670   // C++14 [over.ics.list]p4:
4671   // C++11 [over.ics.list]p3:
4672   //   Otherwise, if the parameter is a non-aggregate class X and overload
4673   //   resolution chooses a single best constructor [...] the implicit
4674   //   conversion sequence is a user-defined conversion sequence. If multiple
4675   //   constructors are viable but none is better than the others, the
4676   //   implicit conversion sequence is a user-defined conversion sequence.
4677   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4678     // This function can deal with initializer lists.
4679     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4680                                     /*AllowExplicit=*/false,
4681                                     InOverloadResolution, /*CStyle=*/false,
4682                                     AllowObjCWritebackConversion,
4683                                     /*AllowObjCConversionOnExplicit=*/false);
4684   }
4685 
4686   // C++14 [over.ics.list]p5:
4687   // C++11 [over.ics.list]p4:
4688   //   Otherwise, if the parameter has an aggregate type which can be
4689   //   initialized from the initializer list [...] the implicit conversion
4690   //   sequence is a user-defined conversion sequence.
4691   if (ToType->isAggregateType()) {
4692     // Type is an aggregate, argument is an init list. At this point it comes
4693     // down to checking whether the initialization works.
4694     // FIXME: Find out whether this parameter is consumed or not.
4695     InitializedEntity Entity =
4696         InitializedEntity::InitializeParameter(S.Context, ToType,
4697                                                /*Consumed=*/false);
4698     if (S.CanPerformCopyInitialization(Entity, From)) {
4699       Result.setUserDefined();
4700       Result.UserDefined.Before.setAsIdentityConversion();
4701       // Initializer lists don't have a type.
4702       Result.UserDefined.Before.setFromType(QualType());
4703       Result.UserDefined.Before.setAllToTypes(QualType());
4704 
4705       Result.UserDefined.After.setAsIdentityConversion();
4706       Result.UserDefined.After.setFromType(ToType);
4707       Result.UserDefined.After.setAllToTypes(ToType);
4708       Result.UserDefined.ConversionFunction = nullptr;
4709     }
4710     return Result;
4711   }
4712 
4713   // C++14 [over.ics.list]p6:
4714   // C++11 [over.ics.list]p5:
4715   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4716   if (ToType->isReferenceType()) {
4717     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4718     // mention initializer lists in any way. So we go by what list-
4719     // initialization would do and try to extrapolate from that.
4720 
4721     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4722 
4723     // If the initializer list has a single element that is reference-related
4724     // to the parameter type, we initialize the reference from that.
4725     if (From->getNumInits() == 1) {
4726       Expr *Init = From->getInit(0);
4727 
4728       QualType T2 = Init->getType();
4729 
4730       // If the initializer is the address of an overloaded function, try
4731       // to resolve the overloaded function. If all goes well, T2 is the
4732       // type of the resulting function.
4733       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4734         DeclAccessPair Found;
4735         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4736                                    Init, ToType, false, Found))
4737           T2 = Fn->getType();
4738       }
4739 
4740       // Compute some basic properties of the types and the initializer.
4741       bool dummy1 = false;
4742       bool dummy2 = false;
4743       bool dummy3 = false;
4744       Sema::ReferenceCompareResult RefRelationship
4745         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4746                                          dummy2, dummy3);
4747 
4748       if (RefRelationship >= Sema::Ref_Related) {
4749         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4750                                 SuppressUserConversions,
4751                                 /*AllowExplicit=*/false);
4752       }
4753     }
4754 
4755     // Otherwise, we bind the reference to a temporary created from the
4756     // initializer list.
4757     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4758                                InOverloadResolution,
4759                                AllowObjCWritebackConversion);
4760     if (Result.isFailure())
4761       return Result;
4762     assert(!Result.isEllipsis() &&
4763            "Sub-initialization cannot result in ellipsis conversion.");
4764 
4765     // Can we even bind to a temporary?
4766     if (ToType->isRValueReferenceType() ||
4767         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4768       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4769                                             Result.UserDefined.After;
4770       SCS.ReferenceBinding = true;
4771       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4772       SCS.BindsToRvalue = true;
4773       SCS.BindsToFunctionLvalue = false;
4774       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4775       SCS.ObjCLifetimeConversionBinding = false;
4776     } else
4777       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4778                     From, ToType);
4779     return Result;
4780   }
4781 
4782   // C++14 [over.ics.list]p7:
4783   // C++11 [over.ics.list]p6:
4784   //   Otherwise, if the parameter type is not a class:
4785   if (!ToType->isRecordType()) {
4786     //    - if the initializer list has one element that is not itself an
4787     //      initializer list, the implicit conversion sequence is the one
4788     //      required to convert the element to the parameter type.
4789     unsigned NumInits = From->getNumInits();
4790     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4791       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4792                                      SuppressUserConversions,
4793                                      InOverloadResolution,
4794                                      AllowObjCWritebackConversion);
4795     //    - if the initializer list has no elements, the implicit conversion
4796     //      sequence is the identity conversion.
4797     else if (NumInits == 0) {
4798       Result.setStandard();
4799       Result.Standard.setAsIdentityConversion();
4800       Result.Standard.setFromType(ToType);
4801       Result.Standard.setAllToTypes(ToType);
4802     }
4803     return Result;
4804   }
4805 
4806   // C++14 [over.ics.list]p8:
4807   // C++11 [over.ics.list]p7:
4808   //   In all cases other than those enumerated above, no conversion is possible
4809   return Result;
4810 }
4811 
4812 /// TryCopyInitialization - Try to copy-initialize a value of type
4813 /// ToType from the expression From. Return the implicit conversion
4814 /// sequence required to pass this argument, which may be a bad
4815 /// conversion sequence (meaning that the argument cannot be passed to
4816 /// a parameter of this type). If @p SuppressUserConversions, then we
4817 /// do not permit any user-defined conversion sequences.
4818 static ImplicitConversionSequence
4819 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4820                       bool SuppressUserConversions,
4821                       bool InOverloadResolution,
4822                       bool AllowObjCWritebackConversion,
4823                       bool AllowExplicit) {
4824   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4825     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4826                              InOverloadResolution,AllowObjCWritebackConversion);
4827 
4828   if (ToType->isReferenceType())
4829     return TryReferenceInit(S, From, ToType,
4830                             /*FIXME:*/From->getLocStart(),
4831                             SuppressUserConversions,
4832                             AllowExplicit);
4833 
4834   return TryImplicitConversion(S, From, ToType,
4835                                SuppressUserConversions,
4836                                /*AllowExplicit=*/false,
4837                                InOverloadResolution,
4838                                /*CStyle=*/false,
4839                                AllowObjCWritebackConversion,
4840                                /*AllowObjCConversionOnExplicit=*/false);
4841 }
4842 
4843 static bool TryCopyInitialization(const CanQualType FromQTy,
4844                                   const CanQualType ToQTy,
4845                                   Sema &S,
4846                                   SourceLocation Loc,
4847                                   ExprValueKind FromVK) {
4848   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4849   ImplicitConversionSequence ICS =
4850     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4851 
4852   return !ICS.isBad();
4853 }
4854 
4855 /// TryObjectArgumentInitialization - Try to initialize the object
4856 /// parameter of the given member function (@c Method) from the
4857 /// expression @p From.
4858 static ImplicitConversionSequence
4859 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4860                                 Expr::Classification FromClassification,
4861                                 CXXMethodDecl *Method,
4862                                 CXXRecordDecl *ActingContext) {
4863   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4864   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4865   //                 const volatile object.
4866   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4867     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4868   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4869 
4870   // Set up the conversion sequence as a "bad" conversion, to allow us
4871   // to exit early.
4872   ImplicitConversionSequence ICS;
4873 
4874   // We need to have an object of class type.
4875   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4876     FromType = PT->getPointeeType();
4877 
4878     // When we had a pointer, it's implicitly dereferenced, so we
4879     // better have an lvalue.
4880     assert(FromClassification.isLValue());
4881   }
4882 
4883   assert(FromType->isRecordType());
4884 
4885   // C++0x [over.match.funcs]p4:
4886   //   For non-static member functions, the type of the implicit object
4887   //   parameter is
4888   //
4889   //     - "lvalue reference to cv X" for functions declared without a
4890   //        ref-qualifier or with the & ref-qualifier
4891   //     - "rvalue reference to cv X" for functions declared with the &&
4892   //        ref-qualifier
4893   //
4894   // where X is the class of which the function is a member and cv is the
4895   // cv-qualification on the member function declaration.
4896   //
4897   // However, when finding an implicit conversion sequence for the argument, we
4898   // are not allowed to create temporaries or perform user-defined conversions
4899   // (C++ [over.match.funcs]p5). We perform a simplified version of
4900   // reference binding here, that allows class rvalues to bind to
4901   // non-constant references.
4902 
4903   // First check the qualifiers.
4904   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4905   if (ImplicitParamType.getCVRQualifiers()
4906                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4907       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4908     ICS.setBad(BadConversionSequence::bad_qualifiers,
4909                FromType, ImplicitParamType);
4910     return ICS;
4911   }
4912 
4913   // Check that we have either the same type or a derived type. It
4914   // affects the conversion rank.
4915   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4916   ImplicitConversionKind SecondKind;
4917   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4918     SecondKind = ICK_Identity;
4919   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4920     SecondKind = ICK_Derived_To_Base;
4921   else {
4922     ICS.setBad(BadConversionSequence::unrelated_class,
4923                FromType, ImplicitParamType);
4924     return ICS;
4925   }
4926 
4927   // Check the ref-qualifier.
4928   switch (Method->getRefQualifier()) {
4929   case RQ_None:
4930     // Do nothing; we don't care about lvalueness or rvalueness.
4931     break;
4932 
4933   case RQ_LValue:
4934     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4935       // non-const lvalue reference cannot bind to an rvalue
4936       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4937                  ImplicitParamType);
4938       return ICS;
4939     }
4940     break;
4941 
4942   case RQ_RValue:
4943     if (!FromClassification.isRValue()) {
4944       // rvalue reference cannot bind to an lvalue
4945       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4946                  ImplicitParamType);
4947       return ICS;
4948     }
4949     break;
4950   }
4951 
4952   // Success. Mark this as a reference binding.
4953   ICS.setStandard();
4954   ICS.Standard.setAsIdentityConversion();
4955   ICS.Standard.Second = SecondKind;
4956   ICS.Standard.setFromType(FromType);
4957   ICS.Standard.setAllToTypes(ImplicitParamType);
4958   ICS.Standard.ReferenceBinding = true;
4959   ICS.Standard.DirectBinding = true;
4960   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4961   ICS.Standard.BindsToFunctionLvalue = false;
4962   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4963   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4964     = (Method->getRefQualifier() == RQ_None);
4965   return ICS;
4966 }
4967 
4968 /// PerformObjectArgumentInitialization - Perform initialization of
4969 /// the implicit object parameter for the given Method with the given
4970 /// expression.
4971 ExprResult
4972 Sema::PerformObjectArgumentInitialization(Expr *From,
4973                                           NestedNameSpecifier *Qualifier,
4974                                           NamedDecl *FoundDecl,
4975                                           CXXMethodDecl *Method) {
4976   QualType FromRecordType, DestType;
4977   QualType ImplicitParamRecordType  =
4978     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4979 
4980   Expr::Classification FromClassification;
4981   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4982     FromRecordType = PT->getPointeeType();
4983     DestType = Method->getThisType(Context);
4984     FromClassification = Expr::Classification::makeSimpleLValue();
4985   } else {
4986     FromRecordType = From->getType();
4987     DestType = ImplicitParamRecordType;
4988     FromClassification = From->Classify(Context);
4989   }
4990 
4991   // Note that we always use the true parent context when performing
4992   // the actual argument initialization.
4993   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4994       *this, From->getLocStart(), From->getType(), FromClassification, Method,
4995       Method->getParent());
4996   if (ICS.isBad()) {
4997     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4998       Qualifiers FromQs = FromRecordType.getQualifiers();
4999       Qualifiers ToQs = DestType.getQualifiers();
5000       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5001       if (CVR) {
5002         Diag(From->getLocStart(),
5003              diag::err_member_function_call_bad_cvr)
5004           << Method->getDeclName() << FromRecordType << (CVR - 1)
5005           << From->getSourceRange();
5006         Diag(Method->getLocation(), diag::note_previous_decl)
5007           << Method->getDeclName();
5008         return ExprError();
5009       }
5010     }
5011 
5012     return Diag(From->getLocStart(),
5013                 diag::err_implicit_object_parameter_init)
5014        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5015   }
5016 
5017   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5018     ExprResult FromRes =
5019       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5020     if (FromRes.isInvalid())
5021       return ExprError();
5022     From = FromRes.get();
5023   }
5024 
5025   if (!Context.hasSameType(From->getType(), DestType))
5026     From = ImpCastExprToType(From, DestType, CK_NoOp,
5027                              From->getValueKind()).get();
5028   return From;
5029 }
5030 
5031 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5032 /// expression From to bool (C++0x [conv]p3).
5033 static ImplicitConversionSequence
5034 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5035   return TryImplicitConversion(S, From, S.Context.BoolTy,
5036                                /*SuppressUserConversions=*/false,
5037                                /*AllowExplicit=*/true,
5038                                /*InOverloadResolution=*/false,
5039                                /*CStyle=*/false,
5040                                /*AllowObjCWritebackConversion=*/false,
5041                                /*AllowObjCConversionOnExplicit=*/false);
5042 }
5043 
5044 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5045 /// of the expression From to bool (C++0x [conv]p3).
5046 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5047   if (checkPlaceholderForOverload(*this, From))
5048     return ExprError();
5049 
5050   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5051   if (!ICS.isBad())
5052     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5053 
5054   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5055     return Diag(From->getLocStart(),
5056                 diag::err_typecheck_bool_condition)
5057                   << From->getType() << From->getSourceRange();
5058   return ExprError();
5059 }
5060 
5061 /// Check that the specified conversion is permitted in a converted constant
5062 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5063 /// is acceptable.
5064 static bool CheckConvertedConstantConversions(Sema &S,
5065                                               StandardConversionSequence &SCS) {
5066   // Since we know that the target type is an integral or unscoped enumeration
5067   // type, most conversion kinds are impossible. All possible First and Third
5068   // conversions are fine.
5069   switch (SCS.Second) {
5070   case ICK_Identity:
5071   case ICK_NoReturn_Adjustment:
5072   case ICK_Integral_Promotion:
5073   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5074     return true;
5075 
5076   case ICK_Boolean_Conversion:
5077     // Conversion from an integral or unscoped enumeration type to bool is
5078     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5079     // conversion, so we allow it in a converted constant expression.
5080     //
5081     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5082     // a lot of popular code. We should at least add a warning for this
5083     // (non-conforming) extension.
5084     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5085            SCS.getToType(2)->isBooleanType();
5086 
5087   case ICK_Pointer_Conversion:
5088   case ICK_Pointer_Member:
5089     // C++1z: null pointer conversions and null member pointer conversions are
5090     // only permitted if the source type is std::nullptr_t.
5091     return SCS.getFromType()->isNullPtrType();
5092 
5093   case ICK_Floating_Promotion:
5094   case ICK_Complex_Promotion:
5095   case ICK_Floating_Conversion:
5096   case ICK_Complex_Conversion:
5097   case ICK_Floating_Integral:
5098   case ICK_Compatible_Conversion:
5099   case ICK_Derived_To_Base:
5100   case ICK_Vector_Conversion:
5101   case ICK_Vector_Splat:
5102   case ICK_Complex_Real:
5103   case ICK_Block_Pointer_Conversion:
5104   case ICK_TransparentUnionConversion:
5105   case ICK_Writeback_Conversion:
5106   case ICK_Zero_Event_Conversion:
5107   case ICK_C_Only_Conversion:
5108     return false;
5109 
5110   case ICK_Lvalue_To_Rvalue:
5111   case ICK_Array_To_Pointer:
5112   case ICK_Function_To_Pointer:
5113     llvm_unreachable("found a first conversion kind in Second");
5114 
5115   case ICK_Qualification:
5116     llvm_unreachable("found a third conversion kind in Second");
5117 
5118   case ICK_Num_Conversion_Kinds:
5119     break;
5120   }
5121 
5122   llvm_unreachable("unknown conversion kind");
5123 }
5124 
5125 /// CheckConvertedConstantExpression - Check that the expression From is a
5126 /// converted constant expression of type T, perform the conversion and produce
5127 /// the converted expression, per C++11 [expr.const]p3.
5128 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5129                                                    QualType T, APValue &Value,
5130                                                    Sema::CCEKind CCE,
5131                                                    bool RequireInt) {
5132   assert(S.getLangOpts().CPlusPlus11 &&
5133          "converted constant expression outside C++11");
5134 
5135   if (checkPlaceholderForOverload(S, From))
5136     return ExprError();
5137 
5138   // C++1z [expr.const]p3:
5139   //  A converted constant expression of type T is an expression,
5140   //  implicitly converted to type T, where the converted
5141   //  expression is a constant expression and the implicit conversion
5142   //  sequence contains only [... list of conversions ...].
5143   ImplicitConversionSequence ICS =
5144     TryCopyInitialization(S, From, T,
5145                           /*SuppressUserConversions=*/false,
5146                           /*InOverloadResolution=*/false,
5147                           /*AllowObjcWritebackConversion=*/false,
5148                           /*AllowExplicit=*/false);
5149   StandardConversionSequence *SCS = nullptr;
5150   switch (ICS.getKind()) {
5151   case ImplicitConversionSequence::StandardConversion:
5152     SCS = &ICS.Standard;
5153     break;
5154   case ImplicitConversionSequence::UserDefinedConversion:
5155     // We are converting to a non-class type, so the Before sequence
5156     // must be trivial.
5157     SCS = &ICS.UserDefined.After;
5158     break;
5159   case ImplicitConversionSequence::AmbiguousConversion:
5160   case ImplicitConversionSequence::BadConversion:
5161     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5162       return S.Diag(From->getLocStart(),
5163                     diag::err_typecheck_converted_constant_expression)
5164                 << From->getType() << From->getSourceRange() << T;
5165     return ExprError();
5166 
5167   case ImplicitConversionSequence::EllipsisConversion:
5168     llvm_unreachable("ellipsis conversion in converted constant expression");
5169   }
5170 
5171   // Check that we would only use permitted conversions.
5172   if (!CheckConvertedConstantConversions(S, *SCS)) {
5173     return S.Diag(From->getLocStart(),
5174                   diag::err_typecheck_converted_constant_expression_disallowed)
5175              << From->getType() << From->getSourceRange() << T;
5176   }
5177   // [...] and where the reference binding (if any) binds directly.
5178   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5179     return S.Diag(From->getLocStart(),
5180                   diag::err_typecheck_converted_constant_expression_indirect)
5181              << From->getType() << From->getSourceRange() << T;
5182   }
5183 
5184   ExprResult Result =
5185       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5186   if (Result.isInvalid())
5187     return Result;
5188 
5189   // Check for a narrowing implicit conversion.
5190   APValue PreNarrowingValue;
5191   QualType PreNarrowingType;
5192   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5193                                 PreNarrowingType)) {
5194   case NK_Variable_Narrowing:
5195     // Implicit conversion to a narrower type, and the value is not a constant
5196     // expression. We'll diagnose this in a moment.
5197   case NK_Not_Narrowing:
5198     break;
5199 
5200   case NK_Constant_Narrowing:
5201     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5202       << CCE << /*Constant*/1
5203       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5204     break;
5205 
5206   case NK_Type_Narrowing:
5207     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5208       << CCE << /*Constant*/0 << From->getType() << T;
5209     break;
5210   }
5211 
5212   // Check the expression is a constant expression.
5213   SmallVector<PartialDiagnosticAt, 8> Notes;
5214   Expr::EvalResult Eval;
5215   Eval.Diag = &Notes;
5216 
5217   if ((T->isReferenceType()
5218            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5219            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5220       (RequireInt && !Eval.Val.isInt())) {
5221     // The expression can't be folded, so we can't keep it at this position in
5222     // the AST.
5223     Result = ExprError();
5224   } else {
5225     Value = Eval.Val;
5226 
5227     if (Notes.empty()) {
5228       // It's a constant expression.
5229       return Result;
5230     }
5231   }
5232 
5233   // It's not a constant expression. Produce an appropriate diagnostic.
5234   if (Notes.size() == 1 &&
5235       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5236     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5237   else {
5238     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5239       << CCE << From->getSourceRange();
5240     for (unsigned I = 0; I < Notes.size(); ++I)
5241       S.Diag(Notes[I].first, Notes[I].second);
5242   }
5243   return ExprError();
5244 }
5245 
5246 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5247                                                   APValue &Value, CCEKind CCE) {
5248   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5249 }
5250 
5251 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5252                                                   llvm::APSInt &Value,
5253                                                   CCEKind CCE) {
5254   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5255 
5256   APValue V;
5257   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5258   if (!R.isInvalid())
5259     Value = V.getInt();
5260   return R;
5261 }
5262 
5263 
5264 /// dropPointerConversions - If the given standard conversion sequence
5265 /// involves any pointer conversions, remove them.  This may change
5266 /// the result type of the conversion sequence.
5267 static void dropPointerConversion(StandardConversionSequence &SCS) {
5268   if (SCS.Second == ICK_Pointer_Conversion) {
5269     SCS.Second = ICK_Identity;
5270     SCS.Third = ICK_Identity;
5271     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5272   }
5273 }
5274 
5275 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5276 /// convert the expression From to an Objective-C pointer type.
5277 static ImplicitConversionSequence
5278 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5279   // Do an implicit conversion to 'id'.
5280   QualType Ty = S.Context.getObjCIdType();
5281   ImplicitConversionSequence ICS
5282     = TryImplicitConversion(S, From, Ty,
5283                             // FIXME: Are these flags correct?
5284                             /*SuppressUserConversions=*/false,
5285                             /*AllowExplicit=*/true,
5286                             /*InOverloadResolution=*/false,
5287                             /*CStyle=*/false,
5288                             /*AllowObjCWritebackConversion=*/false,
5289                             /*AllowObjCConversionOnExplicit=*/true);
5290 
5291   // Strip off any final conversions to 'id'.
5292   switch (ICS.getKind()) {
5293   case ImplicitConversionSequence::BadConversion:
5294   case ImplicitConversionSequence::AmbiguousConversion:
5295   case ImplicitConversionSequence::EllipsisConversion:
5296     break;
5297 
5298   case ImplicitConversionSequence::UserDefinedConversion:
5299     dropPointerConversion(ICS.UserDefined.After);
5300     break;
5301 
5302   case ImplicitConversionSequence::StandardConversion:
5303     dropPointerConversion(ICS.Standard);
5304     break;
5305   }
5306 
5307   return ICS;
5308 }
5309 
5310 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5311 /// conversion of the expression From to an Objective-C pointer type.
5312 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5313   if (checkPlaceholderForOverload(*this, From))
5314     return ExprError();
5315 
5316   QualType Ty = Context.getObjCIdType();
5317   ImplicitConversionSequence ICS =
5318     TryContextuallyConvertToObjCPointer(*this, From);
5319   if (!ICS.isBad())
5320     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5321   return ExprError();
5322 }
5323 
5324 /// Determine whether the provided type is an integral type, or an enumeration
5325 /// type of a permitted flavor.
5326 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5327   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5328                                  : T->isIntegralOrUnscopedEnumerationType();
5329 }
5330 
5331 static ExprResult
5332 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5333                             Sema::ContextualImplicitConverter &Converter,
5334                             QualType T, UnresolvedSetImpl &ViableConversions) {
5335 
5336   if (Converter.Suppress)
5337     return ExprError();
5338 
5339   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5340   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5341     CXXConversionDecl *Conv =
5342         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5343     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5344     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5345   }
5346   return From;
5347 }
5348 
5349 static bool
5350 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5351                            Sema::ContextualImplicitConverter &Converter,
5352                            QualType T, bool HadMultipleCandidates,
5353                            UnresolvedSetImpl &ExplicitConversions) {
5354   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5355     DeclAccessPair Found = ExplicitConversions[0];
5356     CXXConversionDecl *Conversion =
5357         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5358 
5359     // The user probably meant to invoke the given explicit
5360     // conversion; use it.
5361     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5362     std::string TypeStr;
5363     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5364 
5365     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5366         << FixItHint::CreateInsertion(From->getLocStart(),
5367                                       "static_cast<" + TypeStr + ">(")
5368         << FixItHint::CreateInsertion(
5369                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5370     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5371 
5372     // If we aren't in a SFINAE context, build a call to the
5373     // explicit conversion function.
5374     if (SemaRef.isSFINAEContext())
5375       return true;
5376 
5377     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5378     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5379                                                        HadMultipleCandidates);
5380     if (Result.isInvalid())
5381       return true;
5382     // Record usage of conversion in an implicit cast.
5383     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5384                                     CK_UserDefinedConversion, Result.get(),
5385                                     nullptr, Result.get()->getValueKind());
5386   }
5387   return false;
5388 }
5389 
5390 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5391                              Sema::ContextualImplicitConverter &Converter,
5392                              QualType T, bool HadMultipleCandidates,
5393                              DeclAccessPair &Found) {
5394   CXXConversionDecl *Conversion =
5395       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5396   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5397 
5398   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5399   if (!Converter.SuppressConversion) {
5400     if (SemaRef.isSFINAEContext())
5401       return true;
5402 
5403     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5404         << From->getSourceRange();
5405   }
5406 
5407   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5408                                                      HadMultipleCandidates);
5409   if (Result.isInvalid())
5410     return true;
5411   // Record usage of conversion in an implicit cast.
5412   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5413                                   CK_UserDefinedConversion, Result.get(),
5414                                   nullptr, Result.get()->getValueKind());
5415   return false;
5416 }
5417 
5418 static ExprResult finishContextualImplicitConversion(
5419     Sema &SemaRef, SourceLocation Loc, Expr *From,
5420     Sema::ContextualImplicitConverter &Converter) {
5421   if (!Converter.match(From->getType()) && !Converter.Suppress)
5422     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5423         << From->getSourceRange();
5424 
5425   return SemaRef.DefaultLvalueConversion(From);
5426 }
5427 
5428 static void
5429 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5430                                   UnresolvedSetImpl &ViableConversions,
5431                                   OverloadCandidateSet &CandidateSet) {
5432   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5433     DeclAccessPair FoundDecl = ViableConversions[I];
5434     NamedDecl *D = FoundDecl.getDecl();
5435     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5436     if (isa<UsingShadowDecl>(D))
5437       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5438 
5439     CXXConversionDecl *Conv;
5440     FunctionTemplateDecl *ConvTemplate;
5441     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5442       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5443     else
5444       Conv = cast<CXXConversionDecl>(D);
5445 
5446     if (ConvTemplate)
5447       SemaRef.AddTemplateConversionCandidate(
5448         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5449         /*AllowObjCConversionOnExplicit=*/false);
5450     else
5451       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5452                                      ToType, CandidateSet,
5453                                      /*AllowObjCConversionOnExplicit=*/false);
5454   }
5455 }
5456 
5457 /// \brief Attempt to convert the given expression to a type which is accepted
5458 /// by the given converter.
5459 ///
5460 /// This routine will attempt to convert an expression of class type to a
5461 /// type accepted by the specified converter. In C++11 and before, the class
5462 /// must have a single non-explicit conversion function converting to a matching
5463 /// type. In C++1y, there can be multiple such conversion functions, but only
5464 /// one target type.
5465 ///
5466 /// \param Loc The source location of the construct that requires the
5467 /// conversion.
5468 ///
5469 /// \param From The expression we're converting from.
5470 ///
5471 /// \param Converter Used to control and diagnose the conversion process.
5472 ///
5473 /// \returns The expression, converted to an integral or enumeration type if
5474 /// successful.
5475 ExprResult Sema::PerformContextualImplicitConversion(
5476     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5477   // We can't perform any more checking for type-dependent expressions.
5478   if (From->isTypeDependent())
5479     return From;
5480 
5481   // Process placeholders immediately.
5482   if (From->hasPlaceholderType()) {
5483     ExprResult result = CheckPlaceholderExpr(From);
5484     if (result.isInvalid())
5485       return result;
5486     From = result.get();
5487   }
5488 
5489   // If the expression already has a matching type, we're golden.
5490   QualType T = From->getType();
5491   if (Converter.match(T))
5492     return DefaultLvalueConversion(From);
5493 
5494   // FIXME: Check for missing '()' if T is a function type?
5495 
5496   // We can only perform contextual implicit conversions on objects of class
5497   // type.
5498   const RecordType *RecordTy = T->getAs<RecordType>();
5499   if (!RecordTy || !getLangOpts().CPlusPlus) {
5500     if (!Converter.Suppress)
5501       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5502     return From;
5503   }
5504 
5505   // We must have a complete class type.
5506   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5507     ContextualImplicitConverter &Converter;
5508     Expr *From;
5509 
5510     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5511         : Converter(Converter), From(From) {}
5512 
5513     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5514       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5515     }
5516   } IncompleteDiagnoser(Converter, From);
5517 
5518   if (Converter.Suppress ? !isCompleteType(Loc, T)
5519                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5520     return From;
5521 
5522   // Look for a conversion to an integral or enumeration type.
5523   UnresolvedSet<4>
5524       ViableConversions; // These are *potentially* viable in C++1y.
5525   UnresolvedSet<4> ExplicitConversions;
5526   const auto &Conversions =
5527       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5528 
5529   bool HadMultipleCandidates =
5530       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5531 
5532   // To check that there is only one target type, in C++1y:
5533   QualType ToType;
5534   bool HasUniqueTargetType = true;
5535 
5536   // Collect explicit or viable (potentially in C++1y) conversions.
5537   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5538     NamedDecl *D = (*I)->getUnderlyingDecl();
5539     CXXConversionDecl *Conversion;
5540     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5541     if (ConvTemplate) {
5542       if (getLangOpts().CPlusPlus14)
5543         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5544       else
5545         continue; // C++11 does not consider conversion operator templates(?).
5546     } else
5547       Conversion = cast<CXXConversionDecl>(D);
5548 
5549     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5550            "Conversion operator templates are considered potentially "
5551            "viable in C++1y");
5552 
5553     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5554     if (Converter.match(CurToType) || ConvTemplate) {
5555 
5556       if (Conversion->isExplicit()) {
5557         // FIXME: For C++1y, do we need this restriction?
5558         // cf. diagnoseNoViableConversion()
5559         if (!ConvTemplate)
5560           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5561       } else {
5562         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5563           if (ToType.isNull())
5564             ToType = CurToType.getUnqualifiedType();
5565           else if (HasUniqueTargetType &&
5566                    (CurToType.getUnqualifiedType() != ToType))
5567             HasUniqueTargetType = false;
5568         }
5569         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5570       }
5571     }
5572   }
5573 
5574   if (getLangOpts().CPlusPlus14) {
5575     // C++1y [conv]p6:
5576     // ... An expression e of class type E appearing in such a context
5577     // is said to be contextually implicitly converted to a specified
5578     // type T and is well-formed if and only if e can be implicitly
5579     // converted to a type T that is determined as follows: E is searched
5580     // for conversion functions whose return type is cv T or reference to
5581     // cv T such that T is allowed by the context. There shall be
5582     // exactly one such T.
5583 
5584     // If no unique T is found:
5585     if (ToType.isNull()) {
5586       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5587                                      HadMultipleCandidates,
5588                                      ExplicitConversions))
5589         return ExprError();
5590       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5591     }
5592 
5593     // If more than one unique Ts are found:
5594     if (!HasUniqueTargetType)
5595       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5596                                          ViableConversions);
5597 
5598     // If one unique T is found:
5599     // First, build a candidate set from the previously recorded
5600     // potentially viable conversions.
5601     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5602     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5603                                       CandidateSet);
5604 
5605     // Then, perform overload resolution over the candidate set.
5606     OverloadCandidateSet::iterator Best;
5607     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5608     case OR_Success: {
5609       // Apply this conversion.
5610       DeclAccessPair Found =
5611           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5612       if (recordConversion(*this, Loc, From, Converter, T,
5613                            HadMultipleCandidates, Found))
5614         return ExprError();
5615       break;
5616     }
5617     case OR_Ambiguous:
5618       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5619                                          ViableConversions);
5620     case OR_No_Viable_Function:
5621       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5622                                      HadMultipleCandidates,
5623                                      ExplicitConversions))
5624         return ExprError();
5625     // fall through 'OR_Deleted' case.
5626     case OR_Deleted:
5627       // We'll complain below about a non-integral condition type.
5628       break;
5629     }
5630   } else {
5631     switch (ViableConversions.size()) {
5632     case 0: {
5633       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5634                                      HadMultipleCandidates,
5635                                      ExplicitConversions))
5636         return ExprError();
5637 
5638       // We'll complain below about a non-integral condition type.
5639       break;
5640     }
5641     case 1: {
5642       // Apply this conversion.
5643       DeclAccessPair Found = ViableConversions[0];
5644       if (recordConversion(*this, Loc, From, Converter, T,
5645                            HadMultipleCandidates, Found))
5646         return ExprError();
5647       break;
5648     }
5649     default:
5650       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5651                                          ViableConversions);
5652     }
5653   }
5654 
5655   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5656 }
5657 
5658 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5659 /// an acceptable non-member overloaded operator for a call whose
5660 /// arguments have types T1 (and, if non-empty, T2). This routine
5661 /// implements the check in C++ [over.match.oper]p3b2 concerning
5662 /// enumeration types.
5663 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5664                                                    FunctionDecl *Fn,
5665                                                    ArrayRef<Expr *> Args) {
5666   QualType T1 = Args[0]->getType();
5667   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5668 
5669   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5670     return true;
5671 
5672   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5673     return true;
5674 
5675   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5676   if (Proto->getNumParams() < 1)
5677     return false;
5678 
5679   if (T1->isEnumeralType()) {
5680     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5681     if (Context.hasSameUnqualifiedType(T1, ArgType))
5682       return true;
5683   }
5684 
5685   if (Proto->getNumParams() < 2)
5686     return false;
5687 
5688   if (!T2.isNull() && T2->isEnumeralType()) {
5689     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5690     if (Context.hasSameUnqualifiedType(T2, ArgType))
5691       return true;
5692   }
5693 
5694   return false;
5695 }
5696 
5697 /// AddOverloadCandidate - Adds the given function to the set of
5698 /// candidate functions, using the given function call arguments.  If
5699 /// @p SuppressUserConversions, then don't allow user-defined
5700 /// conversions via constructors or conversion operators.
5701 ///
5702 /// \param PartialOverloading true if we are performing "partial" overloading
5703 /// based on an incomplete set of function arguments. This feature is used by
5704 /// code completion.
5705 void
5706 Sema::AddOverloadCandidate(FunctionDecl *Function,
5707                            DeclAccessPair FoundDecl,
5708                            ArrayRef<Expr *> Args,
5709                            OverloadCandidateSet &CandidateSet,
5710                            bool SuppressUserConversions,
5711                            bool PartialOverloading,
5712                            bool AllowExplicit) {
5713   const FunctionProtoType *Proto
5714     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5715   assert(Proto && "Functions without a prototype cannot be overloaded");
5716   assert(!Function->getDescribedFunctionTemplate() &&
5717          "Use AddTemplateOverloadCandidate for function templates");
5718 
5719   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5720     if (!isa<CXXConstructorDecl>(Method)) {
5721       // If we get here, it's because we're calling a member function
5722       // that is named without a member access expression (e.g.,
5723       // "this->f") that was either written explicitly or created
5724       // implicitly. This can happen with a qualified call to a member
5725       // function, e.g., X::f(). We use an empty type for the implied
5726       // object argument (C++ [over.call.func]p3), and the acting context
5727       // is irrelevant.
5728       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5729                          QualType(), Expr::Classification::makeSimpleLValue(),
5730                          Args, CandidateSet, SuppressUserConversions,
5731                          PartialOverloading);
5732       return;
5733     }
5734     // We treat a constructor like a non-member function, since its object
5735     // argument doesn't participate in overload resolution.
5736   }
5737 
5738   if (!CandidateSet.isNewCandidate(Function))
5739     return;
5740 
5741   // C++ [over.match.oper]p3:
5742   //   if no operand has a class type, only those non-member functions in the
5743   //   lookup set that have a first parameter of type T1 or "reference to
5744   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5745   //   is a right operand) a second parameter of type T2 or "reference to
5746   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5747   //   candidate functions.
5748   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5749       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5750     return;
5751 
5752   // C++11 [class.copy]p11: [DR1402]
5753   //   A defaulted move constructor that is defined as deleted is ignored by
5754   //   overload resolution.
5755   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5756   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5757       Constructor->isMoveConstructor())
5758     return;
5759 
5760   // Overload resolution is always an unevaluated context.
5761   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5762 
5763   // Add this candidate
5764   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5765   Candidate.FoundDecl = FoundDecl;
5766   Candidate.Function = Function;
5767   Candidate.Viable = true;
5768   Candidate.IsSurrogate = false;
5769   Candidate.IgnoreObjectArgument = false;
5770   Candidate.ExplicitCallArguments = Args.size();
5771 
5772   if (Constructor) {
5773     // C++ [class.copy]p3:
5774     //   A member function template is never instantiated to perform the copy
5775     //   of a class object to an object of its class type.
5776     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5777     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5778         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5779          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5780                        ClassType))) {
5781       Candidate.Viable = false;
5782       Candidate.FailureKind = ovl_fail_illegal_constructor;
5783       return;
5784     }
5785   }
5786 
5787   unsigned NumParams = Proto->getNumParams();
5788 
5789   // (C++ 13.3.2p2): A candidate function having fewer than m
5790   // parameters is viable only if it has an ellipsis in its parameter
5791   // list (8.3.5).
5792   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5793       !Proto->isVariadic()) {
5794     Candidate.Viable = false;
5795     Candidate.FailureKind = ovl_fail_too_many_arguments;
5796     return;
5797   }
5798 
5799   // (C++ 13.3.2p2): A candidate function having more than m parameters
5800   // is viable only if the (m+1)st parameter has a default argument
5801   // (8.3.6). For the purposes of overload resolution, the
5802   // parameter list is truncated on the right, so that there are
5803   // exactly m parameters.
5804   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5805   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5806     // Not enough arguments.
5807     Candidate.Viable = false;
5808     Candidate.FailureKind = ovl_fail_too_few_arguments;
5809     return;
5810   }
5811 
5812   // (CUDA B.1): Check for invalid calls between targets.
5813   if (getLangOpts().CUDA)
5814     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5815       // Skip the check for callers that are implicit members, because in this
5816       // case we may not yet know what the member's target is; the target is
5817       // inferred for the member automatically, based on the bases and fields of
5818       // the class.
5819       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5820         Candidate.Viable = false;
5821         Candidate.FailureKind = ovl_fail_bad_target;
5822         return;
5823       }
5824 
5825   // Determine the implicit conversion sequences for each of the
5826   // arguments.
5827   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5828     if (ArgIdx < NumParams) {
5829       // (C++ 13.3.2p3): for F to be a viable function, there shall
5830       // exist for each argument an implicit conversion sequence
5831       // (13.3.3.1) that converts that argument to the corresponding
5832       // parameter of F.
5833       QualType ParamType = Proto->getParamType(ArgIdx);
5834       Candidate.Conversions[ArgIdx]
5835         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5836                                 SuppressUserConversions,
5837                                 /*InOverloadResolution=*/true,
5838                                 /*AllowObjCWritebackConversion=*/
5839                                   getLangOpts().ObjCAutoRefCount,
5840                                 AllowExplicit);
5841       if (Candidate.Conversions[ArgIdx].isBad()) {
5842         Candidate.Viable = false;
5843         Candidate.FailureKind = ovl_fail_bad_conversion;
5844         return;
5845       }
5846     } else {
5847       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5848       // argument for which there is no corresponding parameter is
5849       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5850       Candidate.Conversions[ArgIdx].setEllipsis();
5851     }
5852   }
5853 
5854   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5855     Candidate.Viable = false;
5856     Candidate.FailureKind = ovl_fail_enable_if;
5857     Candidate.DeductionFailure.Data = FailedAttr;
5858     return;
5859   }
5860 }
5861 
5862 ObjCMethodDecl *
5863 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5864                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5865   if (Methods.size() <= 1)
5866     return nullptr;
5867 
5868   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5869     bool Match = true;
5870     ObjCMethodDecl *Method = Methods[b];
5871     unsigned NumNamedArgs = Sel.getNumArgs();
5872     // Method might have more arguments than selector indicates. This is due
5873     // to addition of c-style arguments in method.
5874     if (Method->param_size() > NumNamedArgs)
5875       NumNamedArgs = Method->param_size();
5876     if (Args.size() < NumNamedArgs)
5877       continue;
5878 
5879     for (unsigned i = 0; i < NumNamedArgs; i++) {
5880       // We can't do any type-checking on a type-dependent argument.
5881       if (Args[i]->isTypeDependent()) {
5882         Match = false;
5883         break;
5884       }
5885 
5886       ParmVarDecl *param = Method->parameters()[i];
5887       Expr *argExpr = Args[i];
5888       assert(argExpr && "SelectBestMethod(): missing expression");
5889 
5890       // Strip the unbridged-cast placeholder expression off unless it's
5891       // a consumed argument.
5892       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5893           !param->hasAttr<CFConsumedAttr>())
5894         argExpr = stripARCUnbridgedCast(argExpr);
5895 
5896       // If the parameter is __unknown_anytype, move on to the next method.
5897       if (param->getType() == Context.UnknownAnyTy) {
5898         Match = false;
5899         break;
5900       }
5901 
5902       ImplicitConversionSequence ConversionState
5903         = TryCopyInitialization(*this, argExpr, param->getType(),
5904                                 /*SuppressUserConversions*/false,
5905                                 /*InOverloadResolution=*/true,
5906                                 /*AllowObjCWritebackConversion=*/
5907                                 getLangOpts().ObjCAutoRefCount,
5908                                 /*AllowExplicit*/false);
5909         if (ConversionState.isBad()) {
5910           Match = false;
5911           break;
5912         }
5913     }
5914     // Promote additional arguments to variadic methods.
5915     if (Match && Method->isVariadic()) {
5916       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5917         if (Args[i]->isTypeDependent()) {
5918           Match = false;
5919           break;
5920         }
5921         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5922                                                           nullptr);
5923         if (Arg.isInvalid()) {
5924           Match = false;
5925           break;
5926         }
5927       }
5928     } else {
5929       // Check for extra arguments to non-variadic methods.
5930       if (Args.size() != NumNamedArgs)
5931         Match = false;
5932       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5933         // Special case when selectors have no argument. In this case, select
5934         // one with the most general result type of 'id'.
5935         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5936           QualType ReturnT = Methods[b]->getReturnType();
5937           if (ReturnT->isObjCIdType())
5938             return Methods[b];
5939         }
5940       }
5941     }
5942 
5943     if (Match)
5944       return Method;
5945   }
5946   return nullptr;
5947 }
5948 
5949 // specific_attr_iterator iterates over enable_if attributes in reverse, and
5950 // enable_if is order-sensitive. As a result, we need to reverse things
5951 // sometimes. Size of 4 elements is arbitrary.
5952 static SmallVector<EnableIfAttr *, 4>
5953 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5954   SmallVector<EnableIfAttr *, 4> Result;
5955   if (!Function->hasAttrs())
5956     return Result;
5957 
5958   const auto &FuncAttrs = Function->getAttrs();
5959   for (Attr *Attr : FuncAttrs)
5960     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5961       Result.push_back(EnableIf);
5962 
5963   std::reverse(Result.begin(), Result.end());
5964   return Result;
5965 }
5966 
5967 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5968                                   bool MissingImplicitThis) {
5969   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5970   if (EnableIfAttrs.empty())
5971     return nullptr;
5972 
5973   SFINAETrap Trap(*this);
5974   SmallVector<Expr *, 16> ConvertedArgs;
5975   bool InitializationFailed = false;
5976 
5977   // Convert the arguments.
5978   for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5979     ExprResult R;
5980     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5981         !cast<CXXMethodDecl>(Function)->isStatic() &&
5982         !isa<CXXConstructorDecl>(Function)) {
5983       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5984       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5985                                               Method, Method);
5986     } else {
5987       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5988                                         Context, Function->getParamDecl(I)),
5989                                     SourceLocation(), Args[I]);
5990     }
5991 
5992     if (R.isInvalid()) {
5993       InitializationFailed = true;
5994       break;
5995     }
5996 
5997     ConvertedArgs.push_back(R.get());
5998   }
5999 
6000   if (InitializationFailed || Trap.hasErrorOccurred())
6001     return EnableIfAttrs[0];
6002 
6003   // Push default arguments if needed.
6004   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6005     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6006       ParmVarDecl *P = Function->getParamDecl(i);
6007       ExprResult R = PerformCopyInitialization(
6008           InitializedEntity::InitializeParameter(Context,
6009                                                  Function->getParamDecl(i)),
6010           SourceLocation(),
6011           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6012                                            : P->getDefaultArg());
6013       if (R.isInvalid()) {
6014         InitializationFailed = true;
6015         break;
6016       }
6017       ConvertedArgs.push_back(R.get());
6018     }
6019 
6020     if (InitializationFailed || Trap.hasErrorOccurred())
6021       return EnableIfAttrs[0];
6022   }
6023 
6024   for (auto *EIA : EnableIfAttrs) {
6025     APValue Result;
6026     // FIXME: This doesn't consider value-dependent cases, because doing so is
6027     // very difficult. Ideally, we should handle them more gracefully.
6028     if (!EIA->getCond()->EvaluateWithSubstitution(
6029             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6030       return EIA;
6031 
6032     if (!Result.isInt() || !Result.getInt().getBoolValue())
6033       return EIA;
6034   }
6035   return nullptr;
6036 }
6037 
6038 /// \brief Add all of the function declarations in the given function set to
6039 /// the overload candidate set.
6040 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6041                                  ArrayRef<Expr *> Args,
6042                                  OverloadCandidateSet& CandidateSet,
6043                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6044                                  bool SuppressUserConversions,
6045                                  bool PartialOverloading) {
6046   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6047     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6048     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6049       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6050         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6051                            cast<CXXMethodDecl>(FD)->getParent(),
6052                            Args[0]->getType(), Args[0]->Classify(Context),
6053                            Args.slice(1), CandidateSet,
6054                            SuppressUserConversions, PartialOverloading);
6055       else
6056         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6057                              SuppressUserConversions, PartialOverloading);
6058     } else {
6059       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6060       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6061           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6062         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6063                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6064                                    ExplicitTemplateArgs,
6065                                    Args[0]->getType(),
6066                                    Args[0]->Classify(Context), Args.slice(1),
6067                                    CandidateSet, SuppressUserConversions,
6068                                    PartialOverloading);
6069       else
6070         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6071                                      ExplicitTemplateArgs, Args,
6072                                      CandidateSet, SuppressUserConversions,
6073                                      PartialOverloading);
6074     }
6075   }
6076 }
6077 
6078 /// AddMethodCandidate - Adds a named decl (which is some kind of
6079 /// method) as a method candidate to the given overload set.
6080 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6081                               QualType ObjectType,
6082                               Expr::Classification ObjectClassification,
6083                               ArrayRef<Expr *> Args,
6084                               OverloadCandidateSet& CandidateSet,
6085                               bool SuppressUserConversions) {
6086   NamedDecl *Decl = FoundDecl.getDecl();
6087   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6088 
6089   if (isa<UsingShadowDecl>(Decl))
6090     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6091 
6092   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6093     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6094            "Expected a member function template");
6095     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6096                                /*ExplicitArgs*/ nullptr,
6097                                ObjectType, ObjectClassification,
6098                                Args, CandidateSet,
6099                                SuppressUserConversions);
6100   } else {
6101     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6102                        ObjectType, ObjectClassification,
6103                        Args,
6104                        CandidateSet, SuppressUserConversions);
6105   }
6106 }
6107 
6108 /// AddMethodCandidate - Adds the given C++ member function to the set
6109 /// of candidate functions, using the given function call arguments
6110 /// and the object argument (@c Object). For example, in a call
6111 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6112 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6113 /// allow user-defined conversions via constructors or conversion
6114 /// operators.
6115 void
6116 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6117                          CXXRecordDecl *ActingContext, QualType ObjectType,
6118                          Expr::Classification ObjectClassification,
6119                          ArrayRef<Expr *> Args,
6120                          OverloadCandidateSet &CandidateSet,
6121                          bool SuppressUserConversions,
6122                          bool PartialOverloading) {
6123   const FunctionProtoType *Proto
6124     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6125   assert(Proto && "Methods without a prototype cannot be overloaded");
6126   assert(!isa<CXXConstructorDecl>(Method) &&
6127          "Use AddOverloadCandidate for constructors");
6128 
6129   if (!CandidateSet.isNewCandidate(Method))
6130     return;
6131 
6132   // C++11 [class.copy]p23: [DR1402]
6133   //   A defaulted move assignment operator that is defined as deleted is
6134   //   ignored by overload resolution.
6135   if (Method->isDefaulted() && Method->isDeleted() &&
6136       Method->isMoveAssignmentOperator())
6137     return;
6138 
6139   // Overload resolution is always an unevaluated context.
6140   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6141 
6142   // Add this candidate
6143   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6144   Candidate.FoundDecl = FoundDecl;
6145   Candidate.Function = Method;
6146   Candidate.IsSurrogate = false;
6147   Candidate.IgnoreObjectArgument = false;
6148   Candidate.ExplicitCallArguments = Args.size();
6149 
6150   unsigned NumParams = Proto->getNumParams();
6151 
6152   // (C++ 13.3.2p2): A candidate function having fewer than m
6153   // parameters is viable only if it has an ellipsis in its parameter
6154   // list (8.3.5).
6155   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6156       !Proto->isVariadic()) {
6157     Candidate.Viable = false;
6158     Candidate.FailureKind = ovl_fail_too_many_arguments;
6159     return;
6160   }
6161 
6162   // (C++ 13.3.2p2): A candidate function having more than m parameters
6163   // is viable only if the (m+1)st parameter has a default argument
6164   // (8.3.6). For the purposes of overload resolution, the
6165   // parameter list is truncated on the right, so that there are
6166   // exactly m parameters.
6167   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6168   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6169     // Not enough arguments.
6170     Candidate.Viable = false;
6171     Candidate.FailureKind = ovl_fail_too_few_arguments;
6172     return;
6173   }
6174 
6175   Candidate.Viable = true;
6176 
6177   if (Method->isStatic() || ObjectType.isNull())
6178     // The implicit object argument is ignored.
6179     Candidate.IgnoreObjectArgument = true;
6180   else {
6181     // Determine the implicit conversion sequence for the object
6182     // parameter.
6183     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6184         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6185         Method, ActingContext);
6186     if (Candidate.Conversions[0].isBad()) {
6187       Candidate.Viable = false;
6188       Candidate.FailureKind = ovl_fail_bad_conversion;
6189       return;
6190     }
6191   }
6192 
6193   // (CUDA B.1): Check for invalid calls between targets.
6194   if (getLangOpts().CUDA)
6195     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6196       if (!IsAllowedCUDACall(Caller, Method)) {
6197         Candidate.Viable = false;
6198         Candidate.FailureKind = ovl_fail_bad_target;
6199         return;
6200       }
6201 
6202   // Determine the implicit conversion sequences for each of the
6203   // arguments.
6204   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6205     if (ArgIdx < NumParams) {
6206       // (C++ 13.3.2p3): for F to be a viable function, there shall
6207       // exist for each argument an implicit conversion sequence
6208       // (13.3.3.1) that converts that argument to the corresponding
6209       // parameter of F.
6210       QualType ParamType = Proto->getParamType(ArgIdx);
6211       Candidate.Conversions[ArgIdx + 1]
6212         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6213                                 SuppressUserConversions,
6214                                 /*InOverloadResolution=*/true,
6215                                 /*AllowObjCWritebackConversion=*/
6216                                   getLangOpts().ObjCAutoRefCount);
6217       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6218         Candidate.Viable = false;
6219         Candidate.FailureKind = ovl_fail_bad_conversion;
6220         return;
6221       }
6222     } else {
6223       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6224       // argument for which there is no corresponding parameter is
6225       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6226       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6227     }
6228   }
6229 
6230   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6231     Candidate.Viable = false;
6232     Candidate.FailureKind = ovl_fail_enable_if;
6233     Candidate.DeductionFailure.Data = FailedAttr;
6234     return;
6235   }
6236 }
6237 
6238 /// \brief Add a C++ member function template as a candidate to the candidate
6239 /// set, using template argument deduction to produce an appropriate member
6240 /// function template specialization.
6241 void
6242 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6243                                  DeclAccessPair FoundDecl,
6244                                  CXXRecordDecl *ActingContext,
6245                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6246                                  QualType ObjectType,
6247                                  Expr::Classification ObjectClassification,
6248                                  ArrayRef<Expr *> Args,
6249                                  OverloadCandidateSet& CandidateSet,
6250                                  bool SuppressUserConversions,
6251                                  bool PartialOverloading) {
6252   if (!CandidateSet.isNewCandidate(MethodTmpl))
6253     return;
6254 
6255   // C++ [over.match.funcs]p7:
6256   //   In each case where a candidate is a function template, candidate
6257   //   function template specializations are generated using template argument
6258   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6259   //   candidate functions in the usual way.113) A given name can refer to one
6260   //   or more function templates and also to a set of overloaded non-template
6261   //   functions. In such a case, the candidate functions generated from each
6262   //   function template are combined with the set of non-template candidate
6263   //   functions.
6264   TemplateDeductionInfo Info(CandidateSet.getLocation());
6265   FunctionDecl *Specialization = nullptr;
6266   if (TemplateDeductionResult Result
6267       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6268                                 Specialization, Info, PartialOverloading)) {
6269     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6270     Candidate.FoundDecl = FoundDecl;
6271     Candidate.Function = MethodTmpl->getTemplatedDecl();
6272     Candidate.Viable = false;
6273     Candidate.FailureKind = ovl_fail_bad_deduction;
6274     Candidate.IsSurrogate = false;
6275     Candidate.IgnoreObjectArgument = false;
6276     Candidate.ExplicitCallArguments = Args.size();
6277     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6278                                                           Info);
6279     return;
6280   }
6281 
6282   // Add the function template specialization produced by template argument
6283   // deduction as a candidate.
6284   assert(Specialization && "Missing member function template specialization?");
6285   assert(isa<CXXMethodDecl>(Specialization) &&
6286          "Specialization is not a member function?");
6287   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6288                      ActingContext, ObjectType, ObjectClassification, Args,
6289                      CandidateSet, SuppressUserConversions, PartialOverloading);
6290 }
6291 
6292 /// \brief Add a C++ function template specialization as a candidate
6293 /// in the candidate set, using template argument deduction to produce
6294 /// an appropriate function template specialization.
6295 void
6296 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6297                                    DeclAccessPair FoundDecl,
6298                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6299                                    ArrayRef<Expr *> Args,
6300                                    OverloadCandidateSet& CandidateSet,
6301                                    bool SuppressUserConversions,
6302                                    bool PartialOverloading) {
6303   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6304     return;
6305 
6306   // C++ [over.match.funcs]p7:
6307   //   In each case where a candidate is a function template, candidate
6308   //   function template specializations are generated using template argument
6309   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6310   //   candidate functions in the usual way.113) A given name can refer to one
6311   //   or more function templates and also to a set of overloaded non-template
6312   //   functions. In such a case, the candidate functions generated from each
6313   //   function template are combined with the set of non-template candidate
6314   //   functions.
6315   TemplateDeductionInfo Info(CandidateSet.getLocation());
6316   FunctionDecl *Specialization = nullptr;
6317   if (TemplateDeductionResult Result
6318         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6319                                   Specialization, Info, PartialOverloading)) {
6320     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6321     Candidate.FoundDecl = FoundDecl;
6322     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6323     Candidate.Viable = false;
6324     Candidate.FailureKind = ovl_fail_bad_deduction;
6325     Candidate.IsSurrogate = false;
6326     Candidate.IgnoreObjectArgument = false;
6327     Candidate.ExplicitCallArguments = Args.size();
6328     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6329                                                           Info);
6330     return;
6331   }
6332 
6333   // Add the function template specialization produced by template argument
6334   // deduction as a candidate.
6335   assert(Specialization && "Missing function template specialization?");
6336   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6337                        SuppressUserConversions, PartialOverloading);
6338 }
6339 
6340 /// Determine whether this is an allowable conversion from the result
6341 /// of an explicit conversion operator to the expected type, per C++
6342 /// [over.match.conv]p1 and [over.match.ref]p1.
6343 ///
6344 /// \param ConvType The return type of the conversion function.
6345 ///
6346 /// \param ToType The type we are converting to.
6347 ///
6348 /// \param AllowObjCPointerConversion Allow a conversion from one
6349 /// Objective-C pointer to another.
6350 ///
6351 /// \returns true if the conversion is allowable, false otherwise.
6352 static bool isAllowableExplicitConversion(Sema &S,
6353                                           QualType ConvType, QualType ToType,
6354                                           bool AllowObjCPointerConversion) {
6355   QualType ToNonRefType = ToType.getNonReferenceType();
6356 
6357   // Easy case: the types are the same.
6358   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6359     return true;
6360 
6361   // Allow qualification conversions.
6362   bool ObjCLifetimeConversion;
6363   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6364                                   ObjCLifetimeConversion))
6365     return true;
6366 
6367   // If we're not allowed to consider Objective-C pointer conversions,
6368   // we're done.
6369   if (!AllowObjCPointerConversion)
6370     return false;
6371 
6372   // Is this an Objective-C pointer conversion?
6373   bool IncompatibleObjC = false;
6374   QualType ConvertedType;
6375   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6376                                    IncompatibleObjC);
6377 }
6378 
6379 /// AddConversionCandidate - Add a C++ conversion function as a
6380 /// candidate in the candidate set (C++ [over.match.conv],
6381 /// C++ [over.match.copy]). From is the expression we're converting from,
6382 /// and ToType is the type that we're eventually trying to convert to
6383 /// (which may or may not be the same type as the type that the
6384 /// conversion function produces).
6385 void
6386 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6387                              DeclAccessPair FoundDecl,
6388                              CXXRecordDecl *ActingContext,
6389                              Expr *From, QualType ToType,
6390                              OverloadCandidateSet& CandidateSet,
6391                              bool AllowObjCConversionOnExplicit) {
6392   assert(!Conversion->getDescribedFunctionTemplate() &&
6393          "Conversion function templates use AddTemplateConversionCandidate");
6394   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6395   if (!CandidateSet.isNewCandidate(Conversion))
6396     return;
6397 
6398   // If the conversion function has an undeduced return type, trigger its
6399   // deduction now.
6400   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6401     if (DeduceReturnType(Conversion, From->getExprLoc()))
6402       return;
6403     ConvType = Conversion->getConversionType().getNonReferenceType();
6404   }
6405 
6406   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6407   // operator is only a candidate if its return type is the target type or
6408   // can be converted to the target type with a qualification conversion.
6409   if (Conversion->isExplicit() &&
6410       !isAllowableExplicitConversion(*this, ConvType, ToType,
6411                                      AllowObjCConversionOnExplicit))
6412     return;
6413 
6414   // Overload resolution is always an unevaluated context.
6415   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6416 
6417   // Add this candidate
6418   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6419   Candidate.FoundDecl = FoundDecl;
6420   Candidate.Function = Conversion;
6421   Candidate.IsSurrogate = false;
6422   Candidate.IgnoreObjectArgument = false;
6423   Candidate.FinalConversion.setAsIdentityConversion();
6424   Candidate.FinalConversion.setFromType(ConvType);
6425   Candidate.FinalConversion.setAllToTypes(ToType);
6426   Candidate.Viable = true;
6427   Candidate.ExplicitCallArguments = 1;
6428 
6429   // C++ [over.match.funcs]p4:
6430   //   For conversion functions, the function is considered to be a member of
6431   //   the class of the implicit implied object argument for the purpose of
6432   //   defining the type of the implicit object parameter.
6433   //
6434   // Determine the implicit conversion sequence for the implicit
6435   // object parameter.
6436   QualType ImplicitParamType = From->getType();
6437   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6438     ImplicitParamType = FromPtrType->getPointeeType();
6439   CXXRecordDecl *ConversionContext
6440     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6441 
6442   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6443       *this, CandidateSet.getLocation(), From->getType(),
6444       From->Classify(Context), Conversion, ConversionContext);
6445 
6446   if (Candidate.Conversions[0].isBad()) {
6447     Candidate.Viable = false;
6448     Candidate.FailureKind = ovl_fail_bad_conversion;
6449     return;
6450   }
6451 
6452   // We won't go through a user-defined type conversion function to convert a
6453   // derived to base as such conversions are given Conversion Rank. They only
6454   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6455   QualType FromCanon
6456     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6457   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6458   if (FromCanon == ToCanon ||
6459       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6460     Candidate.Viable = false;
6461     Candidate.FailureKind = ovl_fail_trivial_conversion;
6462     return;
6463   }
6464 
6465   // To determine what the conversion from the result of calling the
6466   // conversion function to the type we're eventually trying to
6467   // convert to (ToType), we need to synthesize a call to the
6468   // conversion function and attempt copy initialization from it. This
6469   // makes sure that we get the right semantics with respect to
6470   // lvalues/rvalues and the type. Fortunately, we can allocate this
6471   // call on the stack and we don't need its arguments to be
6472   // well-formed.
6473   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6474                             VK_LValue, From->getLocStart());
6475   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6476                                 Context.getPointerType(Conversion->getType()),
6477                                 CK_FunctionToPointerDecay,
6478                                 &ConversionRef, VK_RValue);
6479 
6480   QualType ConversionType = Conversion->getConversionType();
6481   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6482     Candidate.Viable = false;
6483     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6484     return;
6485   }
6486 
6487   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6488 
6489   // Note that it is safe to allocate CallExpr on the stack here because
6490   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6491   // allocator).
6492   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6493   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6494                 From->getLocStart());
6495   ImplicitConversionSequence ICS =
6496     TryCopyInitialization(*this, &Call, ToType,
6497                           /*SuppressUserConversions=*/true,
6498                           /*InOverloadResolution=*/false,
6499                           /*AllowObjCWritebackConversion=*/false);
6500 
6501   switch (ICS.getKind()) {
6502   case ImplicitConversionSequence::StandardConversion:
6503     Candidate.FinalConversion = ICS.Standard;
6504 
6505     // C++ [over.ics.user]p3:
6506     //   If the user-defined conversion is specified by a specialization of a
6507     //   conversion function template, the second standard conversion sequence
6508     //   shall have exact match rank.
6509     if (Conversion->getPrimaryTemplate() &&
6510         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6511       Candidate.Viable = false;
6512       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6513       return;
6514     }
6515 
6516     // C++0x [dcl.init.ref]p5:
6517     //    In the second case, if the reference is an rvalue reference and
6518     //    the second standard conversion sequence of the user-defined
6519     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6520     //    program is ill-formed.
6521     if (ToType->isRValueReferenceType() &&
6522         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6523       Candidate.Viable = false;
6524       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6525       return;
6526     }
6527     break;
6528 
6529   case ImplicitConversionSequence::BadConversion:
6530     Candidate.Viable = false;
6531     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6532     return;
6533 
6534   default:
6535     llvm_unreachable(
6536            "Can only end up with a standard conversion sequence or failure");
6537   }
6538 
6539   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6540     Candidate.Viable = false;
6541     Candidate.FailureKind = ovl_fail_enable_if;
6542     Candidate.DeductionFailure.Data = FailedAttr;
6543     return;
6544   }
6545 }
6546 
6547 /// \brief Adds a conversion function template specialization
6548 /// candidate to the overload set, using template argument deduction
6549 /// to deduce the template arguments of the conversion function
6550 /// template from the type that we are converting to (C++
6551 /// [temp.deduct.conv]).
6552 void
6553 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6554                                      DeclAccessPair FoundDecl,
6555                                      CXXRecordDecl *ActingDC,
6556                                      Expr *From, QualType ToType,
6557                                      OverloadCandidateSet &CandidateSet,
6558                                      bool AllowObjCConversionOnExplicit) {
6559   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6560          "Only conversion function templates permitted here");
6561 
6562   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6563     return;
6564 
6565   TemplateDeductionInfo Info(CandidateSet.getLocation());
6566   CXXConversionDecl *Specialization = nullptr;
6567   if (TemplateDeductionResult Result
6568         = DeduceTemplateArguments(FunctionTemplate, ToType,
6569                                   Specialization, Info)) {
6570     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6571     Candidate.FoundDecl = FoundDecl;
6572     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6573     Candidate.Viable = false;
6574     Candidate.FailureKind = ovl_fail_bad_deduction;
6575     Candidate.IsSurrogate = false;
6576     Candidate.IgnoreObjectArgument = false;
6577     Candidate.ExplicitCallArguments = 1;
6578     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6579                                                           Info);
6580     return;
6581   }
6582 
6583   // Add the conversion function template specialization produced by
6584   // template argument deduction as a candidate.
6585   assert(Specialization && "Missing function template specialization?");
6586   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6587                          CandidateSet, AllowObjCConversionOnExplicit);
6588 }
6589 
6590 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6591 /// converts the given @c Object to a function pointer via the
6592 /// conversion function @c Conversion, and then attempts to call it
6593 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6594 /// the type of function that we'll eventually be calling.
6595 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6596                                  DeclAccessPair FoundDecl,
6597                                  CXXRecordDecl *ActingContext,
6598                                  const FunctionProtoType *Proto,
6599                                  Expr *Object,
6600                                  ArrayRef<Expr *> Args,
6601                                  OverloadCandidateSet& CandidateSet) {
6602   if (!CandidateSet.isNewCandidate(Conversion))
6603     return;
6604 
6605   // Overload resolution is always an unevaluated context.
6606   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6607 
6608   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6609   Candidate.FoundDecl = FoundDecl;
6610   Candidate.Function = nullptr;
6611   Candidate.Surrogate = Conversion;
6612   Candidate.Viable = true;
6613   Candidate.IsSurrogate = true;
6614   Candidate.IgnoreObjectArgument = false;
6615   Candidate.ExplicitCallArguments = Args.size();
6616 
6617   // Determine the implicit conversion sequence for the implicit
6618   // object parameter.
6619   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6620       *this, CandidateSet.getLocation(), Object->getType(),
6621       Object->Classify(Context), Conversion, ActingContext);
6622   if (ObjectInit.isBad()) {
6623     Candidate.Viable = false;
6624     Candidate.FailureKind = ovl_fail_bad_conversion;
6625     Candidate.Conversions[0] = ObjectInit;
6626     return;
6627   }
6628 
6629   // The first conversion is actually a user-defined conversion whose
6630   // first conversion is ObjectInit's standard conversion (which is
6631   // effectively a reference binding). Record it as such.
6632   Candidate.Conversions[0].setUserDefined();
6633   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6634   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6635   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6636   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6637   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6638   Candidate.Conversions[0].UserDefined.After
6639     = Candidate.Conversions[0].UserDefined.Before;
6640   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6641 
6642   // Find the
6643   unsigned NumParams = Proto->getNumParams();
6644 
6645   // (C++ 13.3.2p2): A candidate function having fewer than m
6646   // parameters is viable only if it has an ellipsis in its parameter
6647   // list (8.3.5).
6648   if (Args.size() > NumParams && !Proto->isVariadic()) {
6649     Candidate.Viable = false;
6650     Candidate.FailureKind = ovl_fail_too_many_arguments;
6651     return;
6652   }
6653 
6654   // Function types don't have any default arguments, so just check if
6655   // we have enough arguments.
6656   if (Args.size() < NumParams) {
6657     // Not enough arguments.
6658     Candidate.Viable = false;
6659     Candidate.FailureKind = ovl_fail_too_few_arguments;
6660     return;
6661   }
6662 
6663   // Determine the implicit conversion sequences for each of the
6664   // arguments.
6665   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6666     if (ArgIdx < NumParams) {
6667       // (C++ 13.3.2p3): for F to be a viable function, there shall
6668       // exist for each argument an implicit conversion sequence
6669       // (13.3.3.1) that converts that argument to the corresponding
6670       // parameter of F.
6671       QualType ParamType = Proto->getParamType(ArgIdx);
6672       Candidate.Conversions[ArgIdx + 1]
6673         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6674                                 /*SuppressUserConversions=*/false,
6675                                 /*InOverloadResolution=*/false,
6676                                 /*AllowObjCWritebackConversion=*/
6677                                   getLangOpts().ObjCAutoRefCount);
6678       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6679         Candidate.Viable = false;
6680         Candidate.FailureKind = ovl_fail_bad_conversion;
6681         return;
6682       }
6683     } else {
6684       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6685       // argument for which there is no corresponding parameter is
6686       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6687       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6688     }
6689   }
6690 
6691   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6692     Candidate.Viable = false;
6693     Candidate.FailureKind = ovl_fail_enable_if;
6694     Candidate.DeductionFailure.Data = FailedAttr;
6695     return;
6696   }
6697 }
6698 
6699 /// \brief Add overload candidates for overloaded operators that are
6700 /// member functions.
6701 ///
6702 /// Add the overloaded operator candidates that are member functions
6703 /// for the operator Op that was used in an operator expression such
6704 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6705 /// CandidateSet will store the added overload candidates. (C++
6706 /// [over.match.oper]).
6707 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6708                                        SourceLocation OpLoc,
6709                                        ArrayRef<Expr *> Args,
6710                                        OverloadCandidateSet& CandidateSet,
6711                                        SourceRange OpRange) {
6712   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6713 
6714   // C++ [over.match.oper]p3:
6715   //   For a unary operator @ with an operand of a type whose
6716   //   cv-unqualified version is T1, and for a binary operator @ with
6717   //   a left operand of a type whose cv-unqualified version is T1 and
6718   //   a right operand of a type whose cv-unqualified version is T2,
6719   //   three sets of candidate functions, designated member
6720   //   candidates, non-member candidates and built-in candidates, are
6721   //   constructed as follows:
6722   QualType T1 = Args[0]->getType();
6723 
6724   //     -- If T1 is a complete class type or a class currently being
6725   //        defined, the set of member candidates is the result of the
6726   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6727   //        the set of member candidates is empty.
6728   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6729     // Complete the type if it can be completed.
6730     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6731       return;
6732     // If the type is neither complete nor being defined, bail out now.
6733     if (!T1Rec->getDecl()->getDefinition())
6734       return;
6735 
6736     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6737     LookupQualifiedName(Operators, T1Rec->getDecl());
6738     Operators.suppressDiagnostics();
6739 
6740     for (LookupResult::iterator Oper = Operators.begin(),
6741                              OperEnd = Operators.end();
6742          Oper != OperEnd;
6743          ++Oper)
6744       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6745                          Args[0]->Classify(Context),
6746                          Args.slice(1),
6747                          CandidateSet,
6748                          /* SuppressUserConversions = */ false);
6749   }
6750 }
6751 
6752 /// AddBuiltinCandidate - Add a candidate for a built-in
6753 /// operator. ResultTy and ParamTys are the result and parameter types
6754 /// of the built-in candidate, respectively. Args and NumArgs are the
6755 /// arguments being passed to the candidate. IsAssignmentOperator
6756 /// should be true when this built-in candidate is an assignment
6757 /// operator. NumContextualBoolArguments is the number of arguments
6758 /// (at the beginning of the argument list) that will be contextually
6759 /// converted to bool.
6760 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6761                                ArrayRef<Expr *> Args,
6762                                OverloadCandidateSet& CandidateSet,
6763                                bool IsAssignmentOperator,
6764                                unsigned NumContextualBoolArguments) {
6765   // Overload resolution is always an unevaluated context.
6766   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6767 
6768   // Add this candidate
6769   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6770   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6771   Candidate.Function = nullptr;
6772   Candidate.IsSurrogate = false;
6773   Candidate.IgnoreObjectArgument = false;
6774   Candidate.BuiltinTypes.ResultTy = ResultTy;
6775   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6776     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6777 
6778   // Determine the implicit conversion sequences for each of the
6779   // arguments.
6780   Candidate.Viable = true;
6781   Candidate.ExplicitCallArguments = Args.size();
6782   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6783     // C++ [over.match.oper]p4:
6784     //   For the built-in assignment operators, conversions of the
6785     //   left operand are restricted as follows:
6786     //     -- no temporaries are introduced to hold the left operand, and
6787     //     -- no user-defined conversions are applied to the left
6788     //        operand to achieve a type match with the left-most
6789     //        parameter of a built-in candidate.
6790     //
6791     // We block these conversions by turning off user-defined
6792     // conversions, since that is the only way that initialization of
6793     // a reference to a non-class type can occur from something that
6794     // is not of the same type.
6795     if (ArgIdx < NumContextualBoolArguments) {
6796       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6797              "Contextual conversion to bool requires bool type");
6798       Candidate.Conversions[ArgIdx]
6799         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6800     } else {
6801       Candidate.Conversions[ArgIdx]
6802         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6803                                 ArgIdx == 0 && IsAssignmentOperator,
6804                                 /*InOverloadResolution=*/false,
6805                                 /*AllowObjCWritebackConversion=*/
6806                                   getLangOpts().ObjCAutoRefCount);
6807     }
6808     if (Candidate.Conversions[ArgIdx].isBad()) {
6809       Candidate.Viable = false;
6810       Candidate.FailureKind = ovl_fail_bad_conversion;
6811       break;
6812     }
6813   }
6814 }
6815 
6816 namespace {
6817 
6818 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6819 /// candidate operator functions for built-in operators (C++
6820 /// [over.built]). The types are separated into pointer types and
6821 /// enumeration types.
6822 class BuiltinCandidateTypeSet  {
6823   /// TypeSet - A set of types.
6824   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6825                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6826 
6827   /// PointerTypes - The set of pointer types that will be used in the
6828   /// built-in candidates.
6829   TypeSet PointerTypes;
6830 
6831   /// MemberPointerTypes - The set of member pointer types that will be
6832   /// used in the built-in candidates.
6833   TypeSet MemberPointerTypes;
6834 
6835   /// EnumerationTypes - The set of enumeration types that will be
6836   /// used in the built-in candidates.
6837   TypeSet EnumerationTypes;
6838 
6839   /// \brief The set of vector types that will be used in the built-in
6840   /// candidates.
6841   TypeSet VectorTypes;
6842 
6843   /// \brief A flag indicating non-record types are viable candidates
6844   bool HasNonRecordTypes;
6845 
6846   /// \brief A flag indicating whether either arithmetic or enumeration types
6847   /// were present in the candidate set.
6848   bool HasArithmeticOrEnumeralTypes;
6849 
6850   /// \brief A flag indicating whether the nullptr type was present in the
6851   /// candidate set.
6852   bool HasNullPtrType;
6853 
6854   /// Sema - The semantic analysis instance where we are building the
6855   /// candidate type set.
6856   Sema &SemaRef;
6857 
6858   /// Context - The AST context in which we will build the type sets.
6859   ASTContext &Context;
6860 
6861   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6862                                                const Qualifiers &VisibleQuals);
6863   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6864 
6865 public:
6866   /// iterator - Iterates through the types that are part of the set.
6867   typedef TypeSet::iterator iterator;
6868 
6869   BuiltinCandidateTypeSet(Sema &SemaRef)
6870     : HasNonRecordTypes(false),
6871       HasArithmeticOrEnumeralTypes(false),
6872       HasNullPtrType(false),
6873       SemaRef(SemaRef),
6874       Context(SemaRef.Context) { }
6875 
6876   void AddTypesConvertedFrom(QualType Ty,
6877                              SourceLocation Loc,
6878                              bool AllowUserConversions,
6879                              bool AllowExplicitConversions,
6880                              const Qualifiers &VisibleTypeConversionsQuals);
6881 
6882   /// pointer_begin - First pointer type found;
6883   iterator pointer_begin() { return PointerTypes.begin(); }
6884 
6885   /// pointer_end - Past the last pointer type found;
6886   iterator pointer_end() { return PointerTypes.end(); }
6887 
6888   /// member_pointer_begin - First member pointer type found;
6889   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6890 
6891   /// member_pointer_end - Past the last member pointer type found;
6892   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6893 
6894   /// enumeration_begin - First enumeration type found;
6895   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6896 
6897   /// enumeration_end - Past the last enumeration type found;
6898   iterator enumeration_end() { return EnumerationTypes.end(); }
6899 
6900   iterator vector_begin() { return VectorTypes.begin(); }
6901   iterator vector_end() { return VectorTypes.end(); }
6902 
6903   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6904   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6905   bool hasNullPtrType() const { return HasNullPtrType; }
6906 };
6907 
6908 } // end anonymous namespace
6909 
6910 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6911 /// the set of pointer types along with any more-qualified variants of
6912 /// that type. For example, if @p Ty is "int const *", this routine
6913 /// will add "int const *", "int const volatile *", "int const
6914 /// restrict *", and "int const volatile restrict *" to the set of
6915 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6916 /// false otherwise.
6917 ///
6918 /// FIXME: what to do about extended qualifiers?
6919 bool
6920 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6921                                              const Qualifiers &VisibleQuals) {
6922 
6923   // Insert this type.
6924   if (!PointerTypes.insert(Ty))
6925     return false;
6926 
6927   QualType PointeeTy;
6928   const PointerType *PointerTy = Ty->getAs<PointerType>();
6929   bool buildObjCPtr = false;
6930   if (!PointerTy) {
6931     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6932     PointeeTy = PTy->getPointeeType();
6933     buildObjCPtr = true;
6934   } else {
6935     PointeeTy = PointerTy->getPointeeType();
6936   }
6937 
6938   // Don't add qualified variants of arrays. For one, they're not allowed
6939   // (the qualifier would sink to the element type), and for another, the
6940   // only overload situation where it matters is subscript or pointer +- int,
6941   // and those shouldn't have qualifier variants anyway.
6942   if (PointeeTy->isArrayType())
6943     return true;
6944 
6945   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6946   bool hasVolatile = VisibleQuals.hasVolatile();
6947   bool hasRestrict = VisibleQuals.hasRestrict();
6948 
6949   // Iterate through all strict supersets of BaseCVR.
6950   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6951     if ((CVR | BaseCVR) != CVR) continue;
6952     // Skip over volatile if no volatile found anywhere in the types.
6953     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6954 
6955     // Skip over restrict if no restrict found anywhere in the types, or if
6956     // the type cannot be restrict-qualified.
6957     if ((CVR & Qualifiers::Restrict) &&
6958         (!hasRestrict ||
6959          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6960       continue;
6961 
6962     // Build qualified pointee type.
6963     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6964 
6965     // Build qualified pointer type.
6966     QualType QPointerTy;
6967     if (!buildObjCPtr)
6968       QPointerTy = Context.getPointerType(QPointeeTy);
6969     else
6970       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6971 
6972     // Insert qualified pointer type.
6973     PointerTypes.insert(QPointerTy);
6974   }
6975 
6976   return true;
6977 }
6978 
6979 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6980 /// to the set of pointer types along with any more-qualified variants of
6981 /// that type. For example, if @p Ty is "int const *", this routine
6982 /// will add "int const *", "int const volatile *", "int const
6983 /// restrict *", and "int const volatile restrict *" to the set of
6984 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6985 /// false otherwise.
6986 ///
6987 /// FIXME: what to do about extended qualifiers?
6988 bool
6989 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6990     QualType Ty) {
6991   // Insert this type.
6992   if (!MemberPointerTypes.insert(Ty))
6993     return false;
6994 
6995   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6996   assert(PointerTy && "type was not a member pointer type!");
6997 
6998   QualType PointeeTy = PointerTy->getPointeeType();
6999   // Don't add qualified variants of arrays. For one, they're not allowed
7000   // (the qualifier would sink to the element type), and for another, the
7001   // only overload situation where it matters is subscript or pointer +- int,
7002   // and those shouldn't have qualifier variants anyway.
7003   if (PointeeTy->isArrayType())
7004     return true;
7005   const Type *ClassTy = PointerTy->getClass();
7006 
7007   // Iterate through all strict supersets of the pointee type's CVR
7008   // qualifiers.
7009   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7010   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7011     if ((CVR | BaseCVR) != CVR) continue;
7012 
7013     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7014     MemberPointerTypes.insert(
7015       Context.getMemberPointerType(QPointeeTy, ClassTy));
7016   }
7017 
7018   return true;
7019 }
7020 
7021 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7022 /// Ty can be implicit converted to the given set of @p Types. We're
7023 /// primarily interested in pointer types and enumeration types. We also
7024 /// take member pointer types, for the conditional operator.
7025 /// AllowUserConversions is true if we should look at the conversion
7026 /// functions of a class type, and AllowExplicitConversions if we
7027 /// should also include the explicit conversion functions of a class
7028 /// type.
7029 void
7030 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7031                                                SourceLocation Loc,
7032                                                bool AllowUserConversions,
7033                                                bool AllowExplicitConversions,
7034                                                const Qualifiers &VisibleQuals) {
7035   // Only deal with canonical types.
7036   Ty = Context.getCanonicalType(Ty);
7037 
7038   // Look through reference types; they aren't part of the type of an
7039   // expression for the purposes of conversions.
7040   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7041     Ty = RefTy->getPointeeType();
7042 
7043   // If we're dealing with an array type, decay to the pointer.
7044   if (Ty->isArrayType())
7045     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7046 
7047   // Otherwise, we don't care about qualifiers on the type.
7048   Ty = Ty.getLocalUnqualifiedType();
7049 
7050   // Flag if we ever add a non-record type.
7051   const RecordType *TyRec = Ty->getAs<RecordType>();
7052   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7053 
7054   // Flag if we encounter an arithmetic type.
7055   HasArithmeticOrEnumeralTypes =
7056     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7057 
7058   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7059     PointerTypes.insert(Ty);
7060   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7061     // Insert our type, and its more-qualified variants, into the set
7062     // of types.
7063     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7064       return;
7065   } else if (Ty->isMemberPointerType()) {
7066     // Member pointers are far easier, since the pointee can't be converted.
7067     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7068       return;
7069   } else if (Ty->isEnumeralType()) {
7070     HasArithmeticOrEnumeralTypes = true;
7071     EnumerationTypes.insert(Ty);
7072   } else if (Ty->isVectorType()) {
7073     // We treat vector types as arithmetic types in many contexts as an
7074     // extension.
7075     HasArithmeticOrEnumeralTypes = true;
7076     VectorTypes.insert(Ty);
7077   } else if (Ty->isNullPtrType()) {
7078     HasNullPtrType = true;
7079   } else if (AllowUserConversions && TyRec) {
7080     // No conversion functions in incomplete types.
7081     if (!SemaRef.isCompleteType(Loc, Ty))
7082       return;
7083 
7084     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7085     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7086       if (isa<UsingShadowDecl>(D))
7087         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7088 
7089       // Skip conversion function templates; they don't tell us anything
7090       // about which builtin types we can convert to.
7091       if (isa<FunctionTemplateDecl>(D))
7092         continue;
7093 
7094       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7095       if (AllowExplicitConversions || !Conv->isExplicit()) {
7096         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7097                               VisibleQuals);
7098       }
7099     }
7100   }
7101 }
7102 
7103 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7104 /// the volatile- and non-volatile-qualified assignment operators for the
7105 /// given type to the candidate set.
7106 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7107                                                    QualType T,
7108                                                    ArrayRef<Expr *> Args,
7109                                     OverloadCandidateSet &CandidateSet) {
7110   QualType ParamTypes[2];
7111 
7112   // T& operator=(T&, T)
7113   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7114   ParamTypes[1] = T;
7115   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7116                         /*IsAssignmentOperator=*/true);
7117 
7118   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7119     // volatile T& operator=(volatile T&, T)
7120     ParamTypes[0]
7121       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7122     ParamTypes[1] = T;
7123     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7124                           /*IsAssignmentOperator=*/true);
7125   }
7126 }
7127 
7128 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7129 /// if any, found in visible type conversion functions found in ArgExpr's type.
7130 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7131     Qualifiers VRQuals;
7132     const RecordType *TyRec;
7133     if (const MemberPointerType *RHSMPType =
7134         ArgExpr->getType()->getAs<MemberPointerType>())
7135       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7136     else
7137       TyRec = ArgExpr->getType()->getAs<RecordType>();
7138     if (!TyRec) {
7139       // Just to be safe, assume the worst case.
7140       VRQuals.addVolatile();
7141       VRQuals.addRestrict();
7142       return VRQuals;
7143     }
7144 
7145     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7146     if (!ClassDecl->hasDefinition())
7147       return VRQuals;
7148 
7149     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7150       if (isa<UsingShadowDecl>(D))
7151         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7152       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7153         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7154         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7155           CanTy = ResTypeRef->getPointeeType();
7156         // Need to go down the pointer/mempointer chain and add qualifiers
7157         // as see them.
7158         bool done = false;
7159         while (!done) {
7160           if (CanTy.isRestrictQualified())
7161             VRQuals.addRestrict();
7162           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7163             CanTy = ResTypePtr->getPointeeType();
7164           else if (const MemberPointerType *ResTypeMPtr =
7165                 CanTy->getAs<MemberPointerType>())
7166             CanTy = ResTypeMPtr->getPointeeType();
7167           else
7168             done = true;
7169           if (CanTy.isVolatileQualified())
7170             VRQuals.addVolatile();
7171           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7172             return VRQuals;
7173         }
7174       }
7175     }
7176     return VRQuals;
7177 }
7178 
7179 namespace {
7180 
7181 /// \brief Helper class to manage the addition of builtin operator overload
7182 /// candidates. It provides shared state and utility methods used throughout
7183 /// the process, as well as a helper method to add each group of builtin
7184 /// operator overloads from the standard to a candidate set.
7185 class BuiltinOperatorOverloadBuilder {
7186   // Common instance state available to all overload candidate addition methods.
7187   Sema &S;
7188   ArrayRef<Expr *> Args;
7189   Qualifiers VisibleTypeConversionsQuals;
7190   bool HasArithmeticOrEnumeralCandidateType;
7191   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7192   OverloadCandidateSet &CandidateSet;
7193 
7194   // Define some constants used to index and iterate over the arithemetic types
7195   // provided via the getArithmeticType() method below.
7196   // The "promoted arithmetic types" are the arithmetic
7197   // types are that preserved by promotion (C++ [over.built]p2).
7198   static const unsigned FirstIntegralType = 4;
7199   static const unsigned LastIntegralType = 21;
7200   static const unsigned FirstPromotedIntegralType = 4,
7201                         LastPromotedIntegralType = 12;
7202   static const unsigned FirstPromotedArithmeticType = 0,
7203                         LastPromotedArithmeticType = 12;
7204   static const unsigned NumArithmeticTypes = 21;
7205 
7206   /// \brief Get the canonical type for a given arithmetic type index.
7207   CanQualType getArithmeticType(unsigned index) {
7208     assert(index < NumArithmeticTypes);
7209     static CanQualType ASTContext::* const
7210       ArithmeticTypes[NumArithmeticTypes] = {
7211       // Start of promoted types.
7212       &ASTContext::FloatTy,
7213       &ASTContext::DoubleTy,
7214       &ASTContext::LongDoubleTy,
7215       &ASTContext::Float128Ty,
7216 
7217       // Start of integral types.
7218       &ASTContext::IntTy,
7219       &ASTContext::LongTy,
7220       &ASTContext::LongLongTy,
7221       &ASTContext::Int128Ty,
7222       &ASTContext::UnsignedIntTy,
7223       &ASTContext::UnsignedLongTy,
7224       &ASTContext::UnsignedLongLongTy,
7225       &ASTContext::UnsignedInt128Ty,
7226       // End of promoted types.
7227 
7228       &ASTContext::BoolTy,
7229       &ASTContext::CharTy,
7230       &ASTContext::WCharTy,
7231       &ASTContext::Char16Ty,
7232       &ASTContext::Char32Ty,
7233       &ASTContext::SignedCharTy,
7234       &ASTContext::ShortTy,
7235       &ASTContext::UnsignedCharTy,
7236       &ASTContext::UnsignedShortTy,
7237       // End of integral types.
7238       // FIXME: What about complex? What about half?
7239     };
7240     return S.Context.*ArithmeticTypes[index];
7241   }
7242 
7243   /// \brief Gets the canonical type resulting from the usual arithemetic
7244   /// converions for the given arithmetic types.
7245   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7246     // Accelerator table for performing the usual arithmetic conversions.
7247     // The rules are basically:
7248     //   - if either is floating-point, use the wider floating-point
7249     //   - if same signedness, use the higher rank
7250     //   - if same size, use unsigned of the higher rank
7251     //   - use the larger type
7252     // These rules, together with the axiom that higher ranks are
7253     // never smaller, are sufficient to precompute all of these results
7254     // *except* when dealing with signed types of higher rank.
7255     // (we could precompute SLL x UI for all known platforms, but it's
7256     // better not to make any assumptions).
7257     // We assume that int128 has a higher rank than long long on all platforms.
7258     enum PromotedType : int8_t {
7259             Dep=-1,
7260             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7261     };
7262     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7263                                         [LastPromotedArithmeticType] = {
7264 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7265 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7266 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7267 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7268 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7269 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7270 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7271 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7272 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7273 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7274 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7275     };
7276 
7277     assert(L < LastPromotedArithmeticType);
7278     assert(R < LastPromotedArithmeticType);
7279     int Idx = ConversionsTable[L][R];
7280 
7281     // Fast path: the table gives us a concrete answer.
7282     if (Idx != Dep) return getArithmeticType(Idx);
7283 
7284     // Slow path: we need to compare widths.
7285     // An invariant is that the signed type has higher rank.
7286     CanQualType LT = getArithmeticType(L),
7287                 RT = getArithmeticType(R);
7288     unsigned LW = S.Context.getIntWidth(LT),
7289              RW = S.Context.getIntWidth(RT);
7290 
7291     // If they're different widths, use the signed type.
7292     if (LW > RW) return LT;
7293     else if (LW < RW) return RT;
7294 
7295     // Otherwise, use the unsigned type of the signed type's rank.
7296     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7297     assert(L == SLL || R == SLL);
7298     return S.Context.UnsignedLongLongTy;
7299   }
7300 
7301   /// \brief Helper method to factor out the common pattern of adding overloads
7302   /// for '++' and '--' builtin operators.
7303   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7304                                            bool HasVolatile,
7305                                            bool HasRestrict) {
7306     QualType ParamTypes[2] = {
7307       S.Context.getLValueReferenceType(CandidateTy),
7308       S.Context.IntTy
7309     };
7310 
7311     // Non-volatile version.
7312     if (Args.size() == 1)
7313       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7314     else
7315       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7316 
7317     // Use a heuristic to reduce number of builtin candidates in the set:
7318     // add volatile version only if there are conversions to a volatile type.
7319     if (HasVolatile) {
7320       ParamTypes[0] =
7321         S.Context.getLValueReferenceType(
7322           S.Context.getVolatileType(CandidateTy));
7323       if (Args.size() == 1)
7324         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7325       else
7326         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7327     }
7328 
7329     // Add restrict version only if there are conversions to a restrict type
7330     // and our candidate type is a non-restrict-qualified pointer.
7331     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7332         !CandidateTy.isRestrictQualified()) {
7333       ParamTypes[0]
7334         = S.Context.getLValueReferenceType(
7335             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7336       if (Args.size() == 1)
7337         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7338       else
7339         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7340 
7341       if (HasVolatile) {
7342         ParamTypes[0]
7343           = S.Context.getLValueReferenceType(
7344               S.Context.getCVRQualifiedType(CandidateTy,
7345                                             (Qualifiers::Volatile |
7346                                              Qualifiers::Restrict)));
7347         if (Args.size() == 1)
7348           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7349         else
7350           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7351       }
7352     }
7353 
7354   }
7355 
7356 public:
7357   BuiltinOperatorOverloadBuilder(
7358     Sema &S, ArrayRef<Expr *> Args,
7359     Qualifiers VisibleTypeConversionsQuals,
7360     bool HasArithmeticOrEnumeralCandidateType,
7361     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7362     OverloadCandidateSet &CandidateSet)
7363     : S(S), Args(Args),
7364       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7365       HasArithmeticOrEnumeralCandidateType(
7366         HasArithmeticOrEnumeralCandidateType),
7367       CandidateTypes(CandidateTypes),
7368       CandidateSet(CandidateSet) {
7369     // Validate some of our static helper constants in debug builds.
7370     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7371            "Invalid first promoted integral type");
7372     assert(getArithmeticType(LastPromotedIntegralType - 1)
7373              == S.Context.UnsignedInt128Ty &&
7374            "Invalid last promoted integral type");
7375     assert(getArithmeticType(FirstPromotedArithmeticType)
7376              == S.Context.FloatTy &&
7377            "Invalid first promoted arithmetic type");
7378     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7379              == S.Context.UnsignedInt128Ty &&
7380            "Invalid last promoted arithmetic type");
7381   }
7382 
7383   // C++ [over.built]p3:
7384   //
7385   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7386   //   is either volatile or empty, there exist candidate operator
7387   //   functions of the form
7388   //
7389   //       VQ T&      operator++(VQ T&);
7390   //       T          operator++(VQ T&, int);
7391   //
7392   // C++ [over.built]p4:
7393   //
7394   //   For every pair (T, VQ), where T is an arithmetic type other
7395   //   than bool, and VQ is either volatile or empty, there exist
7396   //   candidate operator functions of the form
7397   //
7398   //       VQ T&      operator--(VQ T&);
7399   //       T          operator--(VQ T&, int);
7400   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7401     if (!HasArithmeticOrEnumeralCandidateType)
7402       return;
7403 
7404     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7405          Arith < NumArithmeticTypes; ++Arith) {
7406       addPlusPlusMinusMinusStyleOverloads(
7407         getArithmeticType(Arith),
7408         VisibleTypeConversionsQuals.hasVolatile(),
7409         VisibleTypeConversionsQuals.hasRestrict());
7410     }
7411   }
7412 
7413   // C++ [over.built]p5:
7414   //
7415   //   For every pair (T, VQ), where T is a cv-qualified or
7416   //   cv-unqualified object type, and VQ is either volatile or
7417   //   empty, there exist candidate operator functions of the form
7418   //
7419   //       T*VQ&      operator++(T*VQ&);
7420   //       T*VQ&      operator--(T*VQ&);
7421   //       T*         operator++(T*VQ&, int);
7422   //       T*         operator--(T*VQ&, int);
7423   void addPlusPlusMinusMinusPointerOverloads() {
7424     for (BuiltinCandidateTypeSet::iterator
7425               Ptr = CandidateTypes[0].pointer_begin(),
7426            PtrEnd = CandidateTypes[0].pointer_end();
7427          Ptr != PtrEnd; ++Ptr) {
7428       // Skip pointer types that aren't pointers to object types.
7429       if (!(*Ptr)->getPointeeType()->isObjectType())
7430         continue;
7431 
7432       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7433         (!(*Ptr).isVolatileQualified() &&
7434          VisibleTypeConversionsQuals.hasVolatile()),
7435         (!(*Ptr).isRestrictQualified() &&
7436          VisibleTypeConversionsQuals.hasRestrict()));
7437     }
7438   }
7439 
7440   // C++ [over.built]p6:
7441   //   For every cv-qualified or cv-unqualified object type T, there
7442   //   exist candidate operator functions of the form
7443   //
7444   //       T&         operator*(T*);
7445   //
7446   // C++ [over.built]p7:
7447   //   For every function type T that does not have cv-qualifiers or a
7448   //   ref-qualifier, there exist candidate operator functions of the form
7449   //       T&         operator*(T*);
7450   void addUnaryStarPointerOverloads() {
7451     for (BuiltinCandidateTypeSet::iterator
7452               Ptr = CandidateTypes[0].pointer_begin(),
7453            PtrEnd = CandidateTypes[0].pointer_end();
7454          Ptr != PtrEnd; ++Ptr) {
7455       QualType ParamTy = *Ptr;
7456       QualType PointeeTy = ParamTy->getPointeeType();
7457       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7458         continue;
7459 
7460       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7461         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7462           continue;
7463 
7464       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7465                             &ParamTy, Args, CandidateSet);
7466     }
7467   }
7468 
7469   // C++ [over.built]p9:
7470   //  For every promoted arithmetic type T, there exist candidate
7471   //  operator functions of the form
7472   //
7473   //       T         operator+(T);
7474   //       T         operator-(T);
7475   void addUnaryPlusOrMinusArithmeticOverloads() {
7476     if (!HasArithmeticOrEnumeralCandidateType)
7477       return;
7478 
7479     for (unsigned Arith = FirstPromotedArithmeticType;
7480          Arith < LastPromotedArithmeticType; ++Arith) {
7481       QualType ArithTy = getArithmeticType(Arith);
7482       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7483     }
7484 
7485     // Extension: We also add these operators for vector types.
7486     for (BuiltinCandidateTypeSet::iterator
7487               Vec = CandidateTypes[0].vector_begin(),
7488            VecEnd = CandidateTypes[0].vector_end();
7489          Vec != VecEnd; ++Vec) {
7490       QualType VecTy = *Vec;
7491       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7492     }
7493   }
7494 
7495   // C++ [over.built]p8:
7496   //   For every type T, there exist candidate operator functions of
7497   //   the form
7498   //
7499   //       T*         operator+(T*);
7500   void addUnaryPlusPointerOverloads() {
7501     for (BuiltinCandidateTypeSet::iterator
7502               Ptr = CandidateTypes[0].pointer_begin(),
7503            PtrEnd = CandidateTypes[0].pointer_end();
7504          Ptr != PtrEnd; ++Ptr) {
7505       QualType ParamTy = *Ptr;
7506       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7507     }
7508   }
7509 
7510   // C++ [over.built]p10:
7511   //   For every promoted integral type T, there exist candidate
7512   //   operator functions of the form
7513   //
7514   //        T         operator~(T);
7515   void addUnaryTildePromotedIntegralOverloads() {
7516     if (!HasArithmeticOrEnumeralCandidateType)
7517       return;
7518 
7519     for (unsigned Int = FirstPromotedIntegralType;
7520          Int < LastPromotedIntegralType; ++Int) {
7521       QualType IntTy = getArithmeticType(Int);
7522       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7523     }
7524 
7525     // Extension: We also add this operator for vector types.
7526     for (BuiltinCandidateTypeSet::iterator
7527               Vec = CandidateTypes[0].vector_begin(),
7528            VecEnd = CandidateTypes[0].vector_end();
7529          Vec != VecEnd; ++Vec) {
7530       QualType VecTy = *Vec;
7531       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7532     }
7533   }
7534 
7535   // C++ [over.match.oper]p16:
7536   //   For every pointer to member type T, there exist candidate operator
7537   //   functions of the form
7538   //
7539   //        bool operator==(T,T);
7540   //        bool operator!=(T,T);
7541   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7542     /// Set of (canonical) types that we've already handled.
7543     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7544 
7545     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7546       for (BuiltinCandidateTypeSet::iterator
7547                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7548              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7549            MemPtr != MemPtrEnd;
7550            ++MemPtr) {
7551         // Don't add the same builtin candidate twice.
7552         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7553           continue;
7554 
7555         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7556         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7557       }
7558     }
7559   }
7560 
7561   // C++ [over.built]p15:
7562   //
7563   //   For every T, where T is an enumeration type, a pointer type, or
7564   //   std::nullptr_t, there exist candidate operator functions of the form
7565   //
7566   //        bool       operator<(T, T);
7567   //        bool       operator>(T, T);
7568   //        bool       operator<=(T, T);
7569   //        bool       operator>=(T, T);
7570   //        bool       operator==(T, T);
7571   //        bool       operator!=(T, T);
7572   void addRelationalPointerOrEnumeralOverloads() {
7573     // C++ [over.match.oper]p3:
7574     //   [...]the built-in candidates include all of the candidate operator
7575     //   functions defined in 13.6 that, compared to the given operator, [...]
7576     //   do not have the same parameter-type-list as any non-template non-member
7577     //   candidate.
7578     //
7579     // Note that in practice, this only affects enumeration types because there
7580     // aren't any built-in candidates of record type, and a user-defined operator
7581     // must have an operand of record or enumeration type. Also, the only other
7582     // overloaded operator with enumeration arguments, operator=,
7583     // cannot be overloaded for enumeration types, so this is the only place
7584     // where we must suppress candidates like this.
7585     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7586       UserDefinedBinaryOperators;
7587 
7588     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7589       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7590           CandidateTypes[ArgIdx].enumeration_end()) {
7591         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7592                                          CEnd = CandidateSet.end();
7593              C != CEnd; ++C) {
7594           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7595             continue;
7596 
7597           if (C->Function->isFunctionTemplateSpecialization())
7598             continue;
7599 
7600           QualType FirstParamType =
7601             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7602           QualType SecondParamType =
7603             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7604 
7605           // Skip if either parameter isn't of enumeral type.
7606           if (!FirstParamType->isEnumeralType() ||
7607               !SecondParamType->isEnumeralType())
7608             continue;
7609 
7610           // Add this operator to the set of known user-defined operators.
7611           UserDefinedBinaryOperators.insert(
7612             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7613                            S.Context.getCanonicalType(SecondParamType)));
7614         }
7615       }
7616     }
7617 
7618     /// Set of (canonical) types that we've already handled.
7619     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7620 
7621     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7622       for (BuiltinCandidateTypeSet::iterator
7623                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7624              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7625            Ptr != PtrEnd; ++Ptr) {
7626         // Don't add the same builtin candidate twice.
7627         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7628           continue;
7629 
7630         QualType ParamTypes[2] = { *Ptr, *Ptr };
7631         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7632       }
7633       for (BuiltinCandidateTypeSet::iterator
7634                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7635              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7636            Enum != EnumEnd; ++Enum) {
7637         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7638 
7639         // Don't add the same builtin candidate twice, or if a user defined
7640         // candidate exists.
7641         if (!AddedTypes.insert(CanonType).second ||
7642             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7643                                                             CanonType)))
7644           continue;
7645 
7646         QualType ParamTypes[2] = { *Enum, *Enum };
7647         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7648       }
7649 
7650       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7651         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7652         if (AddedTypes.insert(NullPtrTy).second &&
7653             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7654                                                              NullPtrTy))) {
7655           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7656           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7657                                 CandidateSet);
7658         }
7659       }
7660     }
7661   }
7662 
7663   // C++ [over.built]p13:
7664   //
7665   //   For every cv-qualified or cv-unqualified object type T
7666   //   there exist candidate operator functions of the form
7667   //
7668   //      T*         operator+(T*, ptrdiff_t);
7669   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7670   //      T*         operator-(T*, ptrdiff_t);
7671   //      T*         operator+(ptrdiff_t, T*);
7672   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7673   //
7674   // C++ [over.built]p14:
7675   //
7676   //   For every T, where T is a pointer to object type, there
7677   //   exist candidate operator functions of the form
7678   //
7679   //      ptrdiff_t  operator-(T, T);
7680   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7681     /// Set of (canonical) types that we've already handled.
7682     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7683 
7684     for (int Arg = 0; Arg < 2; ++Arg) {
7685       QualType AsymmetricParamTypes[2] = {
7686         S.Context.getPointerDiffType(),
7687         S.Context.getPointerDiffType(),
7688       };
7689       for (BuiltinCandidateTypeSet::iterator
7690                 Ptr = CandidateTypes[Arg].pointer_begin(),
7691              PtrEnd = CandidateTypes[Arg].pointer_end();
7692            Ptr != PtrEnd; ++Ptr) {
7693         QualType PointeeTy = (*Ptr)->getPointeeType();
7694         if (!PointeeTy->isObjectType())
7695           continue;
7696 
7697         AsymmetricParamTypes[Arg] = *Ptr;
7698         if (Arg == 0 || Op == OO_Plus) {
7699           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7700           // T* operator+(ptrdiff_t, T*);
7701           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7702         }
7703         if (Op == OO_Minus) {
7704           // ptrdiff_t operator-(T, T);
7705           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7706             continue;
7707 
7708           QualType ParamTypes[2] = { *Ptr, *Ptr };
7709           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7710                                 Args, CandidateSet);
7711         }
7712       }
7713     }
7714   }
7715 
7716   // C++ [over.built]p12:
7717   //
7718   //   For every pair of promoted arithmetic types L and R, there
7719   //   exist candidate operator functions of the form
7720   //
7721   //        LR         operator*(L, R);
7722   //        LR         operator/(L, R);
7723   //        LR         operator+(L, R);
7724   //        LR         operator-(L, R);
7725   //        bool       operator<(L, R);
7726   //        bool       operator>(L, R);
7727   //        bool       operator<=(L, R);
7728   //        bool       operator>=(L, R);
7729   //        bool       operator==(L, R);
7730   //        bool       operator!=(L, R);
7731   //
7732   //   where LR is the result of the usual arithmetic conversions
7733   //   between types L and R.
7734   //
7735   // C++ [over.built]p24:
7736   //
7737   //   For every pair of promoted arithmetic types L and R, there exist
7738   //   candidate operator functions of the form
7739   //
7740   //        LR       operator?(bool, L, R);
7741   //
7742   //   where LR is the result of the usual arithmetic conversions
7743   //   between types L and R.
7744   // Our candidates ignore the first parameter.
7745   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7746     if (!HasArithmeticOrEnumeralCandidateType)
7747       return;
7748 
7749     for (unsigned Left = FirstPromotedArithmeticType;
7750          Left < LastPromotedArithmeticType; ++Left) {
7751       for (unsigned Right = FirstPromotedArithmeticType;
7752            Right < LastPromotedArithmeticType; ++Right) {
7753         QualType LandR[2] = { getArithmeticType(Left),
7754                               getArithmeticType(Right) };
7755         QualType Result =
7756           isComparison ? S.Context.BoolTy
7757                        : getUsualArithmeticConversions(Left, Right);
7758         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7759       }
7760     }
7761 
7762     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7763     // conditional operator for vector types.
7764     for (BuiltinCandidateTypeSet::iterator
7765               Vec1 = CandidateTypes[0].vector_begin(),
7766            Vec1End = CandidateTypes[0].vector_end();
7767          Vec1 != Vec1End; ++Vec1) {
7768       for (BuiltinCandidateTypeSet::iterator
7769                 Vec2 = CandidateTypes[1].vector_begin(),
7770              Vec2End = CandidateTypes[1].vector_end();
7771            Vec2 != Vec2End; ++Vec2) {
7772         QualType LandR[2] = { *Vec1, *Vec2 };
7773         QualType Result = S.Context.BoolTy;
7774         if (!isComparison) {
7775           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7776             Result = *Vec1;
7777           else
7778             Result = *Vec2;
7779         }
7780 
7781         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7782       }
7783     }
7784   }
7785 
7786   // C++ [over.built]p17:
7787   //
7788   //   For every pair of promoted integral types L and R, there
7789   //   exist candidate operator functions of the form
7790   //
7791   //      LR         operator%(L, R);
7792   //      LR         operator&(L, R);
7793   //      LR         operator^(L, R);
7794   //      LR         operator|(L, R);
7795   //      L          operator<<(L, R);
7796   //      L          operator>>(L, R);
7797   //
7798   //   where LR is the result of the usual arithmetic conversions
7799   //   between types L and R.
7800   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7801     if (!HasArithmeticOrEnumeralCandidateType)
7802       return;
7803 
7804     for (unsigned Left = FirstPromotedIntegralType;
7805          Left < LastPromotedIntegralType; ++Left) {
7806       for (unsigned Right = FirstPromotedIntegralType;
7807            Right < LastPromotedIntegralType; ++Right) {
7808         QualType LandR[2] = { getArithmeticType(Left),
7809                               getArithmeticType(Right) };
7810         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7811             ? LandR[0]
7812             : getUsualArithmeticConversions(Left, Right);
7813         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7814       }
7815     }
7816   }
7817 
7818   // C++ [over.built]p20:
7819   //
7820   //   For every pair (T, VQ), where T is an enumeration or
7821   //   pointer to member type and VQ is either volatile or
7822   //   empty, there exist candidate operator functions of the form
7823   //
7824   //        VQ T&      operator=(VQ T&, T);
7825   void addAssignmentMemberPointerOrEnumeralOverloads() {
7826     /// Set of (canonical) types that we've already handled.
7827     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7828 
7829     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7830       for (BuiltinCandidateTypeSet::iterator
7831                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7832              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7833            Enum != EnumEnd; ++Enum) {
7834         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7835           continue;
7836 
7837         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7838       }
7839 
7840       for (BuiltinCandidateTypeSet::iterator
7841                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7842              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7843            MemPtr != MemPtrEnd; ++MemPtr) {
7844         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7845           continue;
7846 
7847         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7848       }
7849     }
7850   }
7851 
7852   // C++ [over.built]p19:
7853   //
7854   //   For every pair (T, VQ), where T is any type and VQ is either
7855   //   volatile or empty, there exist candidate operator functions
7856   //   of the form
7857   //
7858   //        T*VQ&      operator=(T*VQ&, T*);
7859   //
7860   // C++ [over.built]p21:
7861   //
7862   //   For every pair (T, VQ), where T is a cv-qualified or
7863   //   cv-unqualified object type and VQ is either volatile or
7864   //   empty, there exist candidate operator functions of the form
7865   //
7866   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7867   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7868   void addAssignmentPointerOverloads(bool isEqualOp) {
7869     /// Set of (canonical) types that we've already handled.
7870     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7871 
7872     for (BuiltinCandidateTypeSet::iterator
7873               Ptr = CandidateTypes[0].pointer_begin(),
7874            PtrEnd = CandidateTypes[0].pointer_end();
7875          Ptr != PtrEnd; ++Ptr) {
7876       // If this is operator=, keep track of the builtin candidates we added.
7877       if (isEqualOp)
7878         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7879       else if (!(*Ptr)->getPointeeType()->isObjectType())
7880         continue;
7881 
7882       // non-volatile version
7883       QualType ParamTypes[2] = {
7884         S.Context.getLValueReferenceType(*Ptr),
7885         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7886       };
7887       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7888                             /*IsAssigmentOperator=*/ isEqualOp);
7889 
7890       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7891                           VisibleTypeConversionsQuals.hasVolatile();
7892       if (NeedVolatile) {
7893         // volatile version
7894         ParamTypes[0] =
7895           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7896         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7897                               /*IsAssigmentOperator=*/isEqualOp);
7898       }
7899 
7900       if (!(*Ptr).isRestrictQualified() &&
7901           VisibleTypeConversionsQuals.hasRestrict()) {
7902         // restrict version
7903         ParamTypes[0]
7904           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7905         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7906                               /*IsAssigmentOperator=*/isEqualOp);
7907 
7908         if (NeedVolatile) {
7909           // volatile restrict version
7910           ParamTypes[0]
7911             = S.Context.getLValueReferenceType(
7912                 S.Context.getCVRQualifiedType(*Ptr,
7913                                               (Qualifiers::Volatile |
7914                                                Qualifiers::Restrict)));
7915           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7916                                 /*IsAssigmentOperator=*/isEqualOp);
7917         }
7918       }
7919     }
7920 
7921     if (isEqualOp) {
7922       for (BuiltinCandidateTypeSet::iterator
7923                 Ptr = CandidateTypes[1].pointer_begin(),
7924              PtrEnd = CandidateTypes[1].pointer_end();
7925            Ptr != PtrEnd; ++Ptr) {
7926         // Make sure we don't add the same candidate twice.
7927         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7928           continue;
7929 
7930         QualType ParamTypes[2] = {
7931           S.Context.getLValueReferenceType(*Ptr),
7932           *Ptr,
7933         };
7934 
7935         // non-volatile version
7936         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7937                               /*IsAssigmentOperator=*/true);
7938 
7939         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7940                            VisibleTypeConversionsQuals.hasVolatile();
7941         if (NeedVolatile) {
7942           // volatile version
7943           ParamTypes[0] =
7944             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7945           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7946                                 /*IsAssigmentOperator=*/true);
7947         }
7948 
7949         if (!(*Ptr).isRestrictQualified() &&
7950             VisibleTypeConversionsQuals.hasRestrict()) {
7951           // restrict version
7952           ParamTypes[0]
7953             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7954           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7955                                 /*IsAssigmentOperator=*/true);
7956 
7957           if (NeedVolatile) {
7958             // volatile restrict version
7959             ParamTypes[0]
7960               = S.Context.getLValueReferenceType(
7961                   S.Context.getCVRQualifiedType(*Ptr,
7962                                                 (Qualifiers::Volatile |
7963                                                  Qualifiers::Restrict)));
7964             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7965                                   /*IsAssigmentOperator=*/true);
7966           }
7967         }
7968       }
7969     }
7970   }
7971 
7972   // C++ [over.built]p18:
7973   //
7974   //   For every triple (L, VQ, R), where L is an arithmetic type,
7975   //   VQ is either volatile or empty, and R is a promoted
7976   //   arithmetic type, there exist candidate operator functions of
7977   //   the form
7978   //
7979   //        VQ L&      operator=(VQ L&, R);
7980   //        VQ L&      operator*=(VQ L&, R);
7981   //        VQ L&      operator/=(VQ L&, R);
7982   //        VQ L&      operator+=(VQ L&, R);
7983   //        VQ L&      operator-=(VQ L&, R);
7984   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7985     if (!HasArithmeticOrEnumeralCandidateType)
7986       return;
7987 
7988     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7989       for (unsigned Right = FirstPromotedArithmeticType;
7990            Right < LastPromotedArithmeticType; ++Right) {
7991         QualType ParamTypes[2];
7992         ParamTypes[1] = getArithmeticType(Right);
7993 
7994         // Add this built-in operator as a candidate (VQ is empty).
7995         ParamTypes[0] =
7996           S.Context.getLValueReferenceType(getArithmeticType(Left));
7997         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7998                               /*IsAssigmentOperator=*/isEqualOp);
7999 
8000         // Add this built-in operator as a candidate (VQ is 'volatile').
8001         if (VisibleTypeConversionsQuals.hasVolatile()) {
8002           ParamTypes[0] =
8003             S.Context.getVolatileType(getArithmeticType(Left));
8004           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8005           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8006                                 /*IsAssigmentOperator=*/isEqualOp);
8007         }
8008       }
8009     }
8010 
8011     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8012     for (BuiltinCandidateTypeSet::iterator
8013               Vec1 = CandidateTypes[0].vector_begin(),
8014            Vec1End = CandidateTypes[0].vector_end();
8015          Vec1 != Vec1End; ++Vec1) {
8016       for (BuiltinCandidateTypeSet::iterator
8017                 Vec2 = CandidateTypes[1].vector_begin(),
8018              Vec2End = CandidateTypes[1].vector_end();
8019            Vec2 != Vec2End; ++Vec2) {
8020         QualType ParamTypes[2];
8021         ParamTypes[1] = *Vec2;
8022         // Add this built-in operator as a candidate (VQ is empty).
8023         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8024         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8025                               /*IsAssigmentOperator=*/isEqualOp);
8026 
8027         // Add this built-in operator as a candidate (VQ is 'volatile').
8028         if (VisibleTypeConversionsQuals.hasVolatile()) {
8029           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8030           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8031           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8032                                 /*IsAssigmentOperator=*/isEqualOp);
8033         }
8034       }
8035     }
8036   }
8037 
8038   // C++ [over.built]p22:
8039   //
8040   //   For every triple (L, VQ, R), where L is an integral type, VQ
8041   //   is either volatile or empty, and R is a promoted integral
8042   //   type, there exist candidate operator functions of the form
8043   //
8044   //        VQ L&       operator%=(VQ L&, R);
8045   //        VQ L&       operator<<=(VQ L&, R);
8046   //        VQ L&       operator>>=(VQ L&, R);
8047   //        VQ L&       operator&=(VQ L&, R);
8048   //        VQ L&       operator^=(VQ L&, R);
8049   //        VQ L&       operator|=(VQ L&, R);
8050   void addAssignmentIntegralOverloads() {
8051     if (!HasArithmeticOrEnumeralCandidateType)
8052       return;
8053 
8054     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8055       for (unsigned Right = FirstPromotedIntegralType;
8056            Right < LastPromotedIntegralType; ++Right) {
8057         QualType ParamTypes[2];
8058         ParamTypes[1] = getArithmeticType(Right);
8059 
8060         // Add this built-in operator as a candidate (VQ is empty).
8061         ParamTypes[0] =
8062           S.Context.getLValueReferenceType(getArithmeticType(Left));
8063         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8064         if (VisibleTypeConversionsQuals.hasVolatile()) {
8065           // Add this built-in operator as a candidate (VQ is 'volatile').
8066           ParamTypes[0] = getArithmeticType(Left);
8067           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8068           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8069           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8070         }
8071       }
8072     }
8073   }
8074 
8075   // C++ [over.operator]p23:
8076   //
8077   //   There also exist candidate operator functions of the form
8078   //
8079   //        bool        operator!(bool);
8080   //        bool        operator&&(bool, bool);
8081   //        bool        operator||(bool, bool);
8082   void addExclaimOverload() {
8083     QualType ParamTy = S.Context.BoolTy;
8084     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8085                           /*IsAssignmentOperator=*/false,
8086                           /*NumContextualBoolArguments=*/1);
8087   }
8088   void addAmpAmpOrPipePipeOverload() {
8089     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8090     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8091                           /*IsAssignmentOperator=*/false,
8092                           /*NumContextualBoolArguments=*/2);
8093   }
8094 
8095   // C++ [over.built]p13:
8096   //
8097   //   For every cv-qualified or cv-unqualified object type T there
8098   //   exist candidate operator functions of the form
8099   //
8100   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8101   //        T&         operator[](T*, ptrdiff_t);
8102   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8103   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8104   //        T&         operator[](ptrdiff_t, T*);
8105   void addSubscriptOverloads() {
8106     for (BuiltinCandidateTypeSet::iterator
8107               Ptr = CandidateTypes[0].pointer_begin(),
8108            PtrEnd = CandidateTypes[0].pointer_end();
8109          Ptr != PtrEnd; ++Ptr) {
8110       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8111       QualType PointeeType = (*Ptr)->getPointeeType();
8112       if (!PointeeType->isObjectType())
8113         continue;
8114 
8115       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8116 
8117       // T& operator[](T*, ptrdiff_t)
8118       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8119     }
8120 
8121     for (BuiltinCandidateTypeSet::iterator
8122               Ptr = CandidateTypes[1].pointer_begin(),
8123            PtrEnd = CandidateTypes[1].pointer_end();
8124          Ptr != PtrEnd; ++Ptr) {
8125       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8126       QualType PointeeType = (*Ptr)->getPointeeType();
8127       if (!PointeeType->isObjectType())
8128         continue;
8129 
8130       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8131 
8132       // T& operator[](ptrdiff_t, T*)
8133       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8134     }
8135   }
8136 
8137   // C++ [over.built]p11:
8138   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8139   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8140   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8141   //    there exist candidate operator functions of the form
8142   //
8143   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8144   //
8145   //    where CV12 is the union of CV1 and CV2.
8146   void addArrowStarOverloads() {
8147     for (BuiltinCandidateTypeSet::iterator
8148              Ptr = CandidateTypes[0].pointer_begin(),
8149            PtrEnd = CandidateTypes[0].pointer_end();
8150          Ptr != PtrEnd; ++Ptr) {
8151       QualType C1Ty = (*Ptr);
8152       QualType C1;
8153       QualifierCollector Q1;
8154       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8155       if (!isa<RecordType>(C1))
8156         continue;
8157       // heuristic to reduce number of builtin candidates in the set.
8158       // Add volatile/restrict version only if there are conversions to a
8159       // volatile/restrict type.
8160       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8161         continue;
8162       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8163         continue;
8164       for (BuiltinCandidateTypeSet::iterator
8165                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8166              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8167            MemPtr != MemPtrEnd; ++MemPtr) {
8168         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8169         QualType C2 = QualType(mptr->getClass(), 0);
8170         C2 = C2.getUnqualifiedType();
8171         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8172           break;
8173         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8174         // build CV12 T&
8175         QualType T = mptr->getPointeeType();
8176         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8177             T.isVolatileQualified())
8178           continue;
8179         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8180             T.isRestrictQualified())
8181           continue;
8182         T = Q1.apply(S.Context, T);
8183         QualType ResultTy = S.Context.getLValueReferenceType(T);
8184         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8185       }
8186     }
8187   }
8188 
8189   // Note that we don't consider the first argument, since it has been
8190   // contextually converted to bool long ago. The candidates below are
8191   // therefore added as binary.
8192   //
8193   // C++ [over.built]p25:
8194   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8195   //   enumeration type, there exist candidate operator functions of the form
8196   //
8197   //        T        operator?(bool, T, T);
8198   //
8199   void addConditionalOperatorOverloads() {
8200     /// Set of (canonical) types that we've already handled.
8201     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8202 
8203     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8204       for (BuiltinCandidateTypeSet::iterator
8205                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8206              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8207            Ptr != PtrEnd; ++Ptr) {
8208         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8209           continue;
8210 
8211         QualType ParamTypes[2] = { *Ptr, *Ptr };
8212         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8213       }
8214 
8215       for (BuiltinCandidateTypeSet::iterator
8216                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8217              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8218            MemPtr != MemPtrEnd; ++MemPtr) {
8219         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8220           continue;
8221 
8222         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8223         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8224       }
8225 
8226       if (S.getLangOpts().CPlusPlus11) {
8227         for (BuiltinCandidateTypeSet::iterator
8228                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8229                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8230              Enum != EnumEnd; ++Enum) {
8231           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8232             continue;
8233 
8234           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8235             continue;
8236 
8237           QualType ParamTypes[2] = { *Enum, *Enum };
8238           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8239         }
8240       }
8241     }
8242   }
8243 };
8244 
8245 } // end anonymous namespace
8246 
8247 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8248 /// operator overloads to the candidate set (C++ [over.built]), based
8249 /// on the operator @p Op and the arguments given. For example, if the
8250 /// operator is a binary '+', this routine might add "int
8251 /// operator+(int, int)" to cover integer addition.
8252 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8253                                         SourceLocation OpLoc,
8254                                         ArrayRef<Expr *> Args,
8255                                         OverloadCandidateSet &CandidateSet) {
8256   // Find all of the types that the arguments can convert to, but only
8257   // if the operator we're looking at has built-in operator candidates
8258   // that make use of these types. Also record whether we encounter non-record
8259   // candidate types or either arithmetic or enumeral candidate types.
8260   Qualifiers VisibleTypeConversionsQuals;
8261   VisibleTypeConversionsQuals.addConst();
8262   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8263     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8264 
8265   bool HasNonRecordCandidateType = false;
8266   bool HasArithmeticOrEnumeralCandidateType = false;
8267   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8268   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8269     CandidateTypes.emplace_back(*this);
8270     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8271                                                  OpLoc,
8272                                                  true,
8273                                                  (Op == OO_Exclaim ||
8274                                                   Op == OO_AmpAmp ||
8275                                                   Op == OO_PipePipe),
8276                                                  VisibleTypeConversionsQuals);
8277     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8278         CandidateTypes[ArgIdx].hasNonRecordTypes();
8279     HasArithmeticOrEnumeralCandidateType =
8280         HasArithmeticOrEnumeralCandidateType ||
8281         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8282   }
8283 
8284   // Exit early when no non-record types have been added to the candidate set
8285   // for any of the arguments to the operator.
8286   //
8287   // We can't exit early for !, ||, or &&, since there we have always have
8288   // 'bool' overloads.
8289   if (!HasNonRecordCandidateType &&
8290       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8291     return;
8292 
8293   // Setup an object to manage the common state for building overloads.
8294   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8295                                            VisibleTypeConversionsQuals,
8296                                            HasArithmeticOrEnumeralCandidateType,
8297                                            CandidateTypes, CandidateSet);
8298 
8299   // Dispatch over the operation to add in only those overloads which apply.
8300   switch (Op) {
8301   case OO_None:
8302   case NUM_OVERLOADED_OPERATORS:
8303     llvm_unreachable("Expected an overloaded operator");
8304 
8305   case OO_New:
8306   case OO_Delete:
8307   case OO_Array_New:
8308   case OO_Array_Delete:
8309   case OO_Call:
8310     llvm_unreachable(
8311                     "Special operators don't use AddBuiltinOperatorCandidates");
8312 
8313   case OO_Comma:
8314   case OO_Arrow:
8315   case OO_Coawait:
8316     // C++ [over.match.oper]p3:
8317     //   -- For the operator ',', the unary operator '&', the
8318     //      operator '->', or the operator 'co_await', the
8319     //      built-in candidates set is empty.
8320     break;
8321 
8322   case OO_Plus: // '+' is either unary or binary
8323     if (Args.size() == 1)
8324       OpBuilder.addUnaryPlusPointerOverloads();
8325     // Fall through.
8326 
8327   case OO_Minus: // '-' is either unary or binary
8328     if (Args.size() == 1) {
8329       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8330     } else {
8331       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8332       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8333     }
8334     break;
8335 
8336   case OO_Star: // '*' is either unary or binary
8337     if (Args.size() == 1)
8338       OpBuilder.addUnaryStarPointerOverloads();
8339     else
8340       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8341     break;
8342 
8343   case OO_Slash:
8344     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8345     break;
8346 
8347   case OO_PlusPlus:
8348   case OO_MinusMinus:
8349     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8350     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8351     break;
8352 
8353   case OO_EqualEqual:
8354   case OO_ExclaimEqual:
8355     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8356     // Fall through.
8357 
8358   case OO_Less:
8359   case OO_Greater:
8360   case OO_LessEqual:
8361   case OO_GreaterEqual:
8362     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8363     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8364     break;
8365 
8366   case OO_Percent:
8367   case OO_Caret:
8368   case OO_Pipe:
8369   case OO_LessLess:
8370   case OO_GreaterGreater:
8371     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8372     break;
8373 
8374   case OO_Amp: // '&' is either unary or binary
8375     if (Args.size() == 1)
8376       // C++ [over.match.oper]p3:
8377       //   -- For the operator ',', the unary operator '&', or the
8378       //      operator '->', the built-in candidates set is empty.
8379       break;
8380 
8381     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8382     break;
8383 
8384   case OO_Tilde:
8385     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8386     break;
8387 
8388   case OO_Equal:
8389     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8390     // Fall through.
8391 
8392   case OO_PlusEqual:
8393   case OO_MinusEqual:
8394     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8395     // Fall through.
8396 
8397   case OO_StarEqual:
8398   case OO_SlashEqual:
8399     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8400     break;
8401 
8402   case OO_PercentEqual:
8403   case OO_LessLessEqual:
8404   case OO_GreaterGreaterEqual:
8405   case OO_AmpEqual:
8406   case OO_CaretEqual:
8407   case OO_PipeEqual:
8408     OpBuilder.addAssignmentIntegralOverloads();
8409     break;
8410 
8411   case OO_Exclaim:
8412     OpBuilder.addExclaimOverload();
8413     break;
8414 
8415   case OO_AmpAmp:
8416   case OO_PipePipe:
8417     OpBuilder.addAmpAmpOrPipePipeOverload();
8418     break;
8419 
8420   case OO_Subscript:
8421     OpBuilder.addSubscriptOverloads();
8422     break;
8423 
8424   case OO_ArrowStar:
8425     OpBuilder.addArrowStarOverloads();
8426     break;
8427 
8428   case OO_Conditional:
8429     OpBuilder.addConditionalOperatorOverloads();
8430     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8431     break;
8432   }
8433 }
8434 
8435 /// \brief Add function candidates found via argument-dependent lookup
8436 /// to the set of overloading candidates.
8437 ///
8438 /// This routine performs argument-dependent name lookup based on the
8439 /// given function name (which may also be an operator name) and adds
8440 /// all of the overload candidates found by ADL to the overload
8441 /// candidate set (C++ [basic.lookup.argdep]).
8442 void
8443 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8444                                            SourceLocation Loc,
8445                                            ArrayRef<Expr *> Args,
8446                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8447                                            OverloadCandidateSet& CandidateSet,
8448                                            bool PartialOverloading) {
8449   ADLResult Fns;
8450 
8451   // FIXME: This approach for uniquing ADL results (and removing
8452   // redundant candidates from the set) relies on pointer-equality,
8453   // which means we need to key off the canonical decl.  However,
8454   // always going back to the canonical decl might not get us the
8455   // right set of default arguments.  What default arguments are
8456   // we supposed to consider on ADL candidates, anyway?
8457 
8458   // FIXME: Pass in the explicit template arguments?
8459   ArgumentDependentLookup(Name, Loc, Args, Fns);
8460 
8461   // Erase all of the candidates we already knew about.
8462   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8463                                    CandEnd = CandidateSet.end();
8464        Cand != CandEnd; ++Cand)
8465     if (Cand->Function) {
8466       Fns.erase(Cand->Function);
8467       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8468         Fns.erase(FunTmpl);
8469     }
8470 
8471   // For each of the ADL candidates we found, add it to the overload
8472   // set.
8473   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8474     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8475     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8476       if (ExplicitTemplateArgs)
8477         continue;
8478 
8479       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8480                            PartialOverloading);
8481     } else
8482       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8483                                    FoundDecl, ExplicitTemplateArgs,
8484                                    Args, CandidateSet, PartialOverloading);
8485   }
8486 }
8487 
8488 namespace {
8489 enum class Comparison { Equal, Better, Worse };
8490 }
8491 
8492 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8493 /// overload resolution.
8494 ///
8495 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8496 /// Cand1's first N enable_if attributes have precisely the same conditions as
8497 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8498 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8499 ///
8500 /// Note that you can have a pair of candidates such that Cand1's enable_if
8501 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8502 /// worse than Cand1's.
8503 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8504                                        const FunctionDecl *Cand2) {
8505   // Common case: One (or both) decls don't have enable_if attrs.
8506   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8507   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8508   if (!Cand1Attr || !Cand2Attr) {
8509     if (Cand1Attr == Cand2Attr)
8510       return Comparison::Equal;
8511     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8512   }
8513 
8514   // FIXME: The next several lines are just
8515   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8516   // instead of reverse order which is how they're stored in the AST.
8517   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8518   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8519 
8520   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8521   // has fewer enable_if attributes than Cand2.
8522   if (Cand1Attrs.size() < Cand2Attrs.size())
8523     return Comparison::Worse;
8524 
8525   auto Cand1I = Cand1Attrs.begin();
8526   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8527   for (auto &Cand2A : Cand2Attrs) {
8528     Cand1ID.clear();
8529     Cand2ID.clear();
8530 
8531     auto &Cand1A = *Cand1I++;
8532     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8533     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8534     if (Cand1ID != Cand2ID)
8535       return Comparison::Worse;
8536   }
8537 
8538   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8539 }
8540 
8541 /// isBetterOverloadCandidate - Determines whether the first overload
8542 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8543 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8544                                       const OverloadCandidate &Cand2,
8545                                       SourceLocation Loc,
8546                                       bool UserDefinedConversion) {
8547   // Define viable functions to be better candidates than non-viable
8548   // functions.
8549   if (!Cand2.Viable)
8550     return Cand1.Viable;
8551   else if (!Cand1.Viable)
8552     return false;
8553 
8554   // C++ [over.match.best]p1:
8555   //
8556   //   -- if F is a static member function, ICS1(F) is defined such
8557   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8558   //      any function G, and, symmetrically, ICS1(G) is neither
8559   //      better nor worse than ICS1(F).
8560   unsigned StartArg = 0;
8561   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8562     StartArg = 1;
8563 
8564   // C++ [over.match.best]p1:
8565   //   A viable function F1 is defined to be a better function than another
8566   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8567   //   conversion sequence than ICSi(F2), and then...
8568   unsigned NumArgs = Cand1.NumConversions;
8569   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8570   bool HasBetterConversion = false;
8571   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8572     switch (CompareImplicitConversionSequences(S, Loc,
8573                                                Cand1.Conversions[ArgIdx],
8574                                                Cand2.Conversions[ArgIdx])) {
8575     case ImplicitConversionSequence::Better:
8576       // Cand1 has a better conversion sequence.
8577       HasBetterConversion = true;
8578       break;
8579 
8580     case ImplicitConversionSequence::Worse:
8581       // Cand1 can't be better than Cand2.
8582       return false;
8583 
8584     case ImplicitConversionSequence::Indistinguishable:
8585       // Do nothing.
8586       break;
8587     }
8588   }
8589 
8590   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8591   //       ICSj(F2), or, if not that,
8592   if (HasBetterConversion)
8593     return true;
8594 
8595   //   -- the context is an initialization by user-defined conversion
8596   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8597   //      from the return type of F1 to the destination type (i.e.,
8598   //      the type of the entity being initialized) is a better
8599   //      conversion sequence than the standard conversion sequence
8600   //      from the return type of F2 to the destination type.
8601   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8602       isa<CXXConversionDecl>(Cand1.Function) &&
8603       isa<CXXConversionDecl>(Cand2.Function)) {
8604     // First check whether we prefer one of the conversion functions over the
8605     // other. This only distinguishes the results in non-standard, extension
8606     // cases such as the conversion from a lambda closure type to a function
8607     // pointer or block.
8608     ImplicitConversionSequence::CompareKind Result =
8609         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8610     if (Result == ImplicitConversionSequence::Indistinguishable)
8611       Result = CompareStandardConversionSequences(S, Loc,
8612                                                   Cand1.FinalConversion,
8613                                                   Cand2.FinalConversion);
8614 
8615     if (Result != ImplicitConversionSequence::Indistinguishable)
8616       return Result == ImplicitConversionSequence::Better;
8617 
8618     // FIXME: Compare kind of reference binding if conversion functions
8619     // convert to a reference type used in direct reference binding, per
8620     // C++14 [over.match.best]p1 section 2 bullet 3.
8621   }
8622 
8623   //    -- F1 is a non-template function and F2 is a function template
8624   //       specialization, or, if not that,
8625   bool Cand1IsSpecialization = Cand1.Function &&
8626                                Cand1.Function->getPrimaryTemplate();
8627   bool Cand2IsSpecialization = Cand2.Function &&
8628                                Cand2.Function->getPrimaryTemplate();
8629   if (Cand1IsSpecialization != Cand2IsSpecialization)
8630     return Cand2IsSpecialization;
8631 
8632   //   -- F1 and F2 are function template specializations, and the function
8633   //      template for F1 is more specialized than the template for F2
8634   //      according to the partial ordering rules described in 14.5.5.2, or,
8635   //      if not that,
8636   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8637     if (FunctionTemplateDecl *BetterTemplate
8638           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8639                                          Cand2.Function->getPrimaryTemplate(),
8640                                          Loc,
8641                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8642                                                              : TPOC_Call,
8643                                          Cand1.ExplicitCallArguments,
8644                                          Cand2.ExplicitCallArguments))
8645       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8646   }
8647 
8648   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8649   // A derived-class constructor beats an (inherited) base class constructor.
8650   bool Cand1IsInherited =
8651       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8652   bool Cand2IsInherited =
8653       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8654   if (Cand1IsInherited != Cand2IsInherited)
8655     return Cand2IsInherited;
8656   else if (Cand1IsInherited) {
8657     assert(Cand2IsInherited);
8658     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8659     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8660     if (Cand1Class->isDerivedFrom(Cand2Class))
8661       return true;
8662     if (Cand2Class->isDerivedFrom(Cand1Class))
8663       return false;
8664     // Inherited from sibling base classes: still ambiguous.
8665   }
8666 
8667   // Check for enable_if value-based overload resolution.
8668   if (Cand1.Function && Cand2.Function) {
8669     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8670     if (Cmp != Comparison::Equal)
8671       return Cmp == Comparison::Better;
8672   }
8673 
8674   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8675     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8676     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8677            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8678   }
8679 
8680   bool HasPS1 = Cand1.Function != nullptr &&
8681                 functionHasPassObjectSizeParams(Cand1.Function);
8682   bool HasPS2 = Cand2.Function != nullptr &&
8683                 functionHasPassObjectSizeParams(Cand2.Function);
8684   return HasPS1 != HasPS2 && HasPS1;
8685 }
8686 
8687 /// Determine whether two declarations are "equivalent" for the purposes of
8688 /// name lookup and overload resolution. This applies when the same internal/no
8689 /// linkage entity is defined by two modules (probably by textually including
8690 /// the same header). In such a case, we don't consider the declarations to
8691 /// declare the same entity, but we also don't want lookups with both
8692 /// declarations visible to be ambiguous in some cases (this happens when using
8693 /// a modularized libstdc++).
8694 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8695                                                   const NamedDecl *B) {
8696   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8697   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8698   if (!VA || !VB)
8699     return false;
8700 
8701   // The declarations must be declaring the same name as an internal linkage
8702   // entity in different modules.
8703   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8704           VB->getDeclContext()->getRedeclContext()) ||
8705       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8706           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8707       VA->isExternallyVisible() || VB->isExternallyVisible())
8708     return false;
8709 
8710   // Check that the declarations appear to be equivalent.
8711   //
8712   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8713   // For constants and functions, we should check the initializer or body is
8714   // the same. For non-constant variables, we shouldn't allow it at all.
8715   if (Context.hasSameType(VA->getType(), VB->getType()))
8716     return true;
8717 
8718   // Enum constants within unnamed enumerations will have different types, but
8719   // may still be similar enough to be interchangeable for our purposes.
8720   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8721     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8722       // Only handle anonymous enums. If the enumerations were named and
8723       // equivalent, they would have been merged to the same type.
8724       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8725       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8726       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8727           !Context.hasSameType(EnumA->getIntegerType(),
8728                                EnumB->getIntegerType()))
8729         return false;
8730       // Allow this only if the value is the same for both enumerators.
8731       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8732     }
8733   }
8734 
8735   // Nothing else is sufficiently similar.
8736   return false;
8737 }
8738 
8739 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8740     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8741   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8742 
8743   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8744   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8745       << !M << (M ? M->getFullModuleName() : "");
8746 
8747   for (auto *E : Equiv) {
8748     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8749     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8750         << !M << (M ? M->getFullModuleName() : "");
8751   }
8752 }
8753 
8754 /// \brief Computes the best viable function (C++ 13.3.3)
8755 /// within an overload candidate set.
8756 ///
8757 /// \param Loc The location of the function name (or operator symbol) for
8758 /// which overload resolution occurs.
8759 ///
8760 /// \param Best If overload resolution was successful or found a deleted
8761 /// function, \p Best points to the candidate function found.
8762 ///
8763 /// \returns The result of overload resolution.
8764 OverloadingResult
8765 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8766                                          iterator &Best,
8767                                          bool UserDefinedConversion) {
8768   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8769   std::transform(begin(), end(), std::back_inserter(Candidates),
8770                  [](OverloadCandidate &Cand) { return &Cand; });
8771 
8772   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8773   // are accepted by both clang and NVCC. However, during a particular
8774   // compilation mode only one call variant is viable. We need to
8775   // exclude non-viable overload candidates from consideration based
8776   // only on their host/device attributes. Specifically, if one
8777   // candidate call is WrongSide and the other is SameSide, we ignore
8778   // the WrongSide candidate.
8779   if (S.getLangOpts().CUDA) {
8780     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8781     bool ContainsSameSideCandidate =
8782         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8783           return Cand->Function &&
8784                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8785                      Sema::CFP_SameSide;
8786         });
8787     if (ContainsSameSideCandidate) {
8788       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8789         return Cand->Function &&
8790                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8791                    Sema::CFP_WrongSide;
8792       };
8793       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8794                                       IsWrongSideCandidate),
8795                        Candidates.end());
8796     }
8797   }
8798 
8799   // Find the best viable function.
8800   Best = end();
8801   for (auto *Cand : Candidates)
8802     if (Cand->Viable)
8803       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8804                                                      UserDefinedConversion))
8805         Best = Cand;
8806 
8807   // If we didn't find any viable functions, abort.
8808   if (Best == end())
8809     return OR_No_Viable_Function;
8810 
8811   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8812 
8813   // Make sure that this function is better than every other viable
8814   // function. If not, we have an ambiguity.
8815   for (auto *Cand : Candidates) {
8816     if (Cand->Viable &&
8817         Cand != Best &&
8818         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8819                                    UserDefinedConversion)) {
8820       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8821                                                    Cand->Function)) {
8822         EquivalentCands.push_back(Cand->Function);
8823         continue;
8824       }
8825 
8826       Best = end();
8827       return OR_Ambiguous;
8828     }
8829   }
8830 
8831   // Best is the best viable function.
8832   if (Best->Function &&
8833       (Best->Function->isDeleted() ||
8834        S.isFunctionConsideredUnavailable(Best->Function)))
8835     return OR_Deleted;
8836 
8837   if (!EquivalentCands.empty())
8838     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8839                                                     EquivalentCands);
8840 
8841   return OR_Success;
8842 }
8843 
8844 namespace {
8845 
8846 enum OverloadCandidateKind {
8847   oc_function,
8848   oc_method,
8849   oc_constructor,
8850   oc_function_template,
8851   oc_method_template,
8852   oc_constructor_template,
8853   oc_implicit_default_constructor,
8854   oc_implicit_copy_constructor,
8855   oc_implicit_move_constructor,
8856   oc_implicit_copy_assignment,
8857   oc_implicit_move_assignment,
8858   oc_inherited_constructor,
8859   oc_inherited_constructor_template
8860 };
8861 
8862 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8863                                                 NamedDecl *Found,
8864                                                 FunctionDecl *Fn,
8865                                                 std::string &Description) {
8866   bool isTemplate = false;
8867 
8868   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8869     isTemplate = true;
8870     Description = S.getTemplateArgumentBindingsText(
8871       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8872   }
8873 
8874   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8875     if (!Ctor->isImplicit()) {
8876       if (isa<ConstructorUsingShadowDecl>(Found))
8877         return isTemplate ? oc_inherited_constructor_template
8878                           : oc_inherited_constructor;
8879       else
8880         return isTemplate ? oc_constructor_template : oc_constructor;
8881     }
8882 
8883     if (Ctor->isDefaultConstructor())
8884       return oc_implicit_default_constructor;
8885 
8886     if (Ctor->isMoveConstructor())
8887       return oc_implicit_move_constructor;
8888 
8889     assert(Ctor->isCopyConstructor() &&
8890            "unexpected sort of implicit constructor");
8891     return oc_implicit_copy_constructor;
8892   }
8893 
8894   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8895     // This actually gets spelled 'candidate function' for now, but
8896     // it doesn't hurt to split it out.
8897     if (!Meth->isImplicit())
8898       return isTemplate ? oc_method_template : oc_method;
8899 
8900     if (Meth->isMoveAssignmentOperator())
8901       return oc_implicit_move_assignment;
8902 
8903     if (Meth->isCopyAssignmentOperator())
8904       return oc_implicit_copy_assignment;
8905 
8906     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8907     return oc_method;
8908   }
8909 
8910   return isTemplate ? oc_function_template : oc_function;
8911 }
8912 
8913 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8914   // FIXME: It'd be nice to only emit a note once per using-decl per overload
8915   // set.
8916   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8917     S.Diag(FoundDecl->getLocation(),
8918            diag::note_ovl_candidate_inherited_constructor)
8919       << Shadow->getNominatedBaseClass();
8920 }
8921 
8922 } // end anonymous namespace
8923 
8924 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8925                                     const FunctionDecl *FD) {
8926   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8927     bool AlwaysTrue;
8928     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8929       return false;
8930     if (!AlwaysTrue)
8931       return false;
8932   }
8933   return true;
8934 }
8935 
8936 /// \brief Returns true if we can take the address of the function.
8937 ///
8938 /// \param Complain - If true, we'll emit a diagnostic
8939 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8940 ///   we in overload resolution?
8941 /// \param Loc - The location of the statement we're complaining about. Ignored
8942 ///   if we're not complaining, or if we're in overload resolution.
8943 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8944                                               bool Complain,
8945                                               bool InOverloadResolution,
8946                                               SourceLocation Loc) {
8947   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8948     if (Complain) {
8949       if (InOverloadResolution)
8950         S.Diag(FD->getLocStart(),
8951                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8952       else
8953         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8954     }
8955     return false;
8956   }
8957 
8958   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
8959     return P->hasAttr<PassObjectSizeAttr>();
8960   });
8961   if (I == FD->param_end())
8962     return true;
8963 
8964   if (Complain) {
8965     // Add one to ParamNo because it's user-facing
8966     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8967     if (InOverloadResolution)
8968       S.Diag(FD->getLocation(),
8969              diag::note_ovl_candidate_has_pass_object_size_params)
8970           << ParamNo;
8971     else
8972       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8973           << FD << ParamNo;
8974   }
8975   return false;
8976 }
8977 
8978 static bool checkAddressOfCandidateIsAvailable(Sema &S,
8979                                                const FunctionDecl *FD) {
8980   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8981                                            /*InOverloadResolution=*/true,
8982                                            /*Loc=*/SourceLocation());
8983 }
8984 
8985 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8986                                              bool Complain,
8987                                              SourceLocation Loc) {
8988   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8989                                              /*InOverloadResolution=*/false,
8990                                              Loc);
8991 }
8992 
8993 // Notes the location of an overload candidate.
8994 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
8995                                  QualType DestType, bool TakingAddress) {
8996   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8997     return;
8998 
8999   std::string FnDesc;
9000   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9001   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9002                              << (unsigned) K << FnDesc;
9003 
9004   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9005   Diag(Fn->getLocation(), PD);
9006   MaybeEmitInheritedConstructorNote(*this, Found);
9007 }
9008 
9009 // Notes the location of all overload candidates designated through
9010 // OverloadedExpr
9011 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9012                                      bool TakingAddress) {
9013   assert(OverloadedExpr->getType() == Context.OverloadTy);
9014 
9015   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9016   OverloadExpr *OvlExpr = Ovl.Expression;
9017 
9018   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9019                             IEnd = OvlExpr->decls_end();
9020        I != IEnd; ++I) {
9021     if (FunctionTemplateDecl *FunTmpl =
9022                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9023       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9024                             TakingAddress);
9025     } else if (FunctionDecl *Fun
9026                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9027       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9028     }
9029   }
9030 }
9031 
9032 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9033 /// "lead" diagnostic; it will be given two arguments, the source and
9034 /// target types of the conversion.
9035 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9036                                  Sema &S,
9037                                  SourceLocation CaretLoc,
9038                                  const PartialDiagnostic &PDiag) const {
9039   S.Diag(CaretLoc, PDiag)
9040     << Ambiguous.getFromType() << Ambiguous.getToType();
9041   // FIXME: The note limiting machinery is borrowed from
9042   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9043   // refactoring here.
9044   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9045   unsigned CandsShown = 0;
9046   AmbiguousConversionSequence::const_iterator I, E;
9047   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9048     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9049       break;
9050     ++CandsShown;
9051     S.NoteOverloadCandidate(I->first, I->second);
9052   }
9053   if (I != E)
9054     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9055 }
9056 
9057 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9058                                   unsigned I, bool TakingCandidateAddress) {
9059   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9060   assert(Conv.isBad());
9061   assert(Cand->Function && "for now, candidate must be a function");
9062   FunctionDecl *Fn = Cand->Function;
9063 
9064   // There's a conversion slot for the object argument if this is a
9065   // non-constructor method.  Note that 'I' corresponds the
9066   // conversion-slot index.
9067   bool isObjectArgument = false;
9068   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9069     if (I == 0)
9070       isObjectArgument = true;
9071     else
9072       I--;
9073   }
9074 
9075   std::string FnDesc;
9076   OverloadCandidateKind FnKind =
9077       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9078 
9079   Expr *FromExpr = Conv.Bad.FromExpr;
9080   QualType FromTy = Conv.Bad.getFromType();
9081   QualType ToTy = Conv.Bad.getToType();
9082 
9083   if (FromTy == S.Context.OverloadTy) {
9084     assert(FromExpr && "overload set argument came from implicit argument?");
9085     Expr *E = FromExpr->IgnoreParens();
9086     if (isa<UnaryOperator>(E))
9087       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9088     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9089 
9090     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9091       << (unsigned) FnKind << FnDesc
9092       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9093       << ToTy << Name << I+1;
9094     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9095     return;
9096   }
9097 
9098   // Do some hand-waving analysis to see if the non-viability is due
9099   // to a qualifier mismatch.
9100   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9101   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9102   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9103     CToTy = RT->getPointeeType();
9104   else {
9105     // TODO: detect and diagnose the full richness of const mismatches.
9106     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9107       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9108         CFromTy = FromPT->getPointeeType();
9109         CToTy = ToPT->getPointeeType();
9110       }
9111   }
9112 
9113   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9114       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9115     Qualifiers FromQs = CFromTy.getQualifiers();
9116     Qualifiers ToQs = CToTy.getQualifiers();
9117 
9118     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9119       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9120         << (unsigned) FnKind << FnDesc
9121         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9122         << FromTy
9123         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9124         << (unsigned) isObjectArgument << I+1;
9125       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9126       return;
9127     }
9128 
9129     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9130       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9131         << (unsigned) FnKind << FnDesc
9132         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9133         << FromTy
9134         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9135         << (unsigned) isObjectArgument << I+1;
9136       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9137       return;
9138     }
9139 
9140     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9141       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9142       << (unsigned) FnKind << FnDesc
9143       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9144       << FromTy
9145       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9146       << (unsigned) isObjectArgument << I+1;
9147       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9148       return;
9149     }
9150 
9151     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9152       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9153         << (unsigned) FnKind << FnDesc
9154         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9155         << FromTy << FromQs.hasUnaligned() << I+1;
9156       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9157       return;
9158     }
9159 
9160     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9161     assert(CVR && "unexpected qualifiers mismatch");
9162 
9163     if (isObjectArgument) {
9164       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9165         << (unsigned) FnKind << FnDesc
9166         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9167         << FromTy << (CVR - 1);
9168     } else {
9169       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9170         << (unsigned) FnKind << FnDesc
9171         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9172         << FromTy << (CVR - 1) << I+1;
9173     }
9174     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9175     return;
9176   }
9177 
9178   // Special diagnostic for failure to convert an initializer list, since
9179   // telling the user that it has type void is not useful.
9180   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9181     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9182       << (unsigned) FnKind << FnDesc
9183       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9184       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9185     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9186     return;
9187   }
9188 
9189   // Diagnose references or pointers to incomplete types differently,
9190   // since it's far from impossible that the incompleteness triggered
9191   // the failure.
9192   QualType TempFromTy = FromTy.getNonReferenceType();
9193   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9194     TempFromTy = PTy->getPointeeType();
9195   if (TempFromTy->isIncompleteType()) {
9196     // Emit the generic diagnostic and, optionally, add the hints to it.
9197     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9198       << (unsigned) FnKind << FnDesc
9199       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9200       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9201       << (unsigned) (Cand->Fix.Kind);
9202 
9203     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9204     return;
9205   }
9206 
9207   // Diagnose base -> derived pointer conversions.
9208   unsigned BaseToDerivedConversion = 0;
9209   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9210     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9211       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9212                                                FromPtrTy->getPointeeType()) &&
9213           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9214           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9215           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9216                           FromPtrTy->getPointeeType()))
9217         BaseToDerivedConversion = 1;
9218     }
9219   } else if (const ObjCObjectPointerType *FromPtrTy
9220                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9221     if (const ObjCObjectPointerType *ToPtrTy
9222                                         = ToTy->getAs<ObjCObjectPointerType>())
9223       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9224         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9225           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9226                                                 FromPtrTy->getPointeeType()) &&
9227               FromIface->isSuperClassOf(ToIface))
9228             BaseToDerivedConversion = 2;
9229   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9230     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9231         !FromTy->isIncompleteType() &&
9232         !ToRefTy->getPointeeType()->isIncompleteType() &&
9233         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9234       BaseToDerivedConversion = 3;
9235     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9236                ToTy.getNonReferenceType().getCanonicalType() ==
9237                FromTy.getNonReferenceType().getCanonicalType()) {
9238       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9239         << (unsigned) FnKind << FnDesc
9240         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9241         << (unsigned) isObjectArgument << I + 1;
9242       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9243       return;
9244     }
9245   }
9246 
9247   if (BaseToDerivedConversion) {
9248     S.Diag(Fn->getLocation(),
9249            diag::note_ovl_candidate_bad_base_to_derived_conv)
9250       << (unsigned) FnKind << FnDesc
9251       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9252       << (BaseToDerivedConversion - 1)
9253       << FromTy << ToTy << I+1;
9254     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9255     return;
9256   }
9257 
9258   if (isa<ObjCObjectPointerType>(CFromTy) &&
9259       isa<PointerType>(CToTy)) {
9260       Qualifiers FromQs = CFromTy.getQualifiers();
9261       Qualifiers ToQs = CToTy.getQualifiers();
9262       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9263         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9264         << (unsigned) FnKind << FnDesc
9265         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9266         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9267         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9268         return;
9269       }
9270   }
9271 
9272   if (TakingCandidateAddress &&
9273       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9274     return;
9275 
9276   // Emit the generic diagnostic and, optionally, add the hints to it.
9277   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9278   FDiag << (unsigned) FnKind << FnDesc
9279     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9280     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9281     << (unsigned) (Cand->Fix.Kind);
9282 
9283   // If we can fix the conversion, suggest the FixIts.
9284   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9285        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9286     FDiag << *HI;
9287   S.Diag(Fn->getLocation(), FDiag);
9288 
9289   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9290 }
9291 
9292 /// Additional arity mismatch diagnosis specific to a function overload
9293 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9294 /// over a candidate in any candidate set.
9295 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9296                                unsigned NumArgs) {
9297   FunctionDecl *Fn = Cand->Function;
9298   unsigned MinParams = Fn->getMinRequiredArguments();
9299 
9300   // With invalid overloaded operators, it's possible that we think we
9301   // have an arity mismatch when in fact it looks like we have the
9302   // right number of arguments, because only overloaded operators have
9303   // the weird behavior of overloading member and non-member functions.
9304   // Just don't report anything.
9305   if (Fn->isInvalidDecl() &&
9306       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9307     return true;
9308 
9309   if (NumArgs < MinParams) {
9310     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9311            (Cand->FailureKind == ovl_fail_bad_deduction &&
9312             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9313   } else {
9314     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9315            (Cand->FailureKind == ovl_fail_bad_deduction &&
9316             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9317   }
9318 
9319   return false;
9320 }
9321 
9322 /// General arity mismatch diagnosis over a candidate in a candidate set.
9323 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9324                                   unsigned NumFormalArgs) {
9325   assert(isa<FunctionDecl>(D) &&
9326       "The templated declaration should at least be a function"
9327       " when diagnosing bad template argument deduction due to too many"
9328       " or too few arguments");
9329 
9330   FunctionDecl *Fn = cast<FunctionDecl>(D);
9331 
9332   // TODO: treat calls to a missing default constructor as a special case
9333   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9334   unsigned MinParams = Fn->getMinRequiredArguments();
9335 
9336   // at least / at most / exactly
9337   unsigned mode, modeCount;
9338   if (NumFormalArgs < MinParams) {
9339     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9340         FnTy->isTemplateVariadic())
9341       mode = 0; // "at least"
9342     else
9343       mode = 2; // "exactly"
9344     modeCount = MinParams;
9345   } else {
9346     if (MinParams != FnTy->getNumParams())
9347       mode = 1; // "at most"
9348     else
9349       mode = 2; // "exactly"
9350     modeCount = FnTy->getNumParams();
9351   }
9352 
9353   std::string Description;
9354   OverloadCandidateKind FnKind =
9355       ClassifyOverloadCandidate(S, Found, Fn, Description);
9356 
9357   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9358     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9359       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9360       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9361   else
9362     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9363       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9364       << mode << modeCount << NumFormalArgs;
9365   MaybeEmitInheritedConstructorNote(S, Found);
9366 }
9367 
9368 /// Arity mismatch diagnosis specific to a function overload candidate.
9369 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9370                                   unsigned NumFormalArgs) {
9371   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9372     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9373 }
9374 
9375 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9376   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9377     return TD;
9378   llvm_unreachable("Unsupported: Getting the described template declaration"
9379                    " for bad deduction diagnosis");
9380 }
9381 
9382 /// Diagnose a failed template-argument deduction.
9383 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9384                                  DeductionFailureInfo &DeductionFailure,
9385                                  unsigned NumArgs,
9386                                  bool TakingCandidateAddress) {
9387   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9388   NamedDecl *ParamD;
9389   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9390   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9391   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9392   switch (DeductionFailure.Result) {
9393   case Sema::TDK_Success:
9394     llvm_unreachable("TDK_success while diagnosing bad deduction");
9395 
9396   case Sema::TDK_Incomplete: {
9397     assert(ParamD && "no parameter found for incomplete deduction result");
9398     S.Diag(Templated->getLocation(),
9399            diag::note_ovl_candidate_incomplete_deduction)
9400         << ParamD->getDeclName();
9401     MaybeEmitInheritedConstructorNote(S, Found);
9402     return;
9403   }
9404 
9405   case Sema::TDK_Underqualified: {
9406     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9407     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9408 
9409     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9410 
9411     // Param will have been canonicalized, but it should just be a
9412     // qualified version of ParamD, so move the qualifiers to that.
9413     QualifierCollector Qs;
9414     Qs.strip(Param);
9415     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9416     assert(S.Context.hasSameType(Param, NonCanonParam));
9417 
9418     // Arg has also been canonicalized, but there's nothing we can do
9419     // about that.  It also doesn't matter as much, because it won't
9420     // have any template parameters in it (because deduction isn't
9421     // done on dependent types).
9422     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9423 
9424     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9425         << ParamD->getDeclName() << Arg << NonCanonParam;
9426     MaybeEmitInheritedConstructorNote(S, Found);
9427     return;
9428   }
9429 
9430   case Sema::TDK_Inconsistent: {
9431     assert(ParamD && "no parameter found for inconsistent deduction result");
9432     int which = 0;
9433     if (isa<TemplateTypeParmDecl>(ParamD))
9434       which = 0;
9435     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9436       which = 1;
9437     else {
9438       which = 2;
9439     }
9440 
9441     S.Diag(Templated->getLocation(),
9442            diag::note_ovl_candidate_inconsistent_deduction)
9443         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9444         << *DeductionFailure.getSecondArg();
9445     MaybeEmitInheritedConstructorNote(S, Found);
9446     return;
9447   }
9448 
9449   case Sema::TDK_InvalidExplicitArguments:
9450     assert(ParamD && "no parameter found for invalid explicit arguments");
9451     if (ParamD->getDeclName())
9452       S.Diag(Templated->getLocation(),
9453              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9454           << ParamD->getDeclName();
9455     else {
9456       int index = 0;
9457       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9458         index = TTP->getIndex();
9459       else if (NonTypeTemplateParmDecl *NTTP
9460                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9461         index = NTTP->getIndex();
9462       else
9463         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9464       S.Diag(Templated->getLocation(),
9465              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9466           << (index + 1);
9467     }
9468     MaybeEmitInheritedConstructorNote(S, Found);
9469     return;
9470 
9471   case Sema::TDK_TooManyArguments:
9472   case Sema::TDK_TooFewArguments:
9473     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9474     return;
9475 
9476   case Sema::TDK_InstantiationDepth:
9477     S.Diag(Templated->getLocation(),
9478            diag::note_ovl_candidate_instantiation_depth);
9479     MaybeEmitInheritedConstructorNote(S, Found);
9480     return;
9481 
9482   case Sema::TDK_SubstitutionFailure: {
9483     // Format the template argument list into the argument string.
9484     SmallString<128> TemplateArgString;
9485     if (TemplateArgumentList *Args =
9486             DeductionFailure.getTemplateArgumentList()) {
9487       TemplateArgString = " ";
9488       TemplateArgString += S.getTemplateArgumentBindingsText(
9489           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9490     }
9491 
9492     // If this candidate was disabled by enable_if, say so.
9493     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9494     if (PDiag && PDiag->second.getDiagID() ==
9495           diag::err_typename_nested_not_found_enable_if) {
9496       // FIXME: Use the source range of the condition, and the fully-qualified
9497       //        name of the enable_if template. These are both present in PDiag.
9498       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9499         << "'enable_if'" << TemplateArgString;
9500       return;
9501     }
9502 
9503     // Format the SFINAE diagnostic into the argument string.
9504     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9505     //        formatted message in another diagnostic.
9506     SmallString<128> SFINAEArgString;
9507     SourceRange R;
9508     if (PDiag) {
9509       SFINAEArgString = ": ";
9510       R = SourceRange(PDiag->first, PDiag->first);
9511       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9512     }
9513 
9514     S.Diag(Templated->getLocation(),
9515            diag::note_ovl_candidate_substitution_failure)
9516         << TemplateArgString << SFINAEArgString << R;
9517     MaybeEmitInheritedConstructorNote(S, Found);
9518     return;
9519   }
9520 
9521   case Sema::TDK_FailedOverloadResolution: {
9522     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9523     S.Diag(Templated->getLocation(),
9524            diag::note_ovl_candidate_failed_overload_resolution)
9525         << R.Expression->getName();
9526     return;
9527   }
9528 
9529   case Sema::TDK_DeducedMismatch: {
9530     // Format the template argument list into the argument string.
9531     SmallString<128> TemplateArgString;
9532     if (TemplateArgumentList *Args =
9533             DeductionFailure.getTemplateArgumentList()) {
9534       TemplateArgString = " ";
9535       TemplateArgString += S.getTemplateArgumentBindingsText(
9536           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9537     }
9538 
9539     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9540         << (*DeductionFailure.getCallArgIndex() + 1)
9541         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9542         << TemplateArgString;
9543     break;
9544   }
9545 
9546   case Sema::TDK_NonDeducedMismatch: {
9547     // FIXME: Provide a source location to indicate what we couldn't match.
9548     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9549     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9550     if (FirstTA.getKind() == TemplateArgument::Template &&
9551         SecondTA.getKind() == TemplateArgument::Template) {
9552       TemplateName FirstTN = FirstTA.getAsTemplate();
9553       TemplateName SecondTN = SecondTA.getAsTemplate();
9554       if (FirstTN.getKind() == TemplateName::Template &&
9555           SecondTN.getKind() == TemplateName::Template) {
9556         if (FirstTN.getAsTemplateDecl()->getName() ==
9557             SecondTN.getAsTemplateDecl()->getName()) {
9558           // FIXME: This fixes a bad diagnostic where both templates are named
9559           // the same.  This particular case is a bit difficult since:
9560           // 1) It is passed as a string to the diagnostic printer.
9561           // 2) The diagnostic printer only attempts to find a better
9562           //    name for types, not decls.
9563           // Ideally, this should folded into the diagnostic printer.
9564           S.Diag(Templated->getLocation(),
9565                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9566               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9567           return;
9568         }
9569       }
9570     }
9571 
9572     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9573         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9574       return;
9575 
9576     // FIXME: For generic lambda parameters, check if the function is a lambda
9577     // call operator, and if so, emit a prettier and more informative
9578     // diagnostic that mentions 'auto' and lambda in addition to
9579     // (or instead of?) the canonical template type parameters.
9580     S.Diag(Templated->getLocation(),
9581            diag::note_ovl_candidate_non_deduced_mismatch)
9582         << FirstTA << SecondTA;
9583     return;
9584   }
9585   // TODO: diagnose these individually, then kill off
9586   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9587   case Sema::TDK_MiscellaneousDeductionFailure:
9588     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9589     MaybeEmitInheritedConstructorNote(S, Found);
9590     return;
9591   }
9592 }
9593 
9594 /// Diagnose a failed template-argument deduction, for function calls.
9595 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9596                                  unsigned NumArgs,
9597                                  bool TakingCandidateAddress) {
9598   unsigned TDK = Cand->DeductionFailure.Result;
9599   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9600     if (CheckArityMismatch(S, Cand, NumArgs))
9601       return;
9602   }
9603   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9604                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9605 }
9606 
9607 /// CUDA: diagnose an invalid call across targets.
9608 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9609   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9610   FunctionDecl *Callee = Cand->Function;
9611 
9612   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9613                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9614 
9615   std::string FnDesc;
9616   OverloadCandidateKind FnKind =
9617       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9618 
9619   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9620       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9621 
9622   // This could be an implicit constructor for which we could not infer the
9623   // target due to a collsion. Diagnose that case.
9624   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9625   if (Meth != nullptr && Meth->isImplicit()) {
9626     CXXRecordDecl *ParentClass = Meth->getParent();
9627     Sema::CXXSpecialMember CSM;
9628 
9629     switch (FnKind) {
9630     default:
9631       return;
9632     case oc_implicit_default_constructor:
9633       CSM = Sema::CXXDefaultConstructor;
9634       break;
9635     case oc_implicit_copy_constructor:
9636       CSM = Sema::CXXCopyConstructor;
9637       break;
9638     case oc_implicit_move_constructor:
9639       CSM = Sema::CXXMoveConstructor;
9640       break;
9641     case oc_implicit_copy_assignment:
9642       CSM = Sema::CXXCopyAssignment;
9643       break;
9644     case oc_implicit_move_assignment:
9645       CSM = Sema::CXXMoveAssignment;
9646       break;
9647     };
9648 
9649     bool ConstRHS = false;
9650     if (Meth->getNumParams()) {
9651       if (const ReferenceType *RT =
9652               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9653         ConstRHS = RT->getPointeeType().isConstQualified();
9654       }
9655     }
9656 
9657     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9658                                               /* ConstRHS */ ConstRHS,
9659                                               /* Diagnose */ true);
9660   }
9661 }
9662 
9663 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9664   FunctionDecl *Callee = Cand->Function;
9665   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9666 
9667   S.Diag(Callee->getLocation(),
9668          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9669       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9670 }
9671 
9672 /// Generates a 'note' diagnostic for an overload candidate.  We've
9673 /// already generated a primary error at the call site.
9674 ///
9675 /// It really does need to be a single diagnostic with its caret
9676 /// pointed at the candidate declaration.  Yes, this creates some
9677 /// major challenges of technical writing.  Yes, this makes pointing
9678 /// out problems with specific arguments quite awkward.  It's still
9679 /// better than generating twenty screens of text for every failed
9680 /// overload.
9681 ///
9682 /// It would be great to be able to express per-candidate problems
9683 /// more richly for those diagnostic clients that cared, but we'd
9684 /// still have to be just as careful with the default diagnostics.
9685 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9686                                   unsigned NumArgs,
9687                                   bool TakingCandidateAddress) {
9688   FunctionDecl *Fn = Cand->Function;
9689 
9690   // Note deleted candidates, but only if they're viable.
9691   if (Cand->Viable && (Fn->isDeleted() ||
9692       S.isFunctionConsideredUnavailable(Fn))) {
9693     std::string FnDesc;
9694     OverloadCandidateKind FnKind =
9695         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9696 
9697     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9698       << FnKind << FnDesc
9699       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9700     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9701     return;
9702   }
9703 
9704   // We don't really have anything else to say about viable candidates.
9705   if (Cand->Viable) {
9706     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9707     return;
9708   }
9709 
9710   switch (Cand->FailureKind) {
9711   case ovl_fail_too_many_arguments:
9712   case ovl_fail_too_few_arguments:
9713     return DiagnoseArityMismatch(S, Cand, NumArgs);
9714 
9715   case ovl_fail_bad_deduction:
9716     return DiagnoseBadDeduction(S, Cand, NumArgs,
9717                                 TakingCandidateAddress);
9718 
9719   case ovl_fail_illegal_constructor: {
9720     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9721       << (Fn->getPrimaryTemplate() ? 1 : 0);
9722     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9723     return;
9724   }
9725 
9726   case ovl_fail_trivial_conversion:
9727   case ovl_fail_bad_final_conversion:
9728   case ovl_fail_final_conversion_not_exact:
9729     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9730 
9731   case ovl_fail_bad_conversion: {
9732     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9733     for (unsigned N = Cand->NumConversions; I != N; ++I)
9734       if (Cand->Conversions[I].isBad())
9735         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9736 
9737     // FIXME: this currently happens when we're called from SemaInit
9738     // when user-conversion overload fails.  Figure out how to handle
9739     // those conditions and diagnose them well.
9740     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9741   }
9742 
9743   case ovl_fail_bad_target:
9744     return DiagnoseBadTarget(S, Cand);
9745 
9746   case ovl_fail_enable_if:
9747     return DiagnoseFailedEnableIfAttr(S, Cand);
9748 
9749   case ovl_fail_addr_not_available: {
9750     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9751     (void)Available;
9752     assert(!Available);
9753     break;
9754   }
9755   }
9756 }
9757 
9758 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9759   // Desugar the type of the surrogate down to a function type,
9760   // retaining as many typedefs as possible while still showing
9761   // the function type (and, therefore, its parameter types).
9762   QualType FnType = Cand->Surrogate->getConversionType();
9763   bool isLValueReference = false;
9764   bool isRValueReference = false;
9765   bool isPointer = false;
9766   if (const LValueReferenceType *FnTypeRef =
9767         FnType->getAs<LValueReferenceType>()) {
9768     FnType = FnTypeRef->getPointeeType();
9769     isLValueReference = true;
9770   } else if (const RValueReferenceType *FnTypeRef =
9771                FnType->getAs<RValueReferenceType>()) {
9772     FnType = FnTypeRef->getPointeeType();
9773     isRValueReference = true;
9774   }
9775   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9776     FnType = FnTypePtr->getPointeeType();
9777     isPointer = true;
9778   }
9779   // Desugar down to a function type.
9780   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9781   // Reconstruct the pointer/reference as appropriate.
9782   if (isPointer) FnType = S.Context.getPointerType(FnType);
9783   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9784   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9785 
9786   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9787     << FnType;
9788 }
9789 
9790 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9791                                          SourceLocation OpLoc,
9792                                          OverloadCandidate *Cand) {
9793   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9794   std::string TypeStr("operator");
9795   TypeStr += Opc;
9796   TypeStr += "(";
9797   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9798   if (Cand->NumConversions == 1) {
9799     TypeStr += ")";
9800     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9801   } else {
9802     TypeStr += ", ";
9803     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9804     TypeStr += ")";
9805     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9806   }
9807 }
9808 
9809 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9810                                          OverloadCandidate *Cand) {
9811   unsigned NoOperands = Cand->NumConversions;
9812   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9813     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9814     if (ICS.isBad()) break; // all meaningless after first invalid
9815     if (!ICS.isAmbiguous()) continue;
9816 
9817     ICS.DiagnoseAmbiguousConversion(
9818         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9819   }
9820 }
9821 
9822 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9823   if (Cand->Function)
9824     return Cand->Function->getLocation();
9825   if (Cand->IsSurrogate)
9826     return Cand->Surrogate->getLocation();
9827   return SourceLocation();
9828 }
9829 
9830 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9831   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9832   case Sema::TDK_Success:
9833     llvm_unreachable("TDK_success while diagnosing bad deduction");
9834 
9835   case Sema::TDK_Invalid:
9836   case Sema::TDK_Incomplete:
9837     return 1;
9838 
9839   case Sema::TDK_Underqualified:
9840   case Sema::TDK_Inconsistent:
9841     return 2;
9842 
9843   case Sema::TDK_SubstitutionFailure:
9844   case Sema::TDK_DeducedMismatch:
9845   case Sema::TDK_NonDeducedMismatch:
9846   case Sema::TDK_MiscellaneousDeductionFailure:
9847     return 3;
9848 
9849   case Sema::TDK_InstantiationDepth:
9850   case Sema::TDK_FailedOverloadResolution:
9851     return 4;
9852 
9853   case Sema::TDK_InvalidExplicitArguments:
9854     return 5;
9855 
9856   case Sema::TDK_TooManyArguments:
9857   case Sema::TDK_TooFewArguments:
9858     return 6;
9859   }
9860   llvm_unreachable("Unhandled deduction result");
9861 }
9862 
9863 namespace {
9864 struct CompareOverloadCandidatesForDisplay {
9865   Sema &S;
9866   SourceLocation Loc;
9867   size_t NumArgs;
9868 
9869   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9870       : S(S), NumArgs(nArgs) {}
9871 
9872   bool operator()(const OverloadCandidate *L,
9873                   const OverloadCandidate *R) {
9874     // Fast-path this check.
9875     if (L == R) return false;
9876 
9877     // Order first by viability.
9878     if (L->Viable) {
9879       if (!R->Viable) return true;
9880 
9881       // TODO: introduce a tri-valued comparison for overload
9882       // candidates.  Would be more worthwhile if we had a sort
9883       // that could exploit it.
9884       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9885       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9886     } else if (R->Viable)
9887       return false;
9888 
9889     assert(L->Viable == R->Viable);
9890 
9891     // Criteria by which we can sort non-viable candidates:
9892     if (!L->Viable) {
9893       // 1. Arity mismatches come after other candidates.
9894       if (L->FailureKind == ovl_fail_too_many_arguments ||
9895           L->FailureKind == ovl_fail_too_few_arguments) {
9896         if (R->FailureKind == ovl_fail_too_many_arguments ||
9897             R->FailureKind == ovl_fail_too_few_arguments) {
9898           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9899           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9900           if (LDist == RDist) {
9901             if (L->FailureKind == R->FailureKind)
9902               // Sort non-surrogates before surrogates.
9903               return !L->IsSurrogate && R->IsSurrogate;
9904             // Sort candidates requiring fewer parameters than there were
9905             // arguments given after candidates requiring more parameters
9906             // than there were arguments given.
9907             return L->FailureKind == ovl_fail_too_many_arguments;
9908           }
9909           return LDist < RDist;
9910         }
9911         return false;
9912       }
9913       if (R->FailureKind == ovl_fail_too_many_arguments ||
9914           R->FailureKind == ovl_fail_too_few_arguments)
9915         return true;
9916 
9917       // 2. Bad conversions come first and are ordered by the number
9918       // of bad conversions and quality of good conversions.
9919       if (L->FailureKind == ovl_fail_bad_conversion) {
9920         if (R->FailureKind != ovl_fail_bad_conversion)
9921           return true;
9922 
9923         // The conversion that can be fixed with a smaller number of changes,
9924         // comes first.
9925         unsigned numLFixes = L->Fix.NumConversionsFixed;
9926         unsigned numRFixes = R->Fix.NumConversionsFixed;
9927         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9928         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9929         if (numLFixes != numRFixes) {
9930           return numLFixes < numRFixes;
9931         }
9932 
9933         // If there's any ordering between the defined conversions...
9934         // FIXME: this might not be transitive.
9935         assert(L->NumConversions == R->NumConversions);
9936 
9937         int leftBetter = 0;
9938         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9939         for (unsigned E = L->NumConversions; I != E; ++I) {
9940           switch (CompareImplicitConversionSequences(S, Loc,
9941                                                      L->Conversions[I],
9942                                                      R->Conversions[I])) {
9943           case ImplicitConversionSequence::Better:
9944             leftBetter++;
9945             break;
9946 
9947           case ImplicitConversionSequence::Worse:
9948             leftBetter--;
9949             break;
9950 
9951           case ImplicitConversionSequence::Indistinguishable:
9952             break;
9953           }
9954         }
9955         if (leftBetter > 0) return true;
9956         if (leftBetter < 0) return false;
9957 
9958       } else if (R->FailureKind == ovl_fail_bad_conversion)
9959         return false;
9960 
9961       if (L->FailureKind == ovl_fail_bad_deduction) {
9962         if (R->FailureKind != ovl_fail_bad_deduction)
9963           return true;
9964 
9965         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9966           return RankDeductionFailure(L->DeductionFailure)
9967                < RankDeductionFailure(R->DeductionFailure);
9968       } else if (R->FailureKind == ovl_fail_bad_deduction)
9969         return false;
9970 
9971       // TODO: others?
9972     }
9973 
9974     // Sort everything else by location.
9975     SourceLocation LLoc = GetLocationForCandidate(L);
9976     SourceLocation RLoc = GetLocationForCandidate(R);
9977 
9978     // Put candidates without locations (e.g. builtins) at the end.
9979     if (LLoc.isInvalid()) return false;
9980     if (RLoc.isInvalid()) return true;
9981 
9982     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9983   }
9984 };
9985 }
9986 
9987 /// CompleteNonViableCandidate - Normally, overload resolution only
9988 /// computes up to the first. Produces the FixIt set if possible.
9989 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9990                                        ArrayRef<Expr *> Args) {
9991   assert(!Cand->Viable);
9992 
9993   // Don't do anything on failures other than bad conversion.
9994   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9995 
9996   // We only want the FixIts if all the arguments can be corrected.
9997   bool Unfixable = false;
9998   // Use a implicit copy initialization to check conversion fixes.
9999   Cand->Fix.setConversionChecker(TryCopyInitialization);
10000 
10001   // Skip forward to the first bad conversion.
10002   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10003   unsigned ConvCount = Cand->NumConversions;
10004   while (true) {
10005     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10006     ConvIdx++;
10007     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10008       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10009       break;
10010     }
10011   }
10012 
10013   if (ConvIdx == ConvCount)
10014     return;
10015 
10016   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10017          "remaining conversion is initialized?");
10018 
10019   // FIXME: this should probably be preserved from the overload
10020   // operation somehow.
10021   bool SuppressUserConversions = false;
10022 
10023   const FunctionProtoType* Proto;
10024   unsigned ArgIdx = ConvIdx;
10025 
10026   if (Cand->IsSurrogate) {
10027     QualType ConvType
10028       = Cand->Surrogate->getConversionType().getNonReferenceType();
10029     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10030       ConvType = ConvPtrType->getPointeeType();
10031     Proto = ConvType->getAs<FunctionProtoType>();
10032     ArgIdx--;
10033   } else if (Cand->Function) {
10034     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10035     if (isa<CXXMethodDecl>(Cand->Function) &&
10036         !isa<CXXConstructorDecl>(Cand->Function))
10037       ArgIdx--;
10038   } else {
10039     // Builtin binary operator with a bad first conversion.
10040     assert(ConvCount <= 3);
10041     for (; ConvIdx != ConvCount; ++ConvIdx)
10042       Cand->Conversions[ConvIdx]
10043         = TryCopyInitialization(S, Args[ConvIdx],
10044                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10045                                 SuppressUserConversions,
10046                                 /*InOverloadResolution*/ true,
10047                                 /*AllowObjCWritebackConversion=*/
10048                                   S.getLangOpts().ObjCAutoRefCount);
10049     return;
10050   }
10051 
10052   // Fill in the rest of the conversions.
10053   unsigned NumParams = Proto->getNumParams();
10054   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10055     if (ArgIdx < NumParams) {
10056       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10057           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10058           /*InOverloadResolution=*/true,
10059           /*AllowObjCWritebackConversion=*/
10060           S.getLangOpts().ObjCAutoRefCount);
10061       // Store the FixIt in the candidate if it exists.
10062       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10063         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10064     }
10065     else
10066       Cand->Conversions[ConvIdx].setEllipsis();
10067   }
10068 }
10069 
10070 /// PrintOverloadCandidates - When overload resolution fails, prints
10071 /// diagnostic messages containing the candidates in the candidate
10072 /// set.
10073 void OverloadCandidateSet::NoteCandidates(Sema &S,
10074                                           OverloadCandidateDisplayKind OCD,
10075                                           ArrayRef<Expr *> Args,
10076                                           StringRef Opc,
10077                                           SourceLocation OpLoc) {
10078   // Sort the candidates by viability and position.  Sorting directly would
10079   // be prohibitive, so we make a set of pointers and sort those.
10080   SmallVector<OverloadCandidate*, 32> Cands;
10081   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10082   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10083     if (Cand->Viable)
10084       Cands.push_back(Cand);
10085     else if (OCD == OCD_AllCandidates) {
10086       CompleteNonViableCandidate(S, Cand, Args);
10087       if (Cand->Function || Cand->IsSurrogate)
10088         Cands.push_back(Cand);
10089       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10090       // want to list every possible builtin candidate.
10091     }
10092   }
10093 
10094   std::sort(Cands.begin(), Cands.end(),
10095             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10096 
10097   bool ReportedAmbiguousConversions = false;
10098 
10099   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10100   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10101   unsigned CandsShown = 0;
10102   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10103     OverloadCandidate *Cand = *I;
10104 
10105     // Set an arbitrary limit on the number of candidate functions we'll spam
10106     // the user with.  FIXME: This limit should depend on details of the
10107     // candidate list.
10108     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10109       break;
10110     }
10111     ++CandsShown;
10112 
10113     if (Cand->Function)
10114       NoteFunctionCandidate(S, Cand, Args.size(),
10115                             /*TakingCandidateAddress=*/false);
10116     else if (Cand->IsSurrogate)
10117       NoteSurrogateCandidate(S, Cand);
10118     else {
10119       assert(Cand->Viable &&
10120              "Non-viable built-in candidates are not added to Cands.");
10121       // Generally we only see ambiguities including viable builtin
10122       // operators if overload resolution got screwed up by an
10123       // ambiguous user-defined conversion.
10124       //
10125       // FIXME: It's quite possible for different conversions to see
10126       // different ambiguities, though.
10127       if (!ReportedAmbiguousConversions) {
10128         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10129         ReportedAmbiguousConversions = true;
10130       }
10131 
10132       // If this is a viable builtin, print it.
10133       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10134     }
10135   }
10136 
10137   if (I != E)
10138     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10139 }
10140 
10141 static SourceLocation
10142 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10143   return Cand->Specialization ? Cand->Specialization->getLocation()
10144                               : SourceLocation();
10145 }
10146 
10147 namespace {
10148 struct CompareTemplateSpecCandidatesForDisplay {
10149   Sema &S;
10150   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10151 
10152   bool operator()(const TemplateSpecCandidate *L,
10153                   const TemplateSpecCandidate *R) {
10154     // Fast-path this check.
10155     if (L == R)
10156       return false;
10157 
10158     // Assuming that both candidates are not matches...
10159 
10160     // Sort by the ranking of deduction failures.
10161     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10162       return RankDeductionFailure(L->DeductionFailure) <
10163              RankDeductionFailure(R->DeductionFailure);
10164 
10165     // Sort everything else by location.
10166     SourceLocation LLoc = GetLocationForCandidate(L);
10167     SourceLocation RLoc = GetLocationForCandidate(R);
10168 
10169     // Put candidates without locations (e.g. builtins) at the end.
10170     if (LLoc.isInvalid())
10171       return false;
10172     if (RLoc.isInvalid())
10173       return true;
10174 
10175     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10176   }
10177 };
10178 }
10179 
10180 /// Diagnose a template argument deduction failure.
10181 /// We are treating these failures as overload failures due to bad
10182 /// deductions.
10183 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10184                                                  bool ForTakingAddress) {
10185   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10186                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10187 }
10188 
10189 void TemplateSpecCandidateSet::destroyCandidates() {
10190   for (iterator i = begin(), e = end(); i != e; ++i) {
10191     i->DeductionFailure.Destroy();
10192   }
10193 }
10194 
10195 void TemplateSpecCandidateSet::clear() {
10196   destroyCandidates();
10197   Candidates.clear();
10198 }
10199 
10200 /// NoteCandidates - When no template specialization match is found, prints
10201 /// diagnostic messages containing the non-matching specializations that form
10202 /// the candidate set.
10203 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10204 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10205 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10206   // Sort the candidates by position (assuming no candidate is a match).
10207   // Sorting directly would be prohibitive, so we make a set of pointers
10208   // and sort those.
10209   SmallVector<TemplateSpecCandidate *, 32> Cands;
10210   Cands.reserve(size());
10211   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10212     if (Cand->Specialization)
10213       Cands.push_back(Cand);
10214     // Otherwise, this is a non-matching builtin candidate.  We do not,
10215     // in general, want to list every possible builtin candidate.
10216   }
10217 
10218   std::sort(Cands.begin(), Cands.end(),
10219             CompareTemplateSpecCandidatesForDisplay(S));
10220 
10221   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10222   // for generalization purposes (?).
10223   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10224 
10225   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10226   unsigned CandsShown = 0;
10227   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10228     TemplateSpecCandidate *Cand = *I;
10229 
10230     // Set an arbitrary limit on the number of candidates we'll spam
10231     // the user with.  FIXME: This limit should depend on details of the
10232     // candidate list.
10233     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10234       break;
10235     ++CandsShown;
10236 
10237     assert(Cand->Specialization &&
10238            "Non-matching built-in candidates are not added to Cands.");
10239     Cand->NoteDeductionFailure(S, ForTakingAddress);
10240   }
10241 
10242   if (I != E)
10243     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10244 }
10245 
10246 // [PossiblyAFunctionType]  -->   [Return]
10247 // NonFunctionType --> NonFunctionType
10248 // R (A) --> R(A)
10249 // R (*)(A) --> R (A)
10250 // R (&)(A) --> R (A)
10251 // R (S::*)(A) --> R (A)
10252 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10253   QualType Ret = PossiblyAFunctionType;
10254   if (const PointerType *ToTypePtr =
10255     PossiblyAFunctionType->getAs<PointerType>())
10256     Ret = ToTypePtr->getPointeeType();
10257   else if (const ReferenceType *ToTypeRef =
10258     PossiblyAFunctionType->getAs<ReferenceType>())
10259     Ret = ToTypeRef->getPointeeType();
10260   else if (const MemberPointerType *MemTypePtr =
10261     PossiblyAFunctionType->getAs<MemberPointerType>())
10262     Ret = MemTypePtr->getPointeeType();
10263   Ret =
10264     Context.getCanonicalType(Ret).getUnqualifiedType();
10265   return Ret;
10266 }
10267 
10268 namespace {
10269 // A helper class to help with address of function resolution
10270 // - allows us to avoid passing around all those ugly parameters
10271 class AddressOfFunctionResolver {
10272   Sema& S;
10273   Expr* SourceExpr;
10274   const QualType& TargetType;
10275   QualType TargetFunctionType; // Extracted function type from target type
10276 
10277   bool Complain;
10278   //DeclAccessPair& ResultFunctionAccessPair;
10279   ASTContext& Context;
10280 
10281   bool TargetTypeIsNonStaticMemberFunction;
10282   bool FoundNonTemplateFunction;
10283   bool StaticMemberFunctionFromBoundPointer;
10284   bool HasComplained;
10285 
10286   OverloadExpr::FindResult OvlExprInfo;
10287   OverloadExpr *OvlExpr;
10288   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10289   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10290   TemplateSpecCandidateSet FailedCandidates;
10291 
10292 public:
10293   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10294                             const QualType &TargetType, bool Complain)
10295       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10296         Complain(Complain), Context(S.getASTContext()),
10297         TargetTypeIsNonStaticMemberFunction(
10298             !!TargetType->getAs<MemberPointerType>()),
10299         FoundNonTemplateFunction(false),
10300         StaticMemberFunctionFromBoundPointer(false),
10301         HasComplained(false),
10302         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10303         OvlExpr(OvlExprInfo.Expression),
10304         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10305     ExtractUnqualifiedFunctionTypeFromTargetType();
10306 
10307     if (TargetFunctionType->isFunctionType()) {
10308       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10309         if (!UME->isImplicitAccess() &&
10310             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10311           StaticMemberFunctionFromBoundPointer = true;
10312     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10313       DeclAccessPair dap;
10314       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10315               OvlExpr, false, &dap)) {
10316         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10317           if (!Method->isStatic()) {
10318             // If the target type is a non-function type and the function found
10319             // is a non-static member function, pretend as if that was the
10320             // target, it's the only possible type to end up with.
10321             TargetTypeIsNonStaticMemberFunction = true;
10322 
10323             // And skip adding the function if its not in the proper form.
10324             // We'll diagnose this due to an empty set of functions.
10325             if (!OvlExprInfo.HasFormOfMemberPointer)
10326               return;
10327           }
10328 
10329         Matches.push_back(std::make_pair(dap, Fn));
10330       }
10331       return;
10332     }
10333 
10334     if (OvlExpr->hasExplicitTemplateArgs())
10335       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10336 
10337     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10338       // C++ [over.over]p4:
10339       //   If more than one function is selected, [...]
10340       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10341         if (FoundNonTemplateFunction)
10342           EliminateAllTemplateMatches();
10343         else
10344           EliminateAllExceptMostSpecializedTemplate();
10345       }
10346     }
10347 
10348     if (S.getLangOpts().CUDA && Matches.size() > 1)
10349       EliminateSuboptimalCudaMatches();
10350   }
10351 
10352   bool hasComplained() const { return HasComplained; }
10353 
10354 private:
10355   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10356     QualType Discard;
10357     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10358            S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10359   }
10360 
10361   /// \return true if A is considered a better overload candidate for the
10362   /// desired type than B.
10363   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10364     // If A doesn't have exactly the correct type, we don't want to classify it
10365     // as "better" than anything else. This way, the user is required to
10366     // disambiguate for us if there are multiple candidates and no exact match.
10367     return candidateHasExactlyCorrectType(A) &&
10368            (!candidateHasExactlyCorrectType(B) ||
10369             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10370   }
10371 
10372   /// \return true if we were able to eliminate all but one overload candidate,
10373   /// false otherwise.
10374   bool eliminiateSuboptimalOverloadCandidates() {
10375     // Same algorithm as overload resolution -- one pass to pick the "best",
10376     // another pass to be sure that nothing is better than the best.
10377     auto Best = Matches.begin();
10378     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10379       if (isBetterCandidate(I->second, Best->second))
10380         Best = I;
10381 
10382     const FunctionDecl *BestFn = Best->second;
10383     auto IsBestOrInferiorToBest = [this, BestFn](
10384         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10385       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10386     };
10387 
10388     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10389     // option, so we can potentially give the user a better error
10390     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10391       return false;
10392     Matches[0] = *Best;
10393     Matches.resize(1);
10394     return true;
10395   }
10396 
10397   bool isTargetTypeAFunction() const {
10398     return TargetFunctionType->isFunctionType();
10399   }
10400 
10401   // [ToType]     [Return]
10402 
10403   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10404   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10405   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10406   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10407     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10408   }
10409 
10410   // return true if any matching specializations were found
10411   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10412                                    const DeclAccessPair& CurAccessFunPair) {
10413     if (CXXMethodDecl *Method
10414               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10415       // Skip non-static function templates when converting to pointer, and
10416       // static when converting to member pointer.
10417       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10418         return false;
10419     }
10420     else if (TargetTypeIsNonStaticMemberFunction)
10421       return false;
10422 
10423     // C++ [over.over]p2:
10424     //   If the name is a function template, template argument deduction is
10425     //   done (14.8.2.2), and if the argument deduction succeeds, the
10426     //   resulting template argument list is used to generate a single
10427     //   function template specialization, which is added to the set of
10428     //   overloaded functions considered.
10429     FunctionDecl *Specialization = nullptr;
10430     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10431     if (Sema::TemplateDeductionResult Result
10432           = S.DeduceTemplateArguments(FunctionTemplate,
10433                                       &OvlExplicitTemplateArgs,
10434                                       TargetFunctionType, Specialization,
10435                                       Info, /*InOverloadResolution=*/true)) {
10436       // Make a note of the failed deduction for diagnostics.
10437       FailedCandidates.addCandidate()
10438           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10439                MakeDeductionFailureInfo(Context, Result, Info));
10440       return false;
10441     }
10442 
10443     // Template argument deduction ensures that we have an exact match or
10444     // compatible pointer-to-function arguments that would be adjusted by ICS.
10445     // This function template specicalization works.
10446     assert(S.isSameOrCompatibleFunctionType(
10447               Context.getCanonicalType(Specialization->getType()),
10448               Context.getCanonicalType(TargetFunctionType)));
10449 
10450     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10451       return false;
10452 
10453     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10454     return true;
10455   }
10456 
10457   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10458                                       const DeclAccessPair& CurAccessFunPair) {
10459     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10460       // Skip non-static functions when converting to pointer, and static
10461       // when converting to member pointer.
10462       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10463         return false;
10464     }
10465     else if (TargetTypeIsNonStaticMemberFunction)
10466       return false;
10467 
10468     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10469       if (S.getLangOpts().CUDA)
10470         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10471           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10472             return false;
10473 
10474       // If any candidate has a placeholder return type, trigger its deduction
10475       // now.
10476       if (S.getLangOpts().CPlusPlus14 &&
10477           FunDecl->getReturnType()->isUndeducedType() &&
10478           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10479         HasComplained |= Complain;
10480         return false;
10481       }
10482 
10483       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10484         return false;
10485 
10486       // If we're in C, we need to support types that aren't exactly identical.
10487       if (!S.getLangOpts().CPlusPlus ||
10488           candidateHasExactlyCorrectType(FunDecl)) {
10489         Matches.push_back(std::make_pair(
10490             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10491         FoundNonTemplateFunction = true;
10492         return true;
10493       }
10494     }
10495 
10496     return false;
10497   }
10498 
10499   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10500     bool Ret = false;
10501 
10502     // If the overload expression doesn't have the form of a pointer to
10503     // member, don't try to convert it to a pointer-to-member type.
10504     if (IsInvalidFormOfPointerToMemberFunction())
10505       return false;
10506 
10507     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10508                                E = OvlExpr->decls_end();
10509          I != E; ++I) {
10510       // Look through any using declarations to find the underlying function.
10511       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10512 
10513       // C++ [over.over]p3:
10514       //   Non-member functions and static member functions match
10515       //   targets of type "pointer-to-function" or "reference-to-function."
10516       //   Nonstatic member functions match targets of
10517       //   type "pointer-to-member-function."
10518       // Note that according to DR 247, the containing class does not matter.
10519       if (FunctionTemplateDecl *FunctionTemplate
10520                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10521         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10522           Ret = true;
10523       }
10524       // If we have explicit template arguments supplied, skip non-templates.
10525       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10526                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10527         Ret = true;
10528     }
10529     assert(Ret || Matches.empty());
10530     return Ret;
10531   }
10532 
10533   void EliminateAllExceptMostSpecializedTemplate() {
10534     //   [...] and any given function template specialization F1 is
10535     //   eliminated if the set contains a second function template
10536     //   specialization whose function template is more specialized
10537     //   than the function template of F1 according to the partial
10538     //   ordering rules of 14.5.5.2.
10539 
10540     // The algorithm specified above is quadratic. We instead use a
10541     // two-pass algorithm (similar to the one used to identify the
10542     // best viable function in an overload set) that identifies the
10543     // best function template (if it exists).
10544 
10545     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10546     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10547       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10548 
10549     // TODO: It looks like FailedCandidates does not serve much purpose
10550     // here, since the no_viable diagnostic has index 0.
10551     UnresolvedSetIterator Result = S.getMostSpecialized(
10552         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10553         SourceExpr->getLocStart(), S.PDiag(),
10554         S.PDiag(diag::err_addr_ovl_ambiguous)
10555           << Matches[0].second->getDeclName(),
10556         S.PDiag(diag::note_ovl_candidate)
10557           << (unsigned)oc_function_template,
10558         Complain, TargetFunctionType);
10559 
10560     if (Result != MatchesCopy.end()) {
10561       // Make it the first and only element
10562       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10563       Matches[0].second = cast<FunctionDecl>(*Result);
10564       Matches.resize(1);
10565     } else
10566       HasComplained |= Complain;
10567   }
10568 
10569   void EliminateAllTemplateMatches() {
10570     //   [...] any function template specializations in the set are
10571     //   eliminated if the set also contains a non-template function, [...]
10572     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10573       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10574         ++I;
10575       else {
10576         Matches[I] = Matches[--N];
10577         Matches.resize(N);
10578       }
10579     }
10580   }
10581 
10582   void EliminateSuboptimalCudaMatches() {
10583     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10584   }
10585 
10586 public:
10587   void ComplainNoMatchesFound() const {
10588     assert(Matches.empty());
10589     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10590         << OvlExpr->getName() << TargetFunctionType
10591         << OvlExpr->getSourceRange();
10592     if (FailedCandidates.empty())
10593       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10594                                   /*TakingAddress=*/true);
10595     else {
10596       // We have some deduction failure messages. Use them to diagnose
10597       // the function templates, and diagnose the non-template candidates
10598       // normally.
10599       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10600                                  IEnd = OvlExpr->decls_end();
10601            I != IEnd; ++I)
10602         if (FunctionDecl *Fun =
10603                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10604           if (!functionHasPassObjectSizeParams(Fun))
10605             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10606                                     /*TakingAddress=*/true);
10607       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10608     }
10609   }
10610 
10611   bool IsInvalidFormOfPointerToMemberFunction() const {
10612     return TargetTypeIsNonStaticMemberFunction &&
10613       !OvlExprInfo.HasFormOfMemberPointer;
10614   }
10615 
10616   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10617       // TODO: Should we condition this on whether any functions might
10618       // have matched, or is it more appropriate to do that in callers?
10619       // TODO: a fixit wouldn't hurt.
10620       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10621         << TargetType << OvlExpr->getSourceRange();
10622   }
10623 
10624   bool IsStaticMemberFunctionFromBoundPointer() const {
10625     return StaticMemberFunctionFromBoundPointer;
10626   }
10627 
10628   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10629     S.Diag(OvlExpr->getLocStart(),
10630            diag::err_invalid_form_pointer_member_function)
10631       << OvlExpr->getSourceRange();
10632   }
10633 
10634   void ComplainOfInvalidConversion() const {
10635     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10636       << OvlExpr->getName() << TargetType;
10637   }
10638 
10639   void ComplainMultipleMatchesFound() const {
10640     assert(Matches.size() > 1);
10641     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10642       << OvlExpr->getName()
10643       << OvlExpr->getSourceRange();
10644     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10645                                 /*TakingAddress=*/true);
10646   }
10647 
10648   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10649 
10650   int getNumMatches() const { return Matches.size(); }
10651 
10652   FunctionDecl* getMatchingFunctionDecl() const {
10653     if (Matches.size() != 1) return nullptr;
10654     return Matches[0].second;
10655   }
10656 
10657   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10658     if (Matches.size() != 1) return nullptr;
10659     return &Matches[0].first;
10660   }
10661 };
10662 }
10663 
10664 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10665 /// an overloaded function (C++ [over.over]), where @p From is an
10666 /// expression with overloaded function type and @p ToType is the type
10667 /// we're trying to resolve to. For example:
10668 ///
10669 /// @code
10670 /// int f(double);
10671 /// int f(int);
10672 ///
10673 /// int (*pfd)(double) = f; // selects f(double)
10674 /// @endcode
10675 ///
10676 /// This routine returns the resulting FunctionDecl if it could be
10677 /// resolved, and NULL otherwise. When @p Complain is true, this
10678 /// routine will emit diagnostics if there is an error.
10679 FunctionDecl *
10680 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10681                                          QualType TargetType,
10682                                          bool Complain,
10683                                          DeclAccessPair &FoundResult,
10684                                          bool *pHadMultipleCandidates) {
10685   assert(AddressOfExpr->getType() == Context.OverloadTy);
10686 
10687   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10688                                      Complain);
10689   int NumMatches = Resolver.getNumMatches();
10690   FunctionDecl *Fn = nullptr;
10691   bool ShouldComplain = Complain && !Resolver.hasComplained();
10692   if (NumMatches == 0 && ShouldComplain) {
10693     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10694       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10695     else
10696       Resolver.ComplainNoMatchesFound();
10697   }
10698   else if (NumMatches > 1 && ShouldComplain)
10699     Resolver.ComplainMultipleMatchesFound();
10700   else if (NumMatches == 1) {
10701     Fn = Resolver.getMatchingFunctionDecl();
10702     assert(Fn);
10703     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10704     if (Complain) {
10705       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10706         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10707       else
10708         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10709     }
10710   }
10711 
10712   if (pHadMultipleCandidates)
10713     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10714   return Fn;
10715 }
10716 
10717 /// \brief Given an expression that refers to an overloaded function, try to
10718 /// resolve that function to a single function that can have its address taken.
10719 /// This will modify `Pair` iff it returns non-null.
10720 ///
10721 /// This routine can only realistically succeed if all but one candidates in the
10722 /// overload set for SrcExpr cannot have their addresses taken.
10723 FunctionDecl *
10724 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10725                                                   DeclAccessPair &Pair) {
10726   OverloadExpr::FindResult R = OverloadExpr::find(E);
10727   OverloadExpr *Ovl = R.Expression;
10728   FunctionDecl *Result = nullptr;
10729   DeclAccessPair DAP;
10730   // Don't use the AddressOfResolver because we're specifically looking for
10731   // cases where we have one overload candidate that lacks
10732   // enable_if/pass_object_size/...
10733   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10734     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10735     if (!FD)
10736       return nullptr;
10737 
10738     if (!checkAddressOfFunctionIsAvailable(FD))
10739       continue;
10740 
10741     // We have more than one result; quit.
10742     if (Result)
10743       return nullptr;
10744     DAP = I.getPair();
10745     Result = FD;
10746   }
10747 
10748   if (Result)
10749     Pair = DAP;
10750   return Result;
10751 }
10752 
10753 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10754 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10755 /// will perform access checks, diagnose the use of the resultant decl, and, if
10756 /// necessary, perform a function-to-pointer decay.
10757 ///
10758 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10759 /// Otherwise, returns true. This may emit diagnostics and return true.
10760 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10761     ExprResult &SrcExpr) {
10762   Expr *E = SrcExpr.get();
10763   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10764 
10765   DeclAccessPair DAP;
10766   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10767   if (!Found)
10768     return false;
10769 
10770   // Emitting multiple diagnostics for a function that is both inaccessible and
10771   // unavailable is consistent with our behavior elsewhere. So, always check
10772   // for both.
10773   DiagnoseUseOfDecl(Found, E->getExprLoc());
10774   CheckAddressOfMemberAccess(E, DAP);
10775   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10776   if (Fixed->getType()->isFunctionType())
10777     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10778   else
10779     SrcExpr = Fixed;
10780   return true;
10781 }
10782 
10783 /// \brief Given an expression that refers to an overloaded function, try to
10784 /// resolve that overloaded function expression down to a single function.
10785 ///
10786 /// This routine can only resolve template-ids that refer to a single function
10787 /// template, where that template-id refers to a single template whose template
10788 /// arguments are either provided by the template-id or have defaults,
10789 /// as described in C++0x [temp.arg.explicit]p3.
10790 ///
10791 /// If no template-ids are found, no diagnostics are emitted and NULL is
10792 /// returned.
10793 FunctionDecl *
10794 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10795                                                   bool Complain,
10796                                                   DeclAccessPair *FoundResult) {
10797   // C++ [over.over]p1:
10798   //   [...] [Note: any redundant set of parentheses surrounding the
10799   //   overloaded function name is ignored (5.1). ]
10800   // C++ [over.over]p1:
10801   //   [...] The overloaded function name can be preceded by the &
10802   //   operator.
10803 
10804   // If we didn't actually find any template-ids, we're done.
10805   if (!ovl->hasExplicitTemplateArgs())
10806     return nullptr;
10807 
10808   TemplateArgumentListInfo ExplicitTemplateArgs;
10809   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10810   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10811 
10812   // Look through all of the overloaded functions, searching for one
10813   // whose type matches exactly.
10814   FunctionDecl *Matched = nullptr;
10815   for (UnresolvedSetIterator I = ovl->decls_begin(),
10816          E = ovl->decls_end(); I != E; ++I) {
10817     // C++0x [temp.arg.explicit]p3:
10818     //   [...] In contexts where deduction is done and fails, or in contexts
10819     //   where deduction is not done, if a template argument list is
10820     //   specified and it, along with any default template arguments,
10821     //   identifies a single function template specialization, then the
10822     //   template-id is an lvalue for the function template specialization.
10823     FunctionTemplateDecl *FunctionTemplate
10824       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10825 
10826     // C++ [over.over]p2:
10827     //   If the name is a function template, template argument deduction is
10828     //   done (14.8.2.2), and if the argument deduction succeeds, the
10829     //   resulting template argument list is used to generate a single
10830     //   function template specialization, which is added to the set of
10831     //   overloaded functions considered.
10832     FunctionDecl *Specialization = nullptr;
10833     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10834     if (TemplateDeductionResult Result
10835           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10836                                     Specialization, Info,
10837                                     /*InOverloadResolution=*/true)) {
10838       // Make a note of the failed deduction for diagnostics.
10839       // TODO: Actually use the failed-deduction info?
10840       FailedCandidates.addCandidate()
10841           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10842                MakeDeductionFailureInfo(Context, Result, Info));
10843       continue;
10844     }
10845 
10846     assert(Specialization && "no specialization and no error?");
10847 
10848     // Multiple matches; we can't resolve to a single declaration.
10849     if (Matched) {
10850       if (Complain) {
10851         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10852           << ovl->getName();
10853         NoteAllOverloadCandidates(ovl);
10854       }
10855       return nullptr;
10856     }
10857 
10858     Matched = Specialization;
10859     if (FoundResult) *FoundResult = I.getPair();
10860   }
10861 
10862   if (Matched && getLangOpts().CPlusPlus14 &&
10863       Matched->getReturnType()->isUndeducedType() &&
10864       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10865     return nullptr;
10866 
10867   return Matched;
10868 }
10869 
10870 
10871 
10872 
10873 // Resolve and fix an overloaded expression that can be resolved
10874 // because it identifies a single function template specialization.
10875 //
10876 // Last three arguments should only be supplied if Complain = true
10877 //
10878 // Return true if it was logically possible to so resolve the
10879 // expression, regardless of whether or not it succeeded.  Always
10880 // returns true if 'complain' is set.
10881 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10882                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10883                       bool complain, SourceRange OpRangeForComplaining,
10884                                            QualType DestTypeForComplaining,
10885                                             unsigned DiagIDForComplaining) {
10886   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10887 
10888   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10889 
10890   DeclAccessPair found;
10891   ExprResult SingleFunctionExpression;
10892   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10893                            ovl.Expression, /*complain*/ false, &found)) {
10894     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10895       SrcExpr = ExprError();
10896       return true;
10897     }
10898 
10899     // It is only correct to resolve to an instance method if we're
10900     // resolving a form that's permitted to be a pointer to member.
10901     // Otherwise we'll end up making a bound member expression, which
10902     // is illegal in all the contexts we resolve like this.
10903     if (!ovl.HasFormOfMemberPointer &&
10904         isa<CXXMethodDecl>(fn) &&
10905         cast<CXXMethodDecl>(fn)->isInstance()) {
10906       if (!complain) return false;
10907 
10908       Diag(ovl.Expression->getExprLoc(),
10909            diag::err_bound_member_function)
10910         << 0 << ovl.Expression->getSourceRange();
10911 
10912       // TODO: I believe we only end up here if there's a mix of
10913       // static and non-static candidates (otherwise the expression
10914       // would have 'bound member' type, not 'overload' type).
10915       // Ideally we would note which candidate was chosen and why
10916       // the static candidates were rejected.
10917       SrcExpr = ExprError();
10918       return true;
10919     }
10920 
10921     // Fix the expression to refer to 'fn'.
10922     SingleFunctionExpression =
10923         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10924 
10925     // If desired, do function-to-pointer decay.
10926     if (doFunctionPointerConverion) {
10927       SingleFunctionExpression =
10928         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10929       if (SingleFunctionExpression.isInvalid()) {
10930         SrcExpr = ExprError();
10931         return true;
10932       }
10933     }
10934   }
10935 
10936   if (!SingleFunctionExpression.isUsable()) {
10937     if (complain) {
10938       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10939         << ovl.Expression->getName()
10940         << DestTypeForComplaining
10941         << OpRangeForComplaining
10942         << ovl.Expression->getQualifierLoc().getSourceRange();
10943       NoteAllOverloadCandidates(SrcExpr.get());
10944 
10945       SrcExpr = ExprError();
10946       return true;
10947     }
10948 
10949     return false;
10950   }
10951 
10952   SrcExpr = SingleFunctionExpression;
10953   return true;
10954 }
10955 
10956 /// \brief Add a single candidate to the overload set.
10957 static void AddOverloadedCallCandidate(Sema &S,
10958                                        DeclAccessPair FoundDecl,
10959                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10960                                        ArrayRef<Expr *> Args,
10961                                        OverloadCandidateSet &CandidateSet,
10962                                        bool PartialOverloading,
10963                                        bool KnownValid) {
10964   NamedDecl *Callee = FoundDecl.getDecl();
10965   if (isa<UsingShadowDecl>(Callee))
10966     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10967 
10968   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10969     if (ExplicitTemplateArgs) {
10970       assert(!KnownValid && "Explicit template arguments?");
10971       return;
10972     }
10973     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10974                            /*SuppressUsedConversions=*/false,
10975                            PartialOverloading);
10976     return;
10977   }
10978 
10979   if (FunctionTemplateDecl *FuncTemplate
10980       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10981     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10982                                    ExplicitTemplateArgs, Args, CandidateSet,
10983                                    /*SuppressUsedConversions=*/false,
10984                                    PartialOverloading);
10985     return;
10986   }
10987 
10988   assert(!KnownValid && "unhandled case in overloaded call candidate");
10989 }
10990 
10991 /// \brief Add the overload candidates named by callee and/or found by argument
10992 /// dependent lookup to the given overload set.
10993 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10994                                        ArrayRef<Expr *> Args,
10995                                        OverloadCandidateSet &CandidateSet,
10996                                        bool PartialOverloading) {
10997 
10998 #ifndef NDEBUG
10999   // Verify that ArgumentDependentLookup is consistent with the rules
11000   // in C++0x [basic.lookup.argdep]p3:
11001   //
11002   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11003   //   and let Y be the lookup set produced by argument dependent
11004   //   lookup (defined as follows). If X contains
11005   //
11006   //     -- a declaration of a class member, or
11007   //
11008   //     -- a block-scope function declaration that is not a
11009   //        using-declaration, or
11010   //
11011   //     -- a declaration that is neither a function or a function
11012   //        template
11013   //
11014   //   then Y is empty.
11015 
11016   if (ULE->requiresADL()) {
11017     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11018            E = ULE->decls_end(); I != E; ++I) {
11019       assert(!(*I)->getDeclContext()->isRecord());
11020       assert(isa<UsingShadowDecl>(*I) ||
11021              !(*I)->getDeclContext()->isFunctionOrMethod());
11022       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11023     }
11024   }
11025 #endif
11026 
11027   // It would be nice to avoid this copy.
11028   TemplateArgumentListInfo TABuffer;
11029   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11030   if (ULE->hasExplicitTemplateArgs()) {
11031     ULE->copyTemplateArgumentsInto(TABuffer);
11032     ExplicitTemplateArgs = &TABuffer;
11033   }
11034 
11035   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11036          E = ULE->decls_end(); I != E; ++I)
11037     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11038                                CandidateSet, PartialOverloading,
11039                                /*KnownValid*/ true);
11040 
11041   if (ULE->requiresADL())
11042     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11043                                          Args, ExplicitTemplateArgs,
11044                                          CandidateSet, PartialOverloading);
11045 }
11046 
11047 /// Determine whether a declaration with the specified name could be moved into
11048 /// a different namespace.
11049 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11050   switch (Name.getCXXOverloadedOperator()) {
11051   case OO_New: case OO_Array_New:
11052   case OO_Delete: case OO_Array_Delete:
11053     return false;
11054 
11055   default:
11056     return true;
11057   }
11058 }
11059 
11060 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11061 /// template, where the non-dependent name was declared after the template
11062 /// was defined. This is common in code written for a compilers which do not
11063 /// correctly implement two-stage name lookup.
11064 ///
11065 /// Returns true if a viable candidate was found and a diagnostic was issued.
11066 static bool
11067 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11068                        const CXXScopeSpec &SS, LookupResult &R,
11069                        OverloadCandidateSet::CandidateSetKind CSK,
11070                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11071                        ArrayRef<Expr *> Args,
11072                        bool *DoDiagnoseEmptyLookup = nullptr) {
11073   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11074     return false;
11075 
11076   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11077     if (DC->isTransparentContext())
11078       continue;
11079 
11080     SemaRef.LookupQualifiedName(R, DC);
11081 
11082     if (!R.empty()) {
11083       R.suppressDiagnostics();
11084 
11085       if (isa<CXXRecordDecl>(DC)) {
11086         // Don't diagnose names we find in classes; we get much better
11087         // diagnostics for these from DiagnoseEmptyLookup.
11088         R.clear();
11089         if (DoDiagnoseEmptyLookup)
11090           *DoDiagnoseEmptyLookup = true;
11091         return false;
11092       }
11093 
11094       OverloadCandidateSet Candidates(FnLoc, CSK);
11095       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11096         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11097                                    ExplicitTemplateArgs, Args,
11098                                    Candidates, false, /*KnownValid*/ false);
11099 
11100       OverloadCandidateSet::iterator Best;
11101       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11102         // No viable functions. Don't bother the user with notes for functions
11103         // which don't work and shouldn't be found anyway.
11104         R.clear();
11105         return false;
11106       }
11107 
11108       // Find the namespaces where ADL would have looked, and suggest
11109       // declaring the function there instead.
11110       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11111       Sema::AssociatedClassSet AssociatedClasses;
11112       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11113                                                  AssociatedNamespaces,
11114                                                  AssociatedClasses);
11115       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11116       if (canBeDeclaredInNamespace(R.getLookupName())) {
11117         DeclContext *Std = SemaRef.getStdNamespace();
11118         for (Sema::AssociatedNamespaceSet::iterator
11119                it = AssociatedNamespaces.begin(),
11120                end = AssociatedNamespaces.end(); it != end; ++it) {
11121           // Never suggest declaring a function within namespace 'std'.
11122           if (Std && Std->Encloses(*it))
11123             continue;
11124 
11125           // Never suggest declaring a function within a namespace with a
11126           // reserved name, like __gnu_cxx.
11127           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11128           if (NS &&
11129               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11130             continue;
11131 
11132           SuggestedNamespaces.insert(*it);
11133         }
11134       }
11135 
11136       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11137         << R.getLookupName();
11138       if (SuggestedNamespaces.empty()) {
11139         SemaRef.Diag(Best->Function->getLocation(),
11140                      diag::note_not_found_by_two_phase_lookup)
11141           << R.getLookupName() << 0;
11142       } else if (SuggestedNamespaces.size() == 1) {
11143         SemaRef.Diag(Best->Function->getLocation(),
11144                      diag::note_not_found_by_two_phase_lookup)
11145           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11146       } else {
11147         // FIXME: It would be useful to list the associated namespaces here,
11148         // but the diagnostics infrastructure doesn't provide a way to produce
11149         // a localized representation of a list of items.
11150         SemaRef.Diag(Best->Function->getLocation(),
11151                      diag::note_not_found_by_two_phase_lookup)
11152           << R.getLookupName() << 2;
11153       }
11154 
11155       // Try to recover by calling this function.
11156       return true;
11157     }
11158 
11159     R.clear();
11160   }
11161 
11162   return false;
11163 }
11164 
11165 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11166 /// template, where the non-dependent operator was declared after the template
11167 /// was defined.
11168 ///
11169 /// Returns true if a viable candidate was found and a diagnostic was issued.
11170 static bool
11171 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11172                                SourceLocation OpLoc,
11173                                ArrayRef<Expr *> Args) {
11174   DeclarationName OpName =
11175     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11176   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11177   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11178                                 OverloadCandidateSet::CSK_Operator,
11179                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11180 }
11181 
11182 namespace {
11183 class BuildRecoveryCallExprRAII {
11184   Sema &SemaRef;
11185 public:
11186   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11187     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11188     SemaRef.IsBuildingRecoveryCallExpr = true;
11189   }
11190 
11191   ~BuildRecoveryCallExprRAII() {
11192     SemaRef.IsBuildingRecoveryCallExpr = false;
11193   }
11194 };
11195 
11196 }
11197 
11198 static std::unique_ptr<CorrectionCandidateCallback>
11199 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11200               bool HasTemplateArgs, bool AllowTypoCorrection) {
11201   if (!AllowTypoCorrection)
11202     return llvm::make_unique<NoTypoCorrectionCCC>();
11203   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11204                                                   HasTemplateArgs, ME);
11205 }
11206 
11207 /// Attempts to recover from a call where no functions were found.
11208 ///
11209 /// Returns true if new candidates were found.
11210 static ExprResult
11211 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11212                       UnresolvedLookupExpr *ULE,
11213                       SourceLocation LParenLoc,
11214                       MutableArrayRef<Expr *> Args,
11215                       SourceLocation RParenLoc,
11216                       bool EmptyLookup, bool AllowTypoCorrection) {
11217   // Do not try to recover if it is already building a recovery call.
11218   // This stops infinite loops for template instantiations like
11219   //
11220   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11221   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11222   //
11223   if (SemaRef.IsBuildingRecoveryCallExpr)
11224     return ExprError();
11225   BuildRecoveryCallExprRAII RCE(SemaRef);
11226 
11227   CXXScopeSpec SS;
11228   SS.Adopt(ULE->getQualifierLoc());
11229   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11230 
11231   TemplateArgumentListInfo TABuffer;
11232   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11233   if (ULE->hasExplicitTemplateArgs()) {
11234     ULE->copyTemplateArgumentsInto(TABuffer);
11235     ExplicitTemplateArgs = &TABuffer;
11236   }
11237 
11238   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11239                  Sema::LookupOrdinaryName);
11240   bool DoDiagnoseEmptyLookup = EmptyLookup;
11241   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11242                               OverloadCandidateSet::CSK_Normal,
11243                               ExplicitTemplateArgs, Args,
11244                               &DoDiagnoseEmptyLookup) &&
11245     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11246         S, SS, R,
11247         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11248                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11249         ExplicitTemplateArgs, Args)))
11250     return ExprError();
11251 
11252   assert(!R.empty() && "lookup results empty despite recovery");
11253 
11254   // Build an implicit member call if appropriate.  Just drop the
11255   // casts and such from the call, we don't really care.
11256   ExprResult NewFn = ExprError();
11257   if ((*R.begin())->isCXXClassMember())
11258     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11259                                                     ExplicitTemplateArgs, S);
11260   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11261     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11262                                         ExplicitTemplateArgs);
11263   else
11264     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11265 
11266   if (NewFn.isInvalid())
11267     return ExprError();
11268 
11269   // This shouldn't cause an infinite loop because we're giving it
11270   // an expression with viable lookup results, which should never
11271   // end up here.
11272   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11273                                MultiExprArg(Args.data(), Args.size()),
11274                                RParenLoc);
11275 }
11276 
11277 /// \brief Constructs and populates an OverloadedCandidateSet from
11278 /// the given function.
11279 /// \returns true when an the ExprResult output parameter has been set.
11280 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11281                                   UnresolvedLookupExpr *ULE,
11282                                   MultiExprArg Args,
11283                                   SourceLocation RParenLoc,
11284                                   OverloadCandidateSet *CandidateSet,
11285                                   ExprResult *Result) {
11286 #ifndef NDEBUG
11287   if (ULE->requiresADL()) {
11288     // To do ADL, we must have found an unqualified name.
11289     assert(!ULE->getQualifier() && "qualified name with ADL");
11290 
11291     // We don't perform ADL for implicit declarations of builtins.
11292     // Verify that this was correctly set up.
11293     FunctionDecl *F;
11294     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11295         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11296         F->getBuiltinID() && F->isImplicit())
11297       llvm_unreachable("performing ADL for builtin");
11298 
11299     // We don't perform ADL in C.
11300     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11301   }
11302 #endif
11303 
11304   UnbridgedCastsSet UnbridgedCasts;
11305   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11306     *Result = ExprError();
11307     return true;
11308   }
11309 
11310   // Add the functions denoted by the callee to the set of candidate
11311   // functions, including those from argument-dependent lookup.
11312   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11313 
11314   if (getLangOpts().MSVCCompat &&
11315       CurContext->isDependentContext() && !isSFINAEContext() &&
11316       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11317 
11318     OverloadCandidateSet::iterator Best;
11319     if (CandidateSet->empty() ||
11320         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11321             OR_No_Viable_Function) {
11322       // In Microsoft mode, if we are inside a template class member function then
11323       // create a type dependent CallExpr. The goal is to postpone name lookup
11324       // to instantiation time to be able to search into type dependent base
11325       // classes.
11326       CallExpr *CE = new (Context) CallExpr(
11327           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11328       CE->setTypeDependent(true);
11329       CE->setValueDependent(true);
11330       CE->setInstantiationDependent(true);
11331       *Result = CE;
11332       return true;
11333     }
11334   }
11335 
11336   if (CandidateSet->empty())
11337     return false;
11338 
11339   UnbridgedCasts.restore();
11340   return false;
11341 }
11342 
11343 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11344 /// the completed call expression. If overload resolution fails, emits
11345 /// diagnostics and returns ExprError()
11346 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11347                                            UnresolvedLookupExpr *ULE,
11348                                            SourceLocation LParenLoc,
11349                                            MultiExprArg Args,
11350                                            SourceLocation RParenLoc,
11351                                            Expr *ExecConfig,
11352                                            OverloadCandidateSet *CandidateSet,
11353                                            OverloadCandidateSet::iterator *Best,
11354                                            OverloadingResult OverloadResult,
11355                                            bool AllowTypoCorrection) {
11356   if (CandidateSet->empty())
11357     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11358                                  RParenLoc, /*EmptyLookup=*/true,
11359                                  AllowTypoCorrection);
11360 
11361   switch (OverloadResult) {
11362   case OR_Success: {
11363     FunctionDecl *FDecl = (*Best)->Function;
11364     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11365     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11366       return ExprError();
11367     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11368     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11369                                          ExecConfig);
11370   }
11371 
11372   case OR_No_Viable_Function: {
11373     // Try to recover by looking for viable functions which the user might
11374     // have meant to call.
11375     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11376                                                 Args, RParenLoc,
11377                                                 /*EmptyLookup=*/false,
11378                                                 AllowTypoCorrection);
11379     if (!Recovery.isInvalid())
11380       return Recovery;
11381 
11382     // If the user passes in a function that we can't take the address of, we
11383     // generally end up emitting really bad error messages. Here, we attempt to
11384     // emit better ones.
11385     for (const Expr *Arg : Args) {
11386       if (!Arg->getType()->isFunctionType())
11387         continue;
11388       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11389         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11390         if (FD &&
11391             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11392                                                        Arg->getExprLoc()))
11393           return ExprError();
11394       }
11395     }
11396 
11397     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11398         << ULE->getName() << Fn->getSourceRange();
11399     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11400     break;
11401   }
11402 
11403   case OR_Ambiguous:
11404     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11405       << ULE->getName() << Fn->getSourceRange();
11406     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11407     break;
11408 
11409   case OR_Deleted: {
11410     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11411       << (*Best)->Function->isDeleted()
11412       << ULE->getName()
11413       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11414       << Fn->getSourceRange();
11415     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11416 
11417     // We emitted an error for the unvailable/deleted function call but keep
11418     // the call in the AST.
11419     FunctionDecl *FDecl = (*Best)->Function;
11420     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11421     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11422                                          ExecConfig);
11423   }
11424   }
11425 
11426   // Overload resolution failed.
11427   return ExprError();
11428 }
11429 
11430 static void markUnaddressableCandidatesUnviable(Sema &S,
11431                                                 OverloadCandidateSet &CS) {
11432   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11433     if (I->Viable &&
11434         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11435       I->Viable = false;
11436       I->FailureKind = ovl_fail_addr_not_available;
11437     }
11438   }
11439 }
11440 
11441 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11442 /// (which eventually refers to the declaration Func) and the call
11443 /// arguments Args/NumArgs, attempt to resolve the function call down
11444 /// to a specific function. If overload resolution succeeds, returns
11445 /// the call expression produced by overload resolution.
11446 /// Otherwise, emits diagnostics and returns ExprError.
11447 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11448                                          UnresolvedLookupExpr *ULE,
11449                                          SourceLocation LParenLoc,
11450                                          MultiExprArg Args,
11451                                          SourceLocation RParenLoc,
11452                                          Expr *ExecConfig,
11453                                          bool AllowTypoCorrection,
11454                                          bool CalleesAddressIsTaken) {
11455   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11456                                     OverloadCandidateSet::CSK_Normal);
11457   ExprResult result;
11458 
11459   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11460                              &result))
11461     return result;
11462 
11463   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11464   // functions that aren't addressible are considered unviable.
11465   if (CalleesAddressIsTaken)
11466     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11467 
11468   OverloadCandidateSet::iterator Best;
11469   OverloadingResult OverloadResult =
11470       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11471 
11472   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11473                                   RParenLoc, ExecConfig, &CandidateSet,
11474                                   &Best, OverloadResult,
11475                                   AllowTypoCorrection);
11476 }
11477 
11478 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11479   return Functions.size() > 1 ||
11480     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11481 }
11482 
11483 /// \brief Create a unary operation that may resolve to an overloaded
11484 /// operator.
11485 ///
11486 /// \param OpLoc The location of the operator itself (e.g., '*').
11487 ///
11488 /// \param Opc The UnaryOperatorKind that describes this operator.
11489 ///
11490 /// \param Fns The set of non-member functions that will be
11491 /// considered by overload resolution. The caller needs to build this
11492 /// set based on the context using, e.g.,
11493 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11494 /// set should not contain any member functions; those will be added
11495 /// by CreateOverloadedUnaryOp().
11496 ///
11497 /// \param Input The input argument.
11498 ExprResult
11499 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11500                               const UnresolvedSetImpl &Fns,
11501                               Expr *Input) {
11502   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11503   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11504   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11505   // TODO: provide better source location info.
11506   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11507 
11508   if (checkPlaceholderForOverload(*this, Input))
11509     return ExprError();
11510 
11511   Expr *Args[2] = { Input, nullptr };
11512   unsigned NumArgs = 1;
11513 
11514   // For post-increment and post-decrement, add the implicit '0' as
11515   // the second argument, so that we know this is a post-increment or
11516   // post-decrement.
11517   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11518     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11519     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11520                                      SourceLocation());
11521     NumArgs = 2;
11522   }
11523 
11524   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11525 
11526   if (Input->isTypeDependent()) {
11527     if (Fns.empty())
11528       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11529                                          VK_RValue, OK_Ordinary, OpLoc);
11530 
11531     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11532     UnresolvedLookupExpr *Fn
11533       = UnresolvedLookupExpr::Create(Context, NamingClass,
11534                                      NestedNameSpecifierLoc(), OpNameInfo,
11535                                      /*ADL*/ true, IsOverloaded(Fns),
11536                                      Fns.begin(), Fns.end());
11537     return new (Context)
11538         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11539                             VK_RValue, OpLoc, false);
11540   }
11541 
11542   // Build an empty overload set.
11543   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11544 
11545   // Add the candidates from the given function set.
11546   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11547 
11548   // Add operator candidates that are member functions.
11549   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11550 
11551   // Add candidates from ADL.
11552   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11553                                        /*ExplicitTemplateArgs*/nullptr,
11554                                        CandidateSet);
11555 
11556   // Add builtin operator candidates.
11557   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11558 
11559   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11560 
11561   // Perform overload resolution.
11562   OverloadCandidateSet::iterator Best;
11563   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11564   case OR_Success: {
11565     // We found a built-in operator or an overloaded operator.
11566     FunctionDecl *FnDecl = Best->Function;
11567 
11568     if (FnDecl) {
11569       // We matched an overloaded operator. Build a call to that
11570       // operator.
11571 
11572       // Convert the arguments.
11573       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11574         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11575 
11576         ExprResult InputRes =
11577           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11578                                               Best->FoundDecl, Method);
11579         if (InputRes.isInvalid())
11580           return ExprError();
11581         Input = InputRes.get();
11582       } else {
11583         // Convert the arguments.
11584         ExprResult InputInit
11585           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11586                                                       Context,
11587                                                       FnDecl->getParamDecl(0)),
11588                                       SourceLocation(),
11589                                       Input);
11590         if (InputInit.isInvalid())
11591           return ExprError();
11592         Input = InputInit.get();
11593       }
11594 
11595       // Build the actual expression node.
11596       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11597                                                 HadMultipleCandidates, OpLoc);
11598       if (FnExpr.isInvalid())
11599         return ExprError();
11600 
11601       // Determine the result type.
11602       QualType ResultTy = FnDecl->getReturnType();
11603       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11604       ResultTy = ResultTy.getNonLValueExprType(Context);
11605 
11606       Args[0] = Input;
11607       CallExpr *TheCall =
11608         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11609                                           ResultTy, VK, OpLoc, false);
11610 
11611       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11612         return ExprError();
11613 
11614       return MaybeBindToTemporary(TheCall);
11615     } else {
11616       // We matched a built-in operator. Convert the arguments, then
11617       // break out so that we will build the appropriate built-in
11618       // operator node.
11619       ExprResult InputRes =
11620         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11621                                   Best->Conversions[0], AA_Passing);
11622       if (InputRes.isInvalid())
11623         return ExprError();
11624       Input = InputRes.get();
11625       break;
11626     }
11627   }
11628 
11629   case OR_No_Viable_Function:
11630     // This is an erroneous use of an operator which can be overloaded by
11631     // a non-member function. Check for non-member operators which were
11632     // defined too late to be candidates.
11633     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11634       // FIXME: Recover by calling the found function.
11635       return ExprError();
11636 
11637     // No viable function; fall through to handling this as a
11638     // built-in operator, which will produce an error message for us.
11639     break;
11640 
11641   case OR_Ambiguous:
11642     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11643         << UnaryOperator::getOpcodeStr(Opc)
11644         << Input->getType()
11645         << Input->getSourceRange();
11646     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11647                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11648     return ExprError();
11649 
11650   case OR_Deleted:
11651     Diag(OpLoc, diag::err_ovl_deleted_oper)
11652       << Best->Function->isDeleted()
11653       << UnaryOperator::getOpcodeStr(Opc)
11654       << getDeletedOrUnavailableSuffix(Best->Function)
11655       << Input->getSourceRange();
11656     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11657                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11658     return ExprError();
11659   }
11660 
11661   // Either we found no viable overloaded operator or we matched a
11662   // built-in operator. In either case, fall through to trying to
11663   // build a built-in operation.
11664   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11665 }
11666 
11667 /// \brief Create a binary operation that may resolve to an overloaded
11668 /// operator.
11669 ///
11670 /// \param OpLoc The location of the operator itself (e.g., '+').
11671 ///
11672 /// \param Opc The BinaryOperatorKind that describes this operator.
11673 ///
11674 /// \param Fns The set of non-member functions that will be
11675 /// considered by overload resolution. The caller needs to build this
11676 /// set based on the context using, e.g.,
11677 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11678 /// set should not contain any member functions; those will be added
11679 /// by CreateOverloadedBinOp().
11680 ///
11681 /// \param LHS Left-hand argument.
11682 /// \param RHS Right-hand argument.
11683 ExprResult
11684 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11685                             BinaryOperatorKind Opc,
11686                             const UnresolvedSetImpl &Fns,
11687                             Expr *LHS, Expr *RHS) {
11688   Expr *Args[2] = { LHS, RHS };
11689   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11690 
11691   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11692   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11693 
11694   // If either side is type-dependent, create an appropriate dependent
11695   // expression.
11696   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11697     if (Fns.empty()) {
11698       // If there are no functions to store, just build a dependent
11699       // BinaryOperator or CompoundAssignment.
11700       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11701         return new (Context) BinaryOperator(
11702             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11703             OpLoc, FPFeatures.fp_contract);
11704 
11705       return new (Context) CompoundAssignOperator(
11706           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11707           Context.DependentTy, Context.DependentTy, OpLoc,
11708           FPFeatures.fp_contract);
11709     }
11710 
11711     // FIXME: save results of ADL from here?
11712     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11713     // TODO: provide better source location info in DNLoc component.
11714     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11715     UnresolvedLookupExpr *Fn
11716       = UnresolvedLookupExpr::Create(Context, NamingClass,
11717                                      NestedNameSpecifierLoc(), OpNameInfo,
11718                                      /*ADL*/ true, IsOverloaded(Fns),
11719                                      Fns.begin(), Fns.end());
11720     return new (Context)
11721         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11722                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11723   }
11724 
11725   // Always do placeholder-like conversions on the RHS.
11726   if (checkPlaceholderForOverload(*this, Args[1]))
11727     return ExprError();
11728 
11729   // Do placeholder-like conversion on the LHS; note that we should
11730   // not get here with a PseudoObject LHS.
11731   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11732   if (checkPlaceholderForOverload(*this, Args[0]))
11733     return ExprError();
11734 
11735   // If this is the assignment operator, we only perform overload resolution
11736   // if the left-hand side is a class or enumeration type. This is actually
11737   // a hack. The standard requires that we do overload resolution between the
11738   // various built-in candidates, but as DR507 points out, this can lead to
11739   // problems. So we do it this way, which pretty much follows what GCC does.
11740   // Note that we go the traditional code path for compound assignment forms.
11741   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11742     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11743 
11744   // If this is the .* operator, which is not overloadable, just
11745   // create a built-in binary operator.
11746   if (Opc == BO_PtrMemD)
11747     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11748 
11749   // Build an empty overload set.
11750   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11751 
11752   // Add the candidates from the given function set.
11753   AddFunctionCandidates(Fns, Args, CandidateSet);
11754 
11755   // Add operator candidates that are member functions.
11756   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11757 
11758   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11759   // performed for an assignment operator (nor for operator[] nor operator->,
11760   // which don't get here).
11761   if (Opc != BO_Assign)
11762     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11763                                          /*ExplicitTemplateArgs*/ nullptr,
11764                                          CandidateSet);
11765 
11766   // Add builtin operator candidates.
11767   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11768 
11769   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11770 
11771   // Perform overload resolution.
11772   OverloadCandidateSet::iterator Best;
11773   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11774     case OR_Success: {
11775       // We found a built-in operator or an overloaded operator.
11776       FunctionDecl *FnDecl = Best->Function;
11777 
11778       if (FnDecl) {
11779         // We matched an overloaded operator. Build a call to that
11780         // operator.
11781 
11782         // Convert the arguments.
11783         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11784           // Best->Access is only meaningful for class members.
11785           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11786 
11787           ExprResult Arg1 =
11788             PerformCopyInitialization(
11789               InitializedEntity::InitializeParameter(Context,
11790                                                      FnDecl->getParamDecl(0)),
11791               SourceLocation(), Args[1]);
11792           if (Arg1.isInvalid())
11793             return ExprError();
11794 
11795           ExprResult Arg0 =
11796             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11797                                                 Best->FoundDecl, Method);
11798           if (Arg0.isInvalid())
11799             return ExprError();
11800           Args[0] = Arg0.getAs<Expr>();
11801           Args[1] = RHS = Arg1.getAs<Expr>();
11802         } else {
11803           // Convert the arguments.
11804           ExprResult Arg0 = PerformCopyInitialization(
11805             InitializedEntity::InitializeParameter(Context,
11806                                                    FnDecl->getParamDecl(0)),
11807             SourceLocation(), Args[0]);
11808           if (Arg0.isInvalid())
11809             return ExprError();
11810 
11811           ExprResult Arg1 =
11812             PerformCopyInitialization(
11813               InitializedEntity::InitializeParameter(Context,
11814                                                      FnDecl->getParamDecl(1)),
11815               SourceLocation(), Args[1]);
11816           if (Arg1.isInvalid())
11817             return ExprError();
11818           Args[0] = LHS = Arg0.getAs<Expr>();
11819           Args[1] = RHS = Arg1.getAs<Expr>();
11820         }
11821 
11822         // Build the actual expression node.
11823         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11824                                                   Best->FoundDecl,
11825                                                   HadMultipleCandidates, OpLoc);
11826         if (FnExpr.isInvalid())
11827           return ExprError();
11828 
11829         // Determine the result type.
11830         QualType ResultTy = FnDecl->getReturnType();
11831         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11832         ResultTy = ResultTy.getNonLValueExprType(Context);
11833 
11834         CXXOperatorCallExpr *TheCall =
11835           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11836                                             Args, ResultTy, VK, OpLoc,
11837                                             FPFeatures.fp_contract);
11838 
11839         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11840                                 FnDecl))
11841           return ExprError();
11842 
11843         ArrayRef<const Expr *> ArgsArray(Args, 2);
11844         // Cut off the implicit 'this'.
11845         if (isa<CXXMethodDecl>(FnDecl))
11846           ArgsArray = ArgsArray.slice(1);
11847 
11848         // Check for a self move.
11849         if (Op == OO_Equal)
11850           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11851 
11852         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11853                   TheCall->getSourceRange(), VariadicDoesNotApply);
11854 
11855         return MaybeBindToTemporary(TheCall);
11856       } else {
11857         // We matched a built-in operator. Convert the arguments, then
11858         // break out so that we will build the appropriate built-in
11859         // operator node.
11860         ExprResult ArgsRes0 =
11861           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11862                                     Best->Conversions[0], AA_Passing);
11863         if (ArgsRes0.isInvalid())
11864           return ExprError();
11865         Args[0] = ArgsRes0.get();
11866 
11867         ExprResult ArgsRes1 =
11868           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11869                                     Best->Conversions[1], AA_Passing);
11870         if (ArgsRes1.isInvalid())
11871           return ExprError();
11872         Args[1] = ArgsRes1.get();
11873         break;
11874       }
11875     }
11876 
11877     case OR_No_Viable_Function: {
11878       // C++ [over.match.oper]p9:
11879       //   If the operator is the operator , [...] and there are no
11880       //   viable functions, then the operator is assumed to be the
11881       //   built-in operator and interpreted according to clause 5.
11882       if (Opc == BO_Comma)
11883         break;
11884 
11885       // For class as left operand for assignment or compound assigment
11886       // operator do not fall through to handling in built-in, but report that
11887       // no overloaded assignment operator found
11888       ExprResult Result = ExprError();
11889       if (Args[0]->getType()->isRecordType() &&
11890           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11891         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11892              << BinaryOperator::getOpcodeStr(Opc)
11893              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11894         if (Args[0]->getType()->isIncompleteType()) {
11895           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11896             << Args[0]->getType()
11897             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11898         }
11899       } else {
11900         // This is an erroneous use of an operator which can be overloaded by
11901         // a non-member function. Check for non-member operators which were
11902         // defined too late to be candidates.
11903         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11904           // FIXME: Recover by calling the found function.
11905           return ExprError();
11906 
11907         // No viable function; try to create a built-in operation, which will
11908         // produce an error. Then, show the non-viable candidates.
11909         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11910       }
11911       assert(Result.isInvalid() &&
11912              "C++ binary operator overloading is missing candidates!");
11913       if (Result.isInvalid())
11914         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11915                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11916       return Result;
11917     }
11918 
11919     case OR_Ambiguous:
11920       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11921           << BinaryOperator::getOpcodeStr(Opc)
11922           << Args[0]->getType() << Args[1]->getType()
11923           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11924       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11925                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11926       return ExprError();
11927 
11928     case OR_Deleted:
11929       if (isImplicitlyDeleted(Best->Function)) {
11930         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11931         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11932           << Context.getRecordType(Method->getParent())
11933           << getSpecialMember(Method);
11934 
11935         // The user probably meant to call this special member. Just
11936         // explain why it's deleted.
11937         NoteDeletedFunction(Method);
11938         return ExprError();
11939       } else {
11940         Diag(OpLoc, diag::err_ovl_deleted_oper)
11941           << Best->Function->isDeleted()
11942           << BinaryOperator::getOpcodeStr(Opc)
11943           << getDeletedOrUnavailableSuffix(Best->Function)
11944           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11945       }
11946       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11947                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11948       return ExprError();
11949   }
11950 
11951   // We matched a built-in operator; build it.
11952   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11953 }
11954 
11955 ExprResult
11956 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11957                                          SourceLocation RLoc,
11958                                          Expr *Base, Expr *Idx) {
11959   Expr *Args[2] = { Base, Idx };
11960   DeclarationName OpName =
11961       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11962 
11963   // If either side is type-dependent, create an appropriate dependent
11964   // expression.
11965   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11966 
11967     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11968     // CHECKME: no 'operator' keyword?
11969     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11970     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11971     UnresolvedLookupExpr *Fn
11972       = UnresolvedLookupExpr::Create(Context, NamingClass,
11973                                      NestedNameSpecifierLoc(), OpNameInfo,
11974                                      /*ADL*/ true, /*Overloaded*/ false,
11975                                      UnresolvedSetIterator(),
11976                                      UnresolvedSetIterator());
11977     // Can't add any actual overloads yet
11978 
11979     return new (Context)
11980         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11981                             Context.DependentTy, VK_RValue, RLoc, false);
11982   }
11983 
11984   // Handle placeholders on both operands.
11985   if (checkPlaceholderForOverload(*this, Args[0]))
11986     return ExprError();
11987   if (checkPlaceholderForOverload(*this, Args[1]))
11988     return ExprError();
11989 
11990   // Build an empty overload set.
11991   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11992 
11993   // Subscript can only be overloaded as a member function.
11994 
11995   // Add operator candidates that are member functions.
11996   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11997 
11998   // Add builtin operator candidates.
11999   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12000 
12001   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12002 
12003   // Perform overload resolution.
12004   OverloadCandidateSet::iterator Best;
12005   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12006     case OR_Success: {
12007       // We found a built-in operator or an overloaded operator.
12008       FunctionDecl *FnDecl = Best->Function;
12009 
12010       if (FnDecl) {
12011         // We matched an overloaded operator. Build a call to that
12012         // operator.
12013 
12014         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12015 
12016         // Convert the arguments.
12017         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12018         ExprResult Arg0 =
12019           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12020                                               Best->FoundDecl, Method);
12021         if (Arg0.isInvalid())
12022           return ExprError();
12023         Args[0] = Arg0.get();
12024 
12025         // Convert the arguments.
12026         ExprResult InputInit
12027           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12028                                                       Context,
12029                                                       FnDecl->getParamDecl(0)),
12030                                       SourceLocation(),
12031                                       Args[1]);
12032         if (InputInit.isInvalid())
12033           return ExprError();
12034 
12035         Args[1] = InputInit.getAs<Expr>();
12036 
12037         // Build the actual expression node.
12038         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12039         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12040         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12041                                                   Best->FoundDecl,
12042                                                   HadMultipleCandidates,
12043                                                   OpLocInfo.getLoc(),
12044                                                   OpLocInfo.getInfo());
12045         if (FnExpr.isInvalid())
12046           return ExprError();
12047 
12048         // Determine the result type
12049         QualType ResultTy = FnDecl->getReturnType();
12050         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12051         ResultTy = ResultTy.getNonLValueExprType(Context);
12052 
12053         CXXOperatorCallExpr *TheCall =
12054           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12055                                             FnExpr.get(), Args,
12056                                             ResultTy, VK, RLoc,
12057                                             false);
12058 
12059         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12060           return ExprError();
12061 
12062         return MaybeBindToTemporary(TheCall);
12063       } else {
12064         // We matched a built-in operator. Convert the arguments, then
12065         // break out so that we will build the appropriate built-in
12066         // operator node.
12067         ExprResult ArgsRes0 =
12068           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12069                                     Best->Conversions[0], AA_Passing);
12070         if (ArgsRes0.isInvalid())
12071           return ExprError();
12072         Args[0] = ArgsRes0.get();
12073 
12074         ExprResult ArgsRes1 =
12075           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12076                                     Best->Conversions[1], AA_Passing);
12077         if (ArgsRes1.isInvalid())
12078           return ExprError();
12079         Args[1] = ArgsRes1.get();
12080 
12081         break;
12082       }
12083     }
12084 
12085     case OR_No_Viable_Function: {
12086       if (CandidateSet.empty())
12087         Diag(LLoc, diag::err_ovl_no_oper)
12088           << Args[0]->getType() << /*subscript*/ 0
12089           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12090       else
12091         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12092           << Args[0]->getType()
12093           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12094       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12095                                   "[]", LLoc);
12096       return ExprError();
12097     }
12098 
12099     case OR_Ambiguous:
12100       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12101           << "[]"
12102           << Args[0]->getType() << Args[1]->getType()
12103           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12104       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12105                                   "[]", LLoc);
12106       return ExprError();
12107 
12108     case OR_Deleted:
12109       Diag(LLoc, diag::err_ovl_deleted_oper)
12110         << Best->Function->isDeleted() << "[]"
12111         << getDeletedOrUnavailableSuffix(Best->Function)
12112         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12113       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12114                                   "[]", LLoc);
12115       return ExprError();
12116     }
12117 
12118   // We matched a built-in operator; build it.
12119   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12120 }
12121 
12122 /// BuildCallToMemberFunction - Build a call to a member
12123 /// function. MemExpr is the expression that refers to the member
12124 /// function (and includes the object parameter), Args/NumArgs are the
12125 /// arguments to the function call (not including the object
12126 /// parameter). The caller needs to validate that the member
12127 /// expression refers to a non-static member function or an overloaded
12128 /// member function.
12129 ExprResult
12130 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12131                                 SourceLocation LParenLoc,
12132                                 MultiExprArg Args,
12133                                 SourceLocation RParenLoc) {
12134   assert(MemExprE->getType() == Context.BoundMemberTy ||
12135          MemExprE->getType() == Context.OverloadTy);
12136 
12137   // Dig out the member expression. This holds both the object
12138   // argument and the member function we're referring to.
12139   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12140 
12141   // Determine whether this is a call to a pointer-to-member function.
12142   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12143     assert(op->getType() == Context.BoundMemberTy);
12144     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12145 
12146     QualType fnType =
12147       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12148 
12149     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12150     QualType resultType = proto->getCallResultType(Context);
12151     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12152 
12153     // Check that the object type isn't more qualified than the
12154     // member function we're calling.
12155     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12156 
12157     QualType objectType = op->getLHS()->getType();
12158     if (op->getOpcode() == BO_PtrMemI)
12159       objectType = objectType->castAs<PointerType>()->getPointeeType();
12160     Qualifiers objectQuals = objectType.getQualifiers();
12161 
12162     Qualifiers difference = objectQuals - funcQuals;
12163     difference.removeObjCGCAttr();
12164     difference.removeAddressSpace();
12165     if (difference) {
12166       std::string qualsString = difference.getAsString();
12167       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12168         << fnType.getUnqualifiedType()
12169         << qualsString
12170         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12171     }
12172 
12173     CXXMemberCallExpr *call
12174       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12175                                         resultType, valueKind, RParenLoc);
12176 
12177     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12178                             call, nullptr))
12179       return ExprError();
12180 
12181     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12182       return ExprError();
12183 
12184     if (CheckOtherCall(call, proto))
12185       return ExprError();
12186 
12187     return MaybeBindToTemporary(call);
12188   }
12189 
12190   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12191     return new (Context)
12192         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12193 
12194   UnbridgedCastsSet UnbridgedCasts;
12195   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12196     return ExprError();
12197 
12198   MemberExpr *MemExpr;
12199   CXXMethodDecl *Method = nullptr;
12200   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12201   NestedNameSpecifier *Qualifier = nullptr;
12202   if (isa<MemberExpr>(NakedMemExpr)) {
12203     MemExpr = cast<MemberExpr>(NakedMemExpr);
12204     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12205     FoundDecl = MemExpr->getFoundDecl();
12206     Qualifier = MemExpr->getQualifier();
12207     UnbridgedCasts.restore();
12208   } else {
12209     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12210     Qualifier = UnresExpr->getQualifier();
12211 
12212     QualType ObjectType = UnresExpr->getBaseType();
12213     Expr::Classification ObjectClassification
12214       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12215                             : UnresExpr->getBase()->Classify(Context);
12216 
12217     // Add overload candidates
12218     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12219                                       OverloadCandidateSet::CSK_Normal);
12220 
12221     // FIXME: avoid copy.
12222     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12223     if (UnresExpr->hasExplicitTemplateArgs()) {
12224       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12225       TemplateArgs = &TemplateArgsBuffer;
12226     }
12227 
12228     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12229            E = UnresExpr->decls_end(); I != E; ++I) {
12230 
12231       NamedDecl *Func = *I;
12232       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12233       if (isa<UsingShadowDecl>(Func))
12234         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12235 
12236 
12237       // Microsoft supports direct constructor calls.
12238       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12239         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12240                              Args, CandidateSet);
12241       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12242         // If explicit template arguments were provided, we can't call a
12243         // non-template member function.
12244         if (TemplateArgs)
12245           continue;
12246 
12247         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12248                            ObjectClassification, Args, CandidateSet,
12249                            /*SuppressUserConversions=*/false);
12250       } else {
12251         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12252                                    I.getPair(), ActingDC, TemplateArgs,
12253                                    ObjectType,  ObjectClassification,
12254                                    Args, CandidateSet,
12255                                    /*SuppressUsedConversions=*/false);
12256       }
12257     }
12258 
12259     DeclarationName DeclName = UnresExpr->getMemberName();
12260 
12261     UnbridgedCasts.restore();
12262 
12263     OverloadCandidateSet::iterator Best;
12264     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12265                                             Best)) {
12266     case OR_Success:
12267       Method = cast<CXXMethodDecl>(Best->Function);
12268       FoundDecl = Best->FoundDecl;
12269       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12270       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12271         return ExprError();
12272       // If FoundDecl is different from Method (such as if one is a template
12273       // and the other a specialization), make sure DiagnoseUseOfDecl is
12274       // called on both.
12275       // FIXME: This would be more comprehensively addressed by modifying
12276       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12277       // being used.
12278       if (Method != FoundDecl.getDecl() &&
12279                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12280         return ExprError();
12281       break;
12282 
12283     case OR_No_Viable_Function:
12284       Diag(UnresExpr->getMemberLoc(),
12285            diag::err_ovl_no_viable_member_function_in_call)
12286         << DeclName << MemExprE->getSourceRange();
12287       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12288       // FIXME: Leaking incoming expressions!
12289       return ExprError();
12290 
12291     case OR_Ambiguous:
12292       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12293         << DeclName << MemExprE->getSourceRange();
12294       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12295       // FIXME: Leaking incoming expressions!
12296       return ExprError();
12297 
12298     case OR_Deleted:
12299       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12300         << Best->Function->isDeleted()
12301         << DeclName
12302         << getDeletedOrUnavailableSuffix(Best->Function)
12303         << MemExprE->getSourceRange();
12304       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12305       // FIXME: Leaking incoming expressions!
12306       return ExprError();
12307     }
12308 
12309     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12310 
12311     // If overload resolution picked a static member, build a
12312     // non-member call based on that function.
12313     if (Method->isStatic()) {
12314       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12315                                    RParenLoc);
12316     }
12317 
12318     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12319   }
12320 
12321   QualType ResultType = Method->getReturnType();
12322   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12323   ResultType = ResultType.getNonLValueExprType(Context);
12324 
12325   assert(Method && "Member call to something that isn't a method?");
12326   CXXMemberCallExpr *TheCall =
12327     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12328                                     ResultType, VK, RParenLoc);
12329 
12330   // (CUDA B.1): Check for invalid calls between targets.
12331   if (getLangOpts().CUDA) {
12332     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12333       if (!IsAllowedCUDACall(Caller, Method)) {
12334         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12335             << IdentifyCUDATarget(Method) << Method->getIdentifier()
12336             << IdentifyCUDATarget(Caller);
12337         Diag(Method->getLocation(), diag::note_previous_decl) << Method;
12338         return ExprError();
12339       }
12340     }
12341   }
12342 
12343   // Check for a valid return type.
12344   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12345                           TheCall, Method))
12346     return ExprError();
12347 
12348   // Convert the object argument (for a non-static member function call).
12349   // We only need to do this if there was actually an overload; otherwise
12350   // it was done at lookup.
12351   if (!Method->isStatic()) {
12352     ExprResult ObjectArg =
12353       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12354                                           FoundDecl, Method);
12355     if (ObjectArg.isInvalid())
12356       return ExprError();
12357     MemExpr->setBase(ObjectArg.get());
12358   }
12359 
12360   // Convert the rest of the arguments
12361   const FunctionProtoType *Proto =
12362     Method->getType()->getAs<FunctionProtoType>();
12363   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12364                               RParenLoc))
12365     return ExprError();
12366 
12367   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12368 
12369   if (CheckFunctionCall(Method, TheCall, Proto))
12370     return ExprError();
12371 
12372   // In the case the method to call was not selected by the overloading
12373   // resolution process, we still need to handle the enable_if attribute. Do
12374   // that here, so it will not hide previous -- and more relevant -- errors
12375   if (isa<MemberExpr>(NakedMemExpr)) {
12376     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12377       Diag(MemExprE->getLocStart(),
12378            diag::err_ovl_no_viable_member_function_in_call)
12379           << Method << Method->getSourceRange();
12380       Diag(Method->getLocation(),
12381            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12382           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12383       return ExprError();
12384     }
12385   }
12386 
12387   if ((isa<CXXConstructorDecl>(CurContext) ||
12388        isa<CXXDestructorDecl>(CurContext)) &&
12389       TheCall->getMethodDecl()->isPure()) {
12390     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12391 
12392     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12393         MemExpr->performsVirtualDispatch(getLangOpts())) {
12394       Diag(MemExpr->getLocStart(),
12395            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12396         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12397         << MD->getParent()->getDeclName();
12398 
12399       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12400       if (getLangOpts().AppleKext)
12401         Diag(MemExpr->getLocStart(),
12402              diag::note_pure_qualified_call_kext)
12403              << MD->getParent()->getDeclName()
12404              << MD->getDeclName();
12405     }
12406   }
12407 
12408   if (CXXDestructorDecl *DD =
12409           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12410     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12411     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12412     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12413                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12414                          MemExpr->getMemberLoc());
12415   }
12416 
12417   return MaybeBindToTemporary(TheCall);
12418 }
12419 
12420 /// BuildCallToObjectOfClassType - Build a call to an object of class
12421 /// type (C++ [over.call.object]), which can end up invoking an
12422 /// overloaded function call operator (@c operator()) or performing a
12423 /// user-defined conversion on the object argument.
12424 ExprResult
12425 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12426                                    SourceLocation LParenLoc,
12427                                    MultiExprArg Args,
12428                                    SourceLocation RParenLoc) {
12429   if (checkPlaceholderForOverload(*this, Obj))
12430     return ExprError();
12431   ExprResult Object = Obj;
12432 
12433   UnbridgedCastsSet UnbridgedCasts;
12434   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12435     return ExprError();
12436 
12437   assert(Object.get()->getType()->isRecordType() &&
12438          "Requires object type argument");
12439   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12440 
12441   // C++ [over.call.object]p1:
12442   //  If the primary-expression E in the function call syntax
12443   //  evaluates to a class object of type "cv T", then the set of
12444   //  candidate functions includes at least the function call
12445   //  operators of T. The function call operators of T are obtained by
12446   //  ordinary lookup of the name operator() in the context of
12447   //  (E).operator().
12448   OverloadCandidateSet CandidateSet(LParenLoc,
12449                                     OverloadCandidateSet::CSK_Operator);
12450   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12451 
12452   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12453                           diag::err_incomplete_object_call, Object.get()))
12454     return true;
12455 
12456   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12457   LookupQualifiedName(R, Record->getDecl());
12458   R.suppressDiagnostics();
12459 
12460   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12461        Oper != OperEnd; ++Oper) {
12462     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12463                        Object.get()->Classify(Context),
12464                        Args, CandidateSet,
12465                        /*SuppressUserConversions=*/ false);
12466   }
12467 
12468   // C++ [over.call.object]p2:
12469   //   In addition, for each (non-explicit in C++0x) conversion function
12470   //   declared in T of the form
12471   //
12472   //        operator conversion-type-id () cv-qualifier;
12473   //
12474   //   where cv-qualifier is the same cv-qualification as, or a
12475   //   greater cv-qualification than, cv, and where conversion-type-id
12476   //   denotes the type "pointer to function of (P1,...,Pn) returning
12477   //   R", or the type "reference to pointer to function of
12478   //   (P1,...,Pn) returning R", or the type "reference to function
12479   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12480   //   is also considered as a candidate function. Similarly,
12481   //   surrogate call functions are added to the set of candidate
12482   //   functions for each conversion function declared in an
12483   //   accessible base class provided the function is not hidden
12484   //   within T by another intervening declaration.
12485   const auto &Conversions =
12486       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12487   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12488     NamedDecl *D = *I;
12489     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12490     if (isa<UsingShadowDecl>(D))
12491       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12492 
12493     // Skip over templated conversion functions; they aren't
12494     // surrogates.
12495     if (isa<FunctionTemplateDecl>(D))
12496       continue;
12497 
12498     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12499     if (!Conv->isExplicit()) {
12500       // Strip the reference type (if any) and then the pointer type (if
12501       // any) to get down to what might be a function type.
12502       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12503       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12504         ConvType = ConvPtrType->getPointeeType();
12505 
12506       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12507       {
12508         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12509                               Object.get(), Args, CandidateSet);
12510       }
12511     }
12512   }
12513 
12514   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12515 
12516   // Perform overload resolution.
12517   OverloadCandidateSet::iterator Best;
12518   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12519                              Best)) {
12520   case OR_Success:
12521     // Overload resolution succeeded; we'll build the appropriate call
12522     // below.
12523     break;
12524 
12525   case OR_No_Viable_Function:
12526     if (CandidateSet.empty())
12527       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12528         << Object.get()->getType() << /*call*/ 1
12529         << Object.get()->getSourceRange();
12530     else
12531       Diag(Object.get()->getLocStart(),
12532            diag::err_ovl_no_viable_object_call)
12533         << Object.get()->getType() << Object.get()->getSourceRange();
12534     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12535     break;
12536 
12537   case OR_Ambiguous:
12538     Diag(Object.get()->getLocStart(),
12539          diag::err_ovl_ambiguous_object_call)
12540       << Object.get()->getType() << Object.get()->getSourceRange();
12541     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12542     break;
12543 
12544   case OR_Deleted:
12545     Diag(Object.get()->getLocStart(),
12546          diag::err_ovl_deleted_object_call)
12547       << Best->Function->isDeleted()
12548       << Object.get()->getType()
12549       << getDeletedOrUnavailableSuffix(Best->Function)
12550       << Object.get()->getSourceRange();
12551     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12552     break;
12553   }
12554 
12555   if (Best == CandidateSet.end())
12556     return true;
12557 
12558   UnbridgedCasts.restore();
12559 
12560   if (Best->Function == nullptr) {
12561     // Since there is no function declaration, this is one of the
12562     // surrogate candidates. Dig out the conversion function.
12563     CXXConversionDecl *Conv
12564       = cast<CXXConversionDecl>(
12565                          Best->Conversions[0].UserDefined.ConversionFunction);
12566 
12567     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12568                               Best->FoundDecl);
12569     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12570       return ExprError();
12571     assert(Conv == Best->FoundDecl.getDecl() &&
12572              "Found Decl & conversion-to-functionptr should be same, right?!");
12573     // We selected one of the surrogate functions that converts the
12574     // object parameter to a function pointer. Perform the conversion
12575     // on the object argument, then let ActOnCallExpr finish the job.
12576 
12577     // Create an implicit member expr to refer to the conversion operator.
12578     // and then call it.
12579     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12580                                              Conv, HadMultipleCandidates);
12581     if (Call.isInvalid())
12582       return ExprError();
12583     // Record usage of conversion in an implicit cast.
12584     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12585                                     CK_UserDefinedConversion, Call.get(),
12586                                     nullptr, VK_RValue);
12587 
12588     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12589   }
12590 
12591   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12592 
12593   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12594   // that calls this method, using Object for the implicit object
12595   // parameter and passing along the remaining arguments.
12596   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12597 
12598   // An error diagnostic has already been printed when parsing the declaration.
12599   if (Method->isInvalidDecl())
12600     return ExprError();
12601 
12602   const FunctionProtoType *Proto =
12603     Method->getType()->getAs<FunctionProtoType>();
12604 
12605   unsigned NumParams = Proto->getNumParams();
12606 
12607   DeclarationNameInfo OpLocInfo(
12608                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12609   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12610   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12611                                            HadMultipleCandidates,
12612                                            OpLocInfo.getLoc(),
12613                                            OpLocInfo.getInfo());
12614   if (NewFn.isInvalid())
12615     return true;
12616 
12617   // Build the full argument list for the method call (the implicit object
12618   // parameter is placed at the beginning of the list).
12619   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12620   MethodArgs[0] = Object.get();
12621   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12622 
12623   // Once we've built TheCall, all of the expressions are properly
12624   // owned.
12625   QualType ResultTy = Method->getReturnType();
12626   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12627   ResultTy = ResultTy.getNonLValueExprType(Context);
12628 
12629   CXXOperatorCallExpr *TheCall = new (Context)
12630       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12631                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12632                           ResultTy, VK, RParenLoc, false);
12633   MethodArgs.reset();
12634 
12635   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12636     return true;
12637 
12638   // We may have default arguments. If so, we need to allocate more
12639   // slots in the call for them.
12640   if (Args.size() < NumParams)
12641     TheCall->setNumArgs(Context, NumParams + 1);
12642 
12643   bool IsError = false;
12644 
12645   // Initialize the implicit object parameter.
12646   ExprResult ObjRes =
12647     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12648                                         Best->FoundDecl, Method);
12649   if (ObjRes.isInvalid())
12650     IsError = true;
12651   else
12652     Object = ObjRes;
12653   TheCall->setArg(0, Object.get());
12654 
12655   // Check the argument types.
12656   for (unsigned i = 0; i != NumParams; i++) {
12657     Expr *Arg;
12658     if (i < Args.size()) {
12659       Arg = Args[i];
12660 
12661       // Pass the argument.
12662 
12663       ExprResult InputInit
12664         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12665                                                     Context,
12666                                                     Method->getParamDecl(i)),
12667                                     SourceLocation(), Arg);
12668 
12669       IsError |= InputInit.isInvalid();
12670       Arg = InputInit.getAs<Expr>();
12671     } else {
12672       ExprResult DefArg
12673         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12674       if (DefArg.isInvalid()) {
12675         IsError = true;
12676         break;
12677       }
12678 
12679       Arg = DefArg.getAs<Expr>();
12680     }
12681 
12682     TheCall->setArg(i + 1, Arg);
12683   }
12684 
12685   // If this is a variadic call, handle args passed through "...".
12686   if (Proto->isVariadic()) {
12687     // Promote the arguments (C99 6.5.2.2p7).
12688     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12689       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12690                                                         nullptr);
12691       IsError |= Arg.isInvalid();
12692       TheCall->setArg(i + 1, Arg.get());
12693     }
12694   }
12695 
12696   if (IsError) return true;
12697 
12698   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12699 
12700   if (CheckFunctionCall(Method, TheCall, Proto))
12701     return true;
12702 
12703   return MaybeBindToTemporary(TheCall);
12704 }
12705 
12706 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12707 ///  (if one exists), where @c Base is an expression of class type and
12708 /// @c Member is the name of the member we're trying to find.
12709 ExprResult
12710 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12711                                bool *NoArrowOperatorFound) {
12712   assert(Base->getType()->isRecordType() &&
12713          "left-hand side must have class type");
12714 
12715   if (checkPlaceholderForOverload(*this, Base))
12716     return ExprError();
12717 
12718   SourceLocation Loc = Base->getExprLoc();
12719 
12720   // C++ [over.ref]p1:
12721   //
12722   //   [...] An expression x->m is interpreted as (x.operator->())->m
12723   //   for a class object x of type T if T::operator->() exists and if
12724   //   the operator is selected as the best match function by the
12725   //   overload resolution mechanism (13.3).
12726   DeclarationName OpName =
12727     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12728   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12729   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12730 
12731   if (RequireCompleteType(Loc, Base->getType(),
12732                           diag::err_typecheck_incomplete_tag, Base))
12733     return ExprError();
12734 
12735   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12736   LookupQualifiedName(R, BaseRecord->getDecl());
12737   R.suppressDiagnostics();
12738 
12739   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12740        Oper != OperEnd; ++Oper) {
12741     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12742                        None, CandidateSet, /*SuppressUserConversions=*/false);
12743   }
12744 
12745   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12746 
12747   // Perform overload resolution.
12748   OverloadCandidateSet::iterator Best;
12749   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12750   case OR_Success:
12751     // Overload resolution succeeded; we'll build the call below.
12752     break;
12753 
12754   case OR_No_Viable_Function:
12755     if (CandidateSet.empty()) {
12756       QualType BaseType = Base->getType();
12757       if (NoArrowOperatorFound) {
12758         // Report this specific error to the caller instead of emitting a
12759         // diagnostic, as requested.
12760         *NoArrowOperatorFound = true;
12761         return ExprError();
12762       }
12763       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12764         << BaseType << Base->getSourceRange();
12765       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12766         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12767           << FixItHint::CreateReplacement(OpLoc, ".");
12768       }
12769     } else
12770       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12771         << "operator->" << Base->getSourceRange();
12772     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12773     return ExprError();
12774 
12775   case OR_Ambiguous:
12776     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12777       << "->" << Base->getType() << Base->getSourceRange();
12778     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12779     return ExprError();
12780 
12781   case OR_Deleted:
12782     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12783       << Best->Function->isDeleted()
12784       << "->"
12785       << getDeletedOrUnavailableSuffix(Best->Function)
12786       << Base->getSourceRange();
12787     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12788     return ExprError();
12789   }
12790 
12791   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12792 
12793   // Convert the object parameter.
12794   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12795   ExprResult BaseResult =
12796     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12797                                         Best->FoundDecl, Method);
12798   if (BaseResult.isInvalid())
12799     return ExprError();
12800   Base = BaseResult.get();
12801 
12802   // Build the operator call.
12803   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12804                                             HadMultipleCandidates, OpLoc);
12805   if (FnExpr.isInvalid())
12806     return ExprError();
12807 
12808   QualType ResultTy = Method->getReturnType();
12809   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12810   ResultTy = ResultTy.getNonLValueExprType(Context);
12811   CXXOperatorCallExpr *TheCall =
12812     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12813                                       Base, ResultTy, VK, OpLoc, false);
12814 
12815   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12816           return ExprError();
12817 
12818   return MaybeBindToTemporary(TheCall);
12819 }
12820 
12821 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12822 /// a literal operator described by the provided lookup results.
12823 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12824                                           DeclarationNameInfo &SuffixInfo,
12825                                           ArrayRef<Expr*> Args,
12826                                           SourceLocation LitEndLoc,
12827                                        TemplateArgumentListInfo *TemplateArgs) {
12828   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12829 
12830   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12831                                     OverloadCandidateSet::CSK_Normal);
12832   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12833                         /*SuppressUserConversions=*/true);
12834 
12835   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12836 
12837   // Perform overload resolution. This will usually be trivial, but might need
12838   // to perform substitutions for a literal operator template.
12839   OverloadCandidateSet::iterator Best;
12840   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12841   case OR_Success:
12842   case OR_Deleted:
12843     break;
12844 
12845   case OR_No_Viable_Function:
12846     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12847       << R.getLookupName();
12848     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12849     return ExprError();
12850 
12851   case OR_Ambiguous:
12852     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12853     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12854     return ExprError();
12855   }
12856 
12857   FunctionDecl *FD = Best->Function;
12858   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12859                                         HadMultipleCandidates,
12860                                         SuffixInfo.getLoc(),
12861                                         SuffixInfo.getInfo());
12862   if (Fn.isInvalid())
12863     return true;
12864 
12865   // Check the argument types. This should almost always be a no-op, except
12866   // that array-to-pointer decay is applied to string literals.
12867   Expr *ConvArgs[2];
12868   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12869     ExprResult InputInit = PerformCopyInitialization(
12870       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12871       SourceLocation(), Args[ArgIdx]);
12872     if (InputInit.isInvalid())
12873       return true;
12874     ConvArgs[ArgIdx] = InputInit.get();
12875   }
12876 
12877   QualType ResultTy = FD->getReturnType();
12878   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12879   ResultTy = ResultTy.getNonLValueExprType(Context);
12880 
12881   UserDefinedLiteral *UDL =
12882     new (Context) UserDefinedLiteral(Context, Fn.get(),
12883                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12884                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12885 
12886   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12887     return ExprError();
12888 
12889   if (CheckFunctionCall(FD, UDL, nullptr))
12890     return ExprError();
12891 
12892   return MaybeBindToTemporary(UDL);
12893 }
12894 
12895 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12896 /// given LookupResult is non-empty, it is assumed to describe a member which
12897 /// will be invoked. Otherwise, the function will be found via argument
12898 /// dependent lookup.
12899 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12900 /// otherwise CallExpr is set to ExprError() and some non-success value
12901 /// is returned.
12902 Sema::ForRangeStatus
12903 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12904                                 SourceLocation RangeLoc,
12905                                 const DeclarationNameInfo &NameInfo,
12906                                 LookupResult &MemberLookup,
12907                                 OverloadCandidateSet *CandidateSet,
12908                                 Expr *Range, ExprResult *CallExpr) {
12909   Scope *S = nullptr;
12910 
12911   CandidateSet->clear();
12912   if (!MemberLookup.empty()) {
12913     ExprResult MemberRef =
12914         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12915                                  /*IsPtr=*/false, CXXScopeSpec(),
12916                                  /*TemplateKWLoc=*/SourceLocation(),
12917                                  /*FirstQualifierInScope=*/nullptr,
12918                                  MemberLookup,
12919                                  /*TemplateArgs=*/nullptr, S);
12920     if (MemberRef.isInvalid()) {
12921       *CallExpr = ExprError();
12922       return FRS_DiagnosticIssued;
12923     }
12924     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12925     if (CallExpr->isInvalid()) {
12926       *CallExpr = ExprError();
12927       return FRS_DiagnosticIssued;
12928     }
12929   } else {
12930     UnresolvedSet<0> FoundNames;
12931     UnresolvedLookupExpr *Fn =
12932       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12933                                    NestedNameSpecifierLoc(), NameInfo,
12934                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12935                                    FoundNames.begin(), FoundNames.end());
12936 
12937     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12938                                                     CandidateSet, CallExpr);
12939     if (CandidateSet->empty() || CandidateSetError) {
12940       *CallExpr = ExprError();
12941       return FRS_NoViableFunction;
12942     }
12943     OverloadCandidateSet::iterator Best;
12944     OverloadingResult OverloadResult =
12945         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12946 
12947     if (OverloadResult == OR_No_Viable_Function) {
12948       *CallExpr = ExprError();
12949       return FRS_NoViableFunction;
12950     }
12951     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12952                                          Loc, nullptr, CandidateSet, &Best,
12953                                          OverloadResult,
12954                                          /*AllowTypoCorrection=*/false);
12955     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12956       *CallExpr = ExprError();
12957       return FRS_DiagnosticIssued;
12958     }
12959   }
12960   return FRS_Success;
12961 }
12962 
12963 
12964 /// FixOverloadedFunctionReference - E is an expression that refers to
12965 /// a C++ overloaded function (possibly with some parentheses and
12966 /// perhaps a '&' around it). We have resolved the overloaded function
12967 /// to the function declaration Fn, so patch up the expression E to
12968 /// refer (possibly indirectly) to Fn. Returns the new expr.
12969 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12970                                            FunctionDecl *Fn) {
12971   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12972     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12973                                                    Found, Fn);
12974     if (SubExpr == PE->getSubExpr())
12975       return PE;
12976 
12977     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12978   }
12979 
12980   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12981     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12982                                                    Found, Fn);
12983     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12984                                SubExpr->getType()) &&
12985            "Implicit cast type cannot be determined from overload");
12986     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12987     if (SubExpr == ICE->getSubExpr())
12988       return ICE;
12989 
12990     return ImplicitCastExpr::Create(Context, ICE->getType(),
12991                                     ICE->getCastKind(),
12992                                     SubExpr, nullptr,
12993                                     ICE->getValueKind());
12994   }
12995 
12996   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12997     assert(UnOp->getOpcode() == UO_AddrOf &&
12998            "Can only take the address of an overloaded function");
12999     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13000       if (Method->isStatic()) {
13001         // Do nothing: static member functions aren't any different
13002         // from non-member functions.
13003       } else {
13004         // Fix the subexpression, which really has to be an
13005         // UnresolvedLookupExpr holding an overloaded member function
13006         // or template.
13007         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13008                                                        Found, Fn);
13009         if (SubExpr == UnOp->getSubExpr())
13010           return UnOp;
13011 
13012         assert(isa<DeclRefExpr>(SubExpr)
13013                && "fixed to something other than a decl ref");
13014         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13015                && "fixed to a member ref with no nested name qualifier");
13016 
13017         // We have taken the address of a pointer to member
13018         // function. Perform the computation here so that we get the
13019         // appropriate pointer to member type.
13020         QualType ClassType
13021           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13022         QualType MemPtrType
13023           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13024         // Under the MS ABI, lock down the inheritance model now.
13025         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13026           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13027 
13028         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13029                                            VK_RValue, OK_Ordinary,
13030                                            UnOp->getOperatorLoc());
13031       }
13032     }
13033     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13034                                                    Found, Fn);
13035     if (SubExpr == UnOp->getSubExpr())
13036       return UnOp;
13037 
13038     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13039                                      Context.getPointerType(SubExpr->getType()),
13040                                        VK_RValue, OK_Ordinary,
13041                                        UnOp->getOperatorLoc());
13042   }
13043 
13044   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13045     // FIXME: avoid copy.
13046     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13047     if (ULE->hasExplicitTemplateArgs()) {
13048       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13049       TemplateArgs = &TemplateArgsBuffer;
13050     }
13051 
13052     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13053                                            ULE->getQualifierLoc(),
13054                                            ULE->getTemplateKeywordLoc(),
13055                                            Fn,
13056                                            /*enclosing*/ false, // FIXME?
13057                                            ULE->getNameLoc(),
13058                                            Fn->getType(),
13059                                            VK_LValue,
13060                                            Found.getDecl(),
13061                                            TemplateArgs);
13062     MarkDeclRefReferenced(DRE);
13063     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13064     return DRE;
13065   }
13066 
13067   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13068     // FIXME: avoid copy.
13069     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13070     if (MemExpr->hasExplicitTemplateArgs()) {
13071       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13072       TemplateArgs = &TemplateArgsBuffer;
13073     }
13074 
13075     Expr *Base;
13076 
13077     // If we're filling in a static method where we used to have an
13078     // implicit member access, rewrite to a simple decl ref.
13079     if (MemExpr->isImplicitAccess()) {
13080       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13081         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13082                                                MemExpr->getQualifierLoc(),
13083                                                MemExpr->getTemplateKeywordLoc(),
13084                                                Fn,
13085                                                /*enclosing*/ false,
13086                                                MemExpr->getMemberLoc(),
13087                                                Fn->getType(),
13088                                                VK_LValue,
13089                                                Found.getDecl(),
13090                                                TemplateArgs);
13091         MarkDeclRefReferenced(DRE);
13092         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13093         return DRE;
13094       } else {
13095         SourceLocation Loc = MemExpr->getMemberLoc();
13096         if (MemExpr->getQualifier())
13097           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13098         CheckCXXThisCapture(Loc);
13099         Base = new (Context) CXXThisExpr(Loc,
13100                                          MemExpr->getBaseType(),
13101                                          /*isImplicit=*/true);
13102       }
13103     } else
13104       Base = MemExpr->getBase();
13105 
13106     ExprValueKind valueKind;
13107     QualType type;
13108     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13109       valueKind = VK_LValue;
13110       type = Fn->getType();
13111     } else {
13112       valueKind = VK_RValue;
13113       type = Context.BoundMemberTy;
13114     }
13115 
13116     MemberExpr *ME = MemberExpr::Create(
13117         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13118         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13119         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13120         OK_Ordinary);
13121     ME->setHadMultipleCandidates(true);
13122     MarkMemberReferenced(ME);
13123     return ME;
13124   }
13125 
13126   llvm_unreachable("Invalid reference to overloaded function");
13127 }
13128 
13129 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13130                                                 DeclAccessPair Found,
13131                                                 FunctionDecl *Fn) {
13132   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13133 }
13134