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   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
66                                                  VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
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_Conversion,
133     ICR_Conversion,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isObjCObjectPointerType() ||
226        getFromType()->isBlockPointerType() ||
227        getFromType()->isNullPtrType() ||
228        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
229     return true;
230 
231   return false;
232 }
233 
234 /// isPointerConversionToVoidPointer - Determines whether this
235 /// conversion is a conversion of a pointer to a void pointer. This is
236 /// used as part of the ranking of standard conversion sequences (C++
237 /// 13.3.3.2p4).
238 bool
239 StandardConversionSequence::
240 isPointerConversionToVoidPointer(ASTContext& Context) const {
241   QualType FromType = getFromType();
242   QualType ToType = getToType(1);
243 
244   // Note that FromType has not necessarily been transformed by the
245   // array-to-pointer implicit conversion, so check for its presence
246   // and redo the conversion to get a pointer.
247   if (First == ICK_Array_To_Pointer)
248     FromType = Context.getArrayDecayedType(FromType);
249 
250   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
251     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
252       return ToPtrType->getPointeeType()->isVoidType();
253 
254   return false;
255 }
256 
257 /// Skip any implicit casts which could be either part of a narrowing conversion
258 /// or after one in an implicit conversion.
259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261     switch (ICE->getCastKind()) {
262     case CK_NoOp:
263     case CK_IntegralCast:
264     case CK_IntegralToBoolean:
265     case CK_IntegralToFloating:
266     case CK_BooleanToSignedIntegral:
267     case CK_FloatingToIntegral:
268     case CK_FloatingToBoolean:
269     case CK_FloatingCast:
270       Converted = ICE->getSubExpr();
271       continue;
272 
273     default:
274       return Converted;
275     }
276   }
277 
278   return Converted;
279 }
280 
281 /// Check if this standard conversion sequence represents a narrowing
282 /// conversion, according to C++11 [dcl.init.list]p7.
283 ///
284 /// \param Ctx  The AST context.
285 /// \param Converted  The result of applying this standard conversion sequence.
286 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
287 ///        value of the expression prior to the narrowing conversion.
288 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
289 ///        type of the expression prior to the narrowing conversion.
290 NarrowingKind
291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292                                              const Expr *Converted,
293                                              APValue &ConstantValue,
294                                              QualType &ConstantType) const {
295   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
296 
297   // C++11 [dcl.init.list]p7:
298   //   A narrowing conversion is an implicit conversion ...
299   QualType FromType = getToType(0);
300   QualType ToType = getToType(1);
301 
302   // A conversion to an enumeration type is narrowing if the conversion to
303   // the underlying type is narrowing. This only arises for expressions of
304   // the form 'Enum{init}'.
305   if (auto *ET = ToType->getAs<EnumType>())
306     ToType = ET->getDecl()->getIntegerType();
307 
308   switch (Second) {
309   // 'bool' is an integral type; dispatch to the right place to handle it.
310   case ICK_Boolean_Conversion:
311     if (FromType->isRealFloatingType())
312       goto FloatingIntegralConversion;
313     if (FromType->isIntegralOrUnscopedEnumerationType())
314       goto IntegralConversion;
315     // Boolean conversions can be from pointers and pointers to members
316     // [conv.bool], and those aren't considered narrowing conversions.
317     return NK_Not_Narrowing;
318 
319   // -- from a floating-point type to an integer type, or
320   //
321   // -- from an integer type or unscoped enumeration type to a floating-point
322   //    type, except where the source is a constant expression and the actual
323   //    value after conversion will fit into the target type and will produce
324   //    the original value when converted back to the original type, or
325   case ICK_Floating_Integral:
326   FloatingIntegralConversion:
327     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328       return NK_Type_Narrowing;
329     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330       llvm::APSInt IntConstantValue;
331       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332       if (Initializer &&
333           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334         // Convert the integer to the floating type.
335         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337                                 llvm::APFloat::rmNearestTiesToEven);
338         // And back.
339         llvm::APSInt ConvertedValue = IntConstantValue;
340         bool ignored;
341         Result.convertToInteger(ConvertedValue,
342                                 llvm::APFloat::rmTowardZero, &ignored);
343         // If the resulting value is different, this was a narrowing conversion.
344         if (IntConstantValue != ConvertedValue) {
345           ConstantValue = APValue(IntConstantValue);
346           ConstantType = Initializer->getType();
347           return NK_Constant_Narrowing;
348         }
349       } else {
350         // Variables are always narrowings.
351         return NK_Variable_Narrowing;
352       }
353     }
354     return NK_Not_Narrowing;
355 
356   // -- from long double to double or float, or from double to float, except
357   //    where the source is a constant expression and the actual value after
358   //    conversion is within the range of values that can be represented (even
359   //    if it cannot be represented exactly), or
360   case ICK_Floating_Conversion:
361     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363       // FromType is larger than ToType.
364       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366         // Constant!
367         assert(ConstantValue.isFloat());
368         llvm::APFloat FloatVal = ConstantValue.getFloat();
369         // Convert the source value into the target type.
370         bool ignored;
371         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372           Ctx.getFloatTypeSemantics(ToType),
373           llvm::APFloat::rmNearestTiesToEven, &ignored);
374         // If there was no overflow, the source value is within the range of
375         // values that can be represented.
376         if (ConvertStatus & llvm::APFloat::opOverflow) {
377           ConstantType = Initializer->getType();
378           return NK_Constant_Narrowing;
379         }
380       } else {
381         return NK_Variable_Narrowing;
382       }
383     }
384     return NK_Not_Narrowing;
385 
386   // -- from an integer type or unscoped enumeration type to an integer type
387   //    that cannot represent all the values of the original type, except where
388   //    the source is a constant expression and the actual value after
389   //    conversion will fit into the target type and will produce the original
390   //    value when converted back to the original type.
391   case ICK_Integral_Conversion:
392   IntegralConversion: {
393     assert(FromType->isIntegralOrUnscopedEnumerationType());
394     assert(ToType->isIntegralOrUnscopedEnumerationType());
395     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
396     const unsigned FromWidth = Ctx.getIntWidth(FromType);
397     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
398     const unsigned ToWidth = Ctx.getIntWidth(ToType);
399 
400     if (FromWidth > ToWidth ||
401         (FromWidth == ToWidth && FromSigned != ToSigned) ||
402         (FromSigned && !ToSigned)) {
403       // Not all values of FromType can be represented in ToType.
404       llvm::APSInt InitializerValue;
405       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
406       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
407         // Such conversions on variables are always narrowing.
408         return NK_Variable_Narrowing;
409       }
410       bool Narrowing = false;
411       if (FromWidth < ToWidth) {
412         // Negative -> unsigned is narrowing. Otherwise, more bits is never
413         // narrowing.
414         if (InitializerValue.isSigned() && InitializerValue.isNegative())
415           Narrowing = true;
416       } else {
417         // Add a bit to the InitializerValue so we don't have to worry about
418         // signed vs. unsigned comparisons.
419         InitializerValue = InitializerValue.extend(
420           InitializerValue.getBitWidth() + 1);
421         // Convert the initializer to and from the target width and signed-ness.
422         llvm::APSInt ConvertedValue = InitializerValue;
423         ConvertedValue = ConvertedValue.trunc(ToWidth);
424         ConvertedValue.setIsSigned(ToSigned);
425         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
426         ConvertedValue.setIsSigned(InitializerValue.isSigned());
427         // If the result is different, this was a narrowing conversion.
428         if (ConvertedValue != InitializerValue)
429           Narrowing = true;
430       }
431       if (Narrowing) {
432         ConstantType = Initializer->getType();
433         ConstantValue = APValue(InitializerValue);
434         return NK_Constant_Narrowing;
435       }
436     }
437     return NK_Not_Narrowing;
438   }
439 
440   default:
441     // Other kinds of conversions are not narrowings.
442     return NK_Not_Narrowing;
443   }
444 }
445 
446 /// dump - Print this standard conversion sequence to standard
447 /// error. Useful for debugging overloading issues.
448 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
449   raw_ostream &OS = llvm::errs();
450   bool PrintedSomething = false;
451   if (First != ICK_Identity) {
452     OS << GetImplicitConversionName(First);
453     PrintedSomething = true;
454   }
455 
456   if (Second != ICK_Identity) {
457     if (PrintedSomething) {
458       OS << " -> ";
459     }
460     OS << GetImplicitConversionName(Second);
461 
462     if (CopyConstructor) {
463       OS << " (by copy constructor)";
464     } else if (DirectBinding) {
465       OS << " (direct reference binding)";
466     } else if (ReferenceBinding) {
467       OS << " (reference binding)";
468     }
469     PrintedSomething = true;
470   }
471 
472   if (Third != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Third);
477     PrintedSomething = true;
478   }
479 
480   if (!PrintedSomething) {
481     OS << "No conversions required";
482   }
483 }
484 
485 /// dump - Print this user-defined conversion sequence to standard
486 /// error. Useful for debugging overloading issues.
487 void UserDefinedConversionSequence::dump() const {
488   raw_ostream &OS = llvm::errs();
489   if (Before.First || Before.Second || Before.Third) {
490     Before.dump();
491     OS << " -> ";
492   }
493   if (ConversionFunction)
494     OS << '\'' << *ConversionFunction << '\'';
495   else
496     OS << "aggregate initialization";
497   if (After.First || After.Second || After.Third) {
498     OS << " -> ";
499     After.dump();
500   }
501 }
502 
503 /// dump - Print this implicit conversion sequence to standard
504 /// error. Useful for debugging overloading issues.
505 void ImplicitConversionSequence::dump() const {
506   raw_ostream &OS = llvm::errs();
507   if (isStdInitializerListElement())
508     OS << "Worst std::initializer_list element conversion: ";
509   switch (ConversionKind) {
510   case StandardConversion:
511     OS << "Standard conversion: ";
512     Standard.dump();
513     break;
514   case UserDefinedConversion:
515     OS << "User-defined conversion: ";
516     UserDefined.dump();
517     break;
518   case EllipsisConversion:
519     OS << "Ellipsis conversion";
520     break;
521   case AmbiguousConversion:
522     OS << "Ambiguous conversion";
523     break;
524   case BadConversion:
525     OS << "Bad conversion";
526     break;
527   }
528 
529   OS << "\n";
530 }
531 
532 void AmbiguousConversionSequence::construct() {
533   new (&conversions()) ConversionSet();
534 }
535 
536 void AmbiguousConversionSequence::destruct() {
537   conversions().~ConversionSet();
538 }
539 
540 void
541 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
542   FromTypePtr = O.FromTypePtr;
543   ToTypePtr = O.ToTypePtr;
544   new (&conversions()) ConversionSet(O.conversions());
545 }
546 
547 namespace {
548   // Structure used by DeductionFailureInfo to store
549   // template argument information.
550   struct DFIArguments {
551     TemplateArgument FirstArg;
552     TemplateArgument SecondArg;
553   };
554   // Structure used by DeductionFailureInfo to store
555   // template parameter and template argument information.
556   struct DFIParamWithArguments : DFIArguments {
557     TemplateParameter Param;
558   };
559   // Structure used by DeductionFailureInfo to store template argument
560   // information and the index of the problematic call argument.
561   struct DFIDeducedMismatchArgs : DFIArguments {
562     TemplateArgumentList *TemplateArgs;
563     unsigned CallArgIndex;
564   };
565 }
566 
567 /// \brief Convert from Sema's representation of template deduction information
568 /// to the form used in overload-candidate information.
569 DeductionFailureInfo
570 clang::MakeDeductionFailureInfo(ASTContext &Context,
571                                 Sema::TemplateDeductionResult TDK,
572                                 TemplateDeductionInfo &Info) {
573   DeductionFailureInfo Result;
574   Result.Result = static_cast<unsigned>(TDK);
575   Result.HasDiagnostic = false;
576   switch (TDK) {
577   case Sema::TDK_Success:
578   case Sema::TDK_Invalid:
579   case Sema::TDK_InstantiationDepth:
580   case Sema::TDK_TooManyArguments:
581   case Sema::TDK_TooFewArguments:
582   case Sema::TDK_MiscellaneousDeductionFailure:
583   case Sema::TDK_CUDATargetMismatch:
584     Result.Data = nullptr;
585     break;
586 
587   case Sema::TDK_Incomplete:
588   case Sema::TDK_InvalidExplicitArguments:
589     Result.Data = Info.Param.getOpaqueValue();
590     break;
591 
592   case Sema::TDK_DeducedMismatch: {
593     // FIXME: Should allocate from normal heap so that we can free this later.
594     auto *Saved = new (Context) DFIDeducedMismatchArgs;
595     Saved->FirstArg = Info.FirstArg;
596     Saved->SecondArg = Info.SecondArg;
597     Saved->TemplateArgs = Info.take();
598     Saved->CallArgIndex = Info.CallArgIndex;
599     Result.Data = Saved;
600     break;
601   }
602 
603   case Sema::TDK_NonDeducedMismatch: {
604     // FIXME: Should allocate from normal heap so that we can free this later.
605     DFIArguments *Saved = new (Context) DFIArguments;
606     Saved->FirstArg = Info.FirstArg;
607     Saved->SecondArg = Info.SecondArg;
608     Result.Data = Saved;
609     break;
610   }
611 
612   case Sema::TDK_Inconsistent:
613   case Sema::TDK_Underqualified: {
614     // FIXME: Should allocate from normal heap so that we can free this later.
615     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
616     Saved->Param = Info.Param;
617     Saved->FirstArg = Info.FirstArg;
618     Saved->SecondArg = Info.SecondArg;
619     Result.Data = Saved;
620     break;
621   }
622 
623   case Sema::TDK_SubstitutionFailure:
624     Result.Data = Info.take();
625     if (Info.hasSFINAEDiagnostic()) {
626       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
627           SourceLocation(), PartialDiagnostic::NullDiagnostic());
628       Info.takeSFINAEDiagnostic(*Diag);
629       Result.HasDiagnostic = true;
630     }
631     break;
632 
633   case Sema::TDK_FailedOverloadResolution:
634     Result.Data = Info.Expression;
635     break;
636   }
637 
638   return Result;
639 }
640 
641 void DeductionFailureInfo::Destroy() {
642   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
643   case Sema::TDK_Success:
644   case Sema::TDK_Invalid:
645   case Sema::TDK_InstantiationDepth:
646   case Sema::TDK_Incomplete:
647   case Sema::TDK_TooManyArguments:
648   case Sema::TDK_TooFewArguments:
649   case Sema::TDK_InvalidExplicitArguments:
650   case Sema::TDK_FailedOverloadResolution:
651   case Sema::TDK_CUDATargetMismatch:
652     break;
653 
654   case Sema::TDK_Inconsistent:
655   case Sema::TDK_Underqualified:
656   case Sema::TDK_DeducedMismatch:
657   case Sema::TDK_NonDeducedMismatch:
658     // FIXME: Destroy the data?
659     Data = nullptr;
660     break;
661 
662   case Sema::TDK_SubstitutionFailure:
663     // FIXME: Destroy the template argument list?
664     Data = nullptr;
665     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
666       Diag->~PartialDiagnosticAt();
667       HasDiagnostic = false;
668     }
669     break;
670 
671   // Unhandled
672   case Sema::TDK_MiscellaneousDeductionFailure:
673     break;
674   }
675 }
676 
677 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
678   if (HasDiagnostic)
679     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
680   return nullptr;
681 }
682 
683 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
684   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
685   case Sema::TDK_Success:
686   case Sema::TDK_Invalid:
687   case Sema::TDK_InstantiationDepth:
688   case Sema::TDK_TooManyArguments:
689   case Sema::TDK_TooFewArguments:
690   case Sema::TDK_SubstitutionFailure:
691   case Sema::TDK_DeducedMismatch:
692   case Sema::TDK_NonDeducedMismatch:
693   case Sema::TDK_FailedOverloadResolution:
694   case Sema::TDK_CUDATargetMismatch:
695     return TemplateParameter();
696 
697   case Sema::TDK_Incomplete:
698   case Sema::TDK_InvalidExplicitArguments:
699     return TemplateParameter::getFromOpaqueValue(Data);
700 
701   case Sema::TDK_Inconsistent:
702   case Sema::TDK_Underqualified:
703     return static_cast<DFIParamWithArguments*>(Data)->Param;
704 
705   // Unhandled
706   case Sema::TDK_MiscellaneousDeductionFailure:
707     break;
708   }
709 
710   return TemplateParameter();
711 }
712 
713 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
714   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
715   case Sema::TDK_Success:
716   case Sema::TDK_Invalid:
717   case Sema::TDK_InstantiationDepth:
718   case Sema::TDK_TooManyArguments:
719   case Sema::TDK_TooFewArguments:
720   case Sema::TDK_Incomplete:
721   case Sema::TDK_InvalidExplicitArguments:
722   case Sema::TDK_Inconsistent:
723   case Sema::TDK_Underqualified:
724   case Sema::TDK_NonDeducedMismatch:
725   case Sema::TDK_FailedOverloadResolution:
726   case Sema::TDK_CUDATargetMismatch:
727     return nullptr;
728 
729   case Sema::TDK_DeducedMismatch:
730     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
731 
732   case Sema::TDK_SubstitutionFailure:
733     return static_cast<TemplateArgumentList*>(Data);
734 
735   // Unhandled
736   case Sema::TDK_MiscellaneousDeductionFailure:
737     break;
738   }
739 
740   return nullptr;
741 }
742 
743 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
744   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745   case Sema::TDK_Success:
746   case Sema::TDK_Invalid:
747   case Sema::TDK_InstantiationDepth:
748   case Sema::TDK_Incomplete:
749   case Sema::TDK_TooManyArguments:
750   case Sema::TDK_TooFewArguments:
751   case Sema::TDK_InvalidExplicitArguments:
752   case Sema::TDK_SubstitutionFailure:
753   case Sema::TDK_FailedOverloadResolution:
754   case Sema::TDK_CUDATargetMismatch:
755     return nullptr;
756 
757   case Sema::TDK_Inconsistent:
758   case Sema::TDK_Underqualified:
759   case Sema::TDK_DeducedMismatch:
760   case Sema::TDK_NonDeducedMismatch:
761     return &static_cast<DFIArguments*>(Data)->FirstArg;
762 
763   // Unhandled
764   case Sema::TDK_MiscellaneousDeductionFailure:
765     break;
766   }
767 
768   return nullptr;
769 }
770 
771 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
772   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773   case Sema::TDK_Success:
774   case Sema::TDK_Invalid:
775   case Sema::TDK_InstantiationDepth:
776   case Sema::TDK_Incomplete:
777   case Sema::TDK_TooManyArguments:
778   case Sema::TDK_TooFewArguments:
779   case Sema::TDK_InvalidExplicitArguments:
780   case Sema::TDK_SubstitutionFailure:
781   case Sema::TDK_FailedOverloadResolution:
782   case Sema::TDK_CUDATargetMismatch:
783     return nullptr;
784 
785   case Sema::TDK_Inconsistent:
786   case Sema::TDK_Underqualified:
787   case Sema::TDK_DeducedMismatch:
788   case Sema::TDK_NonDeducedMismatch:
789     return &static_cast<DFIArguments*>(Data)->SecondArg;
790 
791   // Unhandled
792   case Sema::TDK_MiscellaneousDeductionFailure:
793     break;
794   }
795 
796   return nullptr;
797 }
798 
799 Expr *DeductionFailureInfo::getExpr() {
800   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
801         Sema::TDK_FailedOverloadResolution)
802     return static_cast<Expr*>(Data);
803 
804   return nullptr;
805 }
806 
807 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
808   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
809         Sema::TDK_DeducedMismatch)
810     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
811 
812   return llvm::None;
813 }
814 
815 void OverloadCandidateSet::destroyCandidates() {
816   for (iterator i = begin(), e = end(); i != e; ++i) {
817     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
818       i->Conversions[ii].~ImplicitConversionSequence();
819     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
820       i->DeductionFailure.Destroy();
821   }
822 }
823 
824 void OverloadCandidateSet::clear() {
825   destroyCandidates();
826   ConversionSequenceAllocator.Reset();
827   NumInlineSequences = 0;
828   Candidates.clear();
829   Functions.clear();
830 }
831 
832 namespace {
833   class UnbridgedCastsSet {
834     struct Entry {
835       Expr **Addr;
836       Expr *Saved;
837     };
838     SmallVector<Entry, 2> Entries;
839 
840   public:
841     void save(Sema &S, Expr *&E) {
842       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
843       Entry entry = { &E, E };
844       Entries.push_back(entry);
845       E = S.stripARCUnbridgedCast(E);
846     }
847 
848     void restore() {
849       for (SmallVectorImpl<Entry>::iterator
850              i = Entries.begin(), e = Entries.end(); i != e; ++i)
851         *i->Addr = i->Saved;
852     }
853   };
854 }
855 
856 /// checkPlaceholderForOverload - Do any interesting placeholder-like
857 /// preprocessing on the given expression.
858 ///
859 /// \param unbridgedCasts a collection to which to add unbridged casts;
860 ///   without this, they will be immediately diagnosed as errors
861 ///
862 /// Return true on unrecoverable error.
863 static bool
864 checkPlaceholderForOverload(Sema &S, Expr *&E,
865                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
866   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
867     // We can't handle overloaded expressions here because overload
868     // resolution might reasonably tweak them.
869     if (placeholder->getKind() == BuiltinType::Overload) return false;
870 
871     // If the context potentially accepts unbridged ARC casts, strip
872     // the unbridged cast and add it to the collection for later restoration.
873     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
874         unbridgedCasts) {
875       unbridgedCasts->save(S, E);
876       return false;
877     }
878 
879     // Go ahead and check everything else.
880     ExprResult result = S.CheckPlaceholderExpr(E);
881     if (result.isInvalid())
882       return true;
883 
884     E = result.get();
885     return false;
886   }
887 
888   // Nothing to do.
889   return false;
890 }
891 
892 /// checkArgPlaceholdersForOverload - Check a set of call operands for
893 /// placeholders.
894 static bool checkArgPlaceholdersForOverload(Sema &S,
895                                             MultiExprArg Args,
896                                             UnbridgedCastsSet &unbridged) {
897   for (unsigned i = 0, e = Args.size(); i != e; ++i)
898     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
899       return true;
900 
901   return false;
902 }
903 
904 // IsOverload - Determine whether the given New declaration is an
905 // overload of the declarations in Old. This routine returns false if
906 // New and Old cannot be overloaded, e.g., if New has the same
907 // signature as some function in Old (C++ 1.3.10) or if the Old
908 // declarations aren't functions (or function templates) at all. When
909 // it does return false, MatchedDecl will point to the decl that New
910 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
911 // top of the underlying declaration.
912 //
913 // Example: Given the following input:
914 //
915 //   void f(int, float); // #1
916 //   void f(int, int); // #2
917 //   int f(int, int); // #3
918 //
919 // When we process #1, there is no previous declaration of "f",
920 // so IsOverload will not be used.
921 //
922 // When we process #2, Old contains only the FunctionDecl for #1.  By
923 // comparing the parameter types, we see that #1 and #2 are overloaded
924 // (since they have different signatures), so this routine returns
925 // false; MatchedDecl is unchanged.
926 //
927 // When we process #3, Old is an overload set containing #1 and #2. We
928 // compare the signatures of #3 to #1 (they're overloaded, so we do
929 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
930 // identical (return types of functions are not part of the
931 // signature), IsOverload returns false and MatchedDecl will be set to
932 // point to the FunctionDecl for #2.
933 //
934 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
935 // into a class by a using declaration.  The rules for whether to hide
936 // shadow declarations ignore some properties which otherwise figure
937 // into a function template's signature.
938 Sema::OverloadKind
939 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
940                     NamedDecl *&Match, bool NewIsUsingDecl) {
941   for (LookupResult::iterator I = Old.begin(), E = Old.end();
942          I != E; ++I) {
943     NamedDecl *OldD = *I;
944 
945     bool OldIsUsingDecl = false;
946     if (isa<UsingShadowDecl>(OldD)) {
947       OldIsUsingDecl = true;
948 
949       // We can always introduce two using declarations into the same
950       // context, even if they have identical signatures.
951       if (NewIsUsingDecl) continue;
952 
953       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
954     }
955 
956     // A using-declaration does not conflict with another declaration
957     // if one of them is hidden.
958     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
959       continue;
960 
961     // If either declaration was introduced by a using declaration,
962     // we'll need to use slightly different rules for matching.
963     // Essentially, these rules are the normal rules, except that
964     // function templates hide function templates with different
965     // return types or template parameter lists.
966     bool UseMemberUsingDeclRules =
967       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
968       !New->getFriendObjectKind();
969 
970     if (FunctionDecl *OldF = OldD->getAsFunction()) {
971       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
972         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
973           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
974           continue;
975         }
976 
977         if (!isa<FunctionTemplateDecl>(OldD) &&
978             !shouldLinkPossiblyHiddenDecl(*I, New))
979           continue;
980 
981         Match = *I;
982         return Ovl_Match;
983       }
984     } else if (isa<UsingDecl>(OldD)) {
985       // We can overload with these, which can show up when doing
986       // redeclaration checks for UsingDecls.
987       assert(Old.getLookupKind() == LookupUsingDeclName);
988     } else if (isa<TagDecl>(OldD)) {
989       // We can always overload with tags by hiding them.
990     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
991       // Optimistically assume that an unresolved using decl will
992       // overload; if it doesn't, we'll have to diagnose during
993       // template instantiation.
994     } else {
995       // (C++ 13p1):
996       //   Only function declarations can be overloaded; object and type
997       //   declarations cannot be overloaded.
998       Match = *I;
999       return Ovl_NonFunction;
1000     }
1001   }
1002 
1003   return Ovl_Overload;
1004 }
1005 
1006 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1007                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1008   // C++ [basic.start.main]p2: This function shall not be overloaded.
1009   if (New->isMain())
1010     return false;
1011 
1012   // MSVCRT user defined entry points cannot be overloaded.
1013   if (New->isMSVCRTEntryPoint())
1014     return false;
1015 
1016   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1017   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1018 
1019   // C++ [temp.fct]p2:
1020   //   A function template can be overloaded with other function templates
1021   //   and with normal (non-template) functions.
1022   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1023     return true;
1024 
1025   // Is the function New an overload of the function Old?
1026   QualType OldQType = Context.getCanonicalType(Old->getType());
1027   QualType NewQType = Context.getCanonicalType(New->getType());
1028 
1029   // Compare the signatures (C++ 1.3.10) of the two functions to
1030   // determine whether they are overloads. If we find any mismatch
1031   // in the signature, they are overloads.
1032 
1033   // If either of these functions is a K&R-style function (no
1034   // prototype), then we consider them to have matching signatures.
1035   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1036       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1037     return false;
1038 
1039   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1040   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1041 
1042   // The signature of a function includes the types of its
1043   // parameters (C++ 1.3.10), which includes the presence or absence
1044   // of the ellipsis; see C++ DR 357).
1045   if (OldQType != NewQType &&
1046       (OldType->getNumParams() != NewType->getNumParams() ||
1047        OldType->isVariadic() != NewType->isVariadic() ||
1048        !FunctionParamTypesAreEqual(OldType, NewType)))
1049     return true;
1050 
1051   // C++ [temp.over.link]p4:
1052   //   The signature of a function template consists of its function
1053   //   signature, its return type and its template parameter list. The names
1054   //   of the template parameters are significant only for establishing the
1055   //   relationship between the template parameters and the rest of the
1056   //   signature.
1057   //
1058   // We check the return type and template parameter lists for function
1059   // templates first; the remaining checks follow.
1060   //
1061   // However, we don't consider either of these when deciding whether
1062   // a member introduced by a shadow declaration is hidden.
1063   if (!UseMemberUsingDeclRules && NewTemplate &&
1064       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1065                                        OldTemplate->getTemplateParameters(),
1066                                        false, TPL_TemplateMatch) ||
1067        OldType->getReturnType() != NewType->getReturnType()))
1068     return true;
1069 
1070   // If the function is a class member, its signature includes the
1071   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1072   //
1073   // As part of this, also check whether one of the member functions
1074   // is static, in which case they are not overloads (C++
1075   // 13.1p2). While not part of the definition of the signature,
1076   // this check is important to determine whether these functions
1077   // can be overloaded.
1078   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1079   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1080   if (OldMethod && NewMethod &&
1081       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1082     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1083       if (!UseMemberUsingDeclRules &&
1084           (OldMethod->getRefQualifier() == RQ_None ||
1085            NewMethod->getRefQualifier() == RQ_None)) {
1086         // C++0x [over.load]p2:
1087         //   - Member function declarations with the same name and the same
1088         //     parameter-type-list as well as member function template
1089         //     declarations with the same name, the same parameter-type-list, and
1090         //     the same template parameter lists cannot be overloaded if any of
1091         //     them, but not all, have a ref-qualifier (8.3.5).
1092         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1093           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1094         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1095       }
1096       return true;
1097     }
1098 
1099     // We may not have applied the implicit const for a constexpr member
1100     // function yet (because we haven't yet resolved whether this is a static
1101     // or non-static member function). Add it now, on the assumption that this
1102     // is a redeclaration of OldMethod.
1103     unsigned OldQuals = OldMethod->getTypeQualifiers();
1104     unsigned NewQuals = NewMethod->getTypeQualifiers();
1105     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1106         !isa<CXXConstructorDecl>(NewMethod))
1107       NewQuals |= Qualifiers::Const;
1108 
1109     // We do not allow overloading based off of '__restrict'.
1110     OldQuals &= ~Qualifiers::Restrict;
1111     NewQuals &= ~Qualifiers::Restrict;
1112     if (OldQuals != NewQuals)
1113       return true;
1114   }
1115 
1116   // Though pass_object_size is placed on parameters and takes an argument, we
1117   // consider it to be a function-level modifier for the sake of function
1118   // identity. Either the function has one or more parameters with
1119   // pass_object_size or it doesn't.
1120   if (functionHasPassObjectSizeParams(New) !=
1121       functionHasPassObjectSizeParams(Old))
1122     return true;
1123 
1124   // enable_if attributes are an order-sensitive part of the signature.
1125   for (specific_attr_iterator<EnableIfAttr>
1126          NewI = New->specific_attr_begin<EnableIfAttr>(),
1127          NewE = New->specific_attr_end<EnableIfAttr>(),
1128          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1129          OldE = Old->specific_attr_end<EnableIfAttr>();
1130        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1131     if (NewI == NewE || OldI == OldE)
1132       return true;
1133     llvm::FoldingSetNodeID NewID, OldID;
1134     NewI->getCond()->Profile(NewID, Context, true);
1135     OldI->getCond()->Profile(OldID, Context, true);
1136     if (NewID != OldID)
1137       return true;
1138   }
1139 
1140   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1141     // Don't allow overloading of destructors.  (In theory we could, but it
1142     // would be a giant change to clang.)
1143     if (isa<CXXDestructorDecl>(New))
1144       return false;
1145 
1146     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1147                        OldTarget = IdentifyCUDATarget(Old);
1148     if (NewTarget == CFT_InvalidTarget)
1149       return false;
1150 
1151     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1152 
1153     // Allow overloading of functions with same signature and different CUDA
1154     // target attributes.
1155     return NewTarget != OldTarget;
1156   }
1157 
1158   // The signatures match; this is not an overload.
1159   return false;
1160 }
1161 
1162 /// \brief Checks availability of the function depending on the current
1163 /// function context. Inside an unavailable function, unavailability is ignored.
1164 ///
1165 /// \returns true if \arg FD is unavailable and current context is inside
1166 /// an available function, false otherwise.
1167 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1168   if (!FD->isUnavailable())
1169     return false;
1170 
1171   // Walk up the context of the caller.
1172   Decl *C = cast<Decl>(CurContext);
1173   do {
1174     if (C->isUnavailable())
1175       return false;
1176   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1177   return true;
1178 }
1179 
1180 /// \brief Tries a user-defined conversion from From to ToType.
1181 ///
1182 /// Produces an implicit conversion sequence for when a standard conversion
1183 /// is not an option. See TryImplicitConversion for more information.
1184 static ImplicitConversionSequence
1185 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1186                          bool SuppressUserConversions,
1187                          bool AllowExplicit,
1188                          bool InOverloadResolution,
1189                          bool CStyle,
1190                          bool AllowObjCWritebackConversion,
1191                          bool AllowObjCConversionOnExplicit) {
1192   ImplicitConversionSequence ICS;
1193 
1194   if (SuppressUserConversions) {
1195     // We're not in the case above, so there is no conversion that
1196     // we can perform.
1197     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1198     return ICS;
1199   }
1200 
1201   // Attempt user-defined conversion.
1202   OverloadCandidateSet Conversions(From->getExprLoc(),
1203                                    OverloadCandidateSet::CSK_Normal);
1204   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1205                                   Conversions, AllowExplicit,
1206                                   AllowObjCConversionOnExplicit)) {
1207   case OR_Success:
1208   case OR_Deleted:
1209     ICS.setUserDefined();
1210     // C++ [over.ics.user]p4:
1211     //   A conversion of an expression of class type to the same class
1212     //   type is given Exact Match rank, and a conversion of an
1213     //   expression of class type to a base class of that type is
1214     //   given Conversion rank, in spite of the fact that a copy
1215     //   constructor (i.e., a user-defined conversion function) is
1216     //   called for those cases.
1217     if (CXXConstructorDecl *Constructor
1218           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1219       QualType FromCanon
1220         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1221       QualType ToCanon
1222         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1223       if (Constructor->isCopyConstructor() &&
1224           (FromCanon == ToCanon ||
1225            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1226         // Turn this into a "standard" conversion sequence, so that it
1227         // gets ranked with standard conversion sequences.
1228         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1229         ICS.setStandard();
1230         ICS.Standard.setAsIdentityConversion();
1231         ICS.Standard.setFromType(From->getType());
1232         ICS.Standard.setAllToTypes(ToType);
1233         ICS.Standard.CopyConstructor = Constructor;
1234         ICS.Standard.FoundCopyConstructor = Found;
1235         if (ToCanon != FromCanon)
1236           ICS.Standard.Second = ICK_Derived_To_Base;
1237       }
1238     }
1239     break;
1240 
1241   case OR_Ambiguous:
1242     ICS.setAmbiguous();
1243     ICS.Ambiguous.setFromType(From->getType());
1244     ICS.Ambiguous.setToType(ToType);
1245     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1246          Cand != Conversions.end(); ++Cand)
1247       if (Cand->Viable)
1248         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1249     break;
1250 
1251     // Fall through.
1252   case OR_No_Viable_Function:
1253     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1254     break;
1255   }
1256 
1257   return ICS;
1258 }
1259 
1260 /// TryImplicitConversion - Attempt to perform an implicit conversion
1261 /// from the given expression (Expr) to the given type (ToType). This
1262 /// function returns an implicit conversion sequence that can be used
1263 /// to perform the initialization. Given
1264 ///
1265 ///   void f(float f);
1266 ///   void g(int i) { f(i); }
1267 ///
1268 /// this routine would produce an implicit conversion sequence to
1269 /// describe the initialization of f from i, which will be a standard
1270 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1271 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1272 //
1273 /// Note that this routine only determines how the conversion can be
1274 /// performed; it does not actually perform the conversion. As such,
1275 /// it will not produce any diagnostics if no conversion is available,
1276 /// but will instead return an implicit conversion sequence of kind
1277 /// "BadConversion".
1278 ///
1279 /// If @p SuppressUserConversions, then user-defined conversions are
1280 /// not permitted.
1281 /// If @p AllowExplicit, then explicit user-defined conversions are
1282 /// permitted.
1283 ///
1284 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1285 /// writeback conversion, which allows __autoreleasing id* parameters to
1286 /// be initialized with __strong id* or __weak id* arguments.
1287 static ImplicitConversionSequence
1288 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1289                       bool SuppressUserConversions,
1290                       bool AllowExplicit,
1291                       bool InOverloadResolution,
1292                       bool CStyle,
1293                       bool AllowObjCWritebackConversion,
1294                       bool AllowObjCConversionOnExplicit) {
1295   ImplicitConversionSequence ICS;
1296   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1297                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1298     ICS.setStandard();
1299     return ICS;
1300   }
1301 
1302   if (!S.getLangOpts().CPlusPlus) {
1303     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1304     return ICS;
1305   }
1306 
1307   // C++ [over.ics.user]p4:
1308   //   A conversion of an expression of class type to the same class
1309   //   type is given Exact Match rank, and a conversion of an
1310   //   expression of class type to a base class of that type is
1311   //   given Conversion rank, in spite of the fact that a copy/move
1312   //   constructor (i.e., a user-defined conversion function) is
1313   //   called for those cases.
1314   QualType FromType = From->getType();
1315   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1316       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1317        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1318     ICS.setStandard();
1319     ICS.Standard.setAsIdentityConversion();
1320     ICS.Standard.setFromType(FromType);
1321     ICS.Standard.setAllToTypes(ToType);
1322 
1323     // We don't actually check at this point whether there is a valid
1324     // copy/move constructor, since overloading just assumes that it
1325     // exists. When we actually perform initialization, we'll find the
1326     // appropriate constructor to copy the returned object, if needed.
1327     ICS.Standard.CopyConstructor = nullptr;
1328 
1329     // Determine whether this is considered a derived-to-base conversion.
1330     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1331       ICS.Standard.Second = ICK_Derived_To_Base;
1332 
1333     return ICS;
1334   }
1335 
1336   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1337                                   AllowExplicit, InOverloadResolution, CStyle,
1338                                   AllowObjCWritebackConversion,
1339                                   AllowObjCConversionOnExplicit);
1340 }
1341 
1342 ImplicitConversionSequence
1343 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1344                             bool SuppressUserConversions,
1345                             bool AllowExplicit,
1346                             bool InOverloadResolution,
1347                             bool CStyle,
1348                             bool AllowObjCWritebackConversion) {
1349   return ::TryImplicitConversion(*this, From, ToType,
1350                                  SuppressUserConversions, AllowExplicit,
1351                                  InOverloadResolution, CStyle,
1352                                  AllowObjCWritebackConversion,
1353                                  /*AllowObjCConversionOnExplicit=*/false);
1354 }
1355 
1356 /// PerformImplicitConversion - Perform an implicit conversion of the
1357 /// expression From to the type ToType. Returns the
1358 /// converted expression. Flavor is the kind of conversion we're
1359 /// performing, used in the error message. If @p AllowExplicit,
1360 /// explicit user-defined conversions are permitted.
1361 ExprResult
1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1363                                 AssignmentAction Action, bool AllowExplicit) {
1364   ImplicitConversionSequence ICS;
1365   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1366 }
1367 
1368 ExprResult
1369 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1370                                 AssignmentAction Action, bool AllowExplicit,
1371                                 ImplicitConversionSequence& ICS) {
1372   if (checkPlaceholderForOverload(*this, From))
1373     return ExprError();
1374 
1375   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1376   bool AllowObjCWritebackConversion
1377     = getLangOpts().ObjCAutoRefCount &&
1378       (Action == AA_Passing || Action == AA_Sending);
1379   if (getLangOpts().ObjC1)
1380     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1381                                       ToType, From->getType(), From);
1382   ICS = ::TryImplicitConversion(*this, From, ToType,
1383                                 /*SuppressUserConversions=*/false,
1384                                 AllowExplicit,
1385                                 /*InOverloadResolution=*/false,
1386                                 /*CStyle=*/false,
1387                                 AllowObjCWritebackConversion,
1388                                 /*AllowObjCConversionOnExplicit=*/false);
1389   return PerformImplicitConversion(From, ToType, ICS, Action);
1390 }
1391 
1392 /// \brief Determine whether the conversion from FromType to ToType is a valid
1393 /// conversion that strips "noexcept" or "noreturn" off the nested function
1394 /// type.
1395 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1396                                 QualType &ResultTy) {
1397   if (Context.hasSameUnqualifiedType(FromType, ToType))
1398     return false;
1399 
1400   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1401   //                    or F(t noexcept) -> F(t)
1402   // where F adds one of the following at most once:
1403   //   - a pointer
1404   //   - a member pointer
1405   //   - a block pointer
1406   // Changes here need matching changes in FindCompositePointerType.
1407   CanQualType CanTo = Context.getCanonicalType(ToType);
1408   CanQualType CanFrom = Context.getCanonicalType(FromType);
1409   Type::TypeClass TyClass = CanTo->getTypeClass();
1410   if (TyClass != CanFrom->getTypeClass()) return false;
1411   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1412     if (TyClass == Type::Pointer) {
1413       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1414       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1415     } else if (TyClass == Type::BlockPointer) {
1416       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1417       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1418     } else if (TyClass == Type::MemberPointer) {
1419       auto ToMPT = CanTo.getAs<MemberPointerType>();
1420       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1421       // A function pointer conversion cannot change the class of the function.
1422       if (ToMPT->getClass() != FromMPT->getClass())
1423         return false;
1424       CanTo = ToMPT->getPointeeType();
1425       CanFrom = FromMPT->getPointeeType();
1426     } else {
1427       return false;
1428     }
1429 
1430     TyClass = CanTo->getTypeClass();
1431     if (TyClass != CanFrom->getTypeClass()) return false;
1432     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1433       return false;
1434   }
1435 
1436   const auto *FromFn = cast<FunctionType>(CanFrom);
1437   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1438 
1439   const auto *ToFn = cast<FunctionType>(CanTo);
1440   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1441 
1442   bool Changed = false;
1443 
1444   // Drop 'noreturn' if not present in target type.
1445   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1446     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1447     Changed = true;
1448   }
1449 
1450   // Drop 'noexcept' if not present in target type.
1451   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1452     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1453     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1454       FromFn = cast<FunctionType>(
1455           Context.getFunctionType(FromFPT->getReturnType(),
1456                                   FromFPT->getParamTypes(),
1457                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1458                                       FunctionProtoType::ExceptionSpecInfo()))
1459                  .getTypePtr());
1460       Changed = true;
1461     }
1462   }
1463 
1464   if (!Changed)
1465     return false;
1466 
1467   assert(QualType(FromFn, 0).isCanonical());
1468   if (QualType(FromFn, 0) != CanTo) return false;
1469 
1470   ResultTy = ToType;
1471   return true;
1472 }
1473 
1474 /// \brief Determine whether the conversion from FromType to ToType is a valid
1475 /// vector conversion.
1476 ///
1477 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1478 /// conversion.
1479 static bool IsVectorConversion(Sema &S, QualType FromType,
1480                                QualType ToType, ImplicitConversionKind &ICK) {
1481   // We need at least one of these types to be a vector type to have a vector
1482   // conversion.
1483   if (!ToType->isVectorType() && !FromType->isVectorType())
1484     return false;
1485 
1486   // Identical types require no conversions.
1487   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1488     return false;
1489 
1490   // There are no conversions between extended vector types, only identity.
1491   if (ToType->isExtVectorType()) {
1492     // There are no conversions between extended vector types other than the
1493     // identity conversion.
1494     if (FromType->isExtVectorType())
1495       return false;
1496 
1497     // Vector splat from any arithmetic type to a vector.
1498     if (FromType->isArithmeticType()) {
1499       ICK = ICK_Vector_Splat;
1500       return true;
1501     }
1502   }
1503 
1504   // We can perform the conversion between vector types in the following cases:
1505   // 1)vector types are equivalent AltiVec and GCC vector types
1506   // 2)lax vector conversions are permitted and the vector types are of the
1507   //   same size
1508   if (ToType->isVectorType() && FromType->isVectorType()) {
1509     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1510         S.isLaxVectorConversion(FromType, ToType)) {
1511       ICK = ICK_Vector_Conversion;
1512       return true;
1513     }
1514   }
1515 
1516   return false;
1517 }
1518 
1519 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1520                                 bool InOverloadResolution,
1521                                 StandardConversionSequence &SCS,
1522                                 bool CStyle);
1523 
1524 /// IsStandardConversion - Determines whether there is a standard
1525 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1526 /// expression From to the type ToType. Standard conversion sequences
1527 /// only consider non-class types; for conversions that involve class
1528 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1529 /// contain the standard conversion sequence required to perform this
1530 /// conversion and this routine will return true. Otherwise, this
1531 /// routine will return false and the value of SCS is unspecified.
1532 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1533                                  bool InOverloadResolution,
1534                                  StandardConversionSequence &SCS,
1535                                  bool CStyle,
1536                                  bool AllowObjCWritebackConversion) {
1537   QualType FromType = From->getType();
1538 
1539   // Standard conversions (C++ [conv])
1540   SCS.setAsIdentityConversion();
1541   SCS.IncompatibleObjC = false;
1542   SCS.setFromType(FromType);
1543   SCS.CopyConstructor = nullptr;
1544 
1545   // There are no standard conversions for class types in C++, so
1546   // abort early. When overloading in C, however, we do permit them.
1547   if (S.getLangOpts().CPlusPlus &&
1548       (FromType->isRecordType() || ToType->isRecordType()))
1549     return false;
1550 
1551   // The first conversion can be an lvalue-to-rvalue conversion,
1552   // array-to-pointer conversion, or function-to-pointer conversion
1553   // (C++ 4p1).
1554 
1555   if (FromType == S.Context.OverloadTy) {
1556     DeclAccessPair AccessPair;
1557     if (FunctionDecl *Fn
1558           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1559                                                  AccessPair)) {
1560       // We were able to resolve the address of the overloaded function,
1561       // so we can convert to the type of that function.
1562       FromType = Fn->getType();
1563       SCS.setFromType(FromType);
1564 
1565       // we can sometimes resolve &foo<int> regardless of ToType, so check
1566       // if the type matches (identity) or we are converting to bool
1567       if (!S.Context.hasSameUnqualifiedType(
1568                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1569         QualType resultTy;
1570         // if the function type matches except for [[noreturn]], it's ok
1571         if (!S.IsFunctionConversion(FromType,
1572               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1573           // otherwise, only a boolean conversion is standard
1574           if (!ToType->isBooleanType())
1575             return false;
1576       }
1577 
1578       // Check if the "from" expression is taking the address of an overloaded
1579       // function and recompute the FromType accordingly. Take advantage of the
1580       // fact that non-static member functions *must* have such an address-of
1581       // expression.
1582       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1583       if (Method && !Method->isStatic()) {
1584         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1585                "Non-unary operator on non-static member address");
1586         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1587                == UO_AddrOf &&
1588                "Non-address-of operator on non-static member address");
1589         const Type *ClassType
1590           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1591         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1592       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1593         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1594                UO_AddrOf &&
1595                "Non-address-of operator for overloaded function expression");
1596         FromType = S.Context.getPointerType(FromType);
1597       }
1598 
1599       // Check that we've computed the proper type after overload resolution.
1600       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1601       // be calling it from within an NDEBUG block.
1602       assert(S.Context.hasSameType(
1603         FromType,
1604         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1605     } else {
1606       return false;
1607     }
1608   }
1609   // Lvalue-to-rvalue conversion (C++11 4.1):
1610   //   A glvalue (3.10) of a non-function, non-array type T can
1611   //   be converted to a prvalue.
1612   bool argIsLValue = From->isGLValue();
1613   if (argIsLValue &&
1614       !FromType->isFunctionType() && !FromType->isArrayType() &&
1615       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1616     SCS.First = ICK_Lvalue_To_Rvalue;
1617 
1618     // C11 6.3.2.1p2:
1619     //   ... if the lvalue has atomic type, the value has the non-atomic version
1620     //   of the type of the lvalue ...
1621     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1622       FromType = Atomic->getValueType();
1623 
1624     // If T is a non-class type, the type of the rvalue is the
1625     // cv-unqualified version of T. Otherwise, the type of the rvalue
1626     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1627     // just strip the qualifiers because they don't matter.
1628     FromType = FromType.getUnqualifiedType();
1629   } else if (FromType->isArrayType()) {
1630     // Array-to-pointer conversion (C++ 4.2)
1631     SCS.First = ICK_Array_To_Pointer;
1632 
1633     // An lvalue or rvalue of type "array of N T" or "array of unknown
1634     // bound of T" can be converted to an rvalue of type "pointer to
1635     // T" (C++ 4.2p1).
1636     FromType = S.Context.getArrayDecayedType(FromType);
1637 
1638     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1639       // This conversion is deprecated in C++03 (D.4)
1640       SCS.DeprecatedStringLiteralToCharPtr = true;
1641 
1642       // For the purpose of ranking in overload resolution
1643       // (13.3.3.1.1), this conversion is considered an
1644       // array-to-pointer conversion followed by a qualification
1645       // conversion (4.4). (C++ 4.2p2)
1646       SCS.Second = ICK_Identity;
1647       SCS.Third = ICK_Qualification;
1648       SCS.QualificationIncludesObjCLifetime = false;
1649       SCS.setAllToTypes(FromType);
1650       return true;
1651     }
1652   } else if (FromType->isFunctionType() && argIsLValue) {
1653     // Function-to-pointer conversion (C++ 4.3).
1654     SCS.First = ICK_Function_To_Pointer;
1655 
1656     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1657       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1658         if (!S.checkAddressOfFunctionIsAvailable(FD))
1659           return false;
1660 
1661     // An lvalue of function type T can be converted to an rvalue of
1662     // type "pointer to T." The result is a pointer to the
1663     // function. (C++ 4.3p1).
1664     FromType = S.Context.getPointerType(FromType);
1665   } else {
1666     // We don't require any conversions for the first step.
1667     SCS.First = ICK_Identity;
1668   }
1669   SCS.setToType(0, FromType);
1670 
1671   // The second conversion can be an integral promotion, floating
1672   // point promotion, integral conversion, floating point conversion,
1673   // floating-integral conversion, pointer conversion,
1674   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1675   // For overloading in C, this can also be a "compatible-type"
1676   // conversion.
1677   bool IncompatibleObjC = false;
1678   ImplicitConversionKind SecondICK = ICK_Identity;
1679   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1680     // The unqualified versions of the types are the same: there's no
1681     // conversion to do.
1682     SCS.Second = ICK_Identity;
1683   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1684     // Integral promotion (C++ 4.5).
1685     SCS.Second = ICK_Integral_Promotion;
1686     FromType = ToType.getUnqualifiedType();
1687   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1688     // Floating point promotion (C++ 4.6).
1689     SCS.Second = ICK_Floating_Promotion;
1690     FromType = ToType.getUnqualifiedType();
1691   } else if (S.IsComplexPromotion(FromType, ToType)) {
1692     // Complex promotion (Clang extension)
1693     SCS.Second = ICK_Complex_Promotion;
1694     FromType = ToType.getUnqualifiedType();
1695   } else if (ToType->isBooleanType() &&
1696              (FromType->isArithmeticType() ||
1697               FromType->isAnyPointerType() ||
1698               FromType->isBlockPointerType() ||
1699               FromType->isMemberPointerType() ||
1700               FromType->isNullPtrType())) {
1701     // Boolean conversions (C++ 4.12).
1702     SCS.Second = ICK_Boolean_Conversion;
1703     FromType = S.Context.BoolTy;
1704   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1705              ToType->isIntegralType(S.Context)) {
1706     // Integral conversions (C++ 4.7).
1707     SCS.Second = ICK_Integral_Conversion;
1708     FromType = ToType.getUnqualifiedType();
1709   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1710     // Complex conversions (C99 6.3.1.6)
1711     SCS.Second = ICK_Complex_Conversion;
1712     FromType = ToType.getUnqualifiedType();
1713   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1714              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1715     // Complex-real conversions (C99 6.3.1.7)
1716     SCS.Second = ICK_Complex_Real;
1717     FromType = ToType.getUnqualifiedType();
1718   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1719     // FIXME: disable conversions between long double and __float128 if
1720     // their representation is different until there is back end support
1721     // We of course allow this conversion if long double is really double.
1722     if (&S.Context.getFloatTypeSemantics(FromType) !=
1723         &S.Context.getFloatTypeSemantics(ToType)) {
1724       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1725                                     ToType == S.Context.LongDoubleTy) ||
1726                                    (FromType == S.Context.LongDoubleTy &&
1727                                     ToType == S.Context.Float128Ty));
1728       if (Float128AndLongDouble &&
1729           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1730            &llvm::APFloat::IEEEdouble))
1731         return false;
1732     }
1733     // Floating point conversions (C++ 4.8).
1734     SCS.Second = ICK_Floating_Conversion;
1735     FromType = ToType.getUnqualifiedType();
1736   } else if ((FromType->isRealFloatingType() &&
1737               ToType->isIntegralType(S.Context)) ||
1738              (FromType->isIntegralOrUnscopedEnumerationType() &&
1739               ToType->isRealFloatingType())) {
1740     // Floating-integral conversions (C++ 4.9).
1741     SCS.Second = ICK_Floating_Integral;
1742     FromType = ToType.getUnqualifiedType();
1743   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1744     SCS.Second = ICK_Block_Pointer_Conversion;
1745   } else if (AllowObjCWritebackConversion &&
1746              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1747     SCS.Second = ICK_Writeback_Conversion;
1748   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1749                                    FromType, IncompatibleObjC)) {
1750     // Pointer conversions (C++ 4.10).
1751     SCS.Second = ICK_Pointer_Conversion;
1752     SCS.IncompatibleObjC = IncompatibleObjC;
1753     FromType = FromType.getUnqualifiedType();
1754   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1755                                          InOverloadResolution, FromType)) {
1756     // Pointer to member conversions (4.11).
1757     SCS.Second = ICK_Pointer_Member;
1758   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1759     SCS.Second = SecondICK;
1760     FromType = ToType.getUnqualifiedType();
1761   } else if (!S.getLangOpts().CPlusPlus &&
1762              S.Context.typesAreCompatible(ToType, FromType)) {
1763     // Compatible conversions (Clang extension for C function overloading)
1764     SCS.Second = ICK_Compatible_Conversion;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1767                                              InOverloadResolution,
1768                                              SCS, CStyle)) {
1769     SCS.Second = ICK_TransparentUnionConversion;
1770     FromType = ToType;
1771   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1772                                  CStyle)) {
1773     // tryAtomicConversion has updated the standard conversion sequence
1774     // appropriately.
1775     return true;
1776   } else if (ToType->isEventT() &&
1777              From->isIntegerConstantExpr(S.getASTContext()) &&
1778              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1779     SCS.Second = ICK_Zero_Event_Conversion;
1780     FromType = ToType;
1781   } else {
1782     // No second conversion required.
1783     SCS.Second = ICK_Identity;
1784   }
1785   SCS.setToType(1, FromType);
1786 
1787   // The third conversion can be a function pointer conversion or a
1788   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1789   bool ObjCLifetimeConversion;
1790   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1791     // Function pointer conversions (removing 'noexcept') including removal of
1792     // 'noreturn' (Clang extension).
1793     SCS.Third = ICK_Function_Conversion;
1794   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1795                                          ObjCLifetimeConversion)) {
1796     SCS.Third = ICK_Qualification;
1797     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1798     FromType = ToType;
1799   } else {
1800     // No conversion required
1801     SCS.Third = ICK_Identity;
1802   }
1803 
1804   // C++ [over.best.ics]p6:
1805   //   [...] Any difference in top-level cv-qualification is
1806   //   subsumed by the initialization itself and does not constitute
1807   //   a conversion. [...]
1808   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1809   QualType CanonTo = S.Context.getCanonicalType(ToType);
1810   if (CanonFrom.getLocalUnqualifiedType()
1811                                      == CanonTo.getLocalUnqualifiedType() &&
1812       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1813     FromType = ToType;
1814     CanonFrom = CanonTo;
1815   }
1816 
1817   SCS.setToType(2, FromType);
1818 
1819   if (CanonFrom == CanonTo)
1820     return true;
1821 
1822   // If we have not converted the argument type to the parameter type,
1823   // this is a bad conversion sequence, unless we're resolving an overload in C.
1824   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1825     return false;
1826 
1827   ExprResult ER = ExprResult{From};
1828   Sema::AssignConvertType Conv =
1829       S.CheckSingleAssignmentConstraints(ToType, ER,
1830                                          /*Diagnose=*/false,
1831                                          /*DiagnoseCFAudited=*/false,
1832                                          /*ConvertRHS=*/false);
1833   ImplicitConversionKind SecondConv;
1834   switch (Conv) {
1835   case Sema::Compatible:
1836     SecondConv = ICK_C_Only_Conversion;
1837     break;
1838   // For our purposes, discarding qualifiers is just as bad as using an
1839   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1840   // qualifiers, as well.
1841   case Sema::CompatiblePointerDiscardsQualifiers:
1842   case Sema::IncompatiblePointer:
1843   case Sema::IncompatiblePointerSign:
1844     SecondConv = ICK_Incompatible_Pointer_Conversion;
1845     break;
1846   default:
1847     return false;
1848   }
1849 
1850   // First can only be an lvalue conversion, so we pretend that this was the
1851   // second conversion. First should already be valid from earlier in the
1852   // function.
1853   SCS.Second = SecondConv;
1854   SCS.setToType(1, ToType);
1855 
1856   // Third is Identity, because Second should rank us worse than any other
1857   // conversion. This could also be ICK_Qualification, but it's simpler to just
1858   // lump everything in with the second conversion, and we don't gain anything
1859   // from making this ICK_Qualification.
1860   SCS.Third = ICK_Identity;
1861   SCS.setToType(2, ToType);
1862   return true;
1863 }
1864 
1865 static bool
1866 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1867                                      QualType &ToType,
1868                                      bool InOverloadResolution,
1869                                      StandardConversionSequence &SCS,
1870                                      bool CStyle) {
1871 
1872   const RecordType *UT = ToType->getAsUnionType();
1873   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1874     return false;
1875   // The field to initialize within the transparent union.
1876   RecordDecl *UD = UT->getDecl();
1877   // It's compatible if the expression matches any of the fields.
1878   for (const auto *it : UD->fields()) {
1879     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1880                              CStyle, /*ObjCWritebackConversion=*/false)) {
1881       ToType = it->getType();
1882       return true;
1883     }
1884   }
1885   return false;
1886 }
1887 
1888 /// IsIntegralPromotion - Determines whether the conversion from the
1889 /// expression From (whose potentially-adjusted type is FromType) to
1890 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1891 /// sets PromotedType to the promoted type.
1892 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1893   const BuiltinType *To = ToType->getAs<BuiltinType>();
1894   // All integers are built-in.
1895   if (!To) {
1896     return false;
1897   }
1898 
1899   // An rvalue of type char, signed char, unsigned char, short int, or
1900   // unsigned short int can be converted to an rvalue of type int if
1901   // int can represent all the values of the source type; otherwise,
1902   // the source rvalue can be converted to an rvalue of type unsigned
1903   // int (C++ 4.5p1).
1904   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1905       !FromType->isEnumeralType()) {
1906     if (// We can promote any signed, promotable integer type to an int
1907         (FromType->isSignedIntegerType() ||
1908          // We can promote any unsigned integer type whose size is
1909          // less than int to an int.
1910          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1911       return To->getKind() == BuiltinType::Int;
1912     }
1913 
1914     return To->getKind() == BuiltinType::UInt;
1915   }
1916 
1917   // C++11 [conv.prom]p3:
1918   //   A prvalue of an unscoped enumeration type whose underlying type is not
1919   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1920   //   following types that can represent all the values of the enumeration
1921   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1922   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1923   //   long long int. If none of the types in that list can represent all the
1924   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1925   //   type can be converted to an rvalue a prvalue of the extended integer type
1926   //   with lowest integer conversion rank (4.13) greater than the rank of long
1927   //   long in which all the values of the enumeration can be represented. If
1928   //   there are two such extended types, the signed one is chosen.
1929   // C++11 [conv.prom]p4:
1930   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1931   //   can be converted to a prvalue of its underlying type. Moreover, if
1932   //   integral promotion can be applied to its underlying type, a prvalue of an
1933   //   unscoped enumeration type whose underlying type is fixed can also be
1934   //   converted to a prvalue of the promoted underlying type.
1935   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1936     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1937     // provided for a scoped enumeration.
1938     if (FromEnumType->getDecl()->isScoped())
1939       return false;
1940 
1941     // We can perform an integral promotion to the underlying type of the enum,
1942     // even if that's not the promoted type. Note that the check for promoting
1943     // the underlying type is based on the type alone, and does not consider
1944     // the bitfield-ness of the actual source expression.
1945     if (FromEnumType->getDecl()->isFixed()) {
1946       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1947       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1948              IsIntegralPromotion(nullptr, Underlying, ToType);
1949     }
1950 
1951     // We have already pre-calculated the promotion type, so this is trivial.
1952     if (ToType->isIntegerType() &&
1953         isCompleteType(From->getLocStart(), FromType))
1954       return Context.hasSameUnqualifiedType(
1955           ToType, FromEnumType->getDecl()->getPromotionType());
1956   }
1957 
1958   // C++0x [conv.prom]p2:
1959   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1960   //   to an rvalue a prvalue of the first of the following types that can
1961   //   represent all the values of its underlying type: int, unsigned int,
1962   //   long int, unsigned long int, long long int, or unsigned long long int.
1963   //   If none of the types in that list can represent all the values of its
1964   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1965   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1966   //   type.
1967   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1968       ToType->isIntegerType()) {
1969     // Determine whether the type we're converting from is signed or
1970     // unsigned.
1971     bool FromIsSigned = FromType->isSignedIntegerType();
1972     uint64_t FromSize = Context.getTypeSize(FromType);
1973 
1974     // The types we'll try to promote to, in the appropriate
1975     // order. Try each of these types.
1976     QualType PromoteTypes[6] = {
1977       Context.IntTy, Context.UnsignedIntTy,
1978       Context.LongTy, Context.UnsignedLongTy ,
1979       Context.LongLongTy, Context.UnsignedLongLongTy
1980     };
1981     for (int Idx = 0; Idx < 6; ++Idx) {
1982       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1983       if (FromSize < ToSize ||
1984           (FromSize == ToSize &&
1985            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1986         // We found the type that we can promote to. If this is the
1987         // type we wanted, we have a promotion. Otherwise, no
1988         // promotion.
1989         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1990       }
1991     }
1992   }
1993 
1994   // An rvalue for an integral bit-field (9.6) can be converted to an
1995   // rvalue of type int if int can represent all the values of the
1996   // bit-field; otherwise, it can be converted to unsigned int if
1997   // unsigned int can represent all the values of the bit-field. If
1998   // the bit-field is larger yet, no integral promotion applies to
1999   // it. If the bit-field has an enumerated type, it is treated as any
2000   // other value of that type for promotion purposes (C++ 4.5p3).
2001   // FIXME: We should delay checking of bit-fields until we actually perform the
2002   // conversion.
2003   if (From) {
2004     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2005       llvm::APSInt BitWidth;
2006       if (FromType->isIntegralType(Context) &&
2007           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2008         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2009         ToSize = Context.getTypeSize(ToType);
2010 
2011         // Are we promoting to an int from a bitfield that fits in an int?
2012         if (BitWidth < ToSize ||
2013             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2014           return To->getKind() == BuiltinType::Int;
2015         }
2016 
2017         // Are we promoting to an unsigned int from an unsigned bitfield
2018         // that fits into an unsigned int?
2019         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2020           return To->getKind() == BuiltinType::UInt;
2021         }
2022 
2023         return false;
2024       }
2025     }
2026   }
2027 
2028   // An rvalue of type bool can be converted to an rvalue of type int,
2029   // with false becoming zero and true becoming one (C++ 4.5p4).
2030   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2031     return true;
2032   }
2033 
2034   return false;
2035 }
2036 
2037 /// IsFloatingPointPromotion - Determines whether the conversion from
2038 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2039 /// returns true and sets PromotedType to the promoted type.
2040 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2041   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2042     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2043       /// An rvalue of type float can be converted to an rvalue of type
2044       /// double. (C++ 4.6p1).
2045       if (FromBuiltin->getKind() == BuiltinType::Float &&
2046           ToBuiltin->getKind() == BuiltinType::Double)
2047         return true;
2048 
2049       // C99 6.3.1.5p1:
2050       //   When a float is promoted to double or long double, or a
2051       //   double is promoted to long double [...].
2052       if (!getLangOpts().CPlusPlus &&
2053           (FromBuiltin->getKind() == BuiltinType::Float ||
2054            FromBuiltin->getKind() == BuiltinType::Double) &&
2055           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2056            ToBuiltin->getKind() == BuiltinType::Float128))
2057         return true;
2058 
2059       // Half can be promoted to float.
2060       if (!getLangOpts().NativeHalfType &&
2061            FromBuiltin->getKind() == BuiltinType::Half &&
2062           ToBuiltin->getKind() == BuiltinType::Float)
2063         return true;
2064     }
2065 
2066   return false;
2067 }
2068 
2069 /// \brief Determine if a conversion is a complex promotion.
2070 ///
2071 /// A complex promotion is defined as a complex -> complex conversion
2072 /// where the conversion between the underlying real types is a
2073 /// floating-point or integral promotion.
2074 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2075   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2076   if (!FromComplex)
2077     return false;
2078 
2079   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2080   if (!ToComplex)
2081     return false;
2082 
2083   return IsFloatingPointPromotion(FromComplex->getElementType(),
2084                                   ToComplex->getElementType()) ||
2085     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2086                         ToComplex->getElementType());
2087 }
2088 
2089 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2090 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2091 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2092 /// if non-empty, will be a pointer to ToType that may or may not have
2093 /// the right set of qualifiers on its pointee.
2094 ///
2095 static QualType
2096 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2097                                    QualType ToPointee, QualType ToType,
2098                                    ASTContext &Context,
2099                                    bool StripObjCLifetime = false) {
2100   assert((FromPtr->getTypeClass() == Type::Pointer ||
2101           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2102          "Invalid similarly-qualified pointer type");
2103 
2104   /// Conversions to 'id' subsume cv-qualifier conversions.
2105   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2106     return ToType.getUnqualifiedType();
2107 
2108   QualType CanonFromPointee
2109     = Context.getCanonicalType(FromPtr->getPointeeType());
2110   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2111   Qualifiers Quals = CanonFromPointee.getQualifiers();
2112 
2113   if (StripObjCLifetime)
2114     Quals.removeObjCLifetime();
2115 
2116   // Exact qualifier match -> return the pointer type we're converting to.
2117   if (CanonToPointee.getLocalQualifiers() == Quals) {
2118     // ToType is exactly what we need. Return it.
2119     if (!ToType.isNull())
2120       return ToType.getUnqualifiedType();
2121 
2122     // Build a pointer to ToPointee. It has the right qualifiers
2123     // already.
2124     if (isa<ObjCObjectPointerType>(ToType))
2125       return Context.getObjCObjectPointerType(ToPointee);
2126     return Context.getPointerType(ToPointee);
2127   }
2128 
2129   // Just build a canonical type that has the right qualifiers.
2130   QualType QualifiedCanonToPointee
2131     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2132 
2133   if (isa<ObjCObjectPointerType>(ToType))
2134     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2135   return Context.getPointerType(QualifiedCanonToPointee);
2136 }
2137 
2138 static bool isNullPointerConstantForConversion(Expr *Expr,
2139                                                bool InOverloadResolution,
2140                                                ASTContext &Context) {
2141   // Handle value-dependent integral null pointer constants correctly.
2142   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2143   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2144       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2145     return !InOverloadResolution;
2146 
2147   return Expr->isNullPointerConstant(Context,
2148                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2149                                         : Expr::NPC_ValueDependentIsNull);
2150 }
2151 
2152 /// IsPointerConversion - Determines whether the conversion of the
2153 /// expression From, which has the (possibly adjusted) type FromType,
2154 /// can be converted to the type ToType via a pointer conversion (C++
2155 /// 4.10). If so, returns true and places the converted type (that
2156 /// might differ from ToType in its cv-qualifiers at some level) into
2157 /// ConvertedType.
2158 ///
2159 /// This routine also supports conversions to and from block pointers
2160 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2161 /// pointers to interfaces. FIXME: Once we've determined the
2162 /// appropriate overloading rules for Objective-C, we may want to
2163 /// split the Objective-C checks into a different routine; however,
2164 /// GCC seems to consider all of these conversions to be pointer
2165 /// conversions, so for now they live here. IncompatibleObjC will be
2166 /// set if the conversion is an allowed Objective-C conversion that
2167 /// should result in a warning.
2168 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2169                                bool InOverloadResolution,
2170                                QualType& ConvertedType,
2171                                bool &IncompatibleObjC) {
2172   IncompatibleObjC = false;
2173   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2174                               IncompatibleObjC))
2175     return true;
2176 
2177   // Conversion from a null pointer constant to any Objective-C pointer type.
2178   if (ToType->isObjCObjectPointerType() &&
2179       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2180     ConvertedType = ToType;
2181     return true;
2182   }
2183 
2184   // Blocks: Block pointers can be converted to void*.
2185   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2186       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2187     ConvertedType = ToType;
2188     return true;
2189   }
2190   // Blocks: A null pointer constant can be converted to a block
2191   // pointer type.
2192   if (ToType->isBlockPointerType() &&
2193       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2194     ConvertedType = ToType;
2195     return true;
2196   }
2197 
2198   // If the left-hand-side is nullptr_t, the right side can be a null
2199   // pointer constant.
2200   if (ToType->isNullPtrType() &&
2201       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2202     ConvertedType = ToType;
2203     return true;
2204   }
2205 
2206   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2207   if (!ToTypePtr)
2208     return false;
2209 
2210   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2211   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2212     ConvertedType = ToType;
2213     return true;
2214   }
2215 
2216   // Beyond this point, both types need to be pointers
2217   // , including objective-c pointers.
2218   QualType ToPointeeType = ToTypePtr->getPointeeType();
2219   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2220       !getLangOpts().ObjCAutoRefCount) {
2221     ConvertedType = BuildSimilarlyQualifiedPointerType(
2222                                       FromType->getAs<ObjCObjectPointerType>(),
2223                                                        ToPointeeType,
2224                                                        ToType, Context);
2225     return true;
2226   }
2227   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2228   if (!FromTypePtr)
2229     return false;
2230 
2231   QualType FromPointeeType = FromTypePtr->getPointeeType();
2232 
2233   // If the unqualified pointee types are the same, this can't be a
2234   // pointer conversion, so don't do all of the work below.
2235   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2236     return false;
2237 
2238   // An rvalue of type "pointer to cv T," where T is an object type,
2239   // can be converted to an rvalue of type "pointer to cv void" (C++
2240   // 4.10p2).
2241   if (FromPointeeType->isIncompleteOrObjectType() &&
2242       ToPointeeType->isVoidType()) {
2243     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2244                                                        ToPointeeType,
2245                                                        ToType, Context,
2246                                                    /*StripObjCLifetime=*/true);
2247     return true;
2248   }
2249 
2250   // MSVC allows implicit function to void* type conversion.
2251   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2252       ToPointeeType->isVoidType()) {
2253     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2254                                                        ToPointeeType,
2255                                                        ToType, Context);
2256     return true;
2257   }
2258 
2259   // When we're overloading in C, we allow a special kind of pointer
2260   // conversion for compatible-but-not-identical pointee types.
2261   if (!getLangOpts().CPlusPlus &&
2262       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2263     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2264                                                        ToPointeeType,
2265                                                        ToType, Context);
2266     return true;
2267   }
2268 
2269   // C++ [conv.ptr]p3:
2270   //
2271   //   An rvalue of type "pointer to cv D," where D is a class type,
2272   //   can be converted to an rvalue of type "pointer to cv B," where
2273   //   B is a base class (clause 10) of D. If B is an inaccessible
2274   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2275   //   necessitates this conversion is ill-formed. The result of the
2276   //   conversion is a pointer to the base class sub-object of the
2277   //   derived class object. The null pointer value is converted to
2278   //   the null pointer value of the destination type.
2279   //
2280   // Note that we do not check for ambiguity or inaccessibility
2281   // here. That is handled by CheckPointerConversion.
2282   if (getLangOpts().CPlusPlus &&
2283       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2284       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2285       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2286     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2287                                                        ToPointeeType,
2288                                                        ToType, Context);
2289     return true;
2290   }
2291 
2292   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2293       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2294     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2295                                                        ToPointeeType,
2296                                                        ToType, Context);
2297     return true;
2298   }
2299 
2300   return false;
2301 }
2302 
2303 /// \brief Adopt the given qualifiers for the given type.
2304 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2305   Qualifiers TQs = T.getQualifiers();
2306 
2307   // Check whether qualifiers already match.
2308   if (TQs == Qs)
2309     return T;
2310 
2311   if (Qs.compatiblyIncludes(TQs))
2312     return Context.getQualifiedType(T, Qs);
2313 
2314   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2315 }
2316 
2317 /// isObjCPointerConversion - Determines whether this is an
2318 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2319 /// with the same arguments and return values.
2320 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2321                                    QualType& ConvertedType,
2322                                    bool &IncompatibleObjC) {
2323   if (!getLangOpts().ObjC1)
2324     return false;
2325 
2326   // The set of qualifiers on the type we're converting from.
2327   Qualifiers FromQualifiers = FromType.getQualifiers();
2328 
2329   // First, we handle all conversions on ObjC object pointer types.
2330   const ObjCObjectPointerType* ToObjCPtr =
2331     ToType->getAs<ObjCObjectPointerType>();
2332   const ObjCObjectPointerType *FromObjCPtr =
2333     FromType->getAs<ObjCObjectPointerType>();
2334 
2335   if (ToObjCPtr && FromObjCPtr) {
2336     // If the pointee types are the same (ignoring qualifications),
2337     // then this is not a pointer conversion.
2338     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2339                                        FromObjCPtr->getPointeeType()))
2340       return false;
2341 
2342     // Conversion between Objective-C pointers.
2343     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2344       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2345       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2346       if (getLangOpts().CPlusPlus && LHS && RHS &&
2347           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2348                                                 FromObjCPtr->getPointeeType()))
2349         return false;
2350       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2351                                                    ToObjCPtr->getPointeeType(),
2352                                                          ToType, Context);
2353       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2354       return true;
2355     }
2356 
2357     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2358       // Okay: this is some kind of implicit downcast of Objective-C
2359       // interfaces, which is permitted. However, we're going to
2360       // complain about it.
2361       IncompatibleObjC = true;
2362       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2363                                                    ToObjCPtr->getPointeeType(),
2364                                                          ToType, Context);
2365       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2366       return true;
2367     }
2368   }
2369   // Beyond this point, both types need to be C pointers or block pointers.
2370   QualType ToPointeeType;
2371   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2372     ToPointeeType = ToCPtr->getPointeeType();
2373   else if (const BlockPointerType *ToBlockPtr =
2374             ToType->getAs<BlockPointerType>()) {
2375     // Objective C++: We're able to convert from a pointer to any object
2376     // to a block pointer type.
2377     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2378       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2379       return true;
2380     }
2381     ToPointeeType = ToBlockPtr->getPointeeType();
2382   }
2383   else if (FromType->getAs<BlockPointerType>() &&
2384            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2385     // Objective C++: We're able to convert from a block pointer type to a
2386     // pointer to any object.
2387     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2388     return true;
2389   }
2390   else
2391     return false;
2392 
2393   QualType FromPointeeType;
2394   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2395     FromPointeeType = FromCPtr->getPointeeType();
2396   else if (const BlockPointerType *FromBlockPtr =
2397            FromType->getAs<BlockPointerType>())
2398     FromPointeeType = FromBlockPtr->getPointeeType();
2399   else
2400     return false;
2401 
2402   // If we have pointers to pointers, recursively check whether this
2403   // is an Objective-C conversion.
2404   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2405       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2406                               IncompatibleObjC)) {
2407     // We always complain about this conversion.
2408     IncompatibleObjC = true;
2409     ConvertedType = Context.getPointerType(ConvertedType);
2410     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2411     return true;
2412   }
2413   // Allow conversion of pointee being objective-c pointer to another one;
2414   // as in I* to id.
2415   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2416       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2417       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2418                               IncompatibleObjC)) {
2419 
2420     ConvertedType = Context.getPointerType(ConvertedType);
2421     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2422     return true;
2423   }
2424 
2425   // If we have pointers to functions or blocks, check whether the only
2426   // differences in the argument and result types are in Objective-C
2427   // pointer conversions. If so, we permit the conversion (but
2428   // complain about it).
2429   const FunctionProtoType *FromFunctionType
2430     = FromPointeeType->getAs<FunctionProtoType>();
2431   const FunctionProtoType *ToFunctionType
2432     = ToPointeeType->getAs<FunctionProtoType>();
2433   if (FromFunctionType && ToFunctionType) {
2434     // If the function types are exactly the same, this isn't an
2435     // Objective-C pointer conversion.
2436     if (Context.getCanonicalType(FromPointeeType)
2437           == Context.getCanonicalType(ToPointeeType))
2438       return false;
2439 
2440     // Perform the quick checks that will tell us whether these
2441     // function types are obviously different.
2442     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2443         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2444         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2445       return false;
2446 
2447     bool HasObjCConversion = false;
2448     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2449         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2450       // Okay, the types match exactly. Nothing to do.
2451     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2452                                        ToFunctionType->getReturnType(),
2453                                        ConvertedType, IncompatibleObjC)) {
2454       // Okay, we have an Objective-C pointer conversion.
2455       HasObjCConversion = true;
2456     } else {
2457       // Function types are too different. Abort.
2458       return false;
2459     }
2460 
2461     // Check argument types.
2462     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2463          ArgIdx != NumArgs; ++ArgIdx) {
2464       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2465       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2466       if (Context.getCanonicalType(FromArgType)
2467             == Context.getCanonicalType(ToArgType)) {
2468         // Okay, the types match exactly. Nothing to do.
2469       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2470                                          ConvertedType, IncompatibleObjC)) {
2471         // Okay, we have an Objective-C pointer conversion.
2472         HasObjCConversion = true;
2473       } else {
2474         // Argument types are too different. Abort.
2475         return false;
2476       }
2477     }
2478 
2479     if (HasObjCConversion) {
2480       // We had an Objective-C conversion. Allow this pointer
2481       // conversion, but complain about it.
2482       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2483       IncompatibleObjC = true;
2484       return true;
2485     }
2486   }
2487 
2488   return false;
2489 }
2490 
2491 /// \brief Determine whether this is an Objective-C writeback conversion,
2492 /// used for parameter passing when performing automatic reference counting.
2493 ///
2494 /// \param FromType The type we're converting form.
2495 ///
2496 /// \param ToType The type we're converting to.
2497 ///
2498 /// \param ConvertedType The type that will be produced after applying
2499 /// this conversion.
2500 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2501                                      QualType &ConvertedType) {
2502   if (!getLangOpts().ObjCAutoRefCount ||
2503       Context.hasSameUnqualifiedType(FromType, ToType))
2504     return false;
2505 
2506   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2507   QualType ToPointee;
2508   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2509     ToPointee = ToPointer->getPointeeType();
2510   else
2511     return false;
2512 
2513   Qualifiers ToQuals = ToPointee.getQualifiers();
2514   if (!ToPointee->isObjCLifetimeType() ||
2515       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2516       !ToQuals.withoutObjCLifetime().empty())
2517     return false;
2518 
2519   // Argument must be a pointer to __strong to __weak.
2520   QualType FromPointee;
2521   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2522     FromPointee = FromPointer->getPointeeType();
2523   else
2524     return false;
2525 
2526   Qualifiers FromQuals = FromPointee.getQualifiers();
2527   if (!FromPointee->isObjCLifetimeType() ||
2528       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2529        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2530     return false;
2531 
2532   // Make sure that we have compatible qualifiers.
2533   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2534   if (!ToQuals.compatiblyIncludes(FromQuals))
2535     return false;
2536 
2537   // Remove qualifiers from the pointee type we're converting from; they
2538   // aren't used in the compatibility check belong, and we'll be adding back
2539   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2540   FromPointee = FromPointee.getUnqualifiedType();
2541 
2542   // The unqualified form of the pointee types must be compatible.
2543   ToPointee = ToPointee.getUnqualifiedType();
2544   bool IncompatibleObjC;
2545   if (Context.typesAreCompatible(FromPointee, ToPointee))
2546     FromPointee = ToPointee;
2547   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2548                                     IncompatibleObjC))
2549     return false;
2550 
2551   /// \brief Construct the type we're converting to, which is a pointer to
2552   /// __autoreleasing pointee.
2553   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2554   ConvertedType = Context.getPointerType(FromPointee);
2555   return true;
2556 }
2557 
2558 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2559                                     QualType& ConvertedType) {
2560   QualType ToPointeeType;
2561   if (const BlockPointerType *ToBlockPtr =
2562         ToType->getAs<BlockPointerType>())
2563     ToPointeeType = ToBlockPtr->getPointeeType();
2564   else
2565     return false;
2566 
2567   QualType FromPointeeType;
2568   if (const BlockPointerType *FromBlockPtr =
2569       FromType->getAs<BlockPointerType>())
2570     FromPointeeType = FromBlockPtr->getPointeeType();
2571   else
2572     return false;
2573   // We have pointer to blocks, check whether the only
2574   // differences in the argument and result types are in Objective-C
2575   // pointer conversions. If so, we permit the conversion.
2576 
2577   const FunctionProtoType *FromFunctionType
2578     = FromPointeeType->getAs<FunctionProtoType>();
2579   const FunctionProtoType *ToFunctionType
2580     = ToPointeeType->getAs<FunctionProtoType>();
2581 
2582   if (!FromFunctionType || !ToFunctionType)
2583     return false;
2584 
2585   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2586     return true;
2587 
2588   // Perform the quick checks that will tell us whether these
2589   // function types are obviously different.
2590   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2591       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2592     return false;
2593 
2594   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2595   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2596   if (FromEInfo != ToEInfo)
2597     return false;
2598 
2599   bool IncompatibleObjC = false;
2600   if (Context.hasSameType(FromFunctionType->getReturnType(),
2601                           ToFunctionType->getReturnType())) {
2602     // Okay, the types match exactly. Nothing to do.
2603   } else {
2604     QualType RHS = FromFunctionType->getReturnType();
2605     QualType LHS = ToFunctionType->getReturnType();
2606     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2607         !RHS.hasQualifiers() && LHS.hasQualifiers())
2608        LHS = LHS.getUnqualifiedType();
2609 
2610      if (Context.hasSameType(RHS,LHS)) {
2611        // OK exact match.
2612      } else if (isObjCPointerConversion(RHS, LHS,
2613                                         ConvertedType, IncompatibleObjC)) {
2614      if (IncompatibleObjC)
2615        return false;
2616      // Okay, we have an Objective-C pointer conversion.
2617      }
2618      else
2619        return false;
2620    }
2621 
2622    // Check argument types.
2623    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2624         ArgIdx != NumArgs; ++ArgIdx) {
2625      IncompatibleObjC = false;
2626      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2627      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2628      if (Context.hasSameType(FromArgType, ToArgType)) {
2629        // Okay, the types match exactly. Nothing to do.
2630      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2631                                         ConvertedType, IncompatibleObjC)) {
2632        if (IncompatibleObjC)
2633          return false;
2634        // Okay, we have an Objective-C pointer conversion.
2635      } else
2636        // Argument types are too different. Abort.
2637        return false;
2638    }
2639    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2640                                                         ToFunctionType))
2641      return false;
2642 
2643    ConvertedType = ToType;
2644    return true;
2645 }
2646 
2647 enum {
2648   ft_default,
2649   ft_different_class,
2650   ft_parameter_arity,
2651   ft_parameter_mismatch,
2652   ft_return_type,
2653   ft_qualifer_mismatch,
2654   ft_noexcept
2655 };
2656 
2657 /// Attempts to get the FunctionProtoType from a Type. Handles
2658 /// MemberFunctionPointers properly.
2659 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2660   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2661     return FPT;
2662 
2663   if (auto *MPT = FromType->getAs<MemberPointerType>())
2664     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2665 
2666   return nullptr;
2667 }
2668 
2669 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2670 /// function types.  Catches different number of parameter, mismatch in
2671 /// parameter types, and different return types.
2672 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2673                                       QualType FromType, QualType ToType) {
2674   // If either type is not valid, include no extra info.
2675   if (FromType.isNull() || ToType.isNull()) {
2676     PDiag << ft_default;
2677     return;
2678   }
2679 
2680   // Get the function type from the pointers.
2681   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2682     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2683                             *ToMember = ToType->getAs<MemberPointerType>();
2684     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2685       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2686             << QualType(FromMember->getClass(), 0);
2687       return;
2688     }
2689     FromType = FromMember->getPointeeType();
2690     ToType = ToMember->getPointeeType();
2691   }
2692 
2693   if (FromType->isPointerType())
2694     FromType = FromType->getPointeeType();
2695   if (ToType->isPointerType())
2696     ToType = ToType->getPointeeType();
2697 
2698   // Remove references.
2699   FromType = FromType.getNonReferenceType();
2700   ToType = ToType.getNonReferenceType();
2701 
2702   // Don't print extra info for non-specialized template functions.
2703   if (FromType->isInstantiationDependentType() &&
2704       !FromType->getAs<TemplateSpecializationType>()) {
2705     PDiag << ft_default;
2706     return;
2707   }
2708 
2709   // No extra info for same types.
2710   if (Context.hasSameType(FromType, ToType)) {
2711     PDiag << ft_default;
2712     return;
2713   }
2714 
2715   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2716                           *ToFunction = tryGetFunctionProtoType(ToType);
2717 
2718   // Both types need to be function types.
2719   if (!FromFunction || !ToFunction) {
2720     PDiag << ft_default;
2721     return;
2722   }
2723 
2724   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2725     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2726           << FromFunction->getNumParams();
2727     return;
2728   }
2729 
2730   // Handle different parameter types.
2731   unsigned ArgPos;
2732   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2733     PDiag << ft_parameter_mismatch << ArgPos + 1
2734           << ToFunction->getParamType(ArgPos)
2735           << FromFunction->getParamType(ArgPos);
2736     return;
2737   }
2738 
2739   // Handle different return type.
2740   if (!Context.hasSameType(FromFunction->getReturnType(),
2741                            ToFunction->getReturnType())) {
2742     PDiag << ft_return_type << ToFunction->getReturnType()
2743           << FromFunction->getReturnType();
2744     return;
2745   }
2746 
2747   unsigned FromQuals = FromFunction->getTypeQuals(),
2748            ToQuals = ToFunction->getTypeQuals();
2749   if (FromQuals != ToQuals) {
2750     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2751     return;
2752   }
2753 
2754   // Handle exception specification differences on canonical type (in C++17
2755   // onwards).
2756   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2757           ->isNothrow(Context) !=
2758       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2759           ->isNothrow(Context)) {
2760     PDiag << ft_noexcept;
2761     return;
2762   }
2763 
2764   // Unable to find a difference, so add no extra info.
2765   PDiag << ft_default;
2766 }
2767 
2768 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2769 /// for equality of their argument types. Caller has already checked that
2770 /// they have same number of arguments.  If the parameters are different,
2771 /// ArgPos will have the parameter index of the first different parameter.
2772 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2773                                       const FunctionProtoType *NewType,
2774                                       unsigned *ArgPos) {
2775   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2776                                               N = NewType->param_type_begin(),
2777                                               E = OldType->param_type_end();
2778        O && (O != E); ++O, ++N) {
2779     if (!Context.hasSameType(O->getUnqualifiedType(),
2780                              N->getUnqualifiedType())) {
2781       if (ArgPos)
2782         *ArgPos = O - OldType->param_type_begin();
2783       return false;
2784     }
2785   }
2786   return true;
2787 }
2788 
2789 /// CheckPointerConversion - Check the pointer conversion from the
2790 /// expression From to the type ToType. This routine checks for
2791 /// ambiguous or inaccessible derived-to-base pointer
2792 /// conversions for which IsPointerConversion has already returned
2793 /// true. It returns true and produces a diagnostic if there was an
2794 /// error, or returns false otherwise.
2795 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2796                                   CastKind &Kind,
2797                                   CXXCastPath& BasePath,
2798                                   bool IgnoreBaseAccess,
2799                                   bool Diagnose) {
2800   QualType FromType = From->getType();
2801   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2802 
2803   Kind = CK_BitCast;
2804 
2805   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2806       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2807           Expr::NPCK_ZeroExpression) {
2808     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2809       DiagRuntimeBehavior(From->getExprLoc(), From,
2810                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2811                             << ToType << From->getSourceRange());
2812     else if (!isUnevaluatedContext())
2813       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2814         << ToType << From->getSourceRange();
2815   }
2816   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2817     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2818       QualType FromPointeeType = FromPtrType->getPointeeType(),
2819                ToPointeeType   = ToPtrType->getPointeeType();
2820 
2821       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2822           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2823         // We must have a derived-to-base conversion. Check an
2824         // ambiguous or inaccessible conversion.
2825         unsigned InaccessibleID = 0;
2826         unsigned AmbigiousID = 0;
2827         if (Diagnose) {
2828           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2829           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2830         }
2831         if (CheckDerivedToBaseConversion(
2832                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2833                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2834                 &BasePath, IgnoreBaseAccess))
2835           return true;
2836 
2837         // The conversion was successful.
2838         Kind = CK_DerivedToBase;
2839       }
2840 
2841       if (Diagnose && !IsCStyleOrFunctionalCast &&
2842           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2843         assert(getLangOpts().MSVCCompat &&
2844                "this should only be possible with MSVCCompat!");
2845         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2846             << From->getSourceRange();
2847       }
2848     }
2849   } else if (const ObjCObjectPointerType *ToPtrType =
2850                ToType->getAs<ObjCObjectPointerType>()) {
2851     if (const ObjCObjectPointerType *FromPtrType =
2852           FromType->getAs<ObjCObjectPointerType>()) {
2853       // Objective-C++ conversions are always okay.
2854       // FIXME: We should have a different class of conversions for the
2855       // Objective-C++ implicit conversions.
2856       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2857         return false;
2858     } else if (FromType->isBlockPointerType()) {
2859       Kind = CK_BlockPointerToObjCPointerCast;
2860     } else {
2861       Kind = CK_CPointerToObjCPointerCast;
2862     }
2863   } else if (ToType->isBlockPointerType()) {
2864     if (!FromType->isBlockPointerType())
2865       Kind = CK_AnyPointerToBlockPointerCast;
2866   }
2867 
2868   // We shouldn't fall into this case unless it's valid for other
2869   // reasons.
2870   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2871     Kind = CK_NullToPointer;
2872 
2873   return false;
2874 }
2875 
2876 /// IsMemberPointerConversion - Determines whether the conversion of the
2877 /// expression From, which has the (possibly adjusted) type FromType, can be
2878 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2879 /// If so, returns true and places the converted type (that might differ from
2880 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2881 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2882                                      QualType ToType,
2883                                      bool InOverloadResolution,
2884                                      QualType &ConvertedType) {
2885   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2886   if (!ToTypePtr)
2887     return false;
2888 
2889   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2890   if (From->isNullPointerConstant(Context,
2891                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2892                                         : Expr::NPC_ValueDependentIsNull)) {
2893     ConvertedType = ToType;
2894     return true;
2895   }
2896 
2897   // Otherwise, both types have to be member pointers.
2898   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2899   if (!FromTypePtr)
2900     return false;
2901 
2902   // A pointer to member of B can be converted to a pointer to member of D,
2903   // where D is derived from B (C++ 4.11p2).
2904   QualType FromClass(FromTypePtr->getClass(), 0);
2905   QualType ToClass(ToTypePtr->getClass(), 0);
2906 
2907   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2908       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2909     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2910                                                  ToClass.getTypePtr());
2911     return true;
2912   }
2913 
2914   return false;
2915 }
2916 
2917 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2918 /// expression From to the type ToType. This routine checks for ambiguous or
2919 /// virtual or inaccessible base-to-derived member pointer conversions
2920 /// for which IsMemberPointerConversion has already returned true. It returns
2921 /// true and produces a diagnostic if there was an error, or returns false
2922 /// otherwise.
2923 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2924                                         CastKind &Kind,
2925                                         CXXCastPath &BasePath,
2926                                         bool IgnoreBaseAccess) {
2927   QualType FromType = From->getType();
2928   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2929   if (!FromPtrType) {
2930     // This must be a null pointer to member pointer conversion
2931     assert(From->isNullPointerConstant(Context,
2932                                        Expr::NPC_ValueDependentIsNull) &&
2933            "Expr must be null pointer constant!");
2934     Kind = CK_NullToMemberPointer;
2935     return false;
2936   }
2937 
2938   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2939   assert(ToPtrType && "No member pointer cast has a target type "
2940                       "that is not a member pointer.");
2941 
2942   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2943   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2944 
2945   // FIXME: What about dependent types?
2946   assert(FromClass->isRecordType() && "Pointer into non-class.");
2947   assert(ToClass->isRecordType() && "Pointer into non-class.");
2948 
2949   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2950                      /*DetectVirtual=*/true);
2951   bool DerivationOkay =
2952       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2953   assert(DerivationOkay &&
2954          "Should not have been called if derivation isn't OK.");
2955   (void)DerivationOkay;
2956 
2957   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2958                                   getUnqualifiedType())) {
2959     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2960     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2961       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2962     return true;
2963   }
2964 
2965   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2966     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2967       << FromClass << ToClass << QualType(VBase, 0)
2968       << From->getSourceRange();
2969     return true;
2970   }
2971 
2972   if (!IgnoreBaseAccess)
2973     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2974                          Paths.front(),
2975                          diag::err_downcast_from_inaccessible_base);
2976 
2977   // Must be a base to derived member conversion.
2978   BuildBasePathArray(Paths, BasePath);
2979   Kind = CK_BaseToDerivedMemberPointer;
2980   return false;
2981 }
2982 
2983 /// Determine whether the lifetime conversion between the two given
2984 /// qualifiers sets is nontrivial.
2985 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2986                                                Qualifiers ToQuals) {
2987   // Converting anything to const __unsafe_unretained is trivial.
2988   if (ToQuals.hasConst() &&
2989       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2990     return false;
2991 
2992   return true;
2993 }
2994 
2995 /// IsQualificationConversion - Determines whether the conversion from
2996 /// an rvalue of type FromType to ToType is a qualification conversion
2997 /// (C++ 4.4).
2998 ///
2999 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3000 /// when the qualification conversion involves a change in the Objective-C
3001 /// object lifetime.
3002 bool
3003 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3004                                 bool CStyle, bool &ObjCLifetimeConversion) {
3005   FromType = Context.getCanonicalType(FromType);
3006   ToType = Context.getCanonicalType(ToType);
3007   ObjCLifetimeConversion = false;
3008 
3009   // If FromType and ToType are the same type, this is not a
3010   // qualification conversion.
3011   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3012     return false;
3013 
3014   // (C++ 4.4p4):
3015   //   A conversion can add cv-qualifiers at levels other than the first
3016   //   in multi-level pointers, subject to the following rules: [...]
3017   bool PreviousToQualsIncludeConst = true;
3018   bool UnwrappedAnyPointer = false;
3019   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3020     // Within each iteration of the loop, we check the qualifiers to
3021     // determine if this still looks like a qualification
3022     // conversion. Then, if all is well, we unwrap one more level of
3023     // pointers or pointers-to-members and do it all again
3024     // until there are no more pointers or pointers-to-members left to
3025     // unwrap.
3026     UnwrappedAnyPointer = true;
3027 
3028     Qualifiers FromQuals = FromType.getQualifiers();
3029     Qualifiers ToQuals = ToType.getQualifiers();
3030 
3031     // Ignore __unaligned qualifier if this type is void.
3032     if (ToType.getUnqualifiedType()->isVoidType())
3033       FromQuals.removeUnaligned();
3034 
3035     // Objective-C ARC:
3036     //   Check Objective-C lifetime conversions.
3037     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3038         UnwrappedAnyPointer) {
3039       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3040         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3041           ObjCLifetimeConversion = true;
3042         FromQuals.removeObjCLifetime();
3043         ToQuals.removeObjCLifetime();
3044       } else {
3045         // Qualification conversions cannot cast between different
3046         // Objective-C lifetime qualifiers.
3047         return false;
3048       }
3049     }
3050 
3051     // Allow addition/removal of GC attributes but not changing GC attributes.
3052     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3053         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3054       FromQuals.removeObjCGCAttr();
3055       ToQuals.removeObjCGCAttr();
3056     }
3057 
3058     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3059     //      2,j, and similarly for volatile.
3060     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3061       return false;
3062 
3063     //   -- if the cv 1,j and cv 2,j are different, then const is in
3064     //      every cv for 0 < k < j.
3065     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3066         && !PreviousToQualsIncludeConst)
3067       return false;
3068 
3069     // Keep track of whether all prior cv-qualifiers in the "to" type
3070     // include const.
3071     PreviousToQualsIncludeConst
3072       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3073   }
3074 
3075   // We are left with FromType and ToType being the pointee types
3076   // after unwrapping the original FromType and ToType the same number
3077   // of types. If we unwrapped any pointers, and if FromType and
3078   // ToType have the same unqualified type (since we checked
3079   // qualifiers above), then this is a qualification conversion.
3080   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3081 }
3082 
3083 /// \brief - Determine whether this is a conversion from a scalar type to an
3084 /// atomic type.
3085 ///
3086 /// If successful, updates \c SCS's second and third steps in the conversion
3087 /// sequence to finish the conversion.
3088 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3089                                 bool InOverloadResolution,
3090                                 StandardConversionSequence &SCS,
3091                                 bool CStyle) {
3092   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3093   if (!ToAtomic)
3094     return false;
3095 
3096   StandardConversionSequence InnerSCS;
3097   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3098                             InOverloadResolution, InnerSCS,
3099                             CStyle, /*AllowObjCWritebackConversion=*/false))
3100     return false;
3101 
3102   SCS.Second = InnerSCS.Second;
3103   SCS.setToType(1, InnerSCS.getToType(1));
3104   SCS.Third = InnerSCS.Third;
3105   SCS.QualificationIncludesObjCLifetime
3106     = InnerSCS.QualificationIncludesObjCLifetime;
3107   SCS.setToType(2, InnerSCS.getToType(2));
3108   return true;
3109 }
3110 
3111 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3112                                               CXXConstructorDecl *Constructor,
3113                                               QualType Type) {
3114   const FunctionProtoType *CtorType =
3115       Constructor->getType()->getAs<FunctionProtoType>();
3116   if (CtorType->getNumParams() > 0) {
3117     QualType FirstArg = CtorType->getParamType(0);
3118     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3119       return true;
3120   }
3121   return false;
3122 }
3123 
3124 static OverloadingResult
3125 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3126                                        CXXRecordDecl *To,
3127                                        UserDefinedConversionSequence &User,
3128                                        OverloadCandidateSet &CandidateSet,
3129                                        bool AllowExplicit) {
3130   for (auto *D : S.LookupConstructors(To)) {
3131     auto Info = getConstructorInfo(D);
3132     if (!Info)
3133       continue;
3134 
3135     bool Usable = !Info.Constructor->isInvalidDecl() &&
3136                   S.isInitListConstructor(Info.Constructor) &&
3137                   (AllowExplicit || !Info.Constructor->isExplicit());
3138     if (Usable) {
3139       // If the first argument is (a reference to) the target type,
3140       // suppress conversions.
3141       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3142           S.Context, Info.Constructor, ToType);
3143       if (Info.ConstructorTmpl)
3144         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3145                                        /*ExplicitArgs*/ nullptr, From,
3146                                        CandidateSet, SuppressUserConversions);
3147       else
3148         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3149                                CandidateSet, SuppressUserConversions);
3150     }
3151   }
3152 
3153   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3154 
3155   OverloadCandidateSet::iterator Best;
3156   switch (auto Result =
3157             CandidateSet.BestViableFunction(S, From->getLocStart(),
3158                                             Best, true)) {
3159   case OR_Deleted:
3160   case OR_Success: {
3161     // Record the standard conversion we used and the conversion function.
3162     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3163     QualType ThisType = Constructor->getThisType(S.Context);
3164     // Initializer lists don't have conversions as such.
3165     User.Before.setAsIdentityConversion();
3166     User.HadMultipleCandidates = HadMultipleCandidates;
3167     User.ConversionFunction = Constructor;
3168     User.FoundConversionFunction = Best->FoundDecl;
3169     User.After.setAsIdentityConversion();
3170     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3171     User.After.setAllToTypes(ToType);
3172     return Result;
3173   }
3174 
3175   case OR_No_Viable_Function:
3176     return OR_No_Viable_Function;
3177   case OR_Ambiguous:
3178     return OR_Ambiguous;
3179   }
3180 
3181   llvm_unreachable("Invalid OverloadResult!");
3182 }
3183 
3184 /// Determines whether there is a user-defined conversion sequence
3185 /// (C++ [over.ics.user]) that converts expression From to the type
3186 /// ToType. If such a conversion exists, User will contain the
3187 /// user-defined conversion sequence that performs such a conversion
3188 /// and this routine will return true. Otherwise, this routine returns
3189 /// false and User is unspecified.
3190 ///
3191 /// \param AllowExplicit  true if the conversion should consider C++0x
3192 /// "explicit" conversion functions as well as non-explicit conversion
3193 /// functions (C++0x [class.conv.fct]p2).
3194 ///
3195 /// \param AllowObjCConversionOnExplicit true if the conversion should
3196 /// allow an extra Objective-C pointer conversion on uses of explicit
3197 /// constructors. Requires \c AllowExplicit to also be set.
3198 static OverloadingResult
3199 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3200                         UserDefinedConversionSequence &User,
3201                         OverloadCandidateSet &CandidateSet,
3202                         bool AllowExplicit,
3203                         bool AllowObjCConversionOnExplicit) {
3204   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3205 
3206   // Whether we will only visit constructors.
3207   bool ConstructorsOnly = false;
3208 
3209   // If the type we are conversion to is a class type, enumerate its
3210   // constructors.
3211   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3212     // C++ [over.match.ctor]p1:
3213     //   When objects of class type are direct-initialized (8.5), or
3214     //   copy-initialized from an expression of the same or a
3215     //   derived class type (8.5), overload resolution selects the
3216     //   constructor. [...] For copy-initialization, the candidate
3217     //   functions are all the converting constructors (12.3.1) of
3218     //   that class. The argument list is the expression-list within
3219     //   the parentheses of the initializer.
3220     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3221         (From->getType()->getAs<RecordType>() &&
3222          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3223       ConstructorsOnly = true;
3224 
3225     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3226       // We're not going to find any constructors.
3227     } else if (CXXRecordDecl *ToRecordDecl
3228                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3229 
3230       Expr **Args = &From;
3231       unsigned NumArgs = 1;
3232       bool ListInitializing = false;
3233       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3234         // But first, see if there is an init-list-constructor that will work.
3235         OverloadingResult Result = IsInitializerListConstructorConversion(
3236             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3237         if (Result != OR_No_Viable_Function)
3238           return Result;
3239         // Never mind.
3240         CandidateSet.clear();
3241 
3242         // If we're list-initializing, we pass the individual elements as
3243         // arguments, not the entire list.
3244         Args = InitList->getInits();
3245         NumArgs = InitList->getNumInits();
3246         ListInitializing = true;
3247       }
3248 
3249       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3250         auto Info = getConstructorInfo(D);
3251         if (!Info)
3252           continue;
3253 
3254         bool Usable = !Info.Constructor->isInvalidDecl();
3255         if (ListInitializing)
3256           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3257         else
3258           Usable = Usable &&
3259                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3260         if (Usable) {
3261           bool SuppressUserConversions = !ConstructorsOnly;
3262           if (SuppressUserConversions && ListInitializing) {
3263             SuppressUserConversions = false;
3264             if (NumArgs == 1) {
3265               // If the first argument is (a reference to) the target type,
3266               // suppress conversions.
3267               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3268                   S.Context, Info.Constructor, ToType);
3269             }
3270           }
3271           if (Info.ConstructorTmpl)
3272             S.AddTemplateOverloadCandidate(
3273                 Info.ConstructorTmpl, Info.FoundDecl,
3274                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3275                 CandidateSet, SuppressUserConversions);
3276           else
3277             // Allow one user-defined conversion when user specifies a
3278             // From->ToType conversion via an static cast (c-style, etc).
3279             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3280                                    llvm::makeArrayRef(Args, NumArgs),
3281                                    CandidateSet, SuppressUserConversions);
3282         }
3283       }
3284     }
3285   }
3286 
3287   // Enumerate conversion functions, if we're allowed to.
3288   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3289   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3290     // No conversion functions from incomplete types.
3291   } else if (const RecordType *FromRecordType
3292                                    = From->getType()->getAs<RecordType>()) {
3293     if (CXXRecordDecl *FromRecordDecl
3294          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3295       // Add all of the conversion functions as candidates.
3296       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3297       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3298         DeclAccessPair FoundDecl = I.getPair();
3299         NamedDecl *D = FoundDecl.getDecl();
3300         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3301         if (isa<UsingShadowDecl>(D))
3302           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3303 
3304         CXXConversionDecl *Conv;
3305         FunctionTemplateDecl *ConvTemplate;
3306         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3307           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3308         else
3309           Conv = cast<CXXConversionDecl>(D);
3310 
3311         if (AllowExplicit || !Conv->isExplicit()) {
3312           if (ConvTemplate)
3313             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3314                                              ActingContext, From, ToType,
3315                                              CandidateSet,
3316                                              AllowObjCConversionOnExplicit);
3317           else
3318             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3319                                      From, ToType, CandidateSet,
3320                                      AllowObjCConversionOnExplicit);
3321         }
3322       }
3323     }
3324   }
3325 
3326   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3327 
3328   OverloadCandidateSet::iterator Best;
3329   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3330                                                         Best, true)) {
3331   case OR_Success:
3332   case OR_Deleted:
3333     // Record the standard conversion we used and the conversion function.
3334     if (CXXConstructorDecl *Constructor
3335           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3336       // C++ [over.ics.user]p1:
3337       //   If the user-defined conversion is specified by a
3338       //   constructor (12.3.1), the initial standard conversion
3339       //   sequence converts the source type to the type required by
3340       //   the argument of the constructor.
3341       //
3342       QualType ThisType = Constructor->getThisType(S.Context);
3343       if (isa<InitListExpr>(From)) {
3344         // Initializer lists don't have conversions as such.
3345         User.Before.setAsIdentityConversion();
3346       } else {
3347         if (Best->Conversions[0].isEllipsis())
3348           User.EllipsisConversion = true;
3349         else {
3350           User.Before = Best->Conversions[0].Standard;
3351           User.EllipsisConversion = false;
3352         }
3353       }
3354       User.HadMultipleCandidates = HadMultipleCandidates;
3355       User.ConversionFunction = Constructor;
3356       User.FoundConversionFunction = Best->FoundDecl;
3357       User.After.setAsIdentityConversion();
3358       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3359       User.After.setAllToTypes(ToType);
3360       return Result;
3361     }
3362     if (CXXConversionDecl *Conversion
3363                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3364       // C++ [over.ics.user]p1:
3365       //
3366       //   [...] If the user-defined conversion is specified by a
3367       //   conversion function (12.3.2), the initial standard
3368       //   conversion sequence converts the source type to the
3369       //   implicit object parameter of the conversion function.
3370       User.Before = Best->Conversions[0].Standard;
3371       User.HadMultipleCandidates = HadMultipleCandidates;
3372       User.ConversionFunction = Conversion;
3373       User.FoundConversionFunction = Best->FoundDecl;
3374       User.EllipsisConversion = false;
3375 
3376       // C++ [over.ics.user]p2:
3377       //   The second standard conversion sequence converts the
3378       //   result of the user-defined conversion to the target type
3379       //   for the sequence. Since an implicit conversion sequence
3380       //   is an initialization, the special rules for
3381       //   initialization by user-defined conversion apply when
3382       //   selecting the best user-defined conversion for a
3383       //   user-defined conversion sequence (see 13.3.3 and
3384       //   13.3.3.1).
3385       User.After = Best->FinalConversion;
3386       return Result;
3387     }
3388     llvm_unreachable("Not a constructor or conversion function?");
3389 
3390   case OR_No_Viable_Function:
3391     return OR_No_Viable_Function;
3392 
3393   case OR_Ambiguous:
3394     return OR_Ambiguous;
3395   }
3396 
3397   llvm_unreachable("Invalid OverloadResult!");
3398 }
3399 
3400 bool
3401 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3402   ImplicitConversionSequence ICS;
3403   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3404                                     OverloadCandidateSet::CSK_Normal);
3405   OverloadingResult OvResult =
3406     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3407                             CandidateSet, false, false);
3408   if (OvResult == OR_Ambiguous)
3409     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3410         << From->getType() << ToType << From->getSourceRange();
3411   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3412     if (!RequireCompleteType(From->getLocStart(), ToType,
3413                              diag::err_typecheck_nonviable_condition_incomplete,
3414                              From->getType(), From->getSourceRange()))
3415       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3416           << false << From->getType() << From->getSourceRange() << ToType;
3417   } else
3418     return false;
3419   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3420   return true;
3421 }
3422 
3423 /// \brief Compare the user-defined conversion functions or constructors
3424 /// of two user-defined conversion sequences to determine whether any ordering
3425 /// is possible.
3426 static ImplicitConversionSequence::CompareKind
3427 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3428                            FunctionDecl *Function2) {
3429   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3430     return ImplicitConversionSequence::Indistinguishable;
3431 
3432   // Objective-C++:
3433   //   If both conversion functions are implicitly-declared conversions from
3434   //   a lambda closure type to a function pointer and a block pointer,
3435   //   respectively, always prefer the conversion to a function pointer,
3436   //   because the function pointer is more lightweight and is more likely
3437   //   to keep code working.
3438   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3439   if (!Conv1)
3440     return ImplicitConversionSequence::Indistinguishable;
3441 
3442   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3443   if (!Conv2)
3444     return ImplicitConversionSequence::Indistinguishable;
3445 
3446   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3447     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3448     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3449     if (Block1 != Block2)
3450       return Block1 ? ImplicitConversionSequence::Worse
3451                     : ImplicitConversionSequence::Better;
3452   }
3453 
3454   return ImplicitConversionSequence::Indistinguishable;
3455 }
3456 
3457 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3458     const ImplicitConversionSequence &ICS) {
3459   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3460          (ICS.isUserDefined() &&
3461           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3462 }
3463 
3464 /// CompareImplicitConversionSequences - Compare two implicit
3465 /// conversion sequences to determine whether one is better than the
3466 /// other or if they are indistinguishable (C++ 13.3.3.2).
3467 static ImplicitConversionSequence::CompareKind
3468 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3469                                    const ImplicitConversionSequence& ICS1,
3470                                    const ImplicitConversionSequence& ICS2)
3471 {
3472   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3473   // conversion sequences (as defined in 13.3.3.1)
3474   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3475   //      conversion sequence than a user-defined conversion sequence or
3476   //      an ellipsis conversion sequence, and
3477   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3478   //      conversion sequence than an ellipsis conversion sequence
3479   //      (13.3.3.1.3).
3480   //
3481   // C++0x [over.best.ics]p10:
3482   //   For the purpose of ranking implicit conversion sequences as
3483   //   described in 13.3.3.2, the ambiguous conversion sequence is
3484   //   treated as a user-defined sequence that is indistinguishable
3485   //   from any other user-defined conversion sequence.
3486 
3487   // String literal to 'char *' conversion has been deprecated in C++03. It has
3488   // been removed from C++11. We still accept this conversion, if it happens at
3489   // the best viable function. Otherwise, this conversion is considered worse
3490   // than ellipsis conversion. Consider this as an extension; this is not in the
3491   // standard. For example:
3492   //
3493   // int &f(...);    // #1
3494   // void f(char*);  // #2
3495   // void g() { int &r = f("foo"); }
3496   //
3497   // In C++03, we pick #2 as the best viable function.
3498   // In C++11, we pick #1 as the best viable function, because ellipsis
3499   // conversion is better than string-literal to char* conversion (since there
3500   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3501   // convert arguments, #2 would be the best viable function in C++11.
3502   // If the best viable function has this conversion, a warning will be issued
3503   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3504 
3505   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3506       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3507       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3508     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3509                ? ImplicitConversionSequence::Worse
3510                : ImplicitConversionSequence::Better;
3511 
3512   if (ICS1.getKindRank() < ICS2.getKindRank())
3513     return ImplicitConversionSequence::Better;
3514   if (ICS2.getKindRank() < ICS1.getKindRank())
3515     return ImplicitConversionSequence::Worse;
3516 
3517   // The following checks require both conversion sequences to be of
3518   // the same kind.
3519   if (ICS1.getKind() != ICS2.getKind())
3520     return ImplicitConversionSequence::Indistinguishable;
3521 
3522   ImplicitConversionSequence::CompareKind Result =
3523       ImplicitConversionSequence::Indistinguishable;
3524 
3525   // Two implicit conversion sequences of the same form are
3526   // indistinguishable conversion sequences unless one of the
3527   // following rules apply: (C++ 13.3.3.2p3):
3528 
3529   // List-initialization sequence L1 is a better conversion sequence than
3530   // list-initialization sequence L2 if:
3531   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3532   //   if not that,
3533   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3534   //   and N1 is smaller than N2.,
3535   // even if one of the other rules in this paragraph would otherwise apply.
3536   if (!ICS1.isBad()) {
3537     if (ICS1.isStdInitializerListElement() &&
3538         !ICS2.isStdInitializerListElement())
3539       return ImplicitConversionSequence::Better;
3540     if (!ICS1.isStdInitializerListElement() &&
3541         ICS2.isStdInitializerListElement())
3542       return ImplicitConversionSequence::Worse;
3543   }
3544 
3545   if (ICS1.isStandard())
3546     // Standard conversion sequence S1 is a better conversion sequence than
3547     // standard conversion sequence S2 if [...]
3548     Result = CompareStandardConversionSequences(S, Loc,
3549                                                 ICS1.Standard, ICS2.Standard);
3550   else if (ICS1.isUserDefined()) {
3551     // User-defined conversion sequence U1 is a better conversion
3552     // sequence than another user-defined conversion sequence U2 if
3553     // they contain the same user-defined conversion function or
3554     // constructor and if the second standard conversion sequence of
3555     // U1 is better than the second standard conversion sequence of
3556     // U2 (C++ 13.3.3.2p3).
3557     if (ICS1.UserDefined.ConversionFunction ==
3558           ICS2.UserDefined.ConversionFunction)
3559       Result = CompareStandardConversionSequences(S, Loc,
3560                                                   ICS1.UserDefined.After,
3561                                                   ICS2.UserDefined.After);
3562     else
3563       Result = compareConversionFunctions(S,
3564                                           ICS1.UserDefined.ConversionFunction,
3565                                           ICS2.UserDefined.ConversionFunction);
3566   }
3567 
3568   return Result;
3569 }
3570 
3571 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3572   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3573     Qualifiers Quals;
3574     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3575     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3576   }
3577 
3578   return Context.hasSameUnqualifiedType(T1, T2);
3579 }
3580 
3581 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3582 // determine if one is a proper subset of the other.
3583 static ImplicitConversionSequence::CompareKind
3584 compareStandardConversionSubsets(ASTContext &Context,
3585                                  const StandardConversionSequence& SCS1,
3586                                  const StandardConversionSequence& SCS2) {
3587   ImplicitConversionSequence::CompareKind Result
3588     = ImplicitConversionSequence::Indistinguishable;
3589 
3590   // the identity conversion sequence is considered to be a subsequence of
3591   // any non-identity conversion sequence
3592   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3593     return ImplicitConversionSequence::Better;
3594   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3595     return ImplicitConversionSequence::Worse;
3596 
3597   if (SCS1.Second != SCS2.Second) {
3598     if (SCS1.Second == ICK_Identity)
3599       Result = ImplicitConversionSequence::Better;
3600     else if (SCS2.Second == ICK_Identity)
3601       Result = ImplicitConversionSequence::Worse;
3602     else
3603       return ImplicitConversionSequence::Indistinguishable;
3604   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3605     return ImplicitConversionSequence::Indistinguishable;
3606 
3607   if (SCS1.Third == SCS2.Third) {
3608     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3609                              : ImplicitConversionSequence::Indistinguishable;
3610   }
3611 
3612   if (SCS1.Third == ICK_Identity)
3613     return Result == ImplicitConversionSequence::Worse
3614              ? ImplicitConversionSequence::Indistinguishable
3615              : ImplicitConversionSequence::Better;
3616 
3617   if (SCS2.Third == ICK_Identity)
3618     return Result == ImplicitConversionSequence::Better
3619              ? ImplicitConversionSequence::Indistinguishable
3620              : ImplicitConversionSequence::Worse;
3621 
3622   return ImplicitConversionSequence::Indistinguishable;
3623 }
3624 
3625 /// \brief Determine whether one of the given reference bindings is better
3626 /// than the other based on what kind of bindings they are.
3627 static bool
3628 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3629                              const StandardConversionSequence &SCS2) {
3630   // C++0x [over.ics.rank]p3b4:
3631   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3632   //      implicit object parameter of a non-static member function declared
3633   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3634   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3635   //      lvalue reference to a function lvalue and S2 binds an rvalue
3636   //      reference*.
3637   //
3638   // FIXME: Rvalue references. We're going rogue with the above edits,
3639   // because the semantics in the current C++0x working paper (N3225 at the
3640   // time of this writing) break the standard definition of std::forward
3641   // and std::reference_wrapper when dealing with references to functions.
3642   // Proposed wording changes submitted to CWG for consideration.
3643   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3644       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3645     return false;
3646 
3647   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3648           SCS2.IsLvalueReference) ||
3649          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3650           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3651 }
3652 
3653 /// CompareStandardConversionSequences - Compare two standard
3654 /// conversion sequences to determine whether one is better than the
3655 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3656 static ImplicitConversionSequence::CompareKind
3657 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3658                                    const StandardConversionSequence& SCS1,
3659                                    const StandardConversionSequence& SCS2)
3660 {
3661   // Standard conversion sequence S1 is a better conversion sequence
3662   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3663 
3664   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3665   //     sequences in the canonical form defined by 13.3.3.1.1,
3666   //     excluding any Lvalue Transformation; the identity conversion
3667   //     sequence is considered to be a subsequence of any
3668   //     non-identity conversion sequence) or, if not that,
3669   if (ImplicitConversionSequence::CompareKind CK
3670         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3671     return CK;
3672 
3673   //  -- the rank of S1 is better than the rank of S2 (by the rules
3674   //     defined below), or, if not that,
3675   ImplicitConversionRank Rank1 = SCS1.getRank();
3676   ImplicitConversionRank Rank2 = SCS2.getRank();
3677   if (Rank1 < Rank2)
3678     return ImplicitConversionSequence::Better;
3679   else if (Rank2 < Rank1)
3680     return ImplicitConversionSequence::Worse;
3681 
3682   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3683   // are indistinguishable unless one of the following rules
3684   // applies:
3685 
3686   //   A conversion that is not a conversion of a pointer, or
3687   //   pointer to member, to bool is better than another conversion
3688   //   that is such a conversion.
3689   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3690     return SCS2.isPointerConversionToBool()
3691              ? ImplicitConversionSequence::Better
3692              : ImplicitConversionSequence::Worse;
3693 
3694   // C++ [over.ics.rank]p4b2:
3695   //
3696   //   If class B is derived directly or indirectly from class A,
3697   //   conversion of B* to A* is better than conversion of B* to
3698   //   void*, and conversion of A* to void* is better than conversion
3699   //   of B* to void*.
3700   bool SCS1ConvertsToVoid
3701     = SCS1.isPointerConversionToVoidPointer(S.Context);
3702   bool SCS2ConvertsToVoid
3703     = SCS2.isPointerConversionToVoidPointer(S.Context);
3704   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3705     // Exactly one of the conversion sequences is a conversion to
3706     // a void pointer; it's the worse conversion.
3707     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3708                               : ImplicitConversionSequence::Worse;
3709   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3710     // Neither conversion sequence converts to a void pointer; compare
3711     // their derived-to-base conversions.
3712     if (ImplicitConversionSequence::CompareKind DerivedCK
3713           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3714       return DerivedCK;
3715   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3716              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3717     // Both conversion sequences are conversions to void
3718     // pointers. Compare the source types to determine if there's an
3719     // inheritance relationship in their sources.
3720     QualType FromType1 = SCS1.getFromType();
3721     QualType FromType2 = SCS2.getFromType();
3722 
3723     // Adjust the types we're converting from via the array-to-pointer
3724     // conversion, if we need to.
3725     if (SCS1.First == ICK_Array_To_Pointer)
3726       FromType1 = S.Context.getArrayDecayedType(FromType1);
3727     if (SCS2.First == ICK_Array_To_Pointer)
3728       FromType2 = S.Context.getArrayDecayedType(FromType2);
3729 
3730     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3731     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3732 
3733     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3734       return ImplicitConversionSequence::Better;
3735     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3736       return ImplicitConversionSequence::Worse;
3737 
3738     // Objective-C++: If one interface is more specific than the
3739     // other, it is the better one.
3740     const ObjCObjectPointerType* FromObjCPtr1
3741       = FromType1->getAs<ObjCObjectPointerType>();
3742     const ObjCObjectPointerType* FromObjCPtr2
3743       = FromType2->getAs<ObjCObjectPointerType>();
3744     if (FromObjCPtr1 && FromObjCPtr2) {
3745       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3746                                                           FromObjCPtr2);
3747       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3748                                                            FromObjCPtr1);
3749       if (AssignLeft != AssignRight) {
3750         return AssignLeft? ImplicitConversionSequence::Better
3751                          : ImplicitConversionSequence::Worse;
3752       }
3753     }
3754   }
3755 
3756   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3757   // bullet 3).
3758   if (ImplicitConversionSequence::CompareKind QualCK
3759         = CompareQualificationConversions(S, SCS1, SCS2))
3760     return QualCK;
3761 
3762   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3763     // Check for a better reference binding based on the kind of bindings.
3764     if (isBetterReferenceBindingKind(SCS1, SCS2))
3765       return ImplicitConversionSequence::Better;
3766     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3767       return ImplicitConversionSequence::Worse;
3768 
3769     // C++ [over.ics.rank]p3b4:
3770     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3771     //      which the references refer are the same type except for
3772     //      top-level cv-qualifiers, and the type to which the reference
3773     //      initialized by S2 refers is more cv-qualified than the type
3774     //      to which the reference initialized by S1 refers.
3775     QualType T1 = SCS1.getToType(2);
3776     QualType T2 = SCS2.getToType(2);
3777     T1 = S.Context.getCanonicalType(T1);
3778     T2 = S.Context.getCanonicalType(T2);
3779     Qualifiers T1Quals, T2Quals;
3780     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3781     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3782     if (UnqualT1 == UnqualT2) {
3783       // Objective-C++ ARC: If the references refer to objects with different
3784       // lifetimes, prefer bindings that don't change lifetime.
3785       if (SCS1.ObjCLifetimeConversionBinding !=
3786                                           SCS2.ObjCLifetimeConversionBinding) {
3787         return SCS1.ObjCLifetimeConversionBinding
3788                                            ? ImplicitConversionSequence::Worse
3789                                            : ImplicitConversionSequence::Better;
3790       }
3791 
3792       // If the type is an array type, promote the element qualifiers to the
3793       // type for comparison.
3794       if (isa<ArrayType>(T1) && T1Quals)
3795         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3796       if (isa<ArrayType>(T2) && T2Quals)
3797         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3798       if (T2.isMoreQualifiedThan(T1))
3799         return ImplicitConversionSequence::Better;
3800       else if (T1.isMoreQualifiedThan(T2))
3801         return ImplicitConversionSequence::Worse;
3802     }
3803   }
3804 
3805   // In Microsoft mode, prefer an integral conversion to a
3806   // floating-to-integral conversion if the integral conversion
3807   // is between types of the same size.
3808   // For example:
3809   // void f(float);
3810   // void f(int);
3811   // int main {
3812   //    long a;
3813   //    f(a);
3814   // }
3815   // Here, MSVC will call f(int) instead of generating a compile error
3816   // as clang will do in standard mode.
3817   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3818       SCS2.Second == ICK_Floating_Integral &&
3819       S.Context.getTypeSize(SCS1.getFromType()) ==
3820           S.Context.getTypeSize(SCS1.getToType(2)))
3821     return ImplicitConversionSequence::Better;
3822 
3823   return ImplicitConversionSequence::Indistinguishable;
3824 }
3825 
3826 /// CompareQualificationConversions - Compares two standard conversion
3827 /// sequences to determine whether they can be ranked based on their
3828 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3829 static ImplicitConversionSequence::CompareKind
3830 CompareQualificationConversions(Sema &S,
3831                                 const StandardConversionSequence& SCS1,
3832                                 const StandardConversionSequence& SCS2) {
3833   // C++ 13.3.3.2p3:
3834   //  -- S1 and S2 differ only in their qualification conversion and
3835   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3836   //     cv-qualification signature of type T1 is a proper subset of
3837   //     the cv-qualification signature of type T2, and S1 is not the
3838   //     deprecated string literal array-to-pointer conversion (4.2).
3839   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3840       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3841     return ImplicitConversionSequence::Indistinguishable;
3842 
3843   // FIXME: the example in the standard doesn't use a qualification
3844   // conversion (!)
3845   QualType T1 = SCS1.getToType(2);
3846   QualType T2 = SCS2.getToType(2);
3847   T1 = S.Context.getCanonicalType(T1);
3848   T2 = S.Context.getCanonicalType(T2);
3849   Qualifiers T1Quals, T2Quals;
3850   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3851   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3852 
3853   // If the types are the same, we won't learn anything by unwrapped
3854   // them.
3855   if (UnqualT1 == UnqualT2)
3856     return ImplicitConversionSequence::Indistinguishable;
3857 
3858   // If the type is an array type, promote the element qualifiers to the type
3859   // for comparison.
3860   if (isa<ArrayType>(T1) && T1Quals)
3861     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3862   if (isa<ArrayType>(T2) && T2Quals)
3863     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3864 
3865   ImplicitConversionSequence::CompareKind Result
3866     = ImplicitConversionSequence::Indistinguishable;
3867 
3868   // Objective-C++ ARC:
3869   //   Prefer qualification conversions not involving a change in lifetime
3870   //   to qualification conversions that do not change lifetime.
3871   if (SCS1.QualificationIncludesObjCLifetime !=
3872                                       SCS2.QualificationIncludesObjCLifetime) {
3873     Result = SCS1.QualificationIncludesObjCLifetime
3874                ? ImplicitConversionSequence::Worse
3875                : ImplicitConversionSequence::Better;
3876   }
3877 
3878   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3879     // Within each iteration of the loop, we check the qualifiers to
3880     // determine if this still looks like a qualification
3881     // conversion. Then, if all is well, we unwrap one more level of
3882     // pointers or pointers-to-members and do it all again
3883     // until there are no more pointers or pointers-to-members left
3884     // to unwrap. This essentially mimics what
3885     // IsQualificationConversion does, but here we're checking for a
3886     // strict subset of qualifiers.
3887     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3888       // The qualifiers are the same, so this doesn't tell us anything
3889       // about how the sequences rank.
3890       ;
3891     else if (T2.isMoreQualifiedThan(T1)) {
3892       // T1 has fewer qualifiers, so it could be the better sequence.
3893       if (Result == ImplicitConversionSequence::Worse)
3894         // Neither has qualifiers that are a subset of the other's
3895         // qualifiers.
3896         return ImplicitConversionSequence::Indistinguishable;
3897 
3898       Result = ImplicitConversionSequence::Better;
3899     } else if (T1.isMoreQualifiedThan(T2)) {
3900       // T2 has fewer qualifiers, so it could be the better sequence.
3901       if (Result == ImplicitConversionSequence::Better)
3902         // Neither has qualifiers that are a subset of the other's
3903         // qualifiers.
3904         return ImplicitConversionSequence::Indistinguishable;
3905 
3906       Result = ImplicitConversionSequence::Worse;
3907     } else {
3908       // Qualifiers are disjoint.
3909       return ImplicitConversionSequence::Indistinguishable;
3910     }
3911 
3912     // If the types after this point are equivalent, we're done.
3913     if (S.Context.hasSameUnqualifiedType(T1, T2))
3914       break;
3915   }
3916 
3917   // Check that the winning standard conversion sequence isn't using
3918   // the deprecated string literal array to pointer conversion.
3919   switch (Result) {
3920   case ImplicitConversionSequence::Better:
3921     if (SCS1.DeprecatedStringLiteralToCharPtr)
3922       Result = ImplicitConversionSequence::Indistinguishable;
3923     break;
3924 
3925   case ImplicitConversionSequence::Indistinguishable:
3926     break;
3927 
3928   case ImplicitConversionSequence::Worse:
3929     if (SCS2.DeprecatedStringLiteralToCharPtr)
3930       Result = ImplicitConversionSequence::Indistinguishable;
3931     break;
3932   }
3933 
3934   return Result;
3935 }
3936 
3937 /// CompareDerivedToBaseConversions - Compares two standard conversion
3938 /// sequences to determine whether they can be ranked based on their
3939 /// various kinds of derived-to-base conversions (C++
3940 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3941 /// conversions between Objective-C interface types.
3942 static ImplicitConversionSequence::CompareKind
3943 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3944                                 const StandardConversionSequence& SCS1,
3945                                 const StandardConversionSequence& SCS2) {
3946   QualType FromType1 = SCS1.getFromType();
3947   QualType ToType1 = SCS1.getToType(1);
3948   QualType FromType2 = SCS2.getFromType();
3949   QualType ToType2 = SCS2.getToType(1);
3950 
3951   // Adjust the types we're converting from via the array-to-pointer
3952   // conversion, if we need to.
3953   if (SCS1.First == ICK_Array_To_Pointer)
3954     FromType1 = S.Context.getArrayDecayedType(FromType1);
3955   if (SCS2.First == ICK_Array_To_Pointer)
3956     FromType2 = S.Context.getArrayDecayedType(FromType2);
3957 
3958   // Canonicalize all of the types.
3959   FromType1 = S.Context.getCanonicalType(FromType1);
3960   ToType1 = S.Context.getCanonicalType(ToType1);
3961   FromType2 = S.Context.getCanonicalType(FromType2);
3962   ToType2 = S.Context.getCanonicalType(ToType2);
3963 
3964   // C++ [over.ics.rank]p4b3:
3965   //
3966   //   If class B is derived directly or indirectly from class A and
3967   //   class C is derived directly or indirectly from B,
3968   //
3969   // Compare based on pointer conversions.
3970   if (SCS1.Second == ICK_Pointer_Conversion &&
3971       SCS2.Second == ICK_Pointer_Conversion &&
3972       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3973       FromType1->isPointerType() && FromType2->isPointerType() &&
3974       ToType1->isPointerType() && ToType2->isPointerType()) {
3975     QualType FromPointee1
3976       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3977     QualType ToPointee1
3978       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3979     QualType FromPointee2
3980       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3981     QualType ToPointee2
3982       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3983 
3984     //   -- conversion of C* to B* is better than conversion of C* to A*,
3985     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3986       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3987         return ImplicitConversionSequence::Better;
3988       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3989         return ImplicitConversionSequence::Worse;
3990     }
3991 
3992     //   -- conversion of B* to A* is better than conversion of C* to A*,
3993     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3994       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3995         return ImplicitConversionSequence::Better;
3996       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3997         return ImplicitConversionSequence::Worse;
3998     }
3999   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4000              SCS2.Second == ICK_Pointer_Conversion) {
4001     const ObjCObjectPointerType *FromPtr1
4002       = FromType1->getAs<ObjCObjectPointerType>();
4003     const ObjCObjectPointerType *FromPtr2
4004       = FromType2->getAs<ObjCObjectPointerType>();
4005     const ObjCObjectPointerType *ToPtr1
4006       = ToType1->getAs<ObjCObjectPointerType>();
4007     const ObjCObjectPointerType *ToPtr2
4008       = ToType2->getAs<ObjCObjectPointerType>();
4009 
4010     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4011       // Apply the same conversion ranking rules for Objective-C pointer types
4012       // that we do for C++ pointers to class types. However, we employ the
4013       // Objective-C pseudo-subtyping relationship used for assignment of
4014       // Objective-C pointer types.
4015       bool FromAssignLeft
4016         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4017       bool FromAssignRight
4018         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4019       bool ToAssignLeft
4020         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4021       bool ToAssignRight
4022         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4023 
4024       // A conversion to an a non-id object pointer type or qualified 'id'
4025       // type is better than a conversion to 'id'.
4026       if (ToPtr1->isObjCIdType() &&
4027           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4028         return ImplicitConversionSequence::Worse;
4029       if (ToPtr2->isObjCIdType() &&
4030           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4031         return ImplicitConversionSequence::Better;
4032 
4033       // A conversion to a non-id object pointer type is better than a
4034       // conversion to a qualified 'id' type
4035       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4036         return ImplicitConversionSequence::Worse;
4037       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4038         return ImplicitConversionSequence::Better;
4039 
4040       // A conversion to an a non-Class object pointer type or qualified 'Class'
4041       // type is better than a conversion to 'Class'.
4042       if (ToPtr1->isObjCClassType() &&
4043           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4044         return ImplicitConversionSequence::Worse;
4045       if (ToPtr2->isObjCClassType() &&
4046           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4047         return ImplicitConversionSequence::Better;
4048 
4049       // A conversion to a non-Class object pointer type is better than a
4050       // conversion to a qualified 'Class' type.
4051       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4052         return ImplicitConversionSequence::Worse;
4053       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4054         return ImplicitConversionSequence::Better;
4055 
4056       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4057       if (S.Context.hasSameType(FromType1, FromType2) &&
4058           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4059           (ToAssignLeft != ToAssignRight))
4060         return ToAssignLeft? ImplicitConversionSequence::Worse
4061                            : ImplicitConversionSequence::Better;
4062 
4063       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4064       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4065           (FromAssignLeft != FromAssignRight))
4066         return FromAssignLeft? ImplicitConversionSequence::Better
4067         : ImplicitConversionSequence::Worse;
4068     }
4069   }
4070 
4071   // Ranking of member-pointer types.
4072   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4073       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4074       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4075     const MemberPointerType * FromMemPointer1 =
4076                                         FromType1->getAs<MemberPointerType>();
4077     const MemberPointerType * ToMemPointer1 =
4078                                           ToType1->getAs<MemberPointerType>();
4079     const MemberPointerType * FromMemPointer2 =
4080                                           FromType2->getAs<MemberPointerType>();
4081     const MemberPointerType * ToMemPointer2 =
4082                                           ToType2->getAs<MemberPointerType>();
4083     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4084     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4085     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4086     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4087     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4088     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4089     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4090     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4091     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4092     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4093       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4094         return ImplicitConversionSequence::Worse;
4095       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4096         return ImplicitConversionSequence::Better;
4097     }
4098     // conversion of B::* to C::* is better than conversion of A::* to C::*
4099     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4100       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4101         return ImplicitConversionSequence::Better;
4102       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4103         return ImplicitConversionSequence::Worse;
4104     }
4105   }
4106 
4107   if (SCS1.Second == ICK_Derived_To_Base) {
4108     //   -- conversion of C to B is better than conversion of C to A,
4109     //   -- binding of an expression of type C to a reference of type
4110     //      B& is better than binding an expression of type C to a
4111     //      reference of type A&,
4112     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4113         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4114       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4115         return ImplicitConversionSequence::Better;
4116       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4117         return ImplicitConversionSequence::Worse;
4118     }
4119 
4120     //   -- conversion of B to A is better than conversion of C to A.
4121     //   -- binding of an expression of type B to a reference of type
4122     //      A& is better than binding an expression of type C to a
4123     //      reference of type A&,
4124     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4125         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4126       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4127         return ImplicitConversionSequence::Better;
4128       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4129         return ImplicitConversionSequence::Worse;
4130     }
4131   }
4132 
4133   return ImplicitConversionSequence::Indistinguishable;
4134 }
4135 
4136 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4137 /// C++ class.
4138 static bool isTypeValid(QualType T) {
4139   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4140     return !Record->isInvalidDecl();
4141 
4142   return true;
4143 }
4144 
4145 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4146 /// determine whether they are reference-related,
4147 /// reference-compatible, reference-compatible with added
4148 /// qualification, or incompatible, for use in C++ initialization by
4149 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4150 /// type, and the first type (T1) is the pointee type of the reference
4151 /// type being initialized.
4152 Sema::ReferenceCompareResult
4153 Sema::CompareReferenceRelationship(SourceLocation Loc,
4154                                    QualType OrigT1, QualType OrigT2,
4155                                    bool &DerivedToBase,
4156                                    bool &ObjCConversion,
4157                                    bool &ObjCLifetimeConversion) {
4158   assert(!OrigT1->isReferenceType() &&
4159     "T1 must be the pointee type of the reference type");
4160   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4161 
4162   QualType T1 = Context.getCanonicalType(OrigT1);
4163   QualType T2 = Context.getCanonicalType(OrigT2);
4164   Qualifiers T1Quals, T2Quals;
4165   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4166   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4167 
4168   // C++ [dcl.init.ref]p4:
4169   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4170   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4171   //   T1 is a base class of T2.
4172   DerivedToBase = false;
4173   ObjCConversion = false;
4174   ObjCLifetimeConversion = false;
4175   QualType ConvertedT2;
4176   if (UnqualT1 == UnqualT2) {
4177     // Nothing to do.
4178   } else if (isCompleteType(Loc, OrigT2) &&
4179              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4180              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4181     DerivedToBase = true;
4182   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4183            UnqualT2->isObjCObjectOrInterfaceType() &&
4184            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4185     ObjCConversion = true;
4186   else if (UnqualT2->isFunctionType() &&
4187            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4188     // C++1z [dcl.init.ref]p4:
4189     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4190     //   function" and T1 is "function"
4191     //
4192     // We extend this to also apply to 'noreturn', so allow any function
4193     // conversion between function types.
4194     return Ref_Compatible;
4195   else
4196     return Ref_Incompatible;
4197 
4198   // At this point, we know that T1 and T2 are reference-related (at
4199   // least).
4200 
4201   // If the type is an array type, promote the element qualifiers to the type
4202   // for comparison.
4203   if (isa<ArrayType>(T1) && T1Quals)
4204     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4205   if (isa<ArrayType>(T2) && T2Quals)
4206     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4207 
4208   // C++ [dcl.init.ref]p4:
4209   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4210   //   reference-related to T2 and cv1 is the same cv-qualification
4211   //   as, or greater cv-qualification than, cv2. For purposes of
4212   //   overload resolution, cases for which cv1 is greater
4213   //   cv-qualification than cv2 are identified as
4214   //   reference-compatible with added qualification (see 13.3.3.2).
4215   //
4216   // Note that we also require equivalence of Objective-C GC and address-space
4217   // qualifiers when performing these computations, so that e.g., an int in
4218   // address space 1 is not reference-compatible with an int in address
4219   // space 2.
4220   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4221       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4222     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4223       ObjCLifetimeConversion = true;
4224 
4225     T1Quals.removeObjCLifetime();
4226     T2Quals.removeObjCLifetime();
4227   }
4228 
4229   // MS compiler ignores __unaligned qualifier for references; do the same.
4230   T1Quals.removeUnaligned();
4231   T2Quals.removeUnaligned();
4232 
4233   if (T1Quals.compatiblyIncludes(T2Quals))
4234     return Ref_Compatible;
4235   else
4236     return Ref_Related;
4237 }
4238 
4239 /// \brief Look for a user-defined conversion to an value reference-compatible
4240 ///        with DeclType. Return true if something definite is found.
4241 static bool
4242 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4243                          QualType DeclType, SourceLocation DeclLoc,
4244                          Expr *Init, QualType T2, bool AllowRvalues,
4245                          bool AllowExplicit) {
4246   assert(T2->isRecordType() && "Can only find conversions of record types.");
4247   CXXRecordDecl *T2RecordDecl
4248     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4249 
4250   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4251   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4252   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4253     NamedDecl *D = *I;
4254     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4255     if (isa<UsingShadowDecl>(D))
4256       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4257 
4258     FunctionTemplateDecl *ConvTemplate
4259       = dyn_cast<FunctionTemplateDecl>(D);
4260     CXXConversionDecl *Conv;
4261     if (ConvTemplate)
4262       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4263     else
4264       Conv = cast<CXXConversionDecl>(D);
4265 
4266     // If this is an explicit conversion, and we're not allowed to consider
4267     // explicit conversions, skip it.
4268     if (!AllowExplicit && Conv->isExplicit())
4269       continue;
4270 
4271     if (AllowRvalues) {
4272       bool DerivedToBase = false;
4273       bool ObjCConversion = false;
4274       bool ObjCLifetimeConversion = false;
4275 
4276       // If we are initializing an rvalue reference, don't permit conversion
4277       // functions that return lvalues.
4278       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4279         const ReferenceType *RefType
4280           = Conv->getConversionType()->getAs<LValueReferenceType>();
4281         if (RefType && !RefType->getPointeeType()->isFunctionType())
4282           continue;
4283       }
4284 
4285       if (!ConvTemplate &&
4286           S.CompareReferenceRelationship(
4287             DeclLoc,
4288             Conv->getConversionType().getNonReferenceType()
4289               .getUnqualifiedType(),
4290             DeclType.getNonReferenceType().getUnqualifiedType(),
4291             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4292           Sema::Ref_Incompatible)
4293         continue;
4294     } else {
4295       // If the conversion function doesn't return a reference type,
4296       // it can't be considered for this conversion. An rvalue reference
4297       // is only acceptable if its referencee is a function type.
4298 
4299       const ReferenceType *RefType =
4300         Conv->getConversionType()->getAs<ReferenceType>();
4301       if (!RefType ||
4302           (!RefType->isLValueReferenceType() &&
4303            !RefType->getPointeeType()->isFunctionType()))
4304         continue;
4305     }
4306 
4307     if (ConvTemplate)
4308       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4309                                        Init, DeclType, CandidateSet,
4310                                        /*AllowObjCConversionOnExplicit=*/false);
4311     else
4312       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4313                                DeclType, CandidateSet,
4314                                /*AllowObjCConversionOnExplicit=*/false);
4315   }
4316 
4317   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4318 
4319   OverloadCandidateSet::iterator Best;
4320   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4321   case OR_Success:
4322     // C++ [over.ics.ref]p1:
4323     //
4324     //   [...] If the parameter binds directly to the result of
4325     //   applying a conversion function to the argument
4326     //   expression, the implicit conversion sequence is a
4327     //   user-defined conversion sequence (13.3.3.1.2), with the
4328     //   second standard conversion sequence either an identity
4329     //   conversion or, if the conversion function returns an
4330     //   entity of a type that is a derived class of the parameter
4331     //   type, a derived-to-base Conversion.
4332     if (!Best->FinalConversion.DirectBinding)
4333       return false;
4334 
4335     ICS.setUserDefined();
4336     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4337     ICS.UserDefined.After = Best->FinalConversion;
4338     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4339     ICS.UserDefined.ConversionFunction = Best->Function;
4340     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4341     ICS.UserDefined.EllipsisConversion = false;
4342     assert(ICS.UserDefined.After.ReferenceBinding &&
4343            ICS.UserDefined.After.DirectBinding &&
4344            "Expected a direct reference binding!");
4345     return true;
4346 
4347   case OR_Ambiguous:
4348     ICS.setAmbiguous();
4349     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4350          Cand != CandidateSet.end(); ++Cand)
4351       if (Cand->Viable)
4352         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4353     return true;
4354 
4355   case OR_No_Viable_Function:
4356   case OR_Deleted:
4357     // There was no suitable conversion, or we found a deleted
4358     // conversion; continue with other checks.
4359     return false;
4360   }
4361 
4362   llvm_unreachable("Invalid OverloadResult!");
4363 }
4364 
4365 /// \brief Compute an implicit conversion sequence for reference
4366 /// initialization.
4367 static ImplicitConversionSequence
4368 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4369                  SourceLocation DeclLoc,
4370                  bool SuppressUserConversions,
4371                  bool AllowExplicit) {
4372   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4373 
4374   // Most paths end in a failed conversion.
4375   ImplicitConversionSequence ICS;
4376   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4377 
4378   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4379   QualType T2 = Init->getType();
4380 
4381   // If the initializer is the address of an overloaded function, try
4382   // to resolve the overloaded function. If all goes well, T2 is the
4383   // type of the resulting function.
4384   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4385     DeclAccessPair Found;
4386     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4387                                                                 false, Found))
4388       T2 = Fn->getType();
4389   }
4390 
4391   // Compute some basic properties of the types and the initializer.
4392   bool isRValRef = DeclType->isRValueReferenceType();
4393   bool DerivedToBase = false;
4394   bool ObjCConversion = false;
4395   bool ObjCLifetimeConversion = false;
4396   Expr::Classification InitCategory = Init->Classify(S.Context);
4397   Sema::ReferenceCompareResult RefRelationship
4398     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4399                                      ObjCConversion, ObjCLifetimeConversion);
4400 
4401 
4402   // C++0x [dcl.init.ref]p5:
4403   //   A reference to type "cv1 T1" is initialized by an expression
4404   //   of type "cv2 T2" as follows:
4405 
4406   //     -- If reference is an lvalue reference and the initializer expression
4407   if (!isRValRef) {
4408     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4409     //        reference-compatible with "cv2 T2," or
4410     //
4411     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4412     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4413       // C++ [over.ics.ref]p1:
4414       //   When a parameter of reference type binds directly (8.5.3)
4415       //   to an argument expression, the implicit conversion sequence
4416       //   is the identity conversion, unless the argument expression
4417       //   has a type that is a derived class of the parameter type,
4418       //   in which case the implicit conversion sequence is a
4419       //   derived-to-base Conversion (13.3.3.1).
4420       ICS.setStandard();
4421       ICS.Standard.First = ICK_Identity;
4422       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4423                          : ObjCConversion? ICK_Compatible_Conversion
4424                          : ICK_Identity;
4425       ICS.Standard.Third = ICK_Identity;
4426       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4427       ICS.Standard.setToType(0, T2);
4428       ICS.Standard.setToType(1, T1);
4429       ICS.Standard.setToType(2, T1);
4430       ICS.Standard.ReferenceBinding = true;
4431       ICS.Standard.DirectBinding = true;
4432       ICS.Standard.IsLvalueReference = !isRValRef;
4433       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4434       ICS.Standard.BindsToRvalue = false;
4435       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4436       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4437       ICS.Standard.CopyConstructor = nullptr;
4438       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4439 
4440       // Nothing more to do: the inaccessibility/ambiguity check for
4441       // derived-to-base conversions is suppressed when we're
4442       // computing the implicit conversion sequence (C++
4443       // [over.best.ics]p2).
4444       return ICS;
4445     }
4446 
4447     //       -- has a class type (i.e., T2 is a class type), where T1 is
4448     //          not reference-related to T2, and can be implicitly
4449     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4450     //          is reference-compatible with "cv3 T3" 92) (this
4451     //          conversion is selected by enumerating the applicable
4452     //          conversion functions (13.3.1.6) and choosing the best
4453     //          one through overload resolution (13.3)),
4454     if (!SuppressUserConversions && T2->isRecordType() &&
4455         S.isCompleteType(DeclLoc, T2) &&
4456         RefRelationship == Sema::Ref_Incompatible) {
4457       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4458                                    Init, T2, /*AllowRvalues=*/false,
4459                                    AllowExplicit))
4460         return ICS;
4461     }
4462   }
4463 
4464   //     -- Otherwise, the reference shall be an lvalue reference to a
4465   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4466   //        shall be an rvalue reference.
4467   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4468     return ICS;
4469 
4470   //       -- If the initializer expression
4471   //
4472   //            -- is an xvalue, class prvalue, array prvalue or function
4473   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4474   if (RefRelationship == Sema::Ref_Compatible &&
4475       (InitCategory.isXValue() ||
4476        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4477        (InitCategory.isLValue() && T2->isFunctionType()))) {
4478     ICS.setStandard();
4479     ICS.Standard.First = ICK_Identity;
4480     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4481                       : ObjCConversion? ICK_Compatible_Conversion
4482                       : ICK_Identity;
4483     ICS.Standard.Third = ICK_Identity;
4484     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4485     ICS.Standard.setToType(0, T2);
4486     ICS.Standard.setToType(1, T1);
4487     ICS.Standard.setToType(2, T1);
4488     ICS.Standard.ReferenceBinding = true;
4489     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4490     // binding unless we're binding to a class prvalue.
4491     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4492     // allow the use of rvalue references in C++98/03 for the benefit of
4493     // standard library implementors; therefore, we need the xvalue check here.
4494     ICS.Standard.DirectBinding =
4495       S.getLangOpts().CPlusPlus11 ||
4496       !(InitCategory.isPRValue() || T2->isRecordType());
4497     ICS.Standard.IsLvalueReference = !isRValRef;
4498     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4499     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4500     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4501     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4502     ICS.Standard.CopyConstructor = nullptr;
4503     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4504     return ICS;
4505   }
4506 
4507   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4508   //               reference-related to T2, and can be implicitly converted to
4509   //               an xvalue, class prvalue, or function lvalue of type
4510   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4511   //               "cv3 T3",
4512   //
4513   //          then the reference is bound to the value of the initializer
4514   //          expression in the first case and to the result of the conversion
4515   //          in the second case (or, in either case, to an appropriate base
4516   //          class subobject).
4517   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4518       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4519       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4520                                Init, T2, /*AllowRvalues=*/true,
4521                                AllowExplicit)) {
4522     // In the second case, if the reference is an rvalue reference
4523     // and the second standard conversion sequence of the
4524     // user-defined conversion sequence includes an lvalue-to-rvalue
4525     // conversion, the program is ill-formed.
4526     if (ICS.isUserDefined() && isRValRef &&
4527         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4528       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4529 
4530     return ICS;
4531   }
4532 
4533   // A temporary of function type cannot be created; don't even try.
4534   if (T1->isFunctionType())
4535     return ICS;
4536 
4537   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4538   //          initialized from the initializer expression using the
4539   //          rules for a non-reference copy initialization (8.5). The
4540   //          reference is then bound to the temporary. If T1 is
4541   //          reference-related to T2, cv1 must be the same
4542   //          cv-qualification as, or greater cv-qualification than,
4543   //          cv2; otherwise, the program is ill-formed.
4544   if (RefRelationship == Sema::Ref_Related) {
4545     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4546     // we would be reference-compatible or reference-compatible with
4547     // added qualification. But that wasn't the case, so the reference
4548     // initialization fails.
4549     //
4550     // Note that we only want to check address spaces and cvr-qualifiers here.
4551     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4552     Qualifiers T1Quals = T1.getQualifiers();
4553     Qualifiers T2Quals = T2.getQualifiers();
4554     T1Quals.removeObjCGCAttr();
4555     T1Quals.removeObjCLifetime();
4556     T2Quals.removeObjCGCAttr();
4557     T2Quals.removeObjCLifetime();
4558     // MS compiler ignores __unaligned qualifier for references; do the same.
4559     T1Quals.removeUnaligned();
4560     T2Quals.removeUnaligned();
4561     if (!T1Quals.compatiblyIncludes(T2Quals))
4562       return ICS;
4563   }
4564 
4565   // If at least one of the types is a class type, the types are not
4566   // related, and we aren't allowed any user conversions, the
4567   // reference binding fails. This case is important for breaking
4568   // recursion, since TryImplicitConversion below will attempt to
4569   // create a temporary through the use of a copy constructor.
4570   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4571       (T1->isRecordType() || T2->isRecordType()))
4572     return ICS;
4573 
4574   // If T1 is reference-related to T2 and the reference is an rvalue
4575   // reference, the initializer expression shall not be an lvalue.
4576   if (RefRelationship >= Sema::Ref_Related &&
4577       isRValRef && Init->Classify(S.Context).isLValue())
4578     return ICS;
4579 
4580   // C++ [over.ics.ref]p2:
4581   //   When a parameter of reference type is not bound directly to
4582   //   an argument expression, the conversion sequence is the one
4583   //   required to convert the argument expression to the
4584   //   underlying type of the reference according to
4585   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4586   //   to copy-initializing a temporary of the underlying type with
4587   //   the argument expression. Any difference in top-level
4588   //   cv-qualification is subsumed by the initialization itself
4589   //   and does not constitute a conversion.
4590   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4591                               /*AllowExplicit=*/false,
4592                               /*InOverloadResolution=*/false,
4593                               /*CStyle=*/false,
4594                               /*AllowObjCWritebackConversion=*/false,
4595                               /*AllowObjCConversionOnExplicit=*/false);
4596 
4597   // Of course, that's still a reference binding.
4598   if (ICS.isStandard()) {
4599     ICS.Standard.ReferenceBinding = true;
4600     ICS.Standard.IsLvalueReference = !isRValRef;
4601     ICS.Standard.BindsToFunctionLvalue = false;
4602     ICS.Standard.BindsToRvalue = true;
4603     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4604     ICS.Standard.ObjCLifetimeConversionBinding = false;
4605   } else if (ICS.isUserDefined()) {
4606     const ReferenceType *LValRefType =
4607         ICS.UserDefined.ConversionFunction->getReturnType()
4608             ->getAs<LValueReferenceType>();
4609 
4610     // C++ [over.ics.ref]p3:
4611     //   Except for an implicit object parameter, for which see 13.3.1, a
4612     //   standard conversion sequence cannot be formed if it requires [...]
4613     //   binding an rvalue reference to an lvalue other than a function
4614     //   lvalue.
4615     // Note that the function case is not possible here.
4616     if (DeclType->isRValueReferenceType() && LValRefType) {
4617       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4618       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4619       // reference to an rvalue!
4620       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4621       return ICS;
4622     }
4623 
4624     ICS.UserDefined.After.ReferenceBinding = true;
4625     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4626     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4627     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4628     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4629     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4630   }
4631 
4632   return ICS;
4633 }
4634 
4635 static ImplicitConversionSequence
4636 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4637                       bool SuppressUserConversions,
4638                       bool InOverloadResolution,
4639                       bool AllowObjCWritebackConversion,
4640                       bool AllowExplicit = false);
4641 
4642 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4643 /// initializer list From.
4644 static ImplicitConversionSequence
4645 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4646                   bool SuppressUserConversions,
4647                   bool InOverloadResolution,
4648                   bool AllowObjCWritebackConversion) {
4649   // C++11 [over.ics.list]p1:
4650   //   When an argument is an initializer list, it is not an expression and
4651   //   special rules apply for converting it to a parameter type.
4652 
4653   ImplicitConversionSequence Result;
4654   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4655 
4656   // We need a complete type for what follows. Incomplete types can never be
4657   // initialized from init lists.
4658   if (!S.isCompleteType(From->getLocStart(), ToType))
4659     return Result;
4660 
4661   // Per DR1467:
4662   //   If the parameter type is a class X and the initializer list has a single
4663   //   element of type cv U, where U is X or a class derived from X, the
4664   //   implicit conversion sequence is the one required to convert the element
4665   //   to the parameter type.
4666   //
4667   //   Otherwise, if the parameter type is a character array [... ]
4668   //   and the initializer list has a single element that is an
4669   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4670   //   implicit conversion sequence is the identity conversion.
4671   if (From->getNumInits() == 1) {
4672     if (ToType->isRecordType()) {
4673       QualType InitType = From->getInit(0)->getType();
4674       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4675           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4676         return TryCopyInitialization(S, From->getInit(0), ToType,
4677                                      SuppressUserConversions,
4678                                      InOverloadResolution,
4679                                      AllowObjCWritebackConversion);
4680     }
4681     // FIXME: Check the other conditions here: array of character type,
4682     // initializer is a string literal.
4683     if (ToType->isArrayType()) {
4684       InitializedEntity Entity =
4685         InitializedEntity::InitializeParameter(S.Context, ToType,
4686                                                /*Consumed=*/false);
4687       if (S.CanPerformCopyInitialization(Entity, From)) {
4688         Result.setStandard();
4689         Result.Standard.setAsIdentityConversion();
4690         Result.Standard.setFromType(ToType);
4691         Result.Standard.setAllToTypes(ToType);
4692         return Result;
4693       }
4694     }
4695   }
4696 
4697   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4698   // C++11 [over.ics.list]p2:
4699   //   If the parameter type is std::initializer_list<X> or "array of X" and
4700   //   all the elements can be implicitly converted to X, the implicit
4701   //   conversion sequence is the worst conversion necessary to convert an
4702   //   element of the list to X.
4703   //
4704   // C++14 [over.ics.list]p3:
4705   //   Otherwise, if the parameter type is "array of N X", if the initializer
4706   //   list has exactly N elements or if it has fewer than N elements and X is
4707   //   default-constructible, and if all the elements of the initializer list
4708   //   can be implicitly converted to X, the implicit conversion sequence is
4709   //   the worst conversion necessary to convert an element of the list to X.
4710   //
4711   // FIXME: We're missing a lot of these checks.
4712   bool toStdInitializerList = false;
4713   QualType X;
4714   if (ToType->isArrayType())
4715     X = S.Context.getAsArrayType(ToType)->getElementType();
4716   else
4717     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4718   if (!X.isNull()) {
4719     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4720       Expr *Init = From->getInit(i);
4721       ImplicitConversionSequence ICS =
4722           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4723                                 InOverloadResolution,
4724                                 AllowObjCWritebackConversion);
4725       // If a single element isn't convertible, fail.
4726       if (ICS.isBad()) {
4727         Result = ICS;
4728         break;
4729       }
4730       // Otherwise, look for the worst conversion.
4731       if (Result.isBad() ||
4732           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4733                                              Result) ==
4734               ImplicitConversionSequence::Worse)
4735         Result = ICS;
4736     }
4737 
4738     // For an empty list, we won't have computed any conversion sequence.
4739     // Introduce the identity conversion sequence.
4740     if (From->getNumInits() == 0) {
4741       Result.setStandard();
4742       Result.Standard.setAsIdentityConversion();
4743       Result.Standard.setFromType(ToType);
4744       Result.Standard.setAllToTypes(ToType);
4745     }
4746 
4747     Result.setStdInitializerListElement(toStdInitializerList);
4748     return Result;
4749   }
4750 
4751   // C++14 [over.ics.list]p4:
4752   // C++11 [over.ics.list]p3:
4753   //   Otherwise, if the parameter is a non-aggregate class X and overload
4754   //   resolution chooses a single best constructor [...] the implicit
4755   //   conversion sequence is a user-defined conversion sequence. If multiple
4756   //   constructors are viable but none is better than the others, the
4757   //   implicit conversion sequence is a user-defined conversion sequence.
4758   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4759     // This function can deal with initializer lists.
4760     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4761                                     /*AllowExplicit=*/false,
4762                                     InOverloadResolution, /*CStyle=*/false,
4763                                     AllowObjCWritebackConversion,
4764                                     /*AllowObjCConversionOnExplicit=*/false);
4765   }
4766 
4767   // C++14 [over.ics.list]p5:
4768   // C++11 [over.ics.list]p4:
4769   //   Otherwise, if the parameter has an aggregate type which can be
4770   //   initialized from the initializer list [...] the implicit conversion
4771   //   sequence is a user-defined conversion sequence.
4772   if (ToType->isAggregateType()) {
4773     // Type is an aggregate, argument is an init list. At this point it comes
4774     // down to checking whether the initialization works.
4775     // FIXME: Find out whether this parameter is consumed or not.
4776     InitializedEntity Entity =
4777         InitializedEntity::InitializeParameter(S.Context, ToType,
4778                                                /*Consumed=*/false);
4779     if (S.CanPerformCopyInitialization(Entity, From)) {
4780       Result.setUserDefined();
4781       Result.UserDefined.Before.setAsIdentityConversion();
4782       // Initializer lists don't have a type.
4783       Result.UserDefined.Before.setFromType(QualType());
4784       Result.UserDefined.Before.setAllToTypes(QualType());
4785 
4786       Result.UserDefined.After.setAsIdentityConversion();
4787       Result.UserDefined.After.setFromType(ToType);
4788       Result.UserDefined.After.setAllToTypes(ToType);
4789       Result.UserDefined.ConversionFunction = nullptr;
4790     }
4791     return Result;
4792   }
4793 
4794   // C++14 [over.ics.list]p6:
4795   // C++11 [over.ics.list]p5:
4796   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4797   if (ToType->isReferenceType()) {
4798     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4799     // mention initializer lists in any way. So we go by what list-
4800     // initialization would do and try to extrapolate from that.
4801 
4802     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4803 
4804     // If the initializer list has a single element that is reference-related
4805     // to the parameter type, we initialize the reference from that.
4806     if (From->getNumInits() == 1) {
4807       Expr *Init = From->getInit(0);
4808 
4809       QualType T2 = Init->getType();
4810 
4811       // If the initializer is the address of an overloaded function, try
4812       // to resolve the overloaded function. If all goes well, T2 is the
4813       // type of the resulting function.
4814       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4815         DeclAccessPair Found;
4816         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4817                                    Init, ToType, false, Found))
4818           T2 = Fn->getType();
4819       }
4820 
4821       // Compute some basic properties of the types and the initializer.
4822       bool dummy1 = false;
4823       bool dummy2 = false;
4824       bool dummy3 = false;
4825       Sema::ReferenceCompareResult RefRelationship
4826         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4827                                          dummy2, dummy3);
4828 
4829       if (RefRelationship >= Sema::Ref_Related) {
4830         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4831                                 SuppressUserConversions,
4832                                 /*AllowExplicit=*/false);
4833       }
4834     }
4835 
4836     // Otherwise, we bind the reference to a temporary created from the
4837     // initializer list.
4838     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4839                                InOverloadResolution,
4840                                AllowObjCWritebackConversion);
4841     if (Result.isFailure())
4842       return Result;
4843     assert(!Result.isEllipsis() &&
4844            "Sub-initialization cannot result in ellipsis conversion.");
4845 
4846     // Can we even bind to a temporary?
4847     if (ToType->isRValueReferenceType() ||
4848         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4849       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4850                                             Result.UserDefined.After;
4851       SCS.ReferenceBinding = true;
4852       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4853       SCS.BindsToRvalue = true;
4854       SCS.BindsToFunctionLvalue = false;
4855       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4856       SCS.ObjCLifetimeConversionBinding = false;
4857     } else
4858       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4859                     From, ToType);
4860     return Result;
4861   }
4862 
4863   // C++14 [over.ics.list]p7:
4864   // C++11 [over.ics.list]p6:
4865   //   Otherwise, if the parameter type is not a class:
4866   if (!ToType->isRecordType()) {
4867     //    - if the initializer list has one element that is not itself an
4868     //      initializer list, the implicit conversion sequence is the one
4869     //      required to convert the element to the parameter type.
4870     unsigned NumInits = From->getNumInits();
4871     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4872       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4873                                      SuppressUserConversions,
4874                                      InOverloadResolution,
4875                                      AllowObjCWritebackConversion);
4876     //    - if the initializer list has no elements, the implicit conversion
4877     //      sequence is the identity conversion.
4878     else if (NumInits == 0) {
4879       Result.setStandard();
4880       Result.Standard.setAsIdentityConversion();
4881       Result.Standard.setFromType(ToType);
4882       Result.Standard.setAllToTypes(ToType);
4883     }
4884     return Result;
4885   }
4886 
4887   // C++14 [over.ics.list]p8:
4888   // C++11 [over.ics.list]p7:
4889   //   In all cases other than those enumerated above, no conversion is possible
4890   return Result;
4891 }
4892 
4893 /// TryCopyInitialization - Try to copy-initialize a value of type
4894 /// ToType from the expression From. Return the implicit conversion
4895 /// sequence required to pass this argument, which may be a bad
4896 /// conversion sequence (meaning that the argument cannot be passed to
4897 /// a parameter of this type). If @p SuppressUserConversions, then we
4898 /// do not permit any user-defined conversion sequences.
4899 static ImplicitConversionSequence
4900 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4901                       bool SuppressUserConversions,
4902                       bool InOverloadResolution,
4903                       bool AllowObjCWritebackConversion,
4904                       bool AllowExplicit) {
4905   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4906     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4907                              InOverloadResolution,AllowObjCWritebackConversion);
4908 
4909   if (ToType->isReferenceType())
4910     return TryReferenceInit(S, From, ToType,
4911                             /*FIXME:*/From->getLocStart(),
4912                             SuppressUserConversions,
4913                             AllowExplicit);
4914 
4915   return TryImplicitConversion(S, From, ToType,
4916                                SuppressUserConversions,
4917                                /*AllowExplicit=*/false,
4918                                InOverloadResolution,
4919                                /*CStyle=*/false,
4920                                AllowObjCWritebackConversion,
4921                                /*AllowObjCConversionOnExplicit=*/false);
4922 }
4923 
4924 static bool TryCopyInitialization(const CanQualType FromQTy,
4925                                   const CanQualType ToQTy,
4926                                   Sema &S,
4927                                   SourceLocation Loc,
4928                                   ExprValueKind FromVK) {
4929   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4930   ImplicitConversionSequence ICS =
4931     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4932 
4933   return !ICS.isBad();
4934 }
4935 
4936 /// TryObjectArgumentInitialization - Try to initialize the object
4937 /// parameter of the given member function (@c Method) from the
4938 /// expression @p From.
4939 static ImplicitConversionSequence
4940 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4941                                 Expr::Classification FromClassification,
4942                                 CXXMethodDecl *Method,
4943                                 CXXRecordDecl *ActingContext) {
4944   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4945   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4946   //                 const volatile object.
4947   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4948     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4949   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4950 
4951   // Set up the conversion sequence as a "bad" conversion, to allow us
4952   // to exit early.
4953   ImplicitConversionSequence ICS;
4954 
4955   // We need to have an object of class type.
4956   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4957     FromType = PT->getPointeeType();
4958 
4959     // When we had a pointer, it's implicitly dereferenced, so we
4960     // better have an lvalue.
4961     assert(FromClassification.isLValue());
4962   }
4963 
4964   assert(FromType->isRecordType());
4965 
4966   // C++0x [over.match.funcs]p4:
4967   //   For non-static member functions, the type of the implicit object
4968   //   parameter is
4969   //
4970   //     - "lvalue reference to cv X" for functions declared without a
4971   //        ref-qualifier or with the & ref-qualifier
4972   //     - "rvalue reference to cv X" for functions declared with the &&
4973   //        ref-qualifier
4974   //
4975   // where X is the class of which the function is a member and cv is the
4976   // cv-qualification on the member function declaration.
4977   //
4978   // However, when finding an implicit conversion sequence for the argument, we
4979   // are not allowed to perform user-defined conversions
4980   // (C++ [over.match.funcs]p5). We perform a simplified version of
4981   // reference binding here, that allows class rvalues to bind to
4982   // non-constant references.
4983 
4984   // First check the qualifiers.
4985   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4986   if (ImplicitParamType.getCVRQualifiers()
4987                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4988       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4989     ICS.setBad(BadConversionSequence::bad_qualifiers,
4990                FromType, ImplicitParamType);
4991     return ICS;
4992   }
4993 
4994   // Check that we have either the same type or a derived type. It
4995   // affects the conversion rank.
4996   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4997   ImplicitConversionKind SecondKind;
4998   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4999     SecondKind = ICK_Identity;
5000   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5001     SecondKind = ICK_Derived_To_Base;
5002   else {
5003     ICS.setBad(BadConversionSequence::unrelated_class,
5004                FromType, ImplicitParamType);
5005     return ICS;
5006   }
5007 
5008   // Check the ref-qualifier.
5009   switch (Method->getRefQualifier()) {
5010   case RQ_None:
5011     // Do nothing; we don't care about lvalueness or rvalueness.
5012     break;
5013 
5014   case RQ_LValue:
5015     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5016       // non-const lvalue reference cannot bind to an rvalue
5017       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5018                  ImplicitParamType);
5019       return ICS;
5020     }
5021     break;
5022 
5023   case RQ_RValue:
5024     if (!FromClassification.isRValue()) {
5025       // rvalue reference cannot bind to an lvalue
5026       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5027                  ImplicitParamType);
5028       return ICS;
5029     }
5030     break;
5031   }
5032 
5033   // Success. Mark this as a reference binding.
5034   ICS.setStandard();
5035   ICS.Standard.setAsIdentityConversion();
5036   ICS.Standard.Second = SecondKind;
5037   ICS.Standard.setFromType(FromType);
5038   ICS.Standard.setAllToTypes(ImplicitParamType);
5039   ICS.Standard.ReferenceBinding = true;
5040   ICS.Standard.DirectBinding = true;
5041   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5042   ICS.Standard.BindsToFunctionLvalue = false;
5043   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5044   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5045     = (Method->getRefQualifier() == RQ_None);
5046   return ICS;
5047 }
5048 
5049 /// PerformObjectArgumentInitialization - Perform initialization of
5050 /// the implicit object parameter for the given Method with the given
5051 /// expression.
5052 ExprResult
5053 Sema::PerformObjectArgumentInitialization(Expr *From,
5054                                           NestedNameSpecifier *Qualifier,
5055                                           NamedDecl *FoundDecl,
5056                                           CXXMethodDecl *Method) {
5057   QualType FromRecordType, DestType;
5058   QualType ImplicitParamRecordType  =
5059     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5060 
5061   Expr::Classification FromClassification;
5062   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5063     FromRecordType = PT->getPointeeType();
5064     DestType = Method->getThisType(Context);
5065     FromClassification = Expr::Classification::makeSimpleLValue();
5066   } else {
5067     FromRecordType = From->getType();
5068     DestType = ImplicitParamRecordType;
5069     FromClassification = From->Classify(Context);
5070   }
5071 
5072   // Note that we always use the true parent context when performing
5073   // the actual argument initialization.
5074   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5075       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5076       Method->getParent());
5077   if (ICS.isBad()) {
5078     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5079       Qualifiers FromQs = FromRecordType.getQualifiers();
5080       Qualifiers ToQs = DestType.getQualifiers();
5081       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5082       if (CVR) {
5083         Diag(From->getLocStart(),
5084              diag::err_member_function_call_bad_cvr)
5085           << Method->getDeclName() << FromRecordType << (CVR - 1)
5086           << From->getSourceRange();
5087         Diag(Method->getLocation(), diag::note_previous_decl)
5088           << Method->getDeclName();
5089         return ExprError();
5090       }
5091     }
5092 
5093     return Diag(From->getLocStart(),
5094                 diag::err_implicit_object_parameter_init)
5095        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5096   }
5097 
5098   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5099     ExprResult FromRes =
5100       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5101     if (FromRes.isInvalid())
5102       return ExprError();
5103     From = FromRes.get();
5104   }
5105 
5106   if (!Context.hasSameType(From->getType(), DestType))
5107     From = ImpCastExprToType(From, DestType, CK_NoOp,
5108                              From->getValueKind()).get();
5109   return From;
5110 }
5111 
5112 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5113 /// expression From to bool (C++0x [conv]p3).
5114 static ImplicitConversionSequence
5115 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5116   return TryImplicitConversion(S, From, S.Context.BoolTy,
5117                                /*SuppressUserConversions=*/false,
5118                                /*AllowExplicit=*/true,
5119                                /*InOverloadResolution=*/false,
5120                                /*CStyle=*/false,
5121                                /*AllowObjCWritebackConversion=*/false,
5122                                /*AllowObjCConversionOnExplicit=*/false);
5123 }
5124 
5125 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5126 /// of the expression From to bool (C++0x [conv]p3).
5127 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5128   if (checkPlaceholderForOverload(*this, From))
5129     return ExprError();
5130 
5131   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5132   if (!ICS.isBad())
5133     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5134 
5135   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5136     return Diag(From->getLocStart(),
5137                 diag::err_typecheck_bool_condition)
5138                   << From->getType() << From->getSourceRange();
5139   return ExprError();
5140 }
5141 
5142 /// Check that the specified conversion is permitted in a converted constant
5143 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5144 /// is acceptable.
5145 static bool CheckConvertedConstantConversions(Sema &S,
5146                                               StandardConversionSequence &SCS) {
5147   // Since we know that the target type is an integral or unscoped enumeration
5148   // type, most conversion kinds are impossible. All possible First and Third
5149   // conversions are fine.
5150   switch (SCS.Second) {
5151   case ICK_Identity:
5152   case ICK_Function_Conversion:
5153   case ICK_Integral_Promotion:
5154   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5155     return true;
5156 
5157   case ICK_Boolean_Conversion:
5158     // Conversion from an integral or unscoped enumeration type to bool is
5159     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5160     // conversion, so we allow it in a converted constant expression.
5161     //
5162     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5163     // a lot of popular code. We should at least add a warning for this
5164     // (non-conforming) extension.
5165     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5166            SCS.getToType(2)->isBooleanType();
5167 
5168   case ICK_Pointer_Conversion:
5169   case ICK_Pointer_Member:
5170     // C++1z: null pointer conversions and null member pointer conversions are
5171     // only permitted if the source type is std::nullptr_t.
5172     return SCS.getFromType()->isNullPtrType();
5173 
5174   case ICK_Floating_Promotion:
5175   case ICK_Complex_Promotion:
5176   case ICK_Floating_Conversion:
5177   case ICK_Complex_Conversion:
5178   case ICK_Floating_Integral:
5179   case ICK_Compatible_Conversion:
5180   case ICK_Derived_To_Base:
5181   case ICK_Vector_Conversion:
5182   case ICK_Vector_Splat:
5183   case ICK_Complex_Real:
5184   case ICK_Block_Pointer_Conversion:
5185   case ICK_TransparentUnionConversion:
5186   case ICK_Writeback_Conversion:
5187   case ICK_Zero_Event_Conversion:
5188   case ICK_C_Only_Conversion:
5189   case ICK_Incompatible_Pointer_Conversion:
5190     return false;
5191 
5192   case ICK_Lvalue_To_Rvalue:
5193   case ICK_Array_To_Pointer:
5194   case ICK_Function_To_Pointer:
5195     llvm_unreachable("found a first conversion kind in Second");
5196 
5197   case ICK_Qualification:
5198     llvm_unreachable("found a third conversion kind in Second");
5199 
5200   case ICK_Num_Conversion_Kinds:
5201     break;
5202   }
5203 
5204   llvm_unreachable("unknown conversion kind");
5205 }
5206 
5207 /// CheckConvertedConstantExpression - Check that the expression From is a
5208 /// converted constant expression of type T, perform the conversion and produce
5209 /// the converted expression, per C++11 [expr.const]p3.
5210 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5211                                                    QualType T, APValue &Value,
5212                                                    Sema::CCEKind CCE,
5213                                                    bool RequireInt) {
5214   assert(S.getLangOpts().CPlusPlus11 &&
5215          "converted constant expression outside C++11");
5216 
5217   if (checkPlaceholderForOverload(S, From))
5218     return ExprError();
5219 
5220   // C++1z [expr.const]p3:
5221   //  A converted constant expression of type T is an expression,
5222   //  implicitly converted to type T, where the converted
5223   //  expression is a constant expression and the implicit conversion
5224   //  sequence contains only [... list of conversions ...].
5225   // C++1z [stmt.if]p2:
5226   //  If the if statement is of the form if constexpr, the value of the
5227   //  condition shall be a contextually converted constant expression of type
5228   //  bool.
5229   ImplicitConversionSequence ICS =
5230       CCE == Sema::CCEK_ConstexprIf
5231           ? TryContextuallyConvertToBool(S, From)
5232           : TryCopyInitialization(S, From, T,
5233                                   /*SuppressUserConversions=*/false,
5234                                   /*InOverloadResolution=*/false,
5235                                   /*AllowObjcWritebackConversion=*/false,
5236                                   /*AllowExplicit=*/false);
5237   StandardConversionSequence *SCS = nullptr;
5238   switch (ICS.getKind()) {
5239   case ImplicitConversionSequence::StandardConversion:
5240     SCS = &ICS.Standard;
5241     break;
5242   case ImplicitConversionSequence::UserDefinedConversion:
5243     // We are converting to a non-class type, so the Before sequence
5244     // must be trivial.
5245     SCS = &ICS.UserDefined.After;
5246     break;
5247   case ImplicitConversionSequence::AmbiguousConversion:
5248   case ImplicitConversionSequence::BadConversion:
5249     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5250       return S.Diag(From->getLocStart(),
5251                     diag::err_typecheck_converted_constant_expression)
5252                 << From->getType() << From->getSourceRange() << T;
5253     return ExprError();
5254 
5255   case ImplicitConversionSequence::EllipsisConversion:
5256     llvm_unreachable("ellipsis conversion in converted constant expression");
5257   }
5258 
5259   // Check that we would only use permitted conversions.
5260   if (!CheckConvertedConstantConversions(S, *SCS)) {
5261     return S.Diag(From->getLocStart(),
5262                   diag::err_typecheck_converted_constant_expression_disallowed)
5263              << From->getType() << From->getSourceRange() << T;
5264   }
5265   // [...] and where the reference binding (if any) binds directly.
5266   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5267     return S.Diag(From->getLocStart(),
5268                   diag::err_typecheck_converted_constant_expression_indirect)
5269              << From->getType() << From->getSourceRange() << T;
5270   }
5271 
5272   ExprResult Result =
5273       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5274   if (Result.isInvalid())
5275     return Result;
5276 
5277   // Check for a narrowing implicit conversion.
5278   APValue PreNarrowingValue;
5279   QualType PreNarrowingType;
5280   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5281                                 PreNarrowingType)) {
5282   case NK_Variable_Narrowing:
5283     // Implicit conversion to a narrower type, and the value is not a constant
5284     // expression. We'll diagnose this in a moment.
5285   case NK_Not_Narrowing:
5286     break;
5287 
5288   case NK_Constant_Narrowing:
5289     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5290       << CCE << /*Constant*/1
5291       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5292     break;
5293 
5294   case NK_Type_Narrowing:
5295     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5296       << CCE << /*Constant*/0 << From->getType() << T;
5297     break;
5298   }
5299 
5300   // Check the expression is a constant expression.
5301   SmallVector<PartialDiagnosticAt, 8> Notes;
5302   Expr::EvalResult Eval;
5303   Eval.Diag = &Notes;
5304 
5305   if ((T->isReferenceType()
5306            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5307            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5308       (RequireInt && !Eval.Val.isInt())) {
5309     // The expression can't be folded, so we can't keep it at this position in
5310     // the AST.
5311     Result = ExprError();
5312   } else {
5313     Value = Eval.Val;
5314 
5315     if (Notes.empty()) {
5316       // It's a constant expression.
5317       return Result;
5318     }
5319   }
5320 
5321   // It's not a constant expression. Produce an appropriate diagnostic.
5322   if (Notes.size() == 1 &&
5323       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5324     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5325   else {
5326     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5327       << CCE << From->getSourceRange();
5328     for (unsigned I = 0; I < Notes.size(); ++I)
5329       S.Diag(Notes[I].first, Notes[I].second);
5330   }
5331   return ExprError();
5332 }
5333 
5334 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5335                                                   APValue &Value, CCEKind CCE) {
5336   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5337 }
5338 
5339 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5340                                                   llvm::APSInt &Value,
5341                                                   CCEKind CCE) {
5342   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5343 
5344   APValue V;
5345   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5346   if (!R.isInvalid())
5347     Value = V.getInt();
5348   return R;
5349 }
5350 
5351 
5352 /// dropPointerConversions - If the given standard conversion sequence
5353 /// involves any pointer conversions, remove them.  This may change
5354 /// the result type of the conversion sequence.
5355 static void dropPointerConversion(StandardConversionSequence &SCS) {
5356   if (SCS.Second == ICK_Pointer_Conversion) {
5357     SCS.Second = ICK_Identity;
5358     SCS.Third = ICK_Identity;
5359     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5360   }
5361 }
5362 
5363 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5364 /// convert the expression From to an Objective-C pointer type.
5365 static ImplicitConversionSequence
5366 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5367   // Do an implicit conversion to 'id'.
5368   QualType Ty = S.Context.getObjCIdType();
5369   ImplicitConversionSequence ICS
5370     = TryImplicitConversion(S, From, Ty,
5371                             // FIXME: Are these flags correct?
5372                             /*SuppressUserConversions=*/false,
5373                             /*AllowExplicit=*/true,
5374                             /*InOverloadResolution=*/false,
5375                             /*CStyle=*/false,
5376                             /*AllowObjCWritebackConversion=*/false,
5377                             /*AllowObjCConversionOnExplicit=*/true);
5378 
5379   // Strip off any final conversions to 'id'.
5380   switch (ICS.getKind()) {
5381   case ImplicitConversionSequence::BadConversion:
5382   case ImplicitConversionSequence::AmbiguousConversion:
5383   case ImplicitConversionSequence::EllipsisConversion:
5384     break;
5385 
5386   case ImplicitConversionSequence::UserDefinedConversion:
5387     dropPointerConversion(ICS.UserDefined.After);
5388     break;
5389 
5390   case ImplicitConversionSequence::StandardConversion:
5391     dropPointerConversion(ICS.Standard);
5392     break;
5393   }
5394 
5395   return ICS;
5396 }
5397 
5398 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5399 /// conversion of the expression From to an Objective-C pointer type.
5400 /// Returns a valid but null ExprResult if no conversion sequence exists.
5401 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5402   if (checkPlaceholderForOverload(*this, From))
5403     return ExprError();
5404 
5405   QualType Ty = Context.getObjCIdType();
5406   ImplicitConversionSequence ICS =
5407     TryContextuallyConvertToObjCPointer(*this, From);
5408   if (!ICS.isBad())
5409     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5410   return ExprResult();
5411 }
5412 
5413 /// Determine whether the provided type is an integral type, or an enumeration
5414 /// type of a permitted flavor.
5415 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5416   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5417                                  : T->isIntegralOrUnscopedEnumerationType();
5418 }
5419 
5420 static ExprResult
5421 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5422                             Sema::ContextualImplicitConverter &Converter,
5423                             QualType T, UnresolvedSetImpl &ViableConversions) {
5424 
5425   if (Converter.Suppress)
5426     return ExprError();
5427 
5428   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5429   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5430     CXXConversionDecl *Conv =
5431         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5432     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5433     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5434   }
5435   return From;
5436 }
5437 
5438 static bool
5439 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5440                            Sema::ContextualImplicitConverter &Converter,
5441                            QualType T, bool HadMultipleCandidates,
5442                            UnresolvedSetImpl &ExplicitConversions) {
5443   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5444     DeclAccessPair Found = ExplicitConversions[0];
5445     CXXConversionDecl *Conversion =
5446         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5447 
5448     // The user probably meant to invoke the given explicit
5449     // conversion; use it.
5450     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5451     std::string TypeStr;
5452     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5453 
5454     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5455         << FixItHint::CreateInsertion(From->getLocStart(),
5456                                       "static_cast<" + TypeStr + ">(")
5457         << FixItHint::CreateInsertion(
5458                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5459     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5460 
5461     // If we aren't in a SFINAE context, build a call to the
5462     // explicit conversion function.
5463     if (SemaRef.isSFINAEContext())
5464       return true;
5465 
5466     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5467     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5468                                                        HadMultipleCandidates);
5469     if (Result.isInvalid())
5470       return true;
5471     // Record usage of conversion in an implicit cast.
5472     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5473                                     CK_UserDefinedConversion, Result.get(),
5474                                     nullptr, Result.get()->getValueKind());
5475   }
5476   return false;
5477 }
5478 
5479 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5480                              Sema::ContextualImplicitConverter &Converter,
5481                              QualType T, bool HadMultipleCandidates,
5482                              DeclAccessPair &Found) {
5483   CXXConversionDecl *Conversion =
5484       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5485   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5486 
5487   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5488   if (!Converter.SuppressConversion) {
5489     if (SemaRef.isSFINAEContext())
5490       return true;
5491 
5492     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5493         << From->getSourceRange();
5494   }
5495 
5496   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5497                                                      HadMultipleCandidates);
5498   if (Result.isInvalid())
5499     return true;
5500   // Record usage of conversion in an implicit cast.
5501   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5502                                   CK_UserDefinedConversion, Result.get(),
5503                                   nullptr, Result.get()->getValueKind());
5504   return false;
5505 }
5506 
5507 static ExprResult finishContextualImplicitConversion(
5508     Sema &SemaRef, SourceLocation Loc, Expr *From,
5509     Sema::ContextualImplicitConverter &Converter) {
5510   if (!Converter.match(From->getType()) && !Converter.Suppress)
5511     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5512         << From->getSourceRange();
5513 
5514   return SemaRef.DefaultLvalueConversion(From);
5515 }
5516 
5517 static void
5518 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5519                                   UnresolvedSetImpl &ViableConversions,
5520                                   OverloadCandidateSet &CandidateSet) {
5521   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5522     DeclAccessPair FoundDecl = ViableConversions[I];
5523     NamedDecl *D = FoundDecl.getDecl();
5524     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5525     if (isa<UsingShadowDecl>(D))
5526       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5527 
5528     CXXConversionDecl *Conv;
5529     FunctionTemplateDecl *ConvTemplate;
5530     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5531       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5532     else
5533       Conv = cast<CXXConversionDecl>(D);
5534 
5535     if (ConvTemplate)
5536       SemaRef.AddTemplateConversionCandidate(
5537         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5538         /*AllowObjCConversionOnExplicit=*/false);
5539     else
5540       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5541                                      ToType, CandidateSet,
5542                                      /*AllowObjCConversionOnExplicit=*/false);
5543   }
5544 }
5545 
5546 /// \brief Attempt to convert the given expression to a type which is accepted
5547 /// by the given converter.
5548 ///
5549 /// This routine will attempt to convert an expression of class type to a
5550 /// type accepted by the specified converter. In C++11 and before, the class
5551 /// must have a single non-explicit conversion function converting to a matching
5552 /// type. In C++1y, there can be multiple such conversion functions, but only
5553 /// one target type.
5554 ///
5555 /// \param Loc The source location of the construct that requires the
5556 /// conversion.
5557 ///
5558 /// \param From The expression we're converting from.
5559 ///
5560 /// \param Converter Used to control and diagnose the conversion process.
5561 ///
5562 /// \returns The expression, converted to an integral or enumeration type if
5563 /// successful.
5564 ExprResult Sema::PerformContextualImplicitConversion(
5565     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5566   // We can't perform any more checking for type-dependent expressions.
5567   if (From->isTypeDependent())
5568     return From;
5569 
5570   // Process placeholders immediately.
5571   if (From->hasPlaceholderType()) {
5572     ExprResult result = CheckPlaceholderExpr(From);
5573     if (result.isInvalid())
5574       return result;
5575     From = result.get();
5576   }
5577 
5578   // If the expression already has a matching type, we're golden.
5579   QualType T = From->getType();
5580   if (Converter.match(T))
5581     return DefaultLvalueConversion(From);
5582 
5583   // FIXME: Check for missing '()' if T is a function type?
5584 
5585   // We can only perform contextual implicit conversions on objects of class
5586   // type.
5587   const RecordType *RecordTy = T->getAs<RecordType>();
5588   if (!RecordTy || !getLangOpts().CPlusPlus) {
5589     if (!Converter.Suppress)
5590       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5591     return From;
5592   }
5593 
5594   // We must have a complete class type.
5595   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5596     ContextualImplicitConverter &Converter;
5597     Expr *From;
5598 
5599     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5600         : Converter(Converter), From(From) {}
5601 
5602     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5603       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5604     }
5605   } IncompleteDiagnoser(Converter, From);
5606 
5607   if (Converter.Suppress ? !isCompleteType(Loc, T)
5608                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5609     return From;
5610 
5611   // Look for a conversion to an integral or enumeration type.
5612   UnresolvedSet<4>
5613       ViableConversions; // These are *potentially* viable in C++1y.
5614   UnresolvedSet<4> ExplicitConversions;
5615   const auto &Conversions =
5616       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5617 
5618   bool HadMultipleCandidates =
5619       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5620 
5621   // To check that there is only one target type, in C++1y:
5622   QualType ToType;
5623   bool HasUniqueTargetType = true;
5624 
5625   // Collect explicit or viable (potentially in C++1y) conversions.
5626   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5627     NamedDecl *D = (*I)->getUnderlyingDecl();
5628     CXXConversionDecl *Conversion;
5629     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5630     if (ConvTemplate) {
5631       if (getLangOpts().CPlusPlus14)
5632         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5633       else
5634         continue; // C++11 does not consider conversion operator templates(?).
5635     } else
5636       Conversion = cast<CXXConversionDecl>(D);
5637 
5638     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5639            "Conversion operator templates are considered potentially "
5640            "viable in C++1y");
5641 
5642     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5643     if (Converter.match(CurToType) || ConvTemplate) {
5644 
5645       if (Conversion->isExplicit()) {
5646         // FIXME: For C++1y, do we need this restriction?
5647         // cf. diagnoseNoViableConversion()
5648         if (!ConvTemplate)
5649           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5650       } else {
5651         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5652           if (ToType.isNull())
5653             ToType = CurToType.getUnqualifiedType();
5654           else if (HasUniqueTargetType &&
5655                    (CurToType.getUnqualifiedType() != ToType))
5656             HasUniqueTargetType = false;
5657         }
5658         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5659       }
5660     }
5661   }
5662 
5663   if (getLangOpts().CPlusPlus14) {
5664     // C++1y [conv]p6:
5665     // ... An expression e of class type E appearing in such a context
5666     // is said to be contextually implicitly converted to a specified
5667     // type T and is well-formed if and only if e can be implicitly
5668     // converted to a type T that is determined as follows: E is searched
5669     // for conversion functions whose return type is cv T or reference to
5670     // cv T such that T is allowed by the context. There shall be
5671     // exactly one such T.
5672 
5673     // If no unique T is found:
5674     if (ToType.isNull()) {
5675       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5676                                      HadMultipleCandidates,
5677                                      ExplicitConversions))
5678         return ExprError();
5679       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5680     }
5681 
5682     // If more than one unique Ts are found:
5683     if (!HasUniqueTargetType)
5684       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5685                                          ViableConversions);
5686 
5687     // If one unique T is found:
5688     // First, build a candidate set from the previously recorded
5689     // potentially viable conversions.
5690     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5691     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5692                                       CandidateSet);
5693 
5694     // Then, perform overload resolution over the candidate set.
5695     OverloadCandidateSet::iterator Best;
5696     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5697     case OR_Success: {
5698       // Apply this conversion.
5699       DeclAccessPair Found =
5700           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5701       if (recordConversion(*this, Loc, From, Converter, T,
5702                            HadMultipleCandidates, Found))
5703         return ExprError();
5704       break;
5705     }
5706     case OR_Ambiguous:
5707       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5708                                          ViableConversions);
5709     case OR_No_Viable_Function:
5710       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5711                                      HadMultipleCandidates,
5712                                      ExplicitConversions))
5713         return ExprError();
5714     // fall through 'OR_Deleted' case.
5715     case OR_Deleted:
5716       // We'll complain below about a non-integral condition type.
5717       break;
5718     }
5719   } else {
5720     switch (ViableConversions.size()) {
5721     case 0: {
5722       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5723                                      HadMultipleCandidates,
5724                                      ExplicitConversions))
5725         return ExprError();
5726 
5727       // We'll complain below about a non-integral condition type.
5728       break;
5729     }
5730     case 1: {
5731       // Apply this conversion.
5732       DeclAccessPair Found = ViableConversions[0];
5733       if (recordConversion(*this, Loc, From, Converter, T,
5734                            HadMultipleCandidates, Found))
5735         return ExprError();
5736       break;
5737     }
5738     default:
5739       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5740                                          ViableConversions);
5741     }
5742   }
5743 
5744   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5745 }
5746 
5747 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5748 /// an acceptable non-member overloaded operator for a call whose
5749 /// arguments have types T1 (and, if non-empty, T2). This routine
5750 /// implements the check in C++ [over.match.oper]p3b2 concerning
5751 /// enumeration types.
5752 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5753                                                    FunctionDecl *Fn,
5754                                                    ArrayRef<Expr *> Args) {
5755   QualType T1 = Args[0]->getType();
5756   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5757 
5758   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5759     return true;
5760 
5761   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5762     return true;
5763 
5764   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5765   if (Proto->getNumParams() < 1)
5766     return false;
5767 
5768   if (T1->isEnumeralType()) {
5769     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5770     if (Context.hasSameUnqualifiedType(T1, ArgType))
5771       return true;
5772   }
5773 
5774   if (Proto->getNumParams() < 2)
5775     return false;
5776 
5777   if (!T2.isNull() && T2->isEnumeralType()) {
5778     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5779     if (Context.hasSameUnqualifiedType(T2, ArgType))
5780       return true;
5781   }
5782 
5783   return false;
5784 }
5785 
5786 /// AddOverloadCandidate - Adds the given function to the set of
5787 /// candidate functions, using the given function call arguments.  If
5788 /// @p SuppressUserConversions, then don't allow user-defined
5789 /// conversions via constructors or conversion operators.
5790 ///
5791 /// \param PartialOverloading true if we are performing "partial" overloading
5792 /// based on an incomplete set of function arguments. This feature is used by
5793 /// code completion.
5794 void
5795 Sema::AddOverloadCandidate(FunctionDecl *Function,
5796                            DeclAccessPair FoundDecl,
5797                            ArrayRef<Expr *> Args,
5798                            OverloadCandidateSet &CandidateSet,
5799                            bool SuppressUserConversions,
5800                            bool PartialOverloading,
5801                            bool AllowExplicit) {
5802   const FunctionProtoType *Proto
5803     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5804   assert(Proto && "Functions without a prototype cannot be overloaded");
5805   assert(!Function->getDescribedFunctionTemplate() &&
5806          "Use AddTemplateOverloadCandidate for function templates");
5807 
5808   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5809     if (!isa<CXXConstructorDecl>(Method)) {
5810       // If we get here, it's because we're calling a member function
5811       // that is named without a member access expression (e.g.,
5812       // "this->f") that was either written explicitly or created
5813       // implicitly. This can happen with a qualified call to a member
5814       // function, e.g., X::f(). We use an empty type for the implied
5815       // object argument (C++ [over.call.func]p3), and the acting context
5816       // is irrelevant.
5817       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5818                          QualType(), Expr::Classification::makeSimpleLValue(),
5819                          Args, CandidateSet, SuppressUserConversions,
5820                          PartialOverloading);
5821       return;
5822     }
5823     // We treat a constructor like a non-member function, since its object
5824     // argument doesn't participate in overload resolution.
5825   }
5826 
5827   if (!CandidateSet.isNewCandidate(Function))
5828     return;
5829 
5830   // C++ [over.match.oper]p3:
5831   //   if no operand has a class type, only those non-member functions in the
5832   //   lookup set that have a first parameter of type T1 or "reference to
5833   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5834   //   is a right operand) a second parameter of type T2 or "reference to
5835   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5836   //   candidate functions.
5837   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5838       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5839     return;
5840 
5841   // C++11 [class.copy]p11: [DR1402]
5842   //   A defaulted move constructor that is defined as deleted is ignored by
5843   //   overload resolution.
5844   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5845   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5846       Constructor->isMoveConstructor())
5847     return;
5848 
5849   // Overload resolution is always an unevaluated context.
5850   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5851 
5852   // Add this candidate
5853   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5854   Candidate.FoundDecl = FoundDecl;
5855   Candidate.Function = Function;
5856   Candidate.Viable = true;
5857   Candidate.IsSurrogate = false;
5858   Candidate.IgnoreObjectArgument = false;
5859   Candidate.ExplicitCallArguments = Args.size();
5860 
5861   if (Constructor) {
5862     // C++ [class.copy]p3:
5863     //   A member function template is never instantiated to perform the copy
5864     //   of a class object to an object of its class type.
5865     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5866     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5867         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5868          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5869                        ClassType))) {
5870       Candidate.Viable = false;
5871       Candidate.FailureKind = ovl_fail_illegal_constructor;
5872       return;
5873     }
5874   }
5875 
5876   unsigned NumParams = Proto->getNumParams();
5877 
5878   // (C++ 13.3.2p2): A candidate function having fewer than m
5879   // parameters is viable only if it has an ellipsis in its parameter
5880   // list (8.3.5).
5881   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5882       !Proto->isVariadic()) {
5883     Candidate.Viable = false;
5884     Candidate.FailureKind = ovl_fail_too_many_arguments;
5885     return;
5886   }
5887 
5888   // (C++ 13.3.2p2): A candidate function having more than m parameters
5889   // is viable only if the (m+1)st parameter has a default argument
5890   // (8.3.6). For the purposes of overload resolution, the
5891   // parameter list is truncated on the right, so that there are
5892   // exactly m parameters.
5893   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5894   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5895     // Not enough arguments.
5896     Candidate.Viable = false;
5897     Candidate.FailureKind = ovl_fail_too_few_arguments;
5898     return;
5899   }
5900 
5901   // (CUDA B.1): Check for invalid calls between targets.
5902   if (getLangOpts().CUDA)
5903     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5904       // Skip the check for callers that are implicit members, because in this
5905       // case we may not yet know what the member's target is; the target is
5906       // inferred for the member automatically, based on the bases and fields of
5907       // the class.
5908       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5909         Candidate.Viable = false;
5910         Candidate.FailureKind = ovl_fail_bad_target;
5911         return;
5912       }
5913 
5914   // Determine the implicit conversion sequences for each of the
5915   // arguments.
5916   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5917     if (ArgIdx < NumParams) {
5918       // (C++ 13.3.2p3): for F to be a viable function, there shall
5919       // exist for each argument an implicit conversion sequence
5920       // (13.3.3.1) that converts that argument to the corresponding
5921       // parameter of F.
5922       QualType ParamType = Proto->getParamType(ArgIdx);
5923       Candidate.Conversions[ArgIdx]
5924         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5925                                 SuppressUserConversions,
5926                                 /*InOverloadResolution=*/true,
5927                                 /*AllowObjCWritebackConversion=*/
5928                                   getLangOpts().ObjCAutoRefCount,
5929                                 AllowExplicit);
5930       if (Candidate.Conversions[ArgIdx].isBad()) {
5931         Candidate.Viable = false;
5932         Candidate.FailureKind = ovl_fail_bad_conversion;
5933         return;
5934       }
5935     } else {
5936       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5937       // argument for which there is no corresponding parameter is
5938       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5939       Candidate.Conversions[ArgIdx].setEllipsis();
5940     }
5941   }
5942 
5943   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5944     Candidate.Viable = false;
5945     Candidate.FailureKind = ovl_fail_enable_if;
5946     Candidate.DeductionFailure.Data = FailedAttr;
5947     return;
5948   }
5949 }
5950 
5951 ObjCMethodDecl *
5952 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5953                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5954   if (Methods.size() <= 1)
5955     return nullptr;
5956 
5957   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5958     bool Match = true;
5959     ObjCMethodDecl *Method = Methods[b];
5960     unsigned NumNamedArgs = Sel.getNumArgs();
5961     // Method might have more arguments than selector indicates. This is due
5962     // to addition of c-style arguments in method.
5963     if (Method->param_size() > NumNamedArgs)
5964       NumNamedArgs = Method->param_size();
5965     if (Args.size() < NumNamedArgs)
5966       continue;
5967 
5968     for (unsigned i = 0; i < NumNamedArgs; i++) {
5969       // We can't do any type-checking on a type-dependent argument.
5970       if (Args[i]->isTypeDependent()) {
5971         Match = false;
5972         break;
5973       }
5974 
5975       ParmVarDecl *param = Method->parameters()[i];
5976       Expr *argExpr = Args[i];
5977       assert(argExpr && "SelectBestMethod(): missing expression");
5978 
5979       // Strip the unbridged-cast placeholder expression off unless it's
5980       // a consumed argument.
5981       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5982           !param->hasAttr<CFConsumedAttr>())
5983         argExpr = stripARCUnbridgedCast(argExpr);
5984 
5985       // If the parameter is __unknown_anytype, move on to the next method.
5986       if (param->getType() == Context.UnknownAnyTy) {
5987         Match = false;
5988         break;
5989       }
5990 
5991       ImplicitConversionSequence ConversionState
5992         = TryCopyInitialization(*this, argExpr, param->getType(),
5993                                 /*SuppressUserConversions*/false,
5994                                 /*InOverloadResolution=*/true,
5995                                 /*AllowObjCWritebackConversion=*/
5996                                 getLangOpts().ObjCAutoRefCount,
5997                                 /*AllowExplicit*/false);
5998       // This function looks for a reasonably-exact match, so we consider
5999       // incompatible pointer conversions to be a failure here.
6000       if (ConversionState.isBad() ||
6001           (ConversionState.isStandard() &&
6002            ConversionState.Standard.Second ==
6003                ICK_Incompatible_Pointer_Conversion)) {
6004         Match = false;
6005         break;
6006       }
6007     }
6008     // Promote additional arguments to variadic methods.
6009     if (Match && Method->isVariadic()) {
6010       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6011         if (Args[i]->isTypeDependent()) {
6012           Match = false;
6013           break;
6014         }
6015         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6016                                                           nullptr);
6017         if (Arg.isInvalid()) {
6018           Match = false;
6019           break;
6020         }
6021       }
6022     } else {
6023       // Check for extra arguments to non-variadic methods.
6024       if (Args.size() != NumNamedArgs)
6025         Match = false;
6026       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6027         // Special case when selectors have no argument. In this case, select
6028         // one with the most general result type of 'id'.
6029         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6030           QualType ReturnT = Methods[b]->getReturnType();
6031           if (ReturnT->isObjCIdType())
6032             return Methods[b];
6033         }
6034       }
6035     }
6036 
6037     if (Match)
6038       return Method;
6039   }
6040   return nullptr;
6041 }
6042 
6043 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6044 // enable_if is order-sensitive. As a result, we need to reverse things
6045 // sometimes. Size of 4 elements is arbitrary.
6046 static SmallVector<EnableIfAttr *, 4>
6047 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6048   SmallVector<EnableIfAttr *, 4> Result;
6049   if (!Function->hasAttrs())
6050     return Result;
6051 
6052   const auto &FuncAttrs = Function->getAttrs();
6053   for (Attr *Attr : FuncAttrs)
6054     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6055       Result.push_back(EnableIf);
6056 
6057   std::reverse(Result.begin(), Result.end());
6058   return Result;
6059 }
6060 
6061 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6062                                   bool MissingImplicitThis) {
6063   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6064   if (EnableIfAttrs.empty())
6065     return nullptr;
6066 
6067   SFINAETrap Trap(*this);
6068   SmallVector<Expr *, 16> ConvertedArgs;
6069   bool InitializationFailed = false;
6070 
6071   // Ignore any variadic arguments. Converting them is pointless, since the
6072   // user can't refer to them in the enable_if condition.
6073   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6074 
6075   // Convert the arguments.
6076   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6077     ExprResult R;
6078     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
6079         !cast<CXXMethodDecl>(Function)->isStatic() &&
6080         !isa<CXXConstructorDecl>(Function)) {
6081       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6082       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6083                                               Method, Method);
6084     } else {
6085       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6086                                         Context, Function->getParamDecl(I)),
6087                                     SourceLocation(), Args[I]);
6088     }
6089 
6090     if (R.isInvalid()) {
6091       InitializationFailed = true;
6092       break;
6093     }
6094 
6095     ConvertedArgs.push_back(R.get());
6096   }
6097 
6098   if (InitializationFailed || Trap.hasErrorOccurred())
6099     return EnableIfAttrs[0];
6100 
6101   // Push default arguments if needed.
6102   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6103     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6104       ParmVarDecl *P = Function->getParamDecl(i);
6105       ExprResult R = PerformCopyInitialization(
6106           InitializedEntity::InitializeParameter(Context,
6107                                                  Function->getParamDecl(i)),
6108           SourceLocation(),
6109           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6110                                            : P->getDefaultArg());
6111       if (R.isInvalid()) {
6112         InitializationFailed = true;
6113         break;
6114       }
6115       ConvertedArgs.push_back(R.get());
6116     }
6117 
6118     if (InitializationFailed || Trap.hasErrorOccurred())
6119       return EnableIfAttrs[0];
6120   }
6121 
6122   for (auto *EIA : EnableIfAttrs) {
6123     APValue Result;
6124     // FIXME: This doesn't consider value-dependent cases, because doing so is
6125     // very difficult. Ideally, we should handle them more gracefully.
6126     if (!EIA->getCond()->EvaluateWithSubstitution(
6127             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6128       return EIA;
6129 
6130     if (!Result.isInt() || !Result.getInt().getBoolValue())
6131       return EIA;
6132   }
6133   return nullptr;
6134 }
6135 
6136 /// \brief Add all of the function declarations in the given function set to
6137 /// the overload candidate set.
6138 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6139                                  ArrayRef<Expr *> Args,
6140                                  OverloadCandidateSet& CandidateSet,
6141                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6142                                  bool SuppressUserConversions,
6143                                  bool PartialOverloading) {
6144   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6145     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6146     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6147       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6148         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6149                            cast<CXXMethodDecl>(FD)->getParent(),
6150                            Args[0]->getType(), Args[0]->Classify(Context),
6151                            Args.slice(1), CandidateSet,
6152                            SuppressUserConversions, PartialOverloading);
6153       else
6154         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6155                              SuppressUserConversions, PartialOverloading);
6156     } else {
6157       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6158       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6159           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6160         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6161                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6162                                    ExplicitTemplateArgs,
6163                                    Args[0]->getType(),
6164                                    Args[0]->Classify(Context), Args.slice(1),
6165                                    CandidateSet, SuppressUserConversions,
6166                                    PartialOverloading);
6167       else
6168         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6169                                      ExplicitTemplateArgs, Args,
6170                                      CandidateSet, SuppressUserConversions,
6171                                      PartialOverloading);
6172     }
6173   }
6174 }
6175 
6176 /// AddMethodCandidate - Adds a named decl (which is some kind of
6177 /// method) as a method candidate to the given overload set.
6178 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6179                               QualType ObjectType,
6180                               Expr::Classification ObjectClassification,
6181                               ArrayRef<Expr *> Args,
6182                               OverloadCandidateSet& CandidateSet,
6183                               bool SuppressUserConversions) {
6184   NamedDecl *Decl = FoundDecl.getDecl();
6185   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6186 
6187   if (isa<UsingShadowDecl>(Decl))
6188     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6189 
6190   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6191     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6192            "Expected a member function template");
6193     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6194                                /*ExplicitArgs*/ nullptr,
6195                                ObjectType, ObjectClassification,
6196                                Args, CandidateSet,
6197                                SuppressUserConversions);
6198   } else {
6199     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6200                        ObjectType, ObjectClassification,
6201                        Args,
6202                        CandidateSet, SuppressUserConversions);
6203   }
6204 }
6205 
6206 /// AddMethodCandidate - Adds the given C++ member function to the set
6207 /// of candidate functions, using the given function call arguments
6208 /// and the object argument (@c Object). For example, in a call
6209 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6210 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6211 /// allow user-defined conversions via constructors or conversion
6212 /// operators.
6213 void
6214 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6215                          CXXRecordDecl *ActingContext, QualType ObjectType,
6216                          Expr::Classification ObjectClassification,
6217                          ArrayRef<Expr *> Args,
6218                          OverloadCandidateSet &CandidateSet,
6219                          bool SuppressUserConversions,
6220                          bool PartialOverloading) {
6221   const FunctionProtoType *Proto
6222     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6223   assert(Proto && "Methods without a prototype cannot be overloaded");
6224   assert(!isa<CXXConstructorDecl>(Method) &&
6225          "Use AddOverloadCandidate for constructors");
6226 
6227   if (!CandidateSet.isNewCandidate(Method))
6228     return;
6229 
6230   // C++11 [class.copy]p23: [DR1402]
6231   //   A defaulted move assignment operator that is defined as deleted is
6232   //   ignored by overload resolution.
6233   if (Method->isDefaulted() && Method->isDeleted() &&
6234       Method->isMoveAssignmentOperator())
6235     return;
6236 
6237   // Overload resolution is always an unevaluated context.
6238   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6239 
6240   // Add this candidate
6241   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6242   Candidate.FoundDecl = FoundDecl;
6243   Candidate.Function = Method;
6244   Candidate.IsSurrogate = false;
6245   Candidate.IgnoreObjectArgument = false;
6246   Candidate.ExplicitCallArguments = Args.size();
6247 
6248   unsigned NumParams = Proto->getNumParams();
6249 
6250   // (C++ 13.3.2p2): A candidate function having fewer than m
6251   // parameters is viable only if it has an ellipsis in its parameter
6252   // list (8.3.5).
6253   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6254       !Proto->isVariadic()) {
6255     Candidate.Viable = false;
6256     Candidate.FailureKind = ovl_fail_too_many_arguments;
6257     return;
6258   }
6259 
6260   // (C++ 13.3.2p2): A candidate function having more than m parameters
6261   // is viable only if the (m+1)st parameter has a default argument
6262   // (8.3.6). For the purposes of overload resolution, the
6263   // parameter list is truncated on the right, so that there are
6264   // exactly m parameters.
6265   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6266   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6267     // Not enough arguments.
6268     Candidate.Viable = false;
6269     Candidate.FailureKind = ovl_fail_too_few_arguments;
6270     return;
6271   }
6272 
6273   Candidate.Viable = true;
6274 
6275   if (Method->isStatic() || ObjectType.isNull())
6276     // The implicit object argument is ignored.
6277     Candidate.IgnoreObjectArgument = true;
6278   else {
6279     // Determine the implicit conversion sequence for the object
6280     // parameter.
6281     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6282         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6283         Method, ActingContext);
6284     if (Candidate.Conversions[0].isBad()) {
6285       Candidate.Viable = false;
6286       Candidate.FailureKind = ovl_fail_bad_conversion;
6287       return;
6288     }
6289   }
6290 
6291   // (CUDA B.1): Check for invalid calls between targets.
6292   if (getLangOpts().CUDA)
6293     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6294       if (!IsAllowedCUDACall(Caller, Method)) {
6295         Candidate.Viable = false;
6296         Candidate.FailureKind = ovl_fail_bad_target;
6297         return;
6298       }
6299 
6300   // Determine the implicit conversion sequences for each of the
6301   // arguments.
6302   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6303     if (ArgIdx < NumParams) {
6304       // (C++ 13.3.2p3): for F to be a viable function, there shall
6305       // exist for each argument an implicit conversion sequence
6306       // (13.3.3.1) that converts that argument to the corresponding
6307       // parameter of F.
6308       QualType ParamType = Proto->getParamType(ArgIdx);
6309       Candidate.Conversions[ArgIdx + 1]
6310         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6311                                 SuppressUserConversions,
6312                                 /*InOverloadResolution=*/true,
6313                                 /*AllowObjCWritebackConversion=*/
6314                                   getLangOpts().ObjCAutoRefCount);
6315       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6316         Candidate.Viable = false;
6317         Candidate.FailureKind = ovl_fail_bad_conversion;
6318         return;
6319       }
6320     } else {
6321       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6322       // argument for which there is no corresponding parameter is
6323       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6324       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6325     }
6326   }
6327 
6328   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6329     Candidate.Viable = false;
6330     Candidate.FailureKind = ovl_fail_enable_if;
6331     Candidate.DeductionFailure.Data = FailedAttr;
6332     return;
6333   }
6334 }
6335 
6336 /// \brief Add a C++ member function template as a candidate to the candidate
6337 /// set, using template argument deduction to produce an appropriate member
6338 /// function template specialization.
6339 void
6340 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6341                                  DeclAccessPair FoundDecl,
6342                                  CXXRecordDecl *ActingContext,
6343                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6344                                  QualType ObjectType,
6345                                  Expr::Classification ObjectClassification,
6346                                  ArrayRef<Expr *> Args,
6347                                  OverloadCandidateSet& CandidateSet,
6348                                  bool SuppressUserConversions,
6349                                  bool PartialOverloading) {
6350   if (!CandidateSet.isNewCandidate(MethodTmpl))
6351     return;
6352 
6353   // C++ [over.match.funcs]p7:
6354   //   In each case where a candidate is a function template, candidate
6355   //   function template specializations are generated using template argument
6356   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6357   //   candidate functions in the usual way.113) A given name can refer to one
6358   //   or more function templates and also to a set of overloaded non-template
6359   //   functions. In such a case, the candidate functions generated from each
6360   //   function template are combined with the set of non-template candidate
6361   //   functions.
6362   TemplateDeductionInfo Info(CandidateSet.getLocation());
6363   FunctionDecl *Specialization = nullptr;
6364   if (TemplateDeductionResult Result
6365       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6366                                 Specialization, Info, PartialOverloading)) {
6367     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6368     Candidate.FoundDecl = FoundDecl;
6369     Candidate.Function = MethodTmpl->getTemplatedDecl();
6370     Candidate.Viable = false;
6371     Candidate.FailureKind = ovl_fail_bad_deduction;
6372     Candidate.IsSurrogate = false;
6373     Candidate.IgnoreObjectArgument = false;
6374     Candidate.ExplicitCallArguments = Args.size();
6375     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6376                                                           Info);
6377     return;
6378   }
6379 
6380   // Add the function template specialization produced by template argument
6381   // deduction as a candidate.
6382   assert(Specialization && "Missing member function template specialization?");
6383   assert(isa<CXXMethodDecl>(Specialization) &&
6384          "Specialization is not a member function?");
6385   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6386                      ActingContext, ObjectType, ObjectClassification, Args,
6387                      CandidateSet, SuppressUserConversions, PartialOverloading);
6388 }
6389 
6390 /// \brief Add a C++ function template specialization as a candidate
6391 /// in the candidate set, using template argument deduction to produce
6392 /// an appropriate function template specialization.
6393 void
6394 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6395                                    DeclAccessPair FoundDecl,
6396                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6397                                    ArrayRef<Expr *> Args,
6398                                    OverloadCandidateSet& CandidateSet,
6399                                    bool SuppressUserConversions,
6400                                    bool PartialOverloading) {
6401   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6402     return;
6403 
6404   // C++ [over.match.funcs]p7:
6405   //   In each case where a candidate is a function template, candidate
6406   //   function template specializations are generated using template argument
6407   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6408   //   candidate functions in the usual way.113) A given name can refer to one
6409   //   or more function templates and also to a set of overloaded non-template
6410   //   functions. In such a case, the candidate functions generated from each
6411   //   function template are combined with the set of non-template candidate
6412   //   functions.
6413   TemplateDeductionInfo Info(CandidateSet.getLocation());
6414   FunctionDecl *Specialization = nullptr;
6415   if (TemplateDeductionResult Result
6416         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6417                                   Specialization, Info, PartialOverloading)) {
6418     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6419     Candidate.FoundDecl = FoundDecl;
6420     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6421     Candidate.Viable = false;
6422     Candidate.FailureKind = ovl_fail_bad_deduction;
6423     Candidate.IsSurrogate = false;
6424     Candidate.IgnoreObjectArgument = false;
6425     Candidate.ExplicitCallArguments = Args.size();
6426     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6427                                                           Info);
6428     return;
6429   }
6430 
6431   // Add the function template specialization produced by template argument
6432   // deduction as a candidate.
6433   assert(Specialization && "Missing function template specialization?");
6434   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6435                        SuppressUserConversions, PartialOverloading);
6436 }
6437 
6438 /// Determine whether this is an allowable conversion from the result
6439 /// of an explicit conversion operator to the expected type, per C++
6440 /// [over.match.conv]p1 and [over.match.ref]p1.
6441 ///
6442 /// \param ConvType The return type of the conversion function.
6443 ///
6444 /// \param ToType The type we are converting to.
6445 ///
6446 /// \param AllowObjCPointerConversion Allow a conversion from one
6447 /// Objective-C pointer to another.
6448 ///
6449 /// \returns true if the conversion is allowable, false otherwise.
6450 static bool isAllowableExplicitConversion(Sema &S,
6451                                           QualType ConvType, QualType ToType,
6452                                           bool AllowObjCPointerConversion) {
6453   QualType ToNonRefType = ToType.getNonReferenceType();
6454 
6455   // Easy case: the types are the same.
6456   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6457     return true;
6458 
6459   // Allow qualification conversions.
6460   bool ObjCLifetimeConversion;
6461   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6462                                   ObjCLifetimeConversion))
6463     return true;
6464 
6465   // If we're not allowed to consider Objective-C pointer conversions,
6466   // we're done.
6467   if (!AllowObjCPointerConversion)
6468     return false;
6469 
6470   // Is this an Objective-C pointer conversion?
6471   bool IncompatibleObjC = false;
6472   QualType ConvertedType;
6473   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6474                                    IncompatibleObjC);
6475 }
6476 
6477 /// AddConversionCandidate - Add a C++ conversion function as a
6478 /// candidate in the candidate set (C++ [over.match.conv],
6479 /// C++ [over.match.copy]). From is the expression we're converting from,
6480 /// and ToType is the type that we're eventually trying to convert to
6481 /// (which may or may not be the same type as the type that the
6482 /// conversion function produces).
6483 void
6484 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6485                              DeclAccessPair FoundDecl,
6486                              CXXRecordDecl *ActingContext,
6487                              Expr *From, QualType ToType,
6488                              OverloadCandidateSet& CandidateSet,
6489                              bool AllowObjCConversionOnExplicit) {
6490   assert(!Conversion->getDescribedFunctionTemplate() &&
6491          "Conversion function templates use AddTemplateConversionCandidate");
6492   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6493   if (!CandidateSet.isNewCandidate(Conversion))
6494     return;
6495 
6496   // If the conversion function has an undeduced return type, trigger its
6497   // deduction now.
6498   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6499     if (DeduceReturnType(Conversion, From->getExprLoc()))
6500       return;
6501     ConvType = Conversion->getConversionType().getNonReferenceType();
6502   }
6503 
6504   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6505   // operator is only a candidate if its return type is the target type or
6506   // can be converted to the target type with a qualification conversion.
6507   if (Conversion->isExplicit() &&
6508       !isAllowableExplicitConversion(*this, ConvType, ToType,
6509                                      AllowObjCConversionOnExplicit))
6510     return;
6511 
6512   // Overload resolution is always an unevaluated context.
6513   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6514 
6515   // Add this candidate
6516   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6517   Candidate.FoundDecl = FoundDecl;
6518   Candidate.Function = Conversion;
6519   Candidate.IsSurrogate = false;
6520   Candidate.IgnoreObjectArgument = false;
6521   Candidate.FinalConversion.setAsIdentityConversion();
6522   Candidate.FinalConversion.setFromType(ConvType);
6523   Candidate.FinalConversion.setAllToTypes(ToType);
6524   Candidate.Viable = true;
6525   Candidate.ExplicitCallArguments = 1;
6526 
6527   // C++ [over.match.funcs]p4:
6528   //   For conversion functions, the function is considered to be a member of
6529   //   the class of the implicit implied object argument for the purpose of
6530   //   defining the type of the implicit object parameter.
6531   //
6532   // Determine the implicit conversion sequence for the implicit
6533   // object parameter.
6534   QualType ImplicitParamType = From->getType();
6535   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6536     ImplicitParamType = FromPtrType->getPointeeType();
6537   CXXRecordDecl *ConversionContext
6538     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6539 
6540   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6541       *this, CandidateSet.getLocation(), From->getType(),
6542       From->Classify(Context), Conversion, ConversionContext);
6543 
6544   if (Candidate.Conversions[0].isBad()) {
6545     Candidate.Viable = false;
6546     Candidate.FailureKind = ovl_fail_bad_conversion;
6547     return;
6548   }
6549 
6550   // We won't go through a user-defined type conversion function to convert a
6551   // derived to base as such conversions are given Conversion Rank. They only
6552   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6553   QualType FromCanon
6554     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6555   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6556   if (FromCanon == ToCanon ||
6557       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6558     Candidate.Viable = false;
6559     Candidate.FailureKind = ovl_fail_trivial_conversion;
6560     return;
6561   }
6562 
6563   // To determine what the conversion from the result of calling the
6564   // conversion function to the type we're eventually trying to
6565   // convert to (ToType), we need to synthesize a call to the
6566   // conversion function and attempt copy initialization from it. This
6567   // makes sure that we get the right semantics with respect to
6568   // lvalues/rvalues and the type. Fortunately, we can allocate this
6569   // call on the stack and we don't need its arguments to be
6570   // well-formed.
6571   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6572                             VK_LValue, From->getLocStart());
6573   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6574                                 Context.getPointerType(Conversion->getType()),
6575                                 CK_FunctionToPointerDecay,
6576                                 &ConversionRef, VK_RValue);
6577 
6578   QualType ConversionType = Conversion->getConversionType();
6579   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6580     Candidate.Viable = false;
6581     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6582     return;
6583   }
6584 
6585   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6586 
6587   // Note that it is safe to allocate CallExpr on the stack here because
6588   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6589   // allocator).
6590   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6591   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6592                 From->getLocStart());
6593   ImplicitConversionSequence ICS =
6594     TryCopyInitialization(*this, &Call, ToType,
6595                           /*SuppressUserConversions=*/true,
6596                           /*InOverloadResolution=*/false,
6597                           /*AllowObjCWritebackConversion=*/false);
6598 
6599   switch (ICS.getKind()) {
6600   case ImplicitConversionSequence::StandardConversion:
6601     Candidate.FinalConversion = ICS.Standard;
6602 
6603     // C++ [over.ics.user]p3:
6604     //   If the user-defined conversion is specified by a specialization of a
6605     //   conversion function template, the second standard conversion sequence
6606     //   shall have exact match rank.
6607     if (Conversion->getPrimaryTemplate() &&
6608         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6609       Candidate.Viable = false;
6610       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6611       return;
6612     }
6613 
6614     // C++0x [dcl.init.ref]p5:
6615     //    In the second case, if the reference is an rvalue reference and
6616     //    the second standard conversion sequence of the user-defined
6617     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6618     //    program is ill-formed.
6619     if (ToType->isRValueReferenceType() &&
6620         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6621       Candidate.Viable = false;
6622       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6623       return;
6624     }
6625     break;
6626 
6627   case ImplicitConversionSequence::BadConversion:
6628     Candidate.Viable = false;
6629     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6630     return;
6631 
6632   default:
6633     llvm_unreachable(
6634            "Can only end up with a standard conversion sequence or failure");
6635   }
6636 
6637   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6638     Candidate.Viable = false;
6639     Candidate.FailureKind = ovl_fail_enable_if;
6640     Candidate.DeductionFailure.Data = FailedAttr;
6641     return;
6642   }
6643 }
6644 
6645 /// \brief Adds a conversion function template specialization
6646 /// candidate to the overload set, using template argument deduction
6647 /// to deduce the template arguments of the conversion function
6648 /// template from the type that we are converting to (C++
6649 /// [temp.deduct.conv]).
6650 void
6651 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6652                                      DeclAccessPair FoundDecl,
6653                                      CXXRecordDecl *ActingDC,
6654                                      Expr *From, QualType ToType,
6655                                      OverloadCandidateSet &CandidateSet,
6656                                      bool AllowObjCConversionOnExplicit) {
6657   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6658          "Only conversion function templates permitted here");
6659 
6660   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6661     return;
6662 
6663   TemplateDeductionInfo Info(CandidateSet.getLocation());
6664   CXXConversionDecl *Specialization = nullptr;
6665   if (TemplateDeductionResult Result
6666         = DeduceTemplateArguments(FunctionTemplate, ToType,
6667                                   Specialization, Info)) {
6668     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6669     Candidate.FoundDecl = FoundDecl;
6670     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6671     Candidate.Viable = false;
6672     Candidate.FailureKind = ovl_fail_bad_deduction;
6673     Candidate.IsSurrogate = false;
6674     Candidate.IgnoreObjectArgument = false;
6675     Candidate.ExplicitCallArguments = 1;
6676     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6677                                                           Info);
6678     return;
6679   }
6680 
6681   // Add the conversion function template specialization produced by
6682   // template argument deduction as a candidate.
6683   assert(Specialization && "Missing function template specialization?");
6684   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6685                          CandidateSet, AllowObjCConversionOnExplicit);
6686 }
6687 
6688 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6689 /// converts the given @c Object to a function pointer via the
6690 /// conversion function @c Conversion, and then attempts to call it
6691 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6692 /// the type of function that we'll eventually be calling.
6693 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6694                                  DeclAccessPair FoundDecl,
6695                                  CXXRecordDecl *ActingContext,
6696                                  const FunctionProtoType *Proto,
6697                                  Expr *Object,
6698                                  ArrayRef<Expr *> Args,
6699                                  OverloadCandidateSet& CandidateSet) {
6700   if (!CandidateSet.isNewCandidate(Conversion))
6701     return;
6702 
6703   // Overload resolution is always an unevaluated context.
6704   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6705 
6706   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6707   Candidate.FoundDecl = FoundDecl;
6708   Candidate.Function = nullptr;
6709   Candidate.Surrogate = Conversion;
6710   Candidate.Viable = true;
6711   Candidate.IsSurrogate = true;
6712   Candidate.IgnoreObjectArgument = false;
6713   Candidate.ExplicitCallArguments = Args.size();
6714 
6715   // Determine the implicit conversion sequence for the implicit
6716   // object parameter.
6717   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6718       *this, CandidateSet.getLocation(), Object->getType(),
6719       Object->Classify(Context), Conversion, ActingContext);
6720   if (ObjectInit.isBad()) {
6721     Candidate.Viable = false;
6722     Candidate.FailureKind = ovl_fail_bad_conversion;
6723     Candidate.Conversions[0] = ObjectInit;
6724     return;
6725   }
6726 
6727   // The first conversion is actually a user-defined conversion whose
6728   // first conversion is ObjectInit's standard conversion (which is
6729   // effectively a reference binding). Record it as such.
6730   Candidate.Conversions[0].setUserDefined();
6731   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6732   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6733   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6734   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6735   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6736   Candidate.Conversions[0].UserDefined.After
6737     = Candidate.Conversions[0].UserDefined.Before;
6738   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6739 
6740   // Find the
6741   unsigned NumParams = Proto->getNumParams();
6742 
6743   // (C++ 13.3.2p2): A candidate function having fewer than m
6744   // parameters is viable only if it has an ellipsis in its parameter
6745   // list (8.3.5).
6746   if (Args.size() > NumParams && !Proto->isVariadic()) {
6747     Candidate.Viable = false;
6748     Candidate.FailureKind = ovl_fail_too_many_arguments;
6749     return;
6750   }
6751 
6752   // Function types don't have any default arguments, so just check if
6753   // we have enough arguments.
6754   if (Args.size() < NumParams) {
6755     // Not enough arguments.
6756     Candidate.Viable = false;
6757     Candidate.FailureKind = ovl_fail_too_few_arguments;
6758     return;
6759   }
6760 
6761   // Determine the implicit conversion sequences for each of the
6762   // arguments.
6763   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6764     if (ArgIdx < NumParams) {
6765       // (C++ 13.3.2p3): for F to be a viable function, there shall
6766       // exist for each argument an implicit conversion sequence
6767       // (13.3.3.1) that converts that argument to the corresponding
6768       // parameter of F.
6769       QualType ParamType = Proto->getParamType(ArgIdx);
6770       Candidate.Conversions[ArgIdx + 1]
6771         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6772                                 /*SuppressUserConversions=*/false,
6773                                 /*InOverloadResolution=*/false,
6774                                 /*AllowObjCWritebackConversion=*/
6775                                   getLangOpts().ObjCAutoRefCount);
6776       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6777         Candidate.Viable = false;
6778         Candidate.FailureKind = ovl_fail_bad_conversion;
6779         return;
6780       }
6781     } else {
6782       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6783       // argument for which there is no corresponding parameter is
6784       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6785       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6786     }
6787   }
6788 
6789   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6790     Candidate.Viable = false;
6791     Candidate.FailureKind = ovl_fail_enable_if;
6792     Candidate.DeductionFailure.Data = FailedAttr;
6793     return;
6794   }
6795 }
6796 
6797 /// \brief Add overload candidates for overloaded operators that are
6798 /// member functions.
6799 ///
6800 /// Add the overloaded operator candidates that are member functions
6801 /// for the operator Op that was used in an operator expression such
6802 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6803 /// CandidateSet will store the added overload candidates. (C++
6804 /// [over.match.oper]).
6805 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6806                                        SourceLocation OpLoc,
6807                                        ArrayRef<Expr *> Args,
6808                                        OverloadCandidateSet& CandidateSet,
6809                                        SourceRange OpRange) {
6810   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6811 
6812   // C++ [over.match.oper]p3:
6813   //   For a unary operator @ with an operand of a type whose
6814   //   cv-unqualified version is T1, and for a binary operator @ with
6815   //   a left operand of a type whose cv-unqualified version is T1 and
6816   //   a right operand of a type whose cv-unqualified version is T2,
6817   //   three sets of candidate functions, designated member
6818   //   candidates, non-member candidates and built-in candidates, are
6819   //   constructed as follows:
6820   QualType T1 = Args[0]->getType();
6821 
6822   //     -- If T1 is a complete class type or a class currently being
6823   //        defined, the set of member candidates is the result of the
6824   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6825   //        the set of member candidates is empty.
6826   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6827     // Complete the type if it can be completed.
6828     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6829       return;
6830     // If the type is neither complete nor being defined, bail out now.
6831     if (!T1Rec->getDecl()->getDefinition())
6832       return;
6833 
6834     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6835     LookupQualifiedName(Operators, T1Rec->getDecl());
6836     Operators.suppressDiagnostics();
6837 
6838     for (LookupResult::iterator Oper = Operators.begin(),
6839                              OperEnd = Operators.end();
6840          Oper != OperEnd;
6841          ++Oper)
6842       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6843                          Args[0]->Classify(Context),
6844                          Args.slice(1),
6845                          CandidateSet,
6846                          /* SuppressUserConversions = */ false);
6847   }
6848 }
6849 
6850 /// AddBuiltinCandidate - Add a candidate for a built-in
6851 /// operator. ResultTy and ParamTys are the result and parameter types
6852 /// of the built-in candidate, respectively. Args and NumArgs are the
6853 /// arguments being passed to the candidate. IsAssignmentOperator
6854 /// should be true when this built-in candidate is an assignment
6855 /// operator. NumContextualBoolArguments is the number of arguments
6856 /// (at the beginning of the argument list) that will be contextually
6857 /// converted to bool.
6858 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6859                                ArrayRef<Expr *> Args,
6860                                OverloadCandidateSet& CandidateSet,
6861                                bool IsAssignmentOperator,
6862                                unsigned NumContextualBoolArguments) {
6863   // Overload resolution is always an unevaluated context.
6864   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6865 
6866   // Add this candidate
6867   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6868   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6869   Candidate.Function = nullptr;
6870   Candidate.IsSurrogate = false;
6871   Candidate.IgnoreObjectArgument = false;
6872   Candidate.BuiltinTypes.ResultTy = ResultTy;
6873   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6874     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6875 
6876   // Determine the implicit conversion sequences for each of the
6877   // arguments.
6878   Candidate.Viable = true;
6879   Candidate.ExplicitCallArguments = Args.size();
6880   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6881     // C++ [over.match.oper]p4:
6882     //   For the built-in assignment operators, conversions of the
6883     //   left operand are restricted as follows:
6884     //     -- no temporaries are introduced to hold the left operand, and
6885     //     -- no user-defined conversions are applied to the left
6886     //        operand to achieve a type match with the left-most
6887     //        parameter of a built-in candidate.
6888     //
6889     // We block these conversions by turning off user-defined
6890     // conversions, since that is the only way that initialization of
6891     // a reference to a non-class type can occur from something that
6892     // is not of the same type.
6893     if (ArgIdx < NumContextualBoolArguments) {
6894       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6895              "Contextual conversion to bool requires bool type");
6896       Candidate.Conversions[ArgIdx]
6897         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6898     } else {
6899       Candidate.Conversions[ArgIdx]
6900         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6901                                 ArgIdx == 0 && IsAssignmentOperator,
6902                                 /*InOverloadResolution=*/false,
6903                                 /*AllowObjCWritebackConversion=*/
6904                                   getLangOpts().ObjCAutoRefCount);
6905     }
6906     if (Candidate.Conversions[ArgIdx].isBad()) {
6907       Candidate.Viable = false;
6908       Candidate.FailureKind = ovl_fail_bad_conversion;
6909       break;
6910     }
6911   }
6912 }
6913 
6914 namespace {
6915 
6916 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6917 /// candidate operator functions for built-in operators (C++
6918 /// [over.built]). The types are separated into pointer types and
6919 /// enumeration types.
6920 class BuiltinCandidateTypeSet  {
6921   /// TypeSet - A set of types.
6922   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6923                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6924 
6925   /// PointerTypes - The set of pointer types that will be used in the
6926   /// built-in candidates.
6927   TypeSet PointerTypes;
6928 
6929   /// MemberPointerTypes - The set of member pointer types that will be
6930   /// used in the built-in candidates.
6931   TypeSet MemberPointerTypes;
6932 
6933   /// EnumerationTypes - The set of enumeration types that will be
6934   /// used in the built-in candidates.
6935   TypeSet EnumerationTypes;
6936 
6937   /// \brief The set of vector types that will be used in the built-in
6938   /// candidates.
6939   TypeSet VectorTypes;
6940 
6941   /// \brief A flag indicating non-record types are viable candidates
6942   bool HasNonRecordTypes;
6943 
6944   /// \brief A flag indicating whether either arithmetic or enumeration types
6945   /// were present in the candidate set.
6946   bool HasArithmeticOrEnumeralTypes;
6947 
6948   /// \brief A flag indicating whether the nullptr type was present in the
6949   /// candidate set.
6950   bool HasNullPtrType;
6951 
6952   /// Sema - The semantic analysis instance where we are building the
6953   /// candidate type set.
6954   Sema &SemaRef;
6955 
6956   /// Context - The AST context in which we will build the type sets.
6957   ASTContext &Context;
6958 
6959   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6960                                                const Qualifiers &VisibleQuals);
6961   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6962 
6963 public:
6964   /// iterator - Iterates through the types that are part of the set.
6965   typedef TypeSet::iterator iterator;
6966 
6967   BuiltinCandidateTypeSet(Sema &SemaRef)
6968     : HasNonRecordTypes(false),
6969       HasArithmeticOrEnumeralTypes(false),
6970       HasNullPtrType(false),
6971       SemaRef(SemaRef),
6972       Context(SemaRef.Context) { }
6973 
6974   void AddTypesConvertedFrom(QualType Ty,
6975                              SourceLocation Loc,
6976                              bool AllowUserConversions,
6977                              bool AllowExplicitConversions,
6978                              const Qualifiers &VisibleTypeConversionsQuals);
6979 
6980   /// pointer_begin - First pointer type found;
6981   iterator pointer_begin() { return PointerTypes.begin(); }
6982 
6983   /// pointer_end - Past the last pointer type found;
6984   iterator pointer_end() { return PointerTypes.end(); }
6985 
6986   /// member_pointer_begin - First member pointer type found;
6987   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6988 
6989   /// member_pointer_end - Past the last member pointer type found;
6990   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6991 
6992   /// enumeration_begin - First enumeration type found;
6993   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6994 
6995   /// enumeration_end - Past the last enumeration type found;
6996   iterator enumeration_end() { return EnumerationTypes.end(); }
6997 
6998   iterator vector_begin() { return VectorTypes.begin(); }
6999   iterator vector_end() { return VectorTypes.end(); }
7000 
7001   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7002   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7003   bool hasNullPtrType() const { return HasNullPtrType; }
7004 };
7005 
7006 } // end anonymous namespace
7007 
7008 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7009 /// the set of pointer types along with any more-qualified variants of
7010 /// that type. For example, if @p Ty is "int const *", this routine
7011 /// will add "int const *", "int const volatile *", "int const
7012 /// restrict *", and "int const volatile restrict *" to the set of
7013 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7014 /// false otherwise.
7015 ///
7016 /// FIXME: what to do about extended qualifiers?
7017 bool
7018 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7019                                              const Qualifiers &VisibleQuals) {
7020 
7021   // Insert this type.
7022   if (!PointerTypes.insert(Ty))
7023     return false;
7024 
7025   QualType PointeeTy;
7026   const PointerType *PointerTy = Ty->getAs<PointerType>();
7027   bool buildObjCPtr = false;
7028   if (!PointerTy) {
7029     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7030     PointeeTy = PTy->getPointeeType();
7031     buildObjCPtr = true;
7032   } else {
7033     PointeeTy = PointerTy->getPointeeType();
7034   }
7035 
7036   // Don't add qualified variants of arrays. For one, they're not allowed
7037   // (the qualifier would sink to the element type), and for another, the
7038   // only overload situation where it matters is subscript or pointer +- int,
7039   // and those shouldn't have qualifier variants anyway.
7040   if (PointeeTy->isArrayType())
7041     return true;
7042 
7043   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7044   bool hasVolatile = VisibleQuals.hasVolatile();
7045   bool hasRestrict = VisibleQuals.hasRestrict();
7046 
7047   // Iterate through all strict supersets of BaseCVR.
7048   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7049     if ((CVR | BaseCVR) != CVR) continue;
7050     // Skip over volatile if no volatile found anywhere in the types.
7051     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7052 
7053     // Skip over restrict if no restrict found anywhere in the types, or if
7054     // the type cannot be restrict-qualified.
7055     if ((CVR & Qualifiers::Restrict) &&
7056         (!hasRestrict ||
7057          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7058       continue;
7059 
7060     // Build qualified pointee type.
7061     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7062 
7063     // Build qualified pointer type.
7064     QualType QPointerTy;
7065     if (!buildObjCPtr)
7066       QPointerTy = Context.getPointerType(QPointeeTy);
7067     else
7068       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7069 
7070     // Insert qualified pointer type.
7071     PointerTypes.insert(QPointerTy);
7072   }
7073 
7074   return true;
7075 }
7076 
7077 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7078 /// to the set of pointer types along with any more-qualified variants of
7079 /// that type. For example, if @p Ty is "int const *", this routine
7080 /// will add "int const *", "int const volatile *", "int const
7081 /// restrict *", and "int const volatile restrict *" to the set of
7082 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7083 /// false otherwise.
7084 ///
7085 /// FIXME: what to do about extended qualifiers?
7086 bool
7087 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7088     QualType Ty) {
7089   // Insert this type.
7090   if (!MemberPointerTypes.insert(Ty))
7091     return false;
7092 
7093   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7094   assert(PointerTy && "type was not a member pointer type!");
7095 
7096   QualType PointeeTy = PointerTy->getPointeeType();
7097   // Don't add qualified variants of arrays. For one, they're not allowed
7098   // (the qualifier would sink to the element type), and for another, the
7099   // only overload situation where it matters is subscript or pointer +- int,
7100   // and those shouldn't have qualifier variants anyway.
7101   if (PointeeTy->isArrayType())
7102     return true;
7103   const Type *ClassTy = PointerTy->getClass();
7104 
7105   // Iterate through all strict supersets of the pointee type's CVR
7106   // qualifiers.
7107   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7108   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7109     if ((CVR | BaseCVR) != CVR) continue;
7110 
7111     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7112     MemberPointerTypes.insert(
7113       Context.getMemberPointerType(QPointeeTy, ClassTy));
7114   }
7115 
7116   return true;
7117 }
7118 
7119 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7120 /// Ty can be implicit converted to the given set of @p Types. We're
7121 /// primarily interested in pointer types and enumeration types. We also
7122 /// take member pointer types, for the conditional operator.
7123 /// AllowUserConversions is true if we should look at the conversion
7124 /// functions of a class type, and AllowExplicitConversions if we
7125 /// should also include the explicit conversion functions of a class
7126 /// type.
7127 void
7128 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7129                                                SourceLocation Loc,
7130                                                bool AllowUserConversions,
7131                                                bool AllowExplicitConversions,
7132                                                const Qualifiers &VisibleQuals) {
7133   // Only deal with canonical types.
7134   Ty = Context.getCanonicalType(Ty);
7135 
7136   // Look through reference types; they aren't part of the type of an
7137   // expression for the purposes of conversions.
7138   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7139     Ty = RefTy->getPointeeType();
7140 
7141   // If we're dealing with an array type, decay to the pointer.
7142   if (Ty->isArrayType())
7143     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7144 
7145   // Otherwise, we don't care about qualifiers on the type.
7146   Ty = Ty.getLocalUnqualifiedType();
7147 
7148   // Flag if we ever add a non-record type.
7149   const RecordType *TyRec = Ty->getAs<RecordType>();
7150   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7151 
7152   // Flag if we encounter an arithmetic type.
7153   HasArithmeticOrEnumeralTypes =
7154     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7155 
7156   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7157     PointerTypes.insert(Ty);
7158   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7159     // Insert our type, and its more-qualified variants, into the set
7160     // of types.
7161     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7162       return;
7163   } else if (Ty->isMemberPointerType()) {
7164     // Member pointers are far easier, since the pointee can't be converted.
7165     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7166       return;
7167   } else if (Ty->isEnumeralType()) {
7168     HasArithmeticOrEnumeralTypes = true;
7169     EnumerationTypes.insert(Ty);
7170   } else if (Ty->isVectorType()) {
7171     // We treat vector types as arithmetic types in many contexts as an
7172     // extension.
7173     HasArithmeticOrEnumeralTypes = true;
7174     VectorTypes.insert(Ty);
7175   } else if (Ty->isNullPtrType()) {
7176     HasNullPtrType = true;
7177   } else if (AllowUserConversions && TyRec) {
7178     // No conversion functions in incomplete types.
7179     if (!SemaRef.isCompleteType(Loc, Ty))
7180       return;
7181 
7182     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7183     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7184       if (isa<UsingShadowDecl>(D))
7185         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7186 
7187       // Skip conversion function templates; they don't tell us anything
7188       // about which builtin types we can convert to.
7189       if (isa<FunctionTemplateDecl>(D))
7190         continue;
7191 
7192       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7193       if (AllowExplicitConversions || !Conv->isExplicit()) {
7194         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7195                               VisibleQuals);
7196       }
7197     }
7198   }
7199 }
7200 
7201 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7202 /// the volatile- and non-volatile-qualified assignment operators for the
7203 /// given type to the candidate set.
7204 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7205                                                    QualType T,
7206                                                    ArrayRef<Expr *> Args,
7207                                     OverloadCandidateSet &CandidateSet) {
7208   QualType ParamTypes[2];
7209 
7210   // T& operator=(T&, T)
7211   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7212   ParamTypes[1] = T;
7213   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7214                         /*IsAssignmentOperator=*/true);
7215 
7216   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7217     // volatile T& operator=(volatile T&, T)
7218     ParamTypes[0]
7219       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7220     ParamTypes[1] = T;
7221     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7222                           /*IsAssignmentOperator=*/true);
7223   }
7224 }
7225 
7226 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7227 /// if any, found in visible type conversion functions found in ArgExpr's type.
7228 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7229     Qualifiers VRQuals;
7230     const RecordType *TyRec;
7231     if (const MemberPointerType *RHSMPType =
7232         ArgExpr->getType()->getAs<MemberPointerType>())
7233       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7234     else
7235       TyRec = ArgExpr->getType()->getAs<RecordType>();
7236     if (!TyRec) {
7237       // Just to be safe, assume the worst case.
7238       VRQuals.addVolatile();
7239       VRQuals.addRestrict();
7240       return VRQuals;
7241     }
7242 
7243     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7244     if (!ClassDecl->hasDefinition())
7245       return VRQuals;
7246 
7247     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7248       if (isa<UsingShadowDecl>(D))
7249         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7250       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7251         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7252         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7253           CanTy = ResTypeRef->getPointeeType();
7254         // Need to go down the pointer/mempointer chain and add qualifiers
7255         // as see them.
7256         bool done = false;
7257         while (!done) {
7258           if (CanTy.isRestrictQualified())
7259             VRQuals.addRestrict();
7260           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7261             CanTy = ResTypePtr->getPointeeType();
7262           else if (const MemberPointerType *ResTypeMPtr =
7263                 CanTy->getAs<MemberPointerType>())
7264             CanTy = ResTypeMPtr->getPointeeType();
7265           else
7266             done = true;
7267           if (CanTy.isVolatileQualified())
7268             VRQuals.addVolatile();
7269           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7270             return VRQuals;
7271         }
7272       }
7273     }
7274     return VRQuals;
7275 }
7276 
7277 namespace {
7278 
7279 /// \brief Helper class to manage the addition of builtin operator overload
7280 /// candidates. It provides shared state and utility methods used throughout
7281 /// the process, as well as a helper method to add each group of builtin
7282 /// operator overloads from the standard to a candidate set.
7283 class BuiltinOperatorOverloadBuilder {
7284   // Common instance state available to all overload candidate addition methods.
7285   Sema &S;
7286   ArrayRef<Expr *> Args;
7287   Qualifiers VisibleTypeConversionsQuals;
7288   bool HasArithmeticOrEnumeralCandidateType;
7289   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7290   OverloadCandidateSet &CandidateSet;
7291 
7292   // Define some constants used to index and iterate over the arithemetic types
7293   // provided via the getArithmeticType() method below.
7294   // The "promoted arithmetic types" are the arithmetic
7295   // types are that preserved by promotion (C++ [over.built]p2).
7296   static const unsigned FirstIntegralType = 4;
7297   static const unsigned LastIntegralType = 21;
7298   static const unsigned FirstPromotedIntegralType = 4,
7299                         LastPromotedIntegralType = 12;
7300   static const unsigned FirstPromotedArithmeticType = 0,
7301                         LastPromotedArithmeticType = 12;
7302   static const unsigned NumArithmeticTypes = 21;
7303 
7304   /// \brief Get the canonical type for a given arithmetic type index.
7305   CanQualType getArithmeticType(unsigned index) {
7306     assert(index < NumArithmeticTypes);
7307     static CanQualType ASTContext::* const
7308       ArithmeticTypes[NumArithmeticTypes] = {
7309       // Start of promoted types.
7310       &ASTContext::FloatTy,
7311       &ASTContext::DoubleTy,
7312       &ASTContext::LongDoubleTy,
7313       &ASTContext::Float128Ty,
7314 
7315       // Start of integral types.
7316       &ASTContext::IntTy,
7317       &ASTContext::LongTy,
7318       &ASTContext::LongLongTy,
7319       &ASTContext::Int128Ty,
7320       &ASTContext::UnsignedIntTy,
7321       &ASTContext::UnsignedLongTy,
7322       &ASTContext::UnsignedLongLongTy,
7323       &ASTContext::UnsignedInt128Ty,
7324       // End of promoted types.
7325 
7326       &ASTContext::BoolTy,
7327       &ASTContext::CharTy,
7328       &ASTContext::WCharTy,
7329       &ASTContext::Char16Ty,
7330       &ASTContext::Char32Ty,
7331       &ASTContext::SignedCharTy,
7332       &ASTContext::ShortTy,
7333       &ASTContext::UnsignedCharTy,
7334       &ASTContext::UnsignedShortTy,
7335       // End of integral types.
7336       // FIXME: What about complex? What about half?
7337     };
7338     return S.Context.*ArithmeticTypes[index];
7339   }
7340 
7341   /// \brief Gets the canonical type resulting from the usual arithemetic
7342   /// converions for the given arithmetic types.
7343   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7344     // Accelerator table for performing the usual arithmetic conversions.
7345     // The rules are basically:
7346     //   - if either is floating-point, use the wider floating-point
7347     //   - if same signedness, use the higher rank
7348     //   - if same size, use unsigned of the higher rank
7349     //   - use the larger type
7350     // These rules, together with the axiom that higher ranks are
7351     // never smaller, are sufficient to precompute all of these results
7352     // *except* when dealing with signed types of higher rank.
7353     // (we could precompute SLL x UI for all known platforms, but it's
7354     // better not to make any assumptions).
7355     // We assume that int128 has a higher rank than long long on all platforms.
7356     enum PromotedType : int8_t {
7357             Dep=-1,
7358             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7359     };
7360     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7361                                         [LastPromotedArithmeticType] = {
7362 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7363 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7364 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7365 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7366 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7367 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7368 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7369 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7370 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7371 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7372 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7373     };
7374 
7375     assert(L < LastPromotedArithmeticType);
7376     assert(R < LastPromotedArithmeticType);
7377     int Idx = ConversionsTable[L][R];
7378 
7379     // Fast path: the table gives us a concrete answer.
7380     if (Idx != Dep) return getArithmeticType(Idx);
7381 
7382     // Slow path: we need to compare widths.
7383     // An invariant is that the signed type has higher rank.
7384     CanQualType LT = getArithmeticType(L),
7385                 RT = getArithmeticType(R);
7386     unsigned LW = S.Context.getIntWidth(LT),
7387              RW = S.Context.getIntWidth(RT);
7388 
7389     // If they're different widths, use the signed type.
7390     if (LW > RW) return LT;
7391     else if (LW < RW) return RT;
7392 
7393     // Otherwise, use the unsigned type of the signed type's rank.
7394     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7395     assert(L == SLL || R == SLL);
7396     return S.Context.UnsignedLongLongTy;
7397   }
7398 
7399   /// \brief Helper method to factor out the common pattern of adding overloads
7400   /// for '++' and '--' builtin operators.
7401   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7402                                            bool HasVolatile,
7403                                            bool HasRestrict) {
7404     QualType ParamTypes[2] = {
7405       S.Context.getLValueReferenceType(CandidateTy),
7406       S.Context.IntTy
7407     };
7408 
7409     // Non-volatile version.
7410     if (Args.size() == 1)
7411       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7412     else
7413       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7414 
7415     // Use a heuristic to reduce number of builtin candidates in the set:
7416     // add volatile version only if there are conversions to a volatile type.
7417     if (HasVolatile) {
7418       ParamTypes[0] =
7419         S.Context.getLValueReferenceType(
7420           S.Context.getVolatileType(CandidateTy));
7421       if (Args.size() == 1)
7422         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7423       else
7424         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7425     }
7426 
7427     // Add restrict version only if there are conversions to a restrict type
7428     // and our candidate type is a non-restrict-qualified pointer.
7429     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7430         !CandidateTy.isRestrictQualified()) {
7431       ParamTypes[0]
7432         = S.Context.getLValueReferenceType(
7433             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7434       if (Args.size() == 1)
7435         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7436       else
7437         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7438 
7439       if (HasVolatile) {
7440         ParamTypes[0]
7441           = S.Context.getLValueReferenceType(
7442               S.Context.getCVRQualifiedType(CandidateTy,
7443                                             (Qualifiers::Volatile |
7444                                              Qualifiers::Restrict)));
7445         if (Args.size() == 1)
7446           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7447         else
7448           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7449       }
7450     }
7451 
7452   }
7453 
7454 public:
7455   BuiltinOperatorOverloadBuilder(
7456     Sema &S, ArrayRef<Expr *> Args,
7457     Qualifiers VisibleTypeConversionsQuals,
7458     bool HasArithmeticOrEnumeralCandidateType,
7459     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7460     OverloadCandidateSet &CandidateSet)
7461     : S(S), Args(Args),
7462       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7463       HasArithmeticOrEnumeralCandidateType(
7464         HasArithmeticOrEnumeralCandidateType),
7465       CandidateTypes(CandidateTypes),
7466       CandidateSet(CandidateSet) {
7467     // Validate some of our static helper constants in debug builds.
7468     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7469            "Invalid first promoted integral type");
7470     assert(getArithmeticType(LastPromotedIntegralType - 1)
7471              == S.Context.UnsignedInt128Ty &&
7472            "Invalid last promoted integral type");
7473     assert(getArithmeticType(FirstPromotedArithmeticType)
7474              == S.Context.FloatTy &&
7475            "Invalid first promoted arithmetic type");
7476     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7477              == S.Context.UnsignedInt128Ty &&
7478            "Invalid last promoted arithmetic type");
7479   }
7480 
7481   // C++ [over.built]p3:
7482   //
7483   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7484   //   is either volatile or empty, there exist candidate operator
7485   //   functions of the form
7486   //
7487   //       VQ T&      operator++(VQ T&);
7488   //       T          operator++(VQ T&, int);
7489   //
7490   // C++ [over.built]p4:
7491   //
7492   //   For every pair (T, VQ), where T is an arithmetic type other
7493   //   than bool, and VQ is either volatile or empty, there exist
7494   //   candidate operator functions of the form
7495   //
7496   //       VQ T&      operator--(VQ T&);
7497   //       T          operator--(VQ T&, int);
7498   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7499     if (!HasArithmeticOrEnumeralCandidateType)
7500       return;
7501 
7502     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7503          Arith < NumArithmeticTypes; ++Arith) {
7504       addPlusPlusMinusMinusStyleOverloads(
7505         getArithmeticType(Arith),
7506         VisibleTypeConversionsQuals.hasVolatile(),
7507         VisibleTypeConversionsQuals.hasRestrict());
7508     }
7509   }
7510 
7511   // C++ [over.built]p5:
7512   //
7513   //   For every pair (T, VQ), where T is a cv-qualified or
7514   //   cv-unqualified object type, and VQ is either volatile or
7515   //   empty, there exist candidate operator functions of the form
7516   //
7517   //       T*VQ&      operator++(T*VQ&);
7518   //       T*VQ&      operator--(T*VQ&);
7519   //       T*         operator++(T*VQ&, int);
7520   //       T*         operator--(T*VQ&, int);
7521   void addPlusPlusMinusMinusPointerOverloads() {
7522     for (BuiltinCandidateTypeSet::iterator
7523               Ptr = CandidateTypes[0].pointer_begin(),
7524            PtrEnd = CandidateTypes[0].pointer_end();
7525          Ptr != PtrEnd; ++Ptr) {
7526       // Skip pointer types that aren't pointers to object types.
7527       if (!(*Ptr)->getPointeeType()->isObjectType())
7528         continue;
7529 
7530       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7531         (!(*Ptr).isVolatileQualified() &&
7532          VisibleTypeConversionsQuals.hasVolatile()),
7533         (!(*Ptr).isRestrictQualified() &&
7534          VisibleTypeConversionsQuals.hasRestrict()));
7535     }
7536   }
7537 
7538   // C++ [over.built]p6:
7539   //   For every cv-qualified or cv-unqualified object type T, there
7540   //   exist candidate operator functions of the form
7541   //
7542   //       T&         operator*(T*);
7543   //
7544   // C++ [over.built]p7:
7545   //   For every function type T that does not have cv-qualifiers or a
7546   //   ref-qualifier, there exist candidate operator functions of the form
7547   //       T&         operator*(T*);
7548   void addUnaryStarPointerOverloads() {
7549     for (BuiltinCandidateTypeSet::iterator
7550               Ptr = CandidateTypes[0].pointer_begin(),
7551            PtrEnd = CandidateTypes[0].pointer_end();
7552          Ptr != PtrEnd; ++Ptr) {
7553       QualType ParamTy = *Ptr;
7554       QualType PointeeTy = ParamTy->getPointeeType();
7555       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7556         continue;
7557 
7558       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7559         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7560           continue;
7561 
7562       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7563                             &ParamTy, Args, CandidateSet);
7564     }
7565   }
7566 
7567   // C++ [over.built]p9:
7568   //  For every promoted arithmetic type T, there exist candidate
7569   //  operator functions of the form
7570   //
7571   //       T         operator+(T);
7572   //       T         operator-(T);
7573   void addUnaryPlusOrMinusArithmeticOverloads() {
7574     if (!HasArithmeticOrEnumeralCandidateType)
7575       return;
7576 
7577     for (unsigned Arith = FirstPromotedArithmeticType;
7578          Arith < LastPromotedArithmeticType; ++Arith) {
7579       QualType ArithTy = getArithmeticType(Arith);
7580       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7581     }
7582 
7583     // Extension: We also add these operators for vector types.
7584     for (BuiltinCandidateTypeSet::iterator
7585               Vec = CandidateTypes[0].vector_begin(),
7586            VecEnd = CandidateTypes[0].vector_end();
7587          Vec != VecEnd; ++Vec) {
7588       QualType VecTy = *Vec;
7589       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7590     }
7591   }
7592 
7593   // C++ [over.built]p8:
7594   //   For every type T, there exist candidate operator functions of
7595   //   the form
7596   //
7597   //       T*         operator+(T*);
7598   void addUnaryPlusPointerOverloads() {
7599     for (BuiltinCandidateTypeSet::iterator
7600               Ptr = CandidateTypes[0].pointer_begin(),
7601            PtrEnd = CandidateTypes[0].pointer_end();
7602          Ptr != PtrEnd; ++Ptr) {
7603       QualType ParamTy = *Ptr;
7604       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7605     }
7606   }
7607 
7608   // C++ [over.built]p10:
7609   //   For every promoted integral type T, there exist candidate
7610   //   operator functions of the form
7611   //
7612   //        T         operator~(T);
7613   void addUnaryTildePromotedIntegralOverloads() {
7614     if (!HasArithmeticOrEnumeralCandidateType)
7615       return;
7616 
7617     for (unsigned Int = FirstPromotedIntegralType;
7618          Int < LastPromotedIntegralType; ++Int) {
7619       QualType IntTy = getArithmeticType(Int);
7620       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7621     }
7622 
7623     // Extension: We also add this operator for vector types.
7624     for (BuiltinCandidateTypeSet::iterator
7625               Vec = CandidateTypes[0].vector_begin(),
7626            VecEnd = CandidateTypes[0].vector_end();
7627          Vec != VecEnd; ++Vec) {
7628       QualType VecTy = *Vec;
7629       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7630     }
7631   }
7632 
7633   // C++ [over.match.oper]p16:
7634   //   For every pointer to member type T or type std::nullptr_t, there
7635   //   exist candidate operator functions of the form
7636   //
7637   //        bool operator==(T,T);
7638   //        bool operator!=(T,T);
7639   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7640     /// Set of (canonical) types that we've already handled.
7641     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7642 
7643     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7644       for (BuiltinCandidateTypeSet::iterator
7645                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7646              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7647            MemPtr != MemPtrEnd;
7648            ++MemPtr) {
7649         // Don't add the same builtin candidate twice.
7650         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7651           continue;
7652 
7653         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7654         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7655       }
7656 
7657       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7658         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7659         if (AddedTypes.insert(NullPtrTy).second) {
7660           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7661           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7662                                 CandidateSet);
7663         }
7664       }
7665     }
7666   }
7667 
7668   // C++ [over.built]p15:
7669   //
7670   //   For every T, where T is an enumeration type or a pointer type,
7671   //   there exist candidate operator functions of the form
7672   //
7673   //        bool       operator<(T, T);
7674   //        bool       operator>(T, T);
7675   //        bool       operator<=(T, T);
7676   //        bool       operator>=(T, T);
7677   //        bool       operator==(T, T);
7678   //        bool       operator!=(T, T);
7679   void addRelationalPointerOrEnumeralOverloads() {
7680     // C++ [over.match.oper]p3:
7681     //   [...]the built-in candidates include all of the candidate operator
7682     //   functions defined in 13.6 that, compared to the given operator, [...]
7683     //   do not have the same parameter-type-list as any non-template non-member
7684     //   candidate.
7685     //
7686     // Note that in practice, this only affects enumeration types because there
7687     // aren't any built-in candidates of record type, and a user-defined operator
7688     // must have an operand of record or enumeration type. Also, the only other
7689     // overloaded operator with enumeration arguments, operator=,
7690     // cannot be overloaded for enumeration types, so this is the only place
7691     // where we must suppress candidates like this.
7692     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7693       UserDefinedBinaryOperators;
7694 
7695     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7696       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7697           CandidateTypes[ArgIdx].enumeration_end()) {
7698         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7699                                          CEnd = CandidateSet.end();
7700              C != CEnd; ++C) {
7701           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7702             continue;
7703 
7704           if (C->Function->isFunctionTemplateSpecialization())
7705             continue;
7706 
7707           QualType FirstParamType =
7708             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7709           QualType SecondParamType =
7710             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7711 
7712           // Skip if either parameter isn't of enumeral type.
7713           if (!FirstParamType->isEnumeralType() ||
7714               !SecondParamType->isEnumeralType())
7715             continue;
7716 
7717           // Add this operator to the set of known user-defined operators.
7718           UserDefinedBinaryOperators.insert(
7719             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7720                            S.Context.getCanonicalType(SecondParamType)));
7721         }
7722       }
7723     }
7724 
7725     /// Set of (canonical) types that we've already handled.
7726     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7727 
7728     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7729       for (BuiltinCandidateTypeSet::iterator
7730                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7731              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7732            Ptr != PtrEnd; ++Ptr) {
7733         // Don't add the same builtin candidate twice.
7734         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7735           continue;
7736 
7737         QualType ParamTypes[2] = { *Ptr, *Ptr };
7738         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7739       }
7740       for (BuiltinCandidateTypeSet::iterator
7741                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7742              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7743            Enum != EnumEnd; ++Enum) {
7744         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7745 
7746         // Don't add the same builtin candidate twice, or if a user defined
7747         // candidate exists.
7748         if (!AddedTypes.insert(CanonType).second ||
7749             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7750                                                             CanonType)))
7751           continue;
7752 
7753         QualType ParamTypes[2] = { *Enum, *Enum };
7754         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7755       }
7756     }
7757   }
7758 
7759   // C++ [over.built]p13:
7760   //
7761   //   For every cv-qualified or cv-unqualified object type T
7762   //   there exist candidate operator functions of the form
7763   //
7764   //      T*         operator+(T*, ptrdiff_t);
7765   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7766   //      T*         operator-(T*, ptrdiff_t);
7767   //      T*         operator+(ptrdiff_t, T*);
7768   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7769   //
7770   // C++ [over.built]p14:
7771   //
7772   //   For every T, where T is a pointer to object type, there
7773   //   exist candidate operator functions of the form
7774   //
7775   //      ptrdiff_t  operator-(T, T);
7776   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7777     /// Set of (canonical) types that we've already handled.
7778     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7779 
7780     for (int Arg = 0; Arg < 2; ++Arg) {
7781       QualType AsymmetricParamTypes[2] = {
7782         S.Context.getPointerDiffType(),
7783         S.Context.getPointerDiffType(),
7784       };
7785       for (BuiltinCandidateTypeSet::iterator
7786                 Ptr = CandidateTypes[Arg].pointer_begin(),
7787              PtrEnd = CandidateTypes[Arg].pointer_end();
7788            Ptr != PtrEnd; ++Ptr) {
7789         QualType PointeeTy = (*Ptr)->getPointeeType();
7790         if (!PointeeTy->isObjectType())
7791           continue;
7792 
7793         AsymmetricParamTypes[Arg] = *Ptr;
7794         if (Arg == 0 || Op == OO_Plus) {
7795           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7796           // T* operator+(ptrdiff_t, T*);
7797           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7798         }
7799         if (Op == OO_Minus) {
7800           // ptrdiff_t operator-(T, T);
7801           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7802             continue;
7803 
7804           QualType ParamTypes[2] = { *Ptr, *Ptr };
7805           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7806                                 Args, CandidateSet);
7807         }
7808       }
7809     }
7810   }
7811 
7812   // C++ [over.built]p12:
7813   //
7814   //   For every pair of promoted arithmetic types L and R, there
7815   //   exist candidate operator functions of the form
7816   //
7817   //        LR         operator*(L, R);
7818   //        LR         operator/(L, R);
7819   //        LR         operator+(L, R);
7820   //        LR         operator-(L, R);
7821   //        bool       operator<(L, R);
7822   //        bool       operator>(L, R);
7823   //        bool       operator<=(L, R);
7824   //        bool       operator>=(L, R);
7825   //        bool       operator==(L, R);
7826   //        bool       operator!=(L, R);
7827   //
7828   //   where LR is the result of the usual arithmetic conversions
7829   //   between types L and R.
7830   //
7831   // C++ [over.built]p24:
7832   //
7833   //   For every pair of promoted arithmetic types L and R, there exist
7834   //   candidate operator functions of the form
7835   //
7836   //        LR       operator?(bool, L, R);
7837   //
7838   //   where LR is the result of the usual arithmetic conversions
7839   //   between types L and R.
7840   // Our candidates ignore the first parameter.
7841   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7842     if (!HasArithmeticOrEnumeralCandidateType)
7843       return;
7844 
7845     for (unsigned Left = FirstPromotedArithmeticType;
7846          Left < LastPromotedArithmeticType; ++Left) {
7847       for (unsigned Right = FirstPromotedArithmeticType;
7848            Right < LastPromotedArithmeticType; ++Right) {
7849         QualType LandR[2] = { getArithmeticType(Left),
7850                               getArithmeticType(Right) };
7851         QualType Result =
7852           isComparison ? S.Context.BoolTy
7853                        : getUsualArithmeticConversions(Left, Right);
7854         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7855       }
7856     }
7857 
7858     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7859     // conditional operator for vector types.
7860     for (BuiltinCandidateTypeSet::iterator
7861               Vec1 = CandidateTypes[0].vector_begin(),
7862            Vec1End = CandidateTypes[0].vector_end();
7863          Vec1 != Vec1End; ++Vec1) {
7864       for (BuiltinCandidateTypeSet::iterator
7865                 Vec2 = CandidateTypes[1].vector_begin(),
7866              Vec2End = CandidateTypes[1].vector_end();
7867            Vec2 != Vec2End; ++Vec2) {
7868         QualType LandR[2] = { *Vec1, *Vec2 };
7869         QualType Result = S.Context.BoolTy;
7870         if (!isComparison) {
7871           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7872             Result = *Vec1;
7873           else
7874             Result = *Vec2;
7875         }
7876 
7877         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7878       }
7879     }
7880   }
7881 
7882   // C++ [over.built]p17:
7883   //
7884   //   For every pair of promoted integral types L and R, there
7885   //   exist candidate operator functions of the form
7886   //
7887   //      LR         operator%(L, R);
7888   //      LR         operator&(L, R);
7889   //      LR         operator^(L, R);
7890   //      LR         operator|(L, R);
7891   //      L          operator<<(L, R);
7892   //      L          operator>>(L, R);
7893   //
7894   //   where LR is the result of the usual arithmetic conversions
7895   //   between types L and R.
7896   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7897     if (!HasArithmeticOrEnumeralCandidateType)
7898       return;
7899 
7900     for (unsigned Left = FirstPromotedIntegralType;
7901          Left < LastPromotedIntegralType; ++Left) {
7902       for (unsigned Right = FirstPromotedIntegralType;
7903            Right < LastPromotedIntegralType; ++Right) {
7904         QualType LandR[2] = { getArithmeticType(Left),
7905                               getArithmeticType(Right) };
7906         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7907             ? LandR[0]
7908             : getUsualArithmeticConversions(Left, Right);
7909         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7910       }
7911     }
7912   }
7913 
7914   // C++ [over.built]p20:
7915   //
7916   //   For every pair (T, VQ), where T is an enumeration or
7917   //   pointer to member type and VQ is either volatile or
7918   //   empty, there exist candidate operator functions of the form
7919   //
7920   //        VQ T&      operator=(VQ T&, T);
7921   void addAssignmentMemberPointerOrEnumeralOverloads() {
7922     /// Set of (canonical) types that we've already handled.
7923     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7924 
7925     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7926       for (BuiltinCandidateTypeSet::iterator
7927                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7928              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7929            Enum != EnumEnd; ++Enum) {
7930         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7931           continue;
7932 
7933         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7934       }
7935 
7936       for (BuiltinCandidateTypeSet::iterator
7937                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7938              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7939            MemPtr != MemPtrEnd; ++MemPtr) {
7940         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7941           continue;
7942 
7943         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7944       }
7945     }
7946   }
7947 
7948   // C++ [over.built]p19:
7949   //
7950   //   For every pair (T, VQ), where T is any type and VQ is either
7951   //   volatile or empty, there exist candidate operator functions
7952   //   of the form
7953   //
7954   //        T*VQ&      operator=(T*VQ&, T*);
7955   //
7956   // C++ [over.built]p21:
7957   //
7958   //   For every pair (T, VQ), where T is a cv-qualified or
7959   //   cv-unqualified object type and VQ is either volatile or
7960   //   empty, there exist candidate operator functions of the form
7961   //
7962   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7963   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7964   void addAssignmentPointerOverloads(bool isEqualOp) {
7965     /// Set of (canonical) types that we've already handled.
7966     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7967 
7968     for (BuiltinCandidateTypeSet::iterator
7969               Ptr = CandidateTypes[0].pointer_begin(),
7970            PtrEnd = CandidateTypes[0].pointer_end();
7971          Ptr != PtrEnd; ++Ptr) {
7972       // If this is operator=, keep track of the builtin candidates we added.
7973       if (isEqualOp)
7974         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7975       else if (!(*Ptr)->getPointeeType()->isObjectType())
7976         continue;
7977 
7978       // non-volatile version
7979       QualType ParamTypes[2] = {
7980         S.Context.getLValueReferenceType(*Ptr),
7981         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7982       };
7983       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7984                             /*IsAssigmentOperator=*/ isEqualOp);
7985 
7986       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7987                           VisibleTypeConversionsQuals.hasVolatile();
7988       if (NeedVolatile) {
7989         // volatile version
7990         ParamTypes[0] =
7991           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7992         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7993                               /*IsAssigmentOperator=*/isEqualOp);
7994       }
7995 
7996       if (!(*Ptr).isRestrictQualified() &&
7997           VisibleTypeConversionsQuals.hasRestrict()) {
7998         // restrict version
7999         ParamTypes[0]
8000           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8001         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8002                               /*IsAssigmentOperator=*/isEqualOp);
8003 
8004         if (NeedVolatile) {
8005           // volatile restrict version
8006           ParamTypes[0]
8007             = S.Context.getLValueReferenceType(
8008                 S.Context.getCVRQualifiedType(*Ptr,
8009                                               (Qualifiers::Volatile |
8010                                                Qualifiers::Restrict)));
8011           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8012                                 /*IsAssigmentOperator=*/isEqualOp);
8013         }
8014       }
8015     }
8016 
8017     if (isEqualOp) {
8018       for (BuiltinCandidateTypeSet::iterator
8019                 Ptr = CandidateTypes[1].pointer_begin(),
8020              PtrEnd = CandidateTypes[1].pointer_end();
8021            Ptr != PtrEnd; ++Ptr) {
8022         // Make sure we don't add the same candidate twice.
8023         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8024           continue;
8025 
8026         QualType ParamTypes[2] = {
8027           S.Context.getLValueReferenceType(*Ptr),
8028           *Ptr,
8029         };
8030 
8031         // non-volatile version
8032         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8033                               /*IsAssigmentOperator=*/true);
8034 
8035         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8036                            VisibleTypeConversionsQuals.hasVolatile();
8037         if (NeedVolatile) {
8038           // volatile version
8039           ParamTypes[0] =
8040             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8041           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8042                                 /*IsAssigmentOperator=*/true);
8043         }
8044 
8045         if (!(*Ptr).isRestrictQualified() &&
8046             VisibleTypeConversionsQuals.hasRestrict()) {
8047           // restrict version
8048           ParamTypes[0]
8049             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8050           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8051                                 /*IsAssigmentOperator=*/true);
8052 
8053           if (NeedVolatile) {
8054             // volatile restrict version
8055             ParamTypes[0]
8056               = S.Context.getLValueReferenceType(
8057                   S.Context.getCVRQualifiedType(*Ptr,
8058                                                 (Qualifiers::Volatile |
8059                                                  Qualifiers::Restrict)));
8060             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8061                                   /*IsAssigmentOperator=*/true);
8062           }
8063         }
8064       }
8065     }
8066   }
8067 
8068   // C++ [over.built]p18:
8069   //
8070   //   For every triple (L, VQ, R), where L is an arithmetic type,
8071   //   VQ is either volatile or empty, and R is a promoted
8072   //   arithmetic type, there exist candidate operator functions of
8073   //   the form
8074   //
8075   //        VQ L&      operator=(VQ L&, R);
8076   //        VQ L&      operator*=(VQ L&, R);
8077   //        VQ L&      operator/=(VQ L&, R);
8078   //        VQ L&      operator+=(VQ L&, R);
8079   //        VQ L&      operator-=(VQ L&, R);
8080   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8081     if (!HasArithmeticOrEnumeralCandidateType)
8082       return;
8083 
8084     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8085       for (unsigned Right = FirstPromotedArithmeticType;
8086            Right < LastPromotedArithmeticType; ++Right) {
8087         QualType ParamTypes[2];
8088         ParamTypes[1] = getArithmeticType(Right);
8089 
8090         // Add this built-in operator as a candidate (VQ is empty).
8091         ParamTypes[0] =
8092           S.Context.getLValueReferenceType(getArithmeticType(Left));
8093         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8094                               /*IsAssigmentOperator=*/isEqualOp);
8095 
8096         // Add this built-in operator as a candidate (VQ is 'volatile').
8097         if (VisibleTypeConversionsQuals.hasVolatile()) {
8098           ParamTypes[0] =
8099             S.Context.getVolatileType(getArithmeticType(Left));
8100           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8101           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8102                                 /*IsAssigmentOperator=*/isEqualOp);
8103         }
8104       }
8105     }
8106 
8107     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8108     for (BuiltinCandidateTypeSet::iterator
8109               Vec1 = CandidateTypes[0].vector_begin(),
8110            Vec1End = CandidateTypes[0].vector_end();
8111          Vec1 != Vec1End; ++Vec1) {
8112       for (BuiltinCandidateTypeSet::iterator
8113                 Vec2 = CandidateTypes[1].vector_begin(),
8114              Vec2End = CandidateTypes[1].vector_end();
8115            Vec2 != Vec2End; ++Vec2) {
8116         QualType ParamTypes[2];
8117         ParamTypes[1] = *Vec2;
8118         // Add this built-in operator as a candidate (VQ is empty).
8119         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8120         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8121                               /*IsAssigmentOperator=*/isEqualOp);
8122 
8123         // Add this built-in operator as a candidate (VQ is 'volatile').
8124         if (VisibleTypeConversionsQuals.hasVolatile()) {
8125           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8126           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8127           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8128                                 /*IsAssigmentOperator=*/isEqualOp);
8129         }
8130       }
8131     }
8132   }
8133 
8134   // C++ [over.built]p22:
8135   //
8136   //   For every triple (L, VQ, R), where L is an integral type, VQ
8137   //   is either volatile or empty, and R is a promoted integral
8138   //   type, there exist candidate operator functions of the form
8139   //
8140   //        VQ L&       operator%=(VQ L&, R);
8141   //        VQ L&       operator<<=(VQ L&, R);
8142   //        VQ L&       operator>>=(VQ L&, R);
8143   //        VQ L&       operator&=(VQ L&, R);
8144   //        VQ L&       operator^=(VQ L&, R);
8145   //        VQ L&       operator|=(VQ L&, R);
8146   void addAssignmentIntegralOverloads() {
8147     if (!HasArithmeticOrEnumeralCandidateType)
8148       return;
8149 
8150     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8151       for (unsigned Right = FirstPromotedIntegralType;
8152            Right < LastPromotedIntegralType; ++Right) {
8153         QualType ParamTypes[2];
8154         ParamTypes[1] = getArithmeticType(Right);
8155 
8156         // Add this built-in operator as a candidate (VQ is empty).
8157         ParamTypes[0] =
8158           S.Context.getLValueReferenceType(getArithmeticType(Left));
8159         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8160         if (VisibleTypeConversionsQuals.hasVolatile()) {
8161           // Add this built-in operator as a candidate (VQ is 'volatile').
8162           ParamTypes[0] = getArithmeticType(Left);
8163           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8164           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8165           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8166         }
8167       }
8168     }
8169   }
8170 
8171   // C++ [over.operator]p23:
8172   //
8173   //   There also exist candidate operator functions of the form
8174   //
8175   //        bool        operator!(bool);
8176   //        bool        operator&&(bool, bool);
8177   //        bool        operator||(bool, bool);
8178   void addExclaimOverload() {
8179     QualType ParamTy = S.Context.BoolTy;
8180     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8181                           /*IsAssignmentOperator=*/false,
8182                           /*NumContextualBoolArguments=*/1);
8183   }
8184   void addAmpAmpOrPipePipeOverload() {
8185     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8186     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8187                           /*IsAssignmentOperator=*/false,
8188                           /*NumContextualBoolArguments=*/2);
8189   }
8190 
8191   // C++ [over.built]p13:
8192   //
8193   //   For every cv-qualified or cv-unqualified object type T there
8194   //   exist candidate operator functions of the form
8195   //
8196   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8197   //        T&         operator[](T*, ptrdiff_t);
8198   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8199   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8200   //        T&         operator[](ptrdiff_t, T*);
8201   void addSubscriptOverloads() {
8202     for (BuiltinCandidateTypeSet::iterator
8203               Ptr = CandidateTypes[0].pointer_begin(),
8204            PtrEnd = CandidateTypes[0].pointer_end();
8205          Ptr != PtrEnd; ++Ptr) {
8206       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8207       QualType PointeeType = (*Ptr)->getPointeeType();
8208       if (!PointeeType->isObjectType())
8209         continue;
8210 
8211       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8212 
8213       // T& operator[](T*, ptrdiff_t)
8214       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8215     }
8216 
8217     for (BuiltinCandidateTypeSet::iterator
8218               Ptr = CandidateTypes[1].pointer_begin(),
8219            PtrEnd = CandidateTypes[1].pointer_end();
8220          Ptr != PtrEnd; ++Ptr) {
8221       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8222       QualType PointeeType = (*Ptr)->getPointeeType();
8223       if (!PointeeType->isObjectType())
8224         continue;
8225 
8226       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8227 
8228       // T& operator[](ptrdiff_t, T*)
8229       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8230     }
8231   }
8232 
8233   // C++ [over.built]p11:
8234   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8235   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8236   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8237   //    there exist candidate operator functions of the form
8238   //
8239   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8240   //
8241   //    where CV12 is the union of CV1 and CV2.
8242   void addArrowStarOverloads() {
8243     for (BuiltinCandidateTypeSet::iterator
8244              Ptr = CandidateTypes[0].pointer_begin(),
8245            PtrEnd = CandidateTypes[0].pointer_end();
8246          Ptr != PtrEnd; ++Ptr) {
8247       QualType C1Ty = (*Ptr);
8248       QualType C1;
8249       QualifierCollector Q1;
8250       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8251       if (!isa<RecordType>(C1))
8252         continue;
8253       // heuristic to reduce number of builtin candidates in the set.
8254       // Add volatile/restrict version only if there are conversions to a
8255       // volatile/restrict type.
8256       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8257         continue;
8258       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8259         continue;
8260       for (BuiltinCandidateTypeSet::iterator
8261                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8262              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8263            MemPtr != MemPtrEnd; ++MemPtr) {
8264         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8265         QualType C2 = QualType(mptr->getClass(), 0);
8266         C2 = C2.getUnqualifiedType();
8267         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8268           break;
8269         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8270         // build CV12 T&
8271         QualType T = mptr->getPointeeType();
8272         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8273             T.isVolatileQualified())
8274           continue;
8275         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8276             T.isRestrictQualified())
8277           continue;
8278         T = Q1.apply(S.Context, T);
8279         QualType ResultTy = S.Context.getLValueReferenceType(T);
8280         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8281       }
8282     }
8283   }
8284 
8285   // Note that we don't consider the first argument, since it has been
8286   // contextually converted to bool long ago. The candidates below are
8287   // therefore added as binary.
8288   //
8289   // C++ [over.built]p25:
8290   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8291   //   enumeration type, there exist candidate operator functions of the form
8292   //
8293   //        T        operator?(bool, T, T);
8294   //
8295   void addConditionalOperatorOverloads() {
8296     /// Set of (canonical) types that we've already handled.
8297     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8298 
8299     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8300       for (BuiltinCandidateTypeSet::iterator
8301                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8302              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8303            Ptr != PtrEnd; ++Ptr) {
8304         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8305           continue;
8306 
8307         QualType ParamTypes[2] = { *Ptr, *Ptr };
8308         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8309       }
8310 
8311       for (BuiltinCandidateTypeSet::iterator
8312                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8313              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8314            MemPtr != MemPtrEnd; ++MemPtr) {
8315         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8316           continue;
8317 
8318         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8319         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8320       }
8321 
8322       if (S.getLangOpts().CPlusPlus11) {
8323         for (BuiltinCandidateTypeSet::iterator
8324                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8325                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8326              Enum != EnumEnd; ++Enum) {
8327           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8328             continue;
8329 
8330           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8331             continue;
8332 
8333           QualType ParamTypes[2] = { *Enum, *Enum };
8334           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8335         }
8336       }
8337     }
8338   }
8339 };
8340 
8341 } // end anonymous namespace
8342 
8343 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8344 /// operator overloads to the candidate set (C++ [over.built]), based
8345 /// on the operator @p Op and the arguments given. For example, if the
8346 /// operator is a binary '+', this routine might add "int
8347 /// operator+(int, int)" to cover integer addition.
8348 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8349                                         SourceLocation OpLoc,
8350                                         ArrayRef<Expr *> Args,
8351                                         OverloadCandidateSet &CandidateSet) {
8352   // Find all of the types that the arguments can convert to, but only
8353   // if the operator we're looking at has built-in operator candidates
8354   // that make use of these types. Also record whether we encounter non-record
8355   // candidate types or either arithmetic or enumeral candidate types.
8356   Qualifiers VisibleTypeConversionsQuals;
8357   VisibleTypeConversionsQuals.addConst();
8358   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8359     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8360 
8361   bool HasNonRecordCandidateType = false;
8362   bool HasArithmeticOrEnumeralCandidateType = false;
8363   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8364   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8365     CandidateTypes.emplace_back(*this);
8366     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8367                                                  OpLoc,
8368                                                  true,
8369                                                  (Op == OO_Exclaim ||
8370                                                   Op == OO_AmpAmp ||
8371                                                   Op == OO_PipePipe),
8372                                                  VisibleTypeConversionsQuals);
8373     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8374         CandidateTypes[ArgIdx].hasNonRecordTypes();
8375     HasArithmeticOrEnumeralCandidateType =
8376         HasArithmeticOrEnumeralCandidateType ||
8377         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8378   }
8379 
8380   // Exit early when no non-record types have been added to the candidate set
8381   // for any of the arguments to the operator.
8382   //
8383   // We can't exit early for !, ||, or &&, since there we have always have
8384   // 'bool' overloads.
8385   if (!HasNonRecordCandidateType &&
8386       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8387     return;
8388 
8389   // Setup an object to manage the common state for building overloads.
8390   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8391                                            VisibleTypeConversionsQuals,
8392                                            HasArithmeticOrEnumeralCandidateType,
8393                                            CandidateTypes, CandidateSet);
8394 
8395   // Dispatch over the operation to add in only those overloads which apply.
8396   switch (Op) {
8397   case OO_None:
8398   case NUM_OVERLOADED_OPERATORS:
8399     llvm_unreachable("Expected an overloaded operator");
8400 
8401   case OO_New:
8402   case OO_Delete:
8403   case OO_Array_New:
8404   case OO_Array_Delete:
8405   case OO_Call:
8406     llvm_unreachable(
8407                     "Special operators don't use AddBuiltinOperatorCandidates");
8408 
8409   case OO_Comma:
8410   case OO_Arrow:
8411   case OO_Coawait:
8412     // C++ [over.match.oper]p3:
8413     //   -- For the operator ',', the unary operator '&', the
8414     //      operator '->', or the operator 'co_await', the
8415     //      built-in candidates set is empty.
8416     break;
8417 
8418   case OO_Plus: // '+' is either unary or binary
8419     if (Args.size() == 1)
8420       OpBuilder.addUnaryPlusPointerOverloads();
8421     // Fall through.
8422 
8423   case OO_Minus: // '-' is either unary or binary
8424     if (Args.size() == 1) {
8425       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8426     } else {
8427       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8428       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8429     }
8430     break;
8431 
8432   case OO_Star: // '*' is either unary or binary
8433     if (Args.size() == 1)
8434       OpBuilder.addUnaryStarPointerOverloads();
8435     else
8436       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8437     break;
8438 
8439   case OO_Slash:
8440     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8441     break;
8442 
8443   case OO_PlusPlus:
8444   case OO_MinusMinus:
8445     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8446     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8447     break;
8448 
8449   case OO_EqualEqual:
8450   case OO_ExclaimEqual:
8451     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8452     // Fall through.
8453 
8454   case OO_Less:
8455   case OO_Greater:
8456   case OO_LessEqual:
8457   case OO_GreaterEqual:
8458     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8459     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8460     break;
8461 
8462   case OO_Percent:
8463   case OO_Caret:
8464   case OO_Pipe:
8465   case OO_LessLess:
8466   case OO_GreaterGreater:
8467     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8468     break;
8469 
8470   case OO_Amp: // '&' is either unary or binary
8471     if (Args.size() == 1)
8472       // C++ [over.match.oper]p3:
8473       //   -- For the operator ',', the unary operator '&', or the
8474       //      operator '->', the built-in candidates set is empty.
8475       break;
8476 
8477     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8478     break;
8479 
8480   case OO_Tilde:
8481     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8482     break;
8483 
8484   case OO_Equal:
8485     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8486     // Fall through.
8487 
8488   case OO_PlusEqual:
8489   case OO_MinusEqual:
8490     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8491     // Fall through.
8492 
8493   case OO_StarEqual:
8494   case OO_SlashEqual:
8495     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8496     break;
8497 
8498   case OO_PercentEqual:
8499   case OO_LessLessEqual:
8500   case OO_GreaterGreaterEqual:
8501   case OO_AmpEqual:
8502   case OO_CaretEqual:
8503   case OO_PipeEqual:
8504     OpBuilder.addAssignmentIntegralOverloads();
8505     break;
8506 
8507   case OO_Exclaim:
8508     OpBuilder.addExclaimOverload();
8509     break;
8510 
8511   case OO_AmpAmp:
8512   case OO_PipePipe:
8513     OpBuilder.addAmpAmpOrPipePipeOverload();
8514     break;
8515 
8516   case OO_Subscript:
8517     OpBuilder.addSubscriptOverloads();
8518     break;
8519 
8520   case OO_ArrowStar:
8521     OpBuilder.addArrowStarOverloads();
8522     break;
8523 
8524   case OO_Conditional:
8525     OpBuilder.addConditionalOperatorOverloads();
8526     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8527     break;
8528   }
8529 }
8530 
8531 /// \brief Add function candidates found via argument-dependent lookup
8532 /// to the set of overloading candidates.
8533 ///
8534 /// This routine performs argument-dependent name lookup based on the
8535 /// given function name (which may also be an operator name) and adds
8536 /// all of the overload candidates found by ADL to the overload
8537 /// candidate set (C++ [basic.lookup.argdep]).
8538 void
8539 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8540                                            SourceLocation Loc,
8541                                            ArrayRef<Expr *> Args,
8542                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8543                                            OverloadCandidateSet& CandidateSet,
8544                                            bool PartialOverloading) {
8545   ADLResult Fns;
8546 
8547   // FIXME: This approach for uniquing ADL results (and removing
8548   // redundant candidates from the set) relies on pointer-equality,
8549   // which means we need to key off the canonical decl.  However,
8550   // always going back to the canonical decl might not get us the
8551   // right set of default arguments.  What default arguments are
8552   // we supposed to consider on ADL candidates, anyway?
8553 
8554   // FIXME: Pass in the explicit template arguments?
8555   ArgumentDependentLookup(Name, Loc, Args, Fns);
8556 
8557   // Erase all of the candidates we already knew about.
8558   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8559                                    CandEnd = CandidateSet.end();
8560        Cand != CandEnd; ++Cand)
8561     if (Cand->Function) {
8562       Fns.erase(Cand->Function);
8563       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8564         Fns.erase(FunTmpl);
8565     }
8566 
8567   // For each of the ADL candidates we found, add it to the overload
8568   // set.
8569   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8570     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8571     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8572       if (ExplicitTemplateArgs)
8573         continue;
8574 
8575       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8576                            PartialOverloading);
8577     } else
8578       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8579                                    FoundDecl, ExplicitTemplateArgs,
8580                                    Args, CandidateSet, PartialOverloading);
8581   }
8582 }
8583 
8584 namespace {
8585 enum class Comparison { Equal, Better, Worse };
8586 }
8587 
8588 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8589 /// overload resolution.
8590 ///
8591 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8592 /// Cand1's first N enable_if attributes have precisely the same conditions as
8593 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8594 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8595 ///
8596 /// Note that you can have a pair of candidates such that Cand1's enable_if
8597 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8598 /// worse than Cand1's.
8599 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8600                                        const FunctionDecl *Cand2) {
8601   // Common case: One (or both) decls don't have enable_if attrs.
8602   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8603   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8604   if (!Cand1Attr || !Cand2Attr) {
8605     if (Cand1Attr == Cand2Attr)
8606       return Comparison::Equal;
8607     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8608   }
8609 
8610   // FIXME: The next several lines are just
8611   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8612   // instead of reverse order which is how they're stored in the AST.
8613   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8614   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8615 
8616   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8617   // has fewer enable_if attributes than Cand2.
8618   if (Cand1Attrs.size() < Cand2Attrs.size())
8619     return Comparison::Worse;
8620 
8621   auto Cand1I = Cand1Attrs.begin();
8622   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8623   for (auto &Cand2A : Cand2Attrs) {
8624     Cand1ID.clear();
8625     Cand2ID.clear();
8626 
8627     auto &Cand1A = *Cand1I++;
8628     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8629     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8630     if (Cand1ID != Cand2ID)
8631       return Comparison::Worse;
8632   }
8633 
8634   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8635 }
8636 
8637 /// isBetterOverloadCandidate - Determines whether the first overload
8638 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8639 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8640                                       const OverloadCandidate &Cand2,
8641                                       SourceLocation Loc,
8642                                       bool UserDefinedConversion) {
8643   // Define viable functions to be better candidates than non-viable
8644   // functions.
8645   if (!Cand2.Viable)
8646     return Cand1.Viable;
8647   else if (!Cand1.Viable)
8648     return false;
8649 
8650   // C++ [over.match.best]p1:
8651   //
8652   //   -- if F is a static member function, ICS1(F) is defined such
8653   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8654   //      any function G, and, symmetrically, ICS1(G) is neither
8655   //      better nor worse than ICS1(F).
8656   unsigned StartArg = 0;
8657   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8658     StartArg = 1;
8659 
8660   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8661     // We don't allow incompatible pointer conversions in C++.
8662     if (!S.getLangOpts().CPlusPlus)
8663       return ICS.isStandard() &&
8664              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8665 
8666     // The only ill-formed conversion we allow in C++ is the string literal to
8667     // char* conversion, which is only considered ill-formed after C++11.
8668     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8669            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8670   };
8671 
8672   // Define functions that don't require ill-formed conversions for a given
8673   // argument to be better candidates than functions that do.
8674   unsigned NumArgs = Cand1.NumConversions;
8675   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8676   bool HasBetterConversion = false;
8677   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8678     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8679     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8680     if (Cand1Bad != Cand2Bad) {
8681       if (Cand1Bad)
8682         return false;
8683       HasBetterConversion = true;
8684     }
8685   }
8686 
8687   if (HasBetterConversion)
8688     return true;
8689 
8690   // C++ [over.match.best]p1:
8691   //   A viable function F1 is defined to be a better function than another
8692   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8693   //   conversion sequence than ICSi(F2), and then...
8694   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8695     switch (CompareImplicitConversionSequences(S, Loc,
8696                                                Cand1.Conversions[ArgIdx],
8697                                                Cand2.Conversions[ArgIdx])) {
8698     case ImplicitConversionSequence::Better:
8699       // Cand1 has a better conversion sequence.
8700       HasBetterConversion = true;
8701       break;
8702 
8703     case ImplicitConversionSequence::Worse:
8704       // Cand1 can't be better than Cand2.
8705       return false;
8706 
8707     case ImplicitConversionSequence::Indistinguishable:
8708       // Do nothing.
8709       break;
8710     }
8711   }
8712 
8713   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8714   //       ICSj(F2), or, if not that,
8715   if (HasBetterConversion)
8716     return true;
8717 
8718   //   -- the context is an initialization by user-defined conversion
8719   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8720   //      from the return type of F1 to the destination type (i.e.,
8721   //      the type of the entity being initialized) is a better
8722   //      conversion sequence than the standard conversion sequence
8723   //      from the return type of F2 to the destination type.
8724   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8725       isa<CXXConversionDecl>(Cand1.Function) &&
8726       isa<CXXConversionDecl>(Cand2.Function)) {
8727     // First check whether we prefer one of the conversion functions over the
8728     // other. This only distinguishes the results in non-standard, extension
8729     // cases such as the conversion from a lambda closure type to a function
8730     // pointer or block.
8731     ImplicitConversionSequence::CompareKind Result =
8732         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8733     if (Result == ImplicitConversionSequence::Indistinguishable)
8734       Result = CompareStandardConversionSequences(S, Loc,
8735                                                   Cand1.FinalConversion,
8736                                                   Cand2.FinalConversion);
8737 
8738     if (Result != ImplicitConversionSequence::Indistinguishable)
8739       return Result == ImplicitConversionSequence::Better;
8740 
8741     // FIXME: Compare kind of reference binding if conversion functions
8742     // convert to a reference type used in direct reference binding, per
8743     // C++14 [over.match.best]p1 section 2 bullet 3.
8744   }
8745 
8746   //    -- F1 is a non-template function and F2 is a function template
8747   //       specialization, or, if not that,
8748   bool Cand1IsSpecialization = Cand1.Function &&
8749                                Cand1.Function->getPrimaryTemplate();
8750   bool Cand2IsSpecialization = Cand2.Function &&
8751                                Cand2.Function->getPrimaryTemplate();
8752   if (Cand1IsSpecialization != Cand2IsSpecialization)
8753     return Cand2IsSpecialization;
8754 
8755   //   -- F1 and F2 are function template specializations, and the function
8756   //      template for F1 is more specialized than the template for F2
8757   //      according to the partial ordering rules described in 14.5.5.2, or,
8758   //      if not that,
8759   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8760     if (FunctionTemplateDecl *BetterTemplate
8761           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8762                                          Cand2.Function->getPrimaryTemplate(),
8763                                          Loc,
8764                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8765                                                              : TPOC_Call,
8766                                          Cand1.ExplicitCallArguments,
8767                                          Cand2.ExplicitCallArguments))
8768       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8769   }
8770 
8771   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8772   // A derived-class constructor beats an (inherited) base class constructor.
8773   bool Cand1IsInherited =
8774       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8775   bool Cand2IsInherited =
8776       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8777   if (Cand1IsInherited != Cand2IsInherited)
8778     return Cand2IsInherited;
8779   else if (Cand1IsInherited) {
8780     assert(Cand2IsInherited);
8781     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8782     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8783     if (Cand1Class->isDerivedFrom(Cand2Class))
8784       return true;
8785     if (Cand2Class->isDerivedFrom(Cand1Class))
8786       return false;
8787     // Inherited from sibling base classes: still ambiguous.
8788   }
8789 
8790   // Check for enable_if value-based overload resolution.
8791   if (Cand1.Function && Cand2.Function) {
8792     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8793     if (Cmp != Comparison::Equal)
8794       return Cmp == Comparison::Better;
8795   }
8796 
8797   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8798     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8799     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8800            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8801   }
8802 
8803   bool HasPS1 = Cand1.Function != nullptr &&
8804                 functionHasPassObjectSizeParams(Cand1.Function);
8805   bool HasPS2 = Cand2.Function != nullptr &&
8806                 functionHasPassObjectSizeParams(Cand2.Function);
8807   return HasPS1 != HasPS2 && HasPS1;
8808 }
8809 
8810 /// Determine whether two declarations are "equivalent" for the purposes of
8811 /// name lookup and overload resolution. This applies when the same internal/no
8812 /// linkage entity is defined by two modules (probably by textually including
8813 /// the same header). In such a case, we don't consider the declarations to
8814 /// declare the same entity, but we also don't want lookups with both
8815 /// declarations visible to be ambiguous in some cases (this happens when using
8816 /// a modularized libstdc++).
8817 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8818                                                   const NamedDecl *B) {
8819   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8820   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8821   if (!VA || !VB)
8822     return false;
8823 
8824   // The declarations must be declaring the same name as an internal linkage
8825   // entity in different modules.
8826   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8827           VB->getDeclContext()->getRedeclContext()) ||
8828       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8829           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8830       VA->isExternallyVisible() || VB->isExternallyVisible())
8831     return false;
8832 
8833   // Check that the declarations appear to be equivalent.
8834   //
8835   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8836   // For constants and functions, we should check the initializer or body is
8837   // the same. For non-constant variables, we shouldn't allow it at all.
8838   if (Context.hasSameType(VA->getType(), VB->getType()))
8839     return true;
8840 
8841   // Enum constants within unnamed enumerations will have different types, but
8842   // may still be similar enough to be interchangeable for our purposes.
8843   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8844     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8845       // Only handle anonymous enums. If the enumerations were named and
8846       // equivalent, they would have been merged to the same type.
8847       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8848       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8849       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8850           !Context.hasSameType(EnumA->getIntegerType(),
8851                                EnumB->getIntegerType()))
8852         return false;
8853       // Allow this only if the value is the same for both enumerators.
8854       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8855     }
8856   }
8857 
8858   // Nothing else is sufficiently similar.
8859   return false;
8860 }
8861 
8862 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8863     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8864   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8865 
8866   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8867   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8868       << !M << (M ? M->getFullModuleName() : "");
8869 
8870   for (auto *E : Equiv) {
8871     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8872     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8873         << !M << (M ? M->getFullModuleName() : "");
8874   }
8875 }
8876 
8877 /// \brief Computes the best viable function (C++ 13.3.3)
8878 /// within an overload candidate set.
8879 ///
8880 /// \param Loc The location of the function name (or operator symbol) for
8881 /// which overload resolution occurs.
8882 ///
8883 /// \param Best If overload resolution was successful or found a deleted
8884 /// function, \p Best points to the candidate function found.
8885 ///
8886 /// \returns The result of overload resolution.
8887 OverloadingResult
8888 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8889                                          iterator &Best,
8890                                          bool UserDefinedConversion) {
8891   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8892   std::transform(begin(), end(), std::back_inserter(Candidates),
8893                  [](OverloadCandidate &Cand) { return &Cand; });
8894 
8895   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8896   // are accepted by both clang and NVCC. However, during a particular
8897   // compilation mode only one call variant is viable. We need to
8898   // exclude non-viable overload candidates from consideration based
8899   // only on their host/device attributes. Specifically, if one
8900   // candidate call is WrongSide and the other is SameSide, we ignore
8901   // the WrongSide candidate.
8902   if (S.getLangOpts().CUDA) {
8903     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8904     bool ContainsSameSideCandidate =
8905         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8906           return Cand->Function &&
8907                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8908                      Sema::CFP_SameSide;
8909         });
8910     if (ContainsSameSideCandidate) {
8911       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8912         return Cand->Function &&
8913                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8914                    Sema::CFP_WrongSide;
8915       };
8916       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8917                                       IsWrongSideCandidate),
8918                        Candidates.end());
8919     }
8920   }
8921 
8922   // Find the best viable function.
8923   Best = end();
8924   for (auto *Cand : Candidates)
8925     if (Cand->Viable)
8926       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8927                                                      UserDefinedConversion))
8928         Best = Cand;
8929 
8930   // If we didn't find any viable functions, abort.
8931   if (Best == end())
8932     return OR_No_Viable_Function;
8933 
8934   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8935 
8936   // Make sure that this function is better than every other viable
8937   // function. If not, we have an ambiguity.
8938   for (auto *Cand : Candidates) {
8939     if (Cand->Viable &&
8940         Cand != Best &&
8941         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8942                                    UserDefinedConversion)) {
8943       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8944                                                    Cand->Function)) {
8945         EquivalentCands.push_back(Cand->Function);
8946         continue;
8947       }
8948 
8949       Best = end();
8950       return OR_Ambiguous;
8951     }
8952   }
8953 
8954   // Best is the best viable function.
8955   if (Best->Function &&
8956       (Best->Function->isDeleted() ||
8957        S.isFunctionConsideredUnavailable(Best->Function)))
8958     return OR_Deleted;
8959 
8960   if (!EquivalentCands.empty())
8961     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8962                                                     EquivalentCands);
8963 
8964   return OR_Success;
8965 }
8966 
8967 namespace {
8968 
8969 enum OverloadCandidateKind {
8970   oc_function,
8971   oc_method,
8972   oc_constructor,
8973   oc_function_template,
8974   oc_method_template,
8975   oc_constructor_template,
8976   oc_implicit_default_constructor,
8977   oc_implicit_copy_constructor,
8978   oc_implicit_move_constructor,
8979   oc_implicit_copy_assignment,
8980   oc_implicit_move_assignment,
8981   oc_inherited_constructor,
8982   oc_inherited_constructor_template
8983 };
8984 
8985 static OverloadCandidateKind
8986 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
8987                           std::string &Description) {
8988   bool isTemplate = false;
8989 
8990   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8991     isTemplate = true;
8992     Description = S.getTemplateArgumentBindingsText(
8993       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8994   }
8995 
8996   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8997     if (!Ctor->isImplicit()) {
8998       if (isa<ConstructorUsingShadowDecl>(Found))
8999         return isTemplate ? oc_inherited_constructor_template
9000                           : oc_inherited_constructor;
9001       else
9002         return isTemplate ? oc_constructor_template : oc_constructor;
9003     }
9004 
9005     if (Ctor->isDefaultConstructor())
9006       return oc_implicit_default_constructor;
9007 
9008     if (Ctor->isMoveConstructor())
9009       return oc_implicit_move_constructor;
9010 
9011     assert(Ctor->isCopyConstructor() &&
9012            "unexpected sort of implicit constructor");
9013     return oc_implicit_copy_constructor;
9014   }
9015 
9016   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9017     // This actually gets spelled 'candidate function' for now, but
9018     // it doesn't hurt to split it out.
9019     if (!Meth->isImplicit())
9020       return isTemplate ? oc_method_template : oc_method;
9021 
9022     if (Meth->isMoveAssignmentOperator())
9023       return oc_implicit_move_assignment;
9024 
9025     if (Meth->isCopyAssignmentOperator())
9026       return oc_implicit_copy_assignment;
9027 
9028     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9029     return oc_method;
9030   }
9031 
9032   return isTemplate ? oc_function_template : oc_function;
9033 }
9034 
9035 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9036   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9037   // set.
9038   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9039     S.Diag(FoundDecl->getLocation(),
9040            diag::note_ovl_candidate_inherited_constructor)
9041       << Shadow->getNominatedBaseClass();
9042 }
9043 
9044 } // end anonymous namespace
9045 
9046 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9047                                     const FunctionDecl *FD) {
9048   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9049     bool AlwaysTrue;
9050     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9051       return false;
9052     if (!AlwaysTrue)
9053       return false;
9054   }
9055   return true;
9056 }
9057 
9058 /// \brief Returns true if we can take the address of the function.
9059 ///
9060 /// \param Complain - If true, we'll emit a diagnostic
9061 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9062 ///   we in overload resolution?
9063 /// \param Loc - The location of the statement we're complaining about. Ignored
9064 ///   if we're not complaining, or if we're in overload resolution.
9065 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9066                                               bool Complain,
9067                                               bool InOverloadResolution,
9068                                               SourceLocation Loc) {
9069   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9070     if (Complain) {
9071       if (InOverloadResolution)
9072         S.Diag(FD->getLocStart(),
9073                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9074       else
9075         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9076     }
9077     return false;
9078   }
9079 
9080   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9081     return P->hasAttr<PassObjectSizeAttr>();
9082   });
9083   if (I == FD->param_end())
9084     return true;
9085 
9086   if (Complain) {
9087     // Add one to ParamNo because it's user-facing
9088     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9089     if (InOverloadResolution)
9090       S.Diag(FD->getLocation(),
9091              diag::note_ovl_candidate_has_pass_object_size_params)
9092           << ParamNo;
9093     else
9094       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9095           << FD << ParamNo;
9096   }
9097   return false;
9098 }
9099 
9100 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9101                                                const FunctionDecl *FD) {
9102   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9103                                            /*InOverloadResolution=*/true,
9104                                            /*Loc=*/SourceLocation());
9105 }
9106 
9107 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9108                                              bool Complain,
9109                                              SourceLocation Loc) {
9110   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9111                                              /*InOverloadResolution=*/false,
9112                                              Loc);
9113 }
9114 
9115 // Notes the location of an overload candidate.
9116 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9117                                  QualType DestType, bool TakingAddress) {
9118   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9119     return;
9120 
9121   std::string FnDesc;
9122   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9123   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9124                              << (unsigned) K << FnDesc;
9125 
9126   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9127   Diag(Fn->getLocation(), PD);
9128   MaybeEmitInheritedConstructorNote(*this, Found);
9129 }
9130 
9131 // Notes the location of all overload candidates designated through
9132 // OverloadedExpr
9133 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9134                                      bool TakingAddress) {
9135   assert(OverloadedExpr->getType() == Context.OverloadTy);
9136 
9137   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9138   OverloadExpr *OvlExpr = Ovl.Expression;
9139 
9140   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9141                             IEnd = OvlExpr->decls_end();
9142        I != IEnd; ++I) {
9143     if (FunctionTemplateDecl *FunTmpl =
9144                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9145       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9146                             TakingAddress);
9147     } else if (FunctionDecl *Fun
9148                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9149       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9150     }
9151   }
9152 }
9153 
9154 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9155 /// "lead" diagnostic; it will be given two arguments, the source and
9156 /// target types of the conversion.
9157 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9158                                  Sema &S,
9159                                  SourceLocation CaretLoc,
9160                                  const PartialDiagnostic &PDiag) const {
9161   S.Diag(CaretLoc, PDiag)
9162     << Ambiguous.getFromType() << Ambiguous.getToType();
9163   // FIXME: The note limiting machinery is borrowed from
9164   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9165   // refactoring here.
9166   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9167   unsigned CandsShown = 0;
9168   AmbiguousConversionSequence::const_iterator I, E;
9169   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9170     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9171       break;
9172     ++CandsShown;
9173     S.NoteOverloadCandidate(I->first, I->second);
9174   }
9175   if (I != E)
9176     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9177 }
9178 
9179 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9180                                   unsigned I, bool TakingCandidateAddress) {
9181   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9182   assert(Conv.isBad());
9183   assert(Cand->Function && "for now, candidate must be a function");
9184   FunctionDecl *Fn = Cand->Function;
9185 
9186   // There's a conversion slot for the object argument if this is a
9187   // non-constructor method.  Note that 'I' corresponds the
9188   // conversion-slot index.
9189   bool isObjectArgument = false;
9190   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9191     if (I == 0)
9192       isObjectArgument = true;
9193     else
9194       I--;
9195   }
9196 
9197   std::string FnDesc;
9198   OverloadCandidateKind FnKind =
9199       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9200 
9201   Expr *FromExpr = Conv.Bad.FromExpr;
9202   QualType FromTy = Conv.Bad.getFromType();
9203   QualType ToTy = Conv.Bad.getToType();
9204 
9205   if (FromTy == S.Context.OverloadTy) {
9206     assert(FromExpr && "overload set argument came from implicit argument?");
9207     Expr *E = FromExpr->IgnoreParens();
9208     if (isa<UnaryOperator>(E))
9209       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9210     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9211 
9212     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9213       << (unsigned) FnKind << FnDesc
9214       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9215       << ToTy << Name << I+1;
9216     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9217     return;
9218   }
9219 
9220   // Do some hand-waving analysis to see if the non-viability is due
9221   // to a qualifier mismatch.
9222   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9223   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9224   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9225     CToTy = RT->getPointeeType();
9226   else {
9227     // TODO: detect and diagnose the full richness of const mismatches.
9228     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9229       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9230         CFromTy = FromPT->getPointeeType();
9231         CToTy = ToPT->getPointeeType();
9232       }
9233   }
9234 
9235   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9236       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9237     Qualifiers FromQs = CFromTy.getQualifiers();
9238     Qualifiers ToQs = CToTy.getQualifiers();
9239 
9240     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9241       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9242         << (unsigned) FnKind << FnDesc
9243         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9244         << FromTy
9245         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9246         << (unsigned) isObjectArgument << I+1;
9247       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9248       return;
9249     }
9250 
9251     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9252       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9253         << (unsigned) FnKind << FnDesc
9254         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9255         << FromTy
9256         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9257         << (unsigned) isObjectArgument << I+1;
9258       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9259       return;
9260     }
9261 
9262     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9263       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9264       << (unsigned) FnKind << FnDesc
9265       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9266       << FromTy
9267       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9268       << (unsigned) isObjectArgument << I+1;
9269       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9270       return;
9271     }
9272 
9273     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9274       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9275         << (unsigned) FnKind << FnDesc
9276         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9277         << FromTy << FromQs.hasUnaligned() << I+1;
9278       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9279       return;
9280     }
9281 
9282     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9283     assert(CVR && "unexpected qualifiers mismatch");
9284 
9285     if (isObjectArgument) {
9286       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9287         << (unsigned) FnKind << FnDesc
9288         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9289         << FromTy << (CVR - 1);
9290     } else {
9291       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9292         << (unsigned) FnKind << FnDesc
9293         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9294         << FromTy << (CVR - 1) << I+1;
9295     }
9296     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9297     return;
9298   }
9299 
9300   // Special diagnostic for failure to convert an initializer list, since
9301   // telling the user that it has type void is not useful.
9302   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9303     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9304       << (unsigned) FnKind << FnDesc
9305       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9306       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9307     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9308     return;
9309   }
9310 
9311   // Diagnose references or pointers to incomplete types differently,
9312   // since it's far from impossible that the incompleteness triggered
9313   // the failure.
9314   QualType TempFromTy = FromTy.getNonReferenceType();
9315   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9316     TempFromTy = PTy->getPointeeType();
9317   if (TempFromTy->isIncompleteType()) {
9318     // Emit the generic diagnostic and, optionally, add the hints to it.
9319     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9320       << (unsigned) FnKind << FnDesc
9321       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9322       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9323       << (unsigned) (Cand->Fix.Kind);
9324 
9325     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9326     return;
9327   }
9328 
9329   // Diagnose base -> derived pointer conversions.
9330   unsigned BaseToDerivedConversion = 0;
9331   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9332     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9333       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9334                                                FromPtrTy->getPointeeType()) &&
9335           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9336           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9337           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9338                           FromPtrTy->getPointeeType()))
9339         BaseToDerivedConversion = 1;
9340     }
9341   } else if (const ObjCObjectPointerType *FromPtrTy
9342                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9343     if (const ObjCObjectPointerType *ToPtrTy
9344                                         = ToTy->getAs<ObjCObjectPointerType>())
9345       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9346         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9347           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9348                                                 FromPtrTy->getPointeeType()) &&
9349               FromIface->isSuperClassOf(ToIface))
9350             BaseToDerivedConversion = 2;
9351   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9352     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9353         !FromTy->isIncompleteType() &&
9354         !ToRefTy->getPointeeType()->isIncompleteType() &&
9355         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9356       BaseToDerivedConversion = 3;
9357     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9358                ToTy.getNonReferenceType().getCanonicalType() ==
9359                FromTy.getNonReferenceType().getCanonicalType()) {
9360       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9361         << (unsigned) FnKind << FnDesc
9362         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9363         << (unsigned) isObjectArgument << I + 1;
9364       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9365       return;
9366     }
9367   }
9368 
9369   if (BaseToDerivedConversion) {
9370     S.Diag(Fn->getLocation(),
9371            diag::note_ovl_candidate_bad_base_to_derived_conv)
9372       << (unsigned) FnKind << FnDesc
9373       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9374       << (BaseToDerivedConversion - 1)
9375       << FromTy << ToTy << I+1;
9376     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9377     return;
9378   }
9379 
9380   if (isa<ObjCObjectPointerType>(CFromTy) &&
9381       isa<PointerType>(CToTy)) {
9382       Qualifiers FromQs = CFromTy.getQualifiers();
9383       Qualifiers ToQs = CToTy.getQualifiers();
9384       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9385         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9386         << (unsigned) FnKind << FnDesc
9387         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9388         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9389         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9390         return;
9391       }
9392   }
9393 
9394   if (TakingCandidateAddress &&
9395       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9396     return;
9397 
9398   // Emit the generic diagnostic and, optionally, add the hints to it.
9399   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9400   FDiag << (unsigned) FnKind << FnDesc
9401     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9402     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9403     << (unsigned) (Cand->Fix.Kind);
9404 
9405   // If we can fix the conversion, suggest the FixIts.
9406   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9407        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9408     FDiag << *HI;
9409   S.Diag(Fn->getLocation(), FDiag);
9410 
9411   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9412 }
9413 
9414 /// Additional arity mismatch diagnosis specific to a function overload
9415 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9416 /// over a candidate in any candidate set.
9417 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9418                                unsigned NumArgs) {
9419   FunctionDecl *Fn = Cand->Function;
9420   unsigned MinParams = Fn->getMinRequiredArguments();
9421 
9422   // With invalid overloaded operators, it's possible that we think we
9423   // have an arity mismatch when in fact it looks like we have the
9424   // right number of arguments, because only overloaded operators have
9425   // the weird behavior of overloading member and non-member functions.
9426   // Just don't report anything.
9427   if (Fn->isInvalidDecl() &&
9428       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9429     return true;
9430 
9431   if (NumArgs < MinParams) {
9432     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9433            (Cand->FailureKind == ovl_fail_bad_deduction &&
9434             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9435   } else {
9436     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9437            (Cand->FailureKind == ovl_fail_bad_deduction &&
9438             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9439   }
9440 
9441   return false;
9442 }
9443 
9444 /// General arity mismatch diagnosis over a candidate in a candidate set.
9445 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9446                                   unsigned NumFormalArgs) {
9447   assert(isa<FunctionDecl>(D) &&
9448       "The templated declaration should at least be a function"
9449       " when diagnosing bad template argument deduction due to too many"
9450       " or too few arguments");
9451 
9452   FunctionDecl *Fn = cast<FunctionDecl>(D);
9453 
9454   // TODO: treat calls to a missing default constructor as a special case
9455   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9456   unsigned MinParams = Fn->getMinRequiredArguments();
9457 
9458   // at least / at most / exactly
9459   unsigned mode, modeCount;
9460   if (NumFormalArgs < MinParams) {
9461     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9462         FnTy->isTemplateVariadic())
9463       mode = 0; // "at least"
9464     else
9465       mode = 2; // "exactly"
9466     modeCount = MinParams;
9467   } else {
9468     if (MinParams != FnTy->getNumParams())
9469       mode = 1; // "at most"
9470     else
9471       mode = 2; // "exactly"
9472     modeCount = FnTy->getNumParams();
9473   }
9474 
9475   std::string Description;
9476   OverloadCandidateKind FnKind =
9477       ClassifyOverloadCandidate(S, Found, Fn, Description);
9478 
9479   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9480     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9481       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9482       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9483   else
9484     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9485       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9486       << mode << modeCount << NumFormalArgs;
9487   MaybeEmitInheritedConstructorNote(S, Found);
9488 }
9489 
9490 /// Arity mismatch diagnosis specific to a function overload candidate.
9491 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9492                                   unsigned NumFormalArgs) {
9493   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9494     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9495 }
9496 
9497 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9498   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9499     return TD;
9500   llvm_unreachable("Unsupported: Getting the described template declaration"
9501                    " for bad deduction diagnosis");
9502 }
9503 
9504 /// Diagnose a failed template-argument deduction.
9505 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9506                                  DeductionFailureInfo &DeductionFailure,
9507                                  unsigned NumArgs,
9508                                  bool TakingCandidateAddress) {
9509   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9510   NamedDecl *ParamD;
9511   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9512   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9513   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9514   switch (DeductionFailure.Result) {
9515   case Sema::TDK_Success:
9516     llvm_unreachable("TDK_success while diagnosing bad deduction");
9517 
9518   case Sema::TDK_Incomplete: {
9519     assert(ParamD && "no parameter found for incomplete deduction result");
9520     S.Diag(Templated->getLocation(),
9521            diag::note_ovl_candidate_incomplete_deduction)
9522         << ParamD->getDeclName();
9523     MaybeEmitInheritedConstructorNote(S, Found);
9524     return;
9525   }
9526 
9527   case Sema::TDK_Underqualified: {
9528     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9529     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9530 
9531     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9532 
9533     // Param will have been canonicalized, but it should just be a
9534     // qualified version of ParamD, so move the qualifiers to that.
9535     QualifierCollector Qs;
9536     Qs.strip(Param);
9537     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9538     assert(S.Context.hasSameType(Param, NonCanonParam));
9539 
9540     // Arg has also been canonicalized, but there's nothing we can do
9541     // about that.  It also doesn't matter as much, because it won't
9542     // have any template parameters in it (because deduction isn't
9543     // done on dependent types).
9544     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9545 
9546     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9547         << ParamD->getDeclName() << Arg << NonCanonParam;
9548     MaybeEmitInheritedConstructorNote(S, Found);
9549     return;
9550   }
9551 
9552   case Sema::TDK_Inconsistent: {
9553     assert(ParamD && "no parameter found for inconsistent deduction result");
9554     int which = 0;
9555     if (isa<TemplateTypeParmDecl>(ParamD))
9556       which = 0;
9557     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9558       which = 1;
9559     else {
9560       which = 2;
9561     }
9562 
9563     S.Diag(Templated->getLocation(),
9564            diag::note_ovl_candidate_inconsistent_deduction)
9565         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9566         << *DeductionFailure.getSecondArg();
9567     MaybeEmitInheritedConstructorNote(S, Found);
9568     return;
9569   }
9570 
9571   case Sema::TDK_InvalidExplicitArguments:
9572     assert(ParamD && "no parameter found for invalid explicit arguments");
9573     if (ParamD->getDeclName())
9574       S.Diag(Templated->getLocation(),
9575              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9576           << ParamD->getDeclName();
9577     else {
9578       int index = 0;
9579       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9580         index = TTP->getIndex();
9581       else if (NonTypeTemplateParmDecl *NTTP
9582                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9583         index = NTTP->getIndex();
9584       else
9585         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9586       S.Diag(Templated->getLocation(),
9587              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9588           << (index + 1);
9589     }
9590     MaybeEmitInheritedConstructorNote(S, Found);
9591     return;
9592 
9593   case Sema::TDK_TooManyArguments:
9594   case Sema::TDK_TooFewArguments:
9595     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9596     return;
9597 
9598   case Sema::TDK_InstantiationDepth:
9599     S.Diag(Templated->getLocation(),
9600            diag::note_ovl_candidate_instantiation_depth);
9601     MaybeEmitInheritedConstructorNote(S, Found);
9602     return;
9603 
9604   case Sema::TDK_SubstitutionFailure: {
9605     // Format the template argument list into the argument string.
9606     SmallString<128> TemplateArgString;
9607     if (TemplateArgumentList *Args =
9608             DeductionFailure.getTemplateArgumentList()) {
9609       TemplateArgString = " ";
9610       TemplateArgString += S.getTemplateArgumentBindingsText(
9611           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9612     }
9613 
9614     // If this candidate was disabled by enable_if, say so.
9615     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9616     if (PDiag && PDiag->second.getDiagID() ==
9617           diag::err_typename_nested_not_found_enable_if) {
9618       // FIXME: Use the source range of the condition, and the fully-qualified
9619       //        name of the enable_if template. These are both present in PDiag.
9620       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9621         << "'enable_if'" << TemplateArgString;
9622       return;
9623     }
9624 
9625     // Format the SFINAE diagnostic into the argument string.
9626     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9627     //        formatted message in another diagnostic.
9628     SmallString<128> SFINAEArgString;
9629     SourceRange R;
9630     if (PDiag) {
9631       SFINAEArgString = ": ";
9632       R = SourceRange(PDiag->first, PDiag->first);
9633       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9634     }
9635 
9636     S.Diag(Templated->getLocation(),
9637            diag::note_ovl_candidate_substitution_failure)
9638         << TemplateArgString << SFINAEArgString << R;
9639     MaybeEmitInheritedConstructorNote(S, Found);
9640     return;
9641   }
9642 
9643   case Sema::TDK_FailedOverloadResolution: {
9644     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9645     S.Diag(Templated->getLocation(),
9646            diag::note_ovl_candidate_failed_overload_resolution)
9647         << R.Expression->getName();
9648     return;
9649   }
9650 
9651   case Sema::TDK_DeducedMismatch: {
9652     // Format the template argument list into the argument string.
9653     SmallString<128> TemplateArgString;
9654     if (TemplateArgumentList *Args =
9655             DeductionFailure.getTemplateArgumentList()) {
9656       TemplateArgString = " ";
9657       TemplateArgString += S.getTemplateArgumentBindingsText(
9658           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9659     }
9660 
9661     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9662         << (*DeductionFailure.getCallArgIndex() + 1)
9663         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9664         << TemplateArgString;
9665     break;
9666   }
9667 
9668   case Sema::TDK_NonDeducedMismatch: {
9669     // FIXME: Provide a source location to indicate what we couldn't match.
9670     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9671     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9672     if (FirstTA.getKind() == TemplateArgument::Template &&
9673         SecondTA.getKind() == TemplateArgument::Template) {
9674       TemplateName FirstTN = FirstTA.getAsTemplate();
9675       TemplateName SecondTN = SecondTA.getAsTemplate();
9676       if (FirstTN.getKind() == TemplateName::Template &&
9677           SecondTN.getKind() == TemplateName::Template) {
9678         if (FirstTN.getAsTemplateDecl()->getName() ==
9679             SecondTN.getAsTemplateDecl()->getName()) {
9680           // FIXME: This fixes a bad diagnostic where both templates are named
9681           // the same.  This particular case is a bit difficult since:
9682           // 1) It is passed as a string to the diagnostic printer.
9683           // 2) The diagnostic printer only attempts to find a better
9684           //    name for types, not decls.
9685           // Ideally, this should folded into the diagnostic printer.
9686           S.Diag(Templated->getLocation(),
9687                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9688               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9689           return;
9690         }
9691       }
9692     }
9693 
9694     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9695         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9696       return;
9697 
9698     // FIXME: For generic lambda parameters, check if the function is a lambda
9699     // call operator, and if so, emit a prettier and more informative
9700     // diagnostic that mentions 'auto' and lambda in addition to
9701     // (or instead of?) the canonical template type parameters.
9702     S.Diag(Templated->getLocation(),
9703            diag::note_ovl_candidate_non_deduced_mismatch)
9704         << FirstTA << SecondTA;
9705     return;
9706   }
9707   // TODO: diagnose these individually, then kill off
9708   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9709   case Sema::TDK_MiscellaneousDeductionFailure:
9710     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9711     MaybeEmitInheritedConstructorNote(S, Found);
9712     return;
9713   case Sema::TDK_CUDATargetMismatch:
9714     S.Diag(Templated->getLocation(),
9715            diag::note_cuda_ovl_candidate_target_mismatch);
9716     return;
9717   }
9718 }
9719 
9720 /// Diagnose a failed template-argument deduction, for function calls.
9721 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9722                                  unsigned NumArgs,
9723                                  bool TakingCandidateAddress) {
9724   unsigned TDK = Cand->DeductionFailure.Result;
9725   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9726     if (CheckArityMismatch(S, Cand, NumArgs))
9727       return;
9728   }
9729   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9730                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9731 }
9732 
9733 /// CUDA: diagnose an invalid call across targets.
9734 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9735   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9736   FunctionDecl *Callee = Cand->Function;
9737 
9738   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9739                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9740 
9741   std::string FnDesc;
9742   OverloadCandidateKind FnKind =
9743       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9744 
9745   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9746       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9747 
9748   // This could be an implicit constructor for which we could not infer the
9749   // target due to a collsion. Diagnose that case.
9750   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9751   if (Meth != nullptr && Meth->isImplicit()) {
9752     CXXRecordDecl *ParentClass = Meth->getParent();
9753     Sema::CXXSpecialMember CSM;
9754 
9755     switch (FnKind) {
9756     default:
9757       return;
9758     case oc_implicit_default_constructor:
9759       CSM = Sema::CXXDefaultConstructor;
9760       break;
9761     case oc_implicit_copy_constructor:
9762       CSM = Sema::CXXCopyConstructor;
9763       break;
9764     case oc_implicit_move_constructor:
9765       CSM = Sema::CXXMoveConstructor;
9766       break;
9767     case oc_implicit_copy_assignment:
9768       CSM = Sema::CXXCopyAssignment;
9769       break;
9770     case oc_implicit_move_assignment:
9771       CSM = Sema::CXXMoveAssignment;
9772       break;
9773     };
9774 
9775     bool ConstRHS = false;
9776     if (Meth->getNumParams()) {
9777       if (const ReferenceType *RT =
9778               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9779         ConstRHS = RT->getPointeeType().isConstQualified();
9780       }
9781     }
9782 
9783     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9784                                               /* ConstRHS */ ConstRHS,
9785                                               /* Diagnose */ true);
9786   }
9787 }
9788 
9789 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9790   FunctionDecl *Callee = Cand->Function;
9791   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9792 
9793   S.Diag(Callee->getLocation(),
9794          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9795       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9796 }
9797 
9798 /// Generates a 'note' diagnostic for an overload candidate.  We've
9799 /// already generated a primary error at the call site.
9800 ///
9801 /// It really does need to be a single diagnostic with its caret
9802 /// pointed at the candidate declaration.  Yes, this creates some
9803 /// major challenges of technical writing.  Yes, this makes pointing
9804 /// out problems with specific arguments quite awkward.  It's still
9805 /// better than generating twenty screens of text for every failed
9806 /// overload.
9807 ///
9808 /// It would be great to be able to express per-candidate problems
9809 /// more richly for those diagnostic clients that cared, but we'd
9810 /// still have to be just as careful with the default diagnostics.
9811 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9812                                   unsigned NumArgs,
9813                                   bool TakingCandidateAddress) {
9814   FunctionDecl *Fn = Cand->Function;
9815 
9816   // Note deleted candidates, but only if they're viable.
9817   if (Cand->Viable && (Fn->isDeleted() ||
9818       S.isFunctionConsideredUnavailable(Fn))) {
9819     std::string FnDesc;
9820     OverloadCandidateKind FnKind =
9821         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9822 
9823     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9824       << FnKind << FnDesc
9825       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9826     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9827     return;
9828   }
9829 
9830   // We don't really have anything else to say about viable candidates.
9831   if (Cand->Viable) {
9832     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9833     return;
9834   }
9835 
9836   switch (Cand->FailureKind) {
9837   case ovl_fail_too_many_arguments:
9838   case ovl_fail_too_few_arguments:
9839     return DiagnoseArityMismatch(S, Cand, NumArgs);
9840 
9841   case ovl_fail_bad_deduction:
9842     return DiagnoseBadDeduction(S, Cand, NumArgs,
9843                                 TakingCandidateAddress);
9844 
9845   case ovl_fail_illegal_constructor: {
9846     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9847       << (Fn->getPrimaryTemplate() ? 1 : 0);
9848     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9849     return;
9850   }
9851 
9852   case ovl_fail_trivial_conversion:
9853   case ovl_fail_bad_final_conversion:
9854   case ovl_fail_final_conversion_not_exact:
9855     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9856 
9857   case ovl_fail_bad_conversion: {
9858     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9859     for (unsigned N = Cand->NumConversions; I != N; ++I)
9860       if (Cand->Conversions[I].isBad())
9861         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9862 
9863     // FIXME: this currently happens when we're called from SemaInit
9864     // when user-conversion overload fails.  Figure out how to handle
9865     // those conditions and diagnose them well.
9866     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9867   }
9868 
9869   case ovl_fail_bad_target:
9870     return DiagnoseBadTarget(S, Cand);
9871 
9872   case ovl_fail_enable_if:
9873     return DiagnoseFailedEnableIfAttr(S, Cand);
9874 
9875   case ovl_fail_addr_not_available: {
9876     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9877     (void)Available;
9878     assert(!Available);
9879     break;
9880   }
9881   }
9882 }
9883 
9884 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9885   // Desugar the type of the surrogate down to a function type,
9886   // retaining as many typedefs as possible while still showing
9887   // the function type (and, therefore, its parameter types).
9888   QualType FnType = Cand->Surrogate->getConversionType();
9889   bool isLValueReference = false;
9890   bool isRValueReference = false;
9891   bool isPointer = false;
9892   if (const LValueReferenceType *FnTypeRef =
9893         FnType->getAs<LValueReferenceType>()) {
9894     FnType = FnTypeRef->getPointeeType();
9895     isLValueReference = true;
9896   } else if (const RValueReferenceType *FnTypeRef =
9897                FnType->getAs<RValueReferenceType>()) {
9898     FnType = FnTypeRef->getPointeeType();
9899     isRValueReference = true;
9900   }
9901   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9902     FnType = FnTypePtr->getPointeeType();
9903     isPointer = true;
9904   }
9905   // Desugar down to a function type.
9906   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9907   // Reconstruct the pointer/reference as appropriate.
9908   if (isPointer) FnType = S.Context.getPointerType(FnType);
9909   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9910   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9911 
9912   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9913     << FnType;
9914 }
9915 
9916 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9917                                          SourceLocation OpLoc,
9918                                          OverloadCandidate *Cand) {
9919   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9920   std::string TypeStr("operator");
9921   TypeStr += Opc;
9922   TypeStr += "(";
9923   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9924   if (Cand->NumConversions == 1) {
9925     TypeStr += ")";
9926     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9927   } else {
9928     TypeStr += ", ";
9929     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9930     TypeStr += ")";
9931     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9932   }
9933 }
9934 
9935 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9936                                          OverloadCandidate *Cand) {
9937   unsigned NoOperands = Cand->NumConversions;
9938   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9939     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9940     if (ICS.isBad()) break; // all meaningless after first invalid
9941     if (!ICS.isAmbiguous()) continue;
9942 
9943     ICS.DiagnoseAmbiguousConversion(
9944         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9945   }
9946 }
9947 
9948 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9949   if (Cand->Function)
9950     return Cand->Function->getLocation();
9951   if (Cand->IsSurrogate)
9952     return Cand->Surrogate->getLocation();
9953   return SourceLocation();
9954 }
9955 
9956 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9957   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9958   case Sema::TDK_Success:
9959     llvm_unreachable("TDK_success while diagnosing bad deduction");
9960 
9961   case Sema::TDK_Invalid:
9962   case Sema::TDK_Incomplete:
9963     return 1;
9964 
9965   case Sema::TDK_Underqualified:
9966   case Sema::TDK_Inconsistent:
9967     return 2;
9968 
9969   case Sema::TDK_SubstitutionFailure:
9970   case Sema::TDK_DeducedMismatch:
9971   case Sema::TDK_NonDeducedMismatch:
9972   case Sema::TDK_MiscellaneousDeductionFailure:
9973   case Sema::TDK_CUDATargetMismatch:
9974     return 3;
9975 
9976   case Sema::TDK_InstantiationDepth:
9977   case Sema::TDK_FailedOverloadResolution:
9978     return 4;
9979 
9980   case Sema::TDK_InvalidExplicitArguments:
9981     return 5;
9982 
9983   case Sema::TDK_TooManyArguments:
9984   case Sema::TDK_TooFewArguments:
9985     return 6;
9986   }
9987   llvm_unreachable("Unhandled deduction result");
9988 }
9989 
9990 namespace {
9991 struct CompareOverloadCandidatesForDisplay {
9992   Sema &S;
9993   SourceLocation Loc;
9994   size_t NumArgs;
9995 
9996   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9997       : S(S), NumArgs(nArgs) {}
9998 
9999   bool operator()(const OverloadCandidate *L,
10000                   const OverloadCandidate *R) {
10001     // Fast-path this check.
10002     if (L == R) return false;
10003 
10004     // Order first by viability.
10005     if (L->Viable) {
10006       if (!R->Viable) return true;
10007 
10008       // TODO: introduce a tri-valued comparison for overload
10009       // candidates.  Would be more worthwhile if we had a sort
10010       // that could exploit it.
10011       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10012       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10013     } else if (R->Viable)
10014       return false;
10015 
10016     assert(L->Viable == R->Viable);
10017 
10018     // Criteria by which we can sort non-viable candidates:
10019     if (!L->Viable) {
10020       // 1. Arity mismatches come after other candidates.
10021       if (L->FailureKind == ovl_fail_too_many_arguments ||
10022           L->FailureKind == ovl_fail_too_few_arguments) {
10023         if (R->FailureKind == ovl_fail_too_many_arguments ||
10024             R->FailureKind == ovl_fail_too_few_arguments) {
10025           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10026           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10027           if (LDist == RDist) {
10028             if (L->FailureKind == R->FailureKind)
10029               // Sort non-surrogates before surrogates.
10030               return !L->IsSurrogate && R->IsSurrogate;
10031             // Sort candidates requiring fewer parameters than there were
10032             // arguments given after candidates requiring more parameters
10033             // than there were arguments given.
10034             return L->FailureKind == ovl_fail_too_many_arguments;
10035           }
10036           return LDist < RDist;
10037         }
10038         return false;
10039       }
10040       if (R->FailureKind == ovl_fail_too_many_arguments ||
10041           R->FailureKind == ovl_fail_too_few_arguments)
10042         return true;
10043 
10044       // 2. Bad conversions come first and are ordered by the number
10045       // of bad conversions and quality of good conversions.
10046       if (L->FailureKind == ovl_fail_bad_conversion) {
10047         if (R->FailureKind != ovl_fail_bad_conversion)
10048           return true;
10049 
10050         // The conversion that can be fixed with a smaller number of changes,
10051         // comes first.
10052         unsigned numLFixes = L->Fix.NumConversionsFixed;
10053         unsigned numRFixes = R->Fix.NumConversionsFixed;
10054         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10055         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10056         if (numLFixes != numRFixes) {
10057           return numLFixes < numRFixes;
10058         }
10059 
10060         // If there's any ordering between the defined conversions...
10061         // FIXME: this might not be transitive.
10062         assert(L->NumConversions == R->NumConversions);
10063 
10064         int leftBetter = 0;
10065         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10066         for (unsigned E = L->NumConversions; I != E; ++I) {
10067           switch (CompareImplicitConversionSequences(S, Loc,
10068                                                      L->Conversions[I],
10069                                                      R->Conversions[I])) {
10070           case ImplicitConversionSequence::Better:
10071             leftBetter++;
10072             break;
10073 
10074           case ImplicitConversionSequence::Worse:
10075             leftBetter--;
10076             break;
10077 
10078           case ImplicitConversionSequence::Indistinguishable:
10079             break;
10080           }
10081         }
10082         if (leftBetter > 0) return true;
10083         if (leftBetter < 0) return false;
10084 
10085       } else if (R->FailureKind == ovl_fail_bad_conversion)
10086         return false;
10087 
10088       if (L->FailureKind == ovl_fail_bad_deduction) {
10089         if (R->FailureKind != ovl_fail_bad_deduction)
10090           return true;
10091 
10092         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10093           return RankDeductionFailure(L->DeductionFailure)
10094                < RankDeductionFailure(R->DeductionFailure);
10095       } else if (R->FailureKind == ovl_fail_bad_deduction)
10096         return false;
10097 
10098       // TODO: others?
10099     }
10100 
10101     // Sort everything else by location.
10102     SourceLocation LLoc = GetLocationForCandidate(L);
10103     SourceLocation RLoc = GetLocationForCandidate(R);
10104 
10105     // Put candidates without locations (e.g. builtins) at the end.
10106     if (LLoc.isInvalid()) return false;
10107     if (RLoc.isInvalid()) return true;
10108 
10109     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10110   }
10111 };
10112 }
10113 
10114 /// CompleteNonViableCandidate - Normally, overload resolution only
10115 /// computes up to the first. Produces the FixIt set if possible.
10116 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10117                                        ArrayRef<Expr *> Args) {
10118   assert(!Cand->Viable);
10119 
10120   // Don't do anything on failures other than bad conversion.
10121   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10122 
10123   // We only want the FixIts if all the arguments can be corrected.
10124   bool Unfixable = false;
10125   // Use a implicit copy initialization to check conversion fixes.
10126   Cand->Fix.setConversionChecker(TryCopyInitialization);
10127 
10128   // Skip forward to the first bad conversion.
10129   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10130   unsigned ConvCount = Cand->NumConversions;
10131   while (true) {
10132     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10133     ConvIdx++;
10134     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10135       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10136       break;
10137     }
10138   }
10139 
10140   if (ConvIdx == ConvCount)
10141     return;
10142 
10143   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10144          "remaining conversion is initialized?");
10145 
10146   // FIXME: this should probably be preserved from the overload
10147   // operation somehow.
10148   bool SuppressUserConversions = false;
10149 
10150   const FunctionProtoType* Proto;
10151   unsigned ArgIdx = ConvIdx;
10152 
10153   if (Cand->IsSurrogate) {
10154     QualType ConvType
10155       = Cand->Surrogate->getConversionType().getNonReferenceType();
10156     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10157       ConvType = ConvPtrType->getPointeeType();
10158     Proto = ConvType->getAs<FunctionProtoType>();
10159     ArgIdx--;
10160   } else if (Cand->Function) {
10161     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10162     if (isa<CXXMethodDecl>(Cand->Function) &&
10163         !isa<CXXConstructorDecl>(Cand->Function))
10164       ArgIdx--;
10165   } else {
10166     // Builtin binary operator with a bad first conversion.
10167     assert(ConvCount <= 3);
10168     for (; ConvIdx != ConvCount; ++ConvIdx)
10169       Cand->Conversions[ConvIdx]
10170         = TryCopyInitialization(S, Args[ConvIdx],
10171                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10172                                 SuppressUserConversions,
10173                                 /*InOverloadResolution*/ true,
10174                                 /*AllowObjCWritebackConversion=*/
10175                                   S.getLangOpts().ObjCAutoRefCount);
10176     return;
10177   }
10178 
10179   // Fill in the rest of the conversions.
10180   unsigned NumParams = Proto->getNumParams();
10181   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10182     if (ArgIdx < NumParams) {
10183       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10184           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10185           /*InOverloadResolution=*/true,
10186           /*AllowObjCWritebackConversion=*/
10187           S.getLangOpts().ObjCAutoRefCount);
10188       // Store the FixIt in the candidate if it exists.
10189       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10190         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10191     }
10192     else
10193       Cand->Conversions[ConvIdx].setEllipsis();
10194   }
10195 }
10196 
10197 /// PrintOverloadCandidates - When overload resolution fails, prints
10198 /// diagnostic messages containing the candidates in the candidate
10199 /// set.
10200 void OverloadCandidateSet::NoteCandidates(
10201     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10202     StringRef Opc, SourceLocation OpLoc,
10203     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10204   // Sort the candidates by viability and position.  Sorting directly would
10205   // be prohibitive, so we make a set of pointers and sort those.
10206   SmallVector<OverloadCandidate*, 32> Cands;
10207   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10208   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10209     if (!Filter(*Cand))
10210       continue;
10211     if (Cand->Viable)
10212       Cands.push_back(Cand);
10213     else if (OCD == OCD_AllCandidates) {
10214       CompleteNonViableCandidate(S, Cand, Args);
10215       if (Cand->Function || Cand->IsSurrogate)
10216         Cands.push_back(Cand);
10217       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10218       // want to list every possible builtin candidate.
10219     }
10220   }
10221 
10222   std::sort(Cands.begin(), Cands.end(),
10223             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10224 
10225   bool ReportedAmbiguousConversions = false;
10226 
10227   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10228   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10229   unsigned CandsShown = 0;
10230   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10231     OverloadCandidate *Cand = *I;
10232 
10233     // Set an arbitrary limit on the number of candidate functions we'll spam
10234     // the user with.  FIXME: This limit should depend on details of the
10235     // candidate list.
10236     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10237       break;
10238     }
10239     ++CandsShown;
10240 
10241     if (Cand->Function)
10242       NoteFunctionCandidate(S, Cand, Args.size(),
10243                             /*TakingCandidateAddress=*/false);
10244     else if (Cand->IsSurrogate)
10245       NoteSurrogateCandidate(S, Cand);
10246     else {
10247       assert(Cand->Viable &&
10248              "Non-viable built-in candidates are not added to Cands.");
10249       // Generally we only see ambiguities including viable builtin
10250       // operators if overload resolution got screwed up by an
10251       // ambiguous user-defined conversion.
10252       //
10253       // FIXME: It's quite possible for different conversions to see
10254       // different ambiguities, though.
10255       if (!ReportedAmbiguousConversions) {
10256         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10257         ReportedAmbiguousConversions = true;
10258       }
10259 
10260       // If this is a viable builtin, print it.
10261       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10262     }
10263   }
10264 
10265   if (I != E)
10266     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10267 }
10268 
10269 static SourceLocation
10270 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10271   return Cand->Specialization ? Cand->Specialization->getLocation()
10272                               : SourceLocation();
10273 }
10274 
10275 namespace {
10276 struct CompareTemplateSpecCandidatesForDisplay {
10277   Sema &S;
10278   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10279 
10280   bool operator()(const TemplateSpecCandidate *L,
10281                   const TemplateSpecCandidate *R) {
10282     // Fast-path this check.
10283     if (L == R)
10284       return false;
10285 
10286     // Assuming that both candidates are not matches...
10287 
10288     // Sort by the ranking of deduction failures.
10289     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10290       return RankDeductionFailure(L->DeductionFailure) <
10291              RankDeductionFailure(R->DeductionFailure);
10292 
10293     // Sort everything else by location.
10294     SourceLocation LLoc = GetLocationForCandidate(L);
10295     SourceLocation RLoc = GetLocationForCandidate(R);
10296 
10297     // Put candidates without locations (e.g. builtins) at the end.
10298     if (LLoc.isInvalid())
10299       return false;
10300     if (RLoc.isInvalid())
10301       return true;
10302 
10303     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10304   }
10305 };
10306 }
10307 
10308 /// Diagnose a template argument deduction failure.
10309 /// We are treating these failures as overload failures due to bad
10310 /// deductions.
10311 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10312                                                  bool ForTakingAddress) {
10313   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10314                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10315 }
10316 
10317 void TemplateSpecCandidateSet::destroyCandidates() {
10318   for (iterator i = begin(), e = end(); i != e; ++i) {
10319     i->DeductionFailure.Destroy();
10320   }
10321 }
10322 
10323 void TemplateSpecCandidateSet::clear() {
10324   destroyCandidates();
10325   Candidates.clear();
10326 }
10327 
10328 /// NoteCandidates - When no template specialization match is found, prints
10329 /// diagnostic messages containing the non-matching specializations that form
10330 /// the candidate set.
10331 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10332 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10333 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10334   // Sort the candidates by position (assuming no candidate is a match).
10335   // Sorting directly would be prohibitive, so we make a set of pointers
10336   // and sort those.
10337   SmallVector<TemplateSpecCandidate *, 32> Cands;
10338   Cands.reserve(size());
10339   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10340     if (Cand->Specialization)
10341       Cands.push_back(Cand);
10342     // Otherwise, this is a non-matching builtin candidate.  We do not,
10343     // in general, want to list every possible builtin candidate.
10344   }
10345 
10346   std::sort(Cands.begin(), Cands.end(),
10347             CompareTemplateSpecCandidatesForDisplay(S));
10348 
10349   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10350   // for generalization purposes (?).
10351   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10352 
10353   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10354   unsigned CandsShown = 0;
10355   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10356     TemplateSpecCandidate *Cand = *I;
10357 
10358     // Set an arbitrary limit on the number of candidates we'll spam
10359     // the user with.  FIXME: This limit should depend on details of the
10360     // candidate list.
10361     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10362       break;
10363     ++CandsShown;
10364 
10365     assert(Cand->Specialization &&
10366            "Non-matching built-in candidates are not added to Cands.");
10367     Cand->NoteDeductionFailure(S, ForTakingAddress);
10368   }
10369 
10370   if (I != E)
10371     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10372 }
10373 
10374 // [PossiblyAFunctionType]  -->   [Return]
10375 // NonFunctionType --> NonFunctionType
10376 // R (A) --> R(A)
10377 // R (*)(A) --> R (A)
10378 // R (&)(A) --> R (A)
10379 // R (S::*)(A) --> R (A)
10380 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10381   QualType Ret = PossiblyAFunctionType;
10382   if (const PointerType *ToTypePtr =
10383     PossiblyAFunctionType->getAs<PointerType>())
10384     Ret = ToTypePtr->getPointeeType();
10385   else if (const ReferenceType *ToTypeRef =
10386     PossiblyAFunctionType->getAs<ReferenceType>())
10387     Ret = ToTypeRef->getPointeeType();
10388   else if (const MemberPointerType *MemTypePtr =
10389     PossiblyAFunctionType->getAs<MemberPointerType>())
10390     Ret = MemTypePtr->getPointeeType();
10391   Ret =
10392     Context.getCanonicalType(Ret).getUnqualifiedType();
10393   return Ret;
10394 }
10395 
10396 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10397                                  bool Complain = true) {
10398   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10399       S.DeduceReturnType(FD, Loc, Complain))
10400     return true;
10401 
10402   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10403   if (S.getLangOpts().CPlusPlus1z &&
10404       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10405       !S.ResolveExceptionSpec(Loc, FPT))
10406     return true;
10407 
10408   return false;
10409 }
10410 
10411 namespace {
10412 // A helper class to help with address of function resolution
10413 // - allows us to avoid passing around all those ugly parameters
10414 class AddressOfFunctionResolver {
10415   Sema& S;
10416   Expr* SourceExpr;
10417   const QualType& TargetType;
10418   QualType TargetFunctionType; // Extracted function type from target type
10419 
10420   bool Complain;
10421   //DeclAccessPair& ResultFunctionAccessPair;
10422   ASTContext& Context;
10423 
10424   bool TargetTypeIsNonStaticMemberFunction;
10425   bool FoundNonTemplateFunction;
10426   bool StaticMemberFunctionFromBoundPointer;
10427   bool HasComplained;
10428 
10429   OverloadExpr::FindResult OvlExprInfo;
10430   OverloadExpr *OvlExpr;
10431   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10432   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10433   TemplateSpecCandidateSet FailedCandidates;
10434 
10435 public:
10436   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10437                             const QualType &TargetType, bool Complain)
10438       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10439         Complain(Complain), Context(S.getASTContext()),
10440         TargetTypeIsNonStaticMemberFunction(
10441             !!TargetType->getAs<MemberPointerType>()),
10442         FoundNonTemplateFunction(false),
10443         StaticMemberFunctionFromBoundPointer(false),
10444         HasComplained(false),
10445         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10446         OvlExpr(OvlExprInfo.Expression),
10447         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10448     ExtractUnqualifiedFunctionTypeFromTargetType();
10449 
10450     if (TargetFunctionType->isFunctionType()) {
10451       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10452         if (!UME->isImplicitAccess() &&
10453             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10454           StaticMemberFunctionFromBoundPointer = true;
10455     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10456       DeclAccessPair dap;
10457       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10458               OvlExpr, false, &dap)) {
10459         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10460           if (!Method->isStatic()) {
10461             // If the target type is a non-function type and the function found
10462             // is a non-static member function, pretend as if that was the
10463             // target, it's the only possible type to end up with.
10464             TargetTypeIsNonStaticMemberFunction = true;
10465 
10466             // And skip adding the function if its not in the proper form.
10467             // We'll diagnose this due to an empty set of functions.
10468             if (!OvlExprInfo.HasFormOfMemberPointer)
10469               return;
10470           }
10471 
10472         Matches.push_back(std::make_pair(dap, Fn));
10473       }
10474       return;
10475     }
10476 
10477     if (OvlExpr->hasExplicitTemplateArgs())
10478       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10479 
10480     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10481       // C++ [over.over]p4:
10482       //   If more than one function is selected, [...]
10483       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10484         if (FoundNonTemplateFunction)
10485           EliminateAllTemplateMatches();
10486         else
10487           EliminateAllExceptMostSpecializedTemplate();
10488       }
10489     }
10490 
10491     if (S.getLangOpts().CUDA && Matches.size() > 1)
10492       EliminateSuboptimalCudaMatches();
10493   }
10494 
10495   bool hasComplained() const { return HasComplained; }
10496 
10497 private:
10498   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10499     QualType Discard;
10500     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10501            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10502   }
10503 
10504   /// \return true if A is considered a better overload candidate for the
10505   /// desired type than B.
10506   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10507     // If A doesn't have exactly the correct type, we don't want to classify it
10508     // as "better" than anything else. This way, the user is required to
10509     // disambiguate for us if there are multiple candidates and no exact match.
10510     return candidateHasExactlyCorrectType(A) &&
10511            (!candidateHasExactlyCorrectType(B) ||
10512             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10513   }
10514 
10515   /// \return true if we were able to eliminate all but one overload candidate,
10516   /// false otherwise.
10517   bool eliminiateSuboptimalOverloadCandidates() {
10518     // Same algorithm as overload resolution -- one pass to pick the "best",
10519     // another pass to be sure that nothing is better than the best.
10520     auto Best = Matches.begin();
10521     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10522       if (isBetterCandidate(I->second, Best->second))
10523         Best = I;
10524 
10525     const FunctionDecl *BestFn = Best->second;
10526     auto IsBestOrInferiorToBest = [this, BestFn](
10527         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10528       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10529     };
10530 
10531     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10532     // option, so we can potentially give the user a better error
10533     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10534       return false;
10535     Matches[0] = *Best;
10536     Matches.resize(1);
10537     return true;
10538   }
10539 
10540   bool isTargetTypeAFunction() const {
10541     return TargetFunctionType->isFunctionType();
10542   }
10543 
10544   // [ToType]     [Return]
10545 
10546   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10547   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10548   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10549   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10550     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10551   }
10552 
10553   // return true if any matching specializations were found
10554   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10555                                    const DeclAccessPair& CurAccessFunPair) {
10556     if (CXXMethodDecl *Method
10557               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10558       // Skip non-static function templates when converting to pointer, and
10559       // static when converting to member pointer.
10560       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10561         return false;
10562     }
10563     else if (TargetTypeIsNonStaticMemberFunction)
10564       return false;
10565 
10566     // C++ [over.over]p2:
10567     //   If the name is a function template, template argument deduction is
10568     //   done (14.8.2.2), and if the argument deduction succeeds, the
10569     //   resulting template argument list is used to generate a single
10570     //   function template specialization, which is added to the set of
10571     //   overloaded functions considered.
10572     FunctionDecl *Specialization = nullptr;
10573     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10574     if (Sema::TemplateDeductionResult Result
10575           = S.DeduceTemplateArguments(FunctionTemplate,
10576                                       &OvlExplicitTemplateArgs,
10577                                       TargetFunctionType, Specialization,
10578                                       Info, /*IsAddressOfFunction*/true)) {
10579       // Make a note of the failed deduction for diagnostics.
10580       FailedCandidates.addCandidate()
10581           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10582                MakeDeductionFailureInfo(Context, Result, Info));
10583       return false;
10584     }
10585 
10586     // Template argument deduction ensures that we have an exact match or
10587     // compatible pointer-to-function arguments that would be adjusted by ICS.
10588     // This function template specicalization works.
10589     assert(S.isSameOrCompatibleFunctionType(
10590               Context.getCanonicalType(Specialization->getType()),
10591               Context.getCanonicalType(TargetFunctionType)));
10592 
10593     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10594       return false;
10595 
10596     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10597     return true;
10598   }
10599 
10600   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10601                                       const DeclAccessPair& CurAccessFunPair) {
10602     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10603       // Skip non-static functions when converting to pointer, and static
10604       // when converting to member pointer.
10605       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10606         return false;
10607     }
10608     else if (TargetTypeIsNonStaticMemberFunction)
10609       return false;
10610 
10611     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10612       if (S.getLangOpts().CUDA)
10613         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10614           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10615             return false;
10616 
10617       // If any candidate has a placeholder return type, trigger its deduction
10618       // now.
10619       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10620                                Complain)) {
10621         HasComplained |= Complain;
10622         return false;
10623       }
10624 
10625       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10626         return false;
10627 
10628       // If we're in C, we need to support types that aren't exactly identical.
10629       if (!S.getLangOpts().CPlusPlus ||
10630           candidateHasExactlyCorrectType(FunDecl)) {
10631         Matches.push_back(std::make_pair(
10632             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10633         FoundNonTemplateFunction = true;
10634         return true;
10635       }
10636     }
10637 
10638     return false;
10639   }
10640 
10641   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10642     bool Ret = false;
10643 
10644     // If the overload expression doesn't have the form of a pointer to
10645     // member, don't try to convert it to a pointer-to-member type.
10646     if (IsInvalidFormOfPointerToMemberFunction())
10647       return false;
10648 
10649     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10650                                E = OvlExpr->decls_end();
10651          I != E; ++I) {
10652       // Look through any using declarations to find the underlying function.
10653       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10654 
10655       // C++ [over.over]p3:
10656       //   Non-member functions and static member functions match
10657       //   targets of type "pointer-to-function" or "reference-to-function."
10658       //   Nonstatic member functions match targets of
10659       //   type "pointer-to-member-function."
10660       // Note that according to DR 247, the containing class does not matter.
10661       if (FunctionTemplateDecl *FunctionTemplate
10662                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10663         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10664           Ret = true;
10665       }
10666       // If we have explicit template arguments supplied, skip non-templates.
10667       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10668                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10669         Ret = true;
10670     }
10671     assert(Ret || Matches.empty());
10672     return Ret;
10673   }
10674 
10675   void EliminateAllExceptMostSpecializedTemplate() {
10676     //   [...] and any given function template specialization F1 is
10677     //   eliminated if the set contains a second function template
10678     //   specialization whose function template is more specialized
10679     //   than the function template of F1 according to the partial
10680     //   ordering rules of 14.5.5.2.
10681 
10682     // The algorithm specified above is quadratic. We instead use a
10683     // two-pass algorithm (similar to the one used to identify the
10684     // best viable function in an overload set) that identifies the
10685     // best function template (if it exists).
10686 
10687     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10688     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10689       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10690 
10691     // TODO: It looks like FailedCandidates does not serve much purpose
10692     // here, since the no_viable diagnostic has index 0.
10693     UnresolvedSetIterator Result = S.getMostSpecialized(
10694         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10695         SourceExpr->getLocStart(), S.PDiag(),
10696         S.PDiag(diag::err_addr_ovl_ambiguous)
10697           << Matches[0].second->getDeclName(),
10698         S.PDiag(diag::note_ovl_candidate)
10699           << (unsigned)oc_function_template,
10700         Complain, TargetFunctionType);
10701 
10702     if (Result != MatchesCopy.end()) {
10703       // Make it the first and only element
10704       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10705       Matches[0].second = cast<FunctionDecl>(*Result);
10706       Matches.resize(1);
10707     } else
10708       HasComplained |= Complain;
10709   }
10710 
10711   void EliminateAllTemplateMatches() {
10712     //   [...] any function template specializations in the set are
10713     //   eliminated if the set also contains a non-template function, [...]
10714     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10715       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10716         ++I;
10717       else {
10718         Matches[I] = Matches[--N];
10719         Matches.resize(N);
10720       }
10721     }
10722   }
10723 
10724   void EliminateSuboptimalCudaMatches() {
10725     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10726   }
10727 
10728 public:
10729   void ComplainNoMatchesFound() const {
10730     assert(Matches.empty());
10731     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10732         << OvlExpr->getName() << TargetFunctionType
10733         << OvlExpr->getSourceRange();
10734     if (FailedCandidates.empty())
10735       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10736                                   /*TakingAddress=*/true);
10737     else {
10738       // We have some deduction failure messages. Use them to diagnose
10739       // the function templates, and diagnose the non-template candidates
10740       // normally.
10741       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10742                                  IEnd = OvlExpr->decls_end();
10743            I != IEnd; ++I)
10744         if (FunctionDecl *Fun =
10745                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10746           if (!functionHasPassObjectSizeParams(Fun))
10747             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10748                                     /*TakingAddress=*/true);
10749       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10750     }
10751   }
10752 
10753   bool IsInvalidFormOfPointerToMemberFunction() const {
10754     return TargetTypeIsNonStaticMemberFunction &&
10755       !OvlExprInfo.HasFormOfMemberPointer;
10756   }
10757 
10758   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10759       // TODO: Should we condition this on whether any functions might
10760       // have matched, or is it more appropriate to do that in callers?
10761       // TODO: a fixit wouldn't hurt.
10762       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10763         << TargetType << OvlExpr->getSourceRange();
10764   }
10765 
10766   bool IsStaticMemberFunctionFromBoundPointer() const {
10767     return StaticMemberFunctionFromBoundPointer;
10768   }
10769 
10770   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10771     S.Diag(OvlExpr->getLocStart(),
10772            diag::err_invalid_form_pointer_member_function)
10773       << OvlExpr->getSourceRange();
10774   }
10775 
10776   void ComplainOfInvalidConversion() const {
10777     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10778       << OvlExpr->getName() << TargetType;
10779   }
10780 
10781   void ComplainMultipleMatchesFound() const {
10782     assert(Matches.size() > 1);
10783     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10784       << OvlExpr->getName()
10785       << OvlExpr->getSourceRange();
10786     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10787                                 /*TakingAddress=*/true);
10788   }
10789 
10790   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10791 
10792   int getNumMatches() const { return Matches.size(); }
10793 
10794   FunctionDecl* getMatchingFunctionDecl() const {
10795     if (Matches.size() != 1) return nullptr;
10796     return Matches[0].second;
10797   }
10798 
10799   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10800     if (Matches.size() != 1) return nullptr;
10801     return &Matches[0].first;
10802   }
10803 };
10804 }
10805 
10806 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10807 /// an overloaded function (C++ [over.over]), where @p From is an
10808 /// expression with overloaded function type and @p ToType is the type
10809 /// we're trying to resolve to. For example:
10810 ///
10811 /// @code
10812 /// int f(double);
10813 /// int f(int);
10814 ///
10815 /// int (*pfd)(double) = f; // selects f(double)
10816 /// @endcode
10817 ///
10818 /// This routine returns the resulting FunctionDecl if it could be
10819 /// resolved, and NULL otherwise. When @p Complain is true, this
10820 /// routine will emit diagnostics if there is an error.
10821 FunctionDecl *
10822 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10823                                          QualType TargetType,
10824                                          bool Complain,
10825                                          DeclAccessPair &FoundResult,
10826                                          bool *pHadMultipleCandidates) {
10827   assert(AddressOfExpr->getType() == Context.OverloadTy);
10828 
10829   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10830                                      Complain);
10831   int NumMatches = Resolver.getNumMatches();
10832   FunctionDecl *Fn = nullptr;
10833   bool ShouldComplain = Complain && !Resolver.hasComplained();
10834   if (NumMatches == 0 && ShouldComplain) {
10835     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10836       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10837     else
10838       Resolver.ComplainNoMatchesFound();
10839   }
10840   else if (NumMatches > 1 && ShouldComplain)
10841     Resolver.ComplainMultipleMatchesFound();
10842   else if (NumMatches == 1) {
10843     Fn = Resolver.getMatchingFunctionDecl();
10844     assert(Fn);
10845     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10846       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
10847     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10848     if (Complain) {
10849       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10850         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10851       else
10852         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10853     }
10854   }
10855 
10856   if (pHadMultipleCandidates)
10857     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10858   return Fn;
10859 }
10860 
10861 /// \brief Given an expression that refers to an overloaded function, try to
10862 /// resolve that function to a single function that can have its address taken.
10863 /// This will modify `Pair` iff it returns non-null.
10864 ///
10865 /// This routine can only realistically succeed if all but one candidates in the
10866 /// overload set for SrcExpr cannot have their addresses taken.
10867 FunctionDecl *
10868 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10869                                                   DeclAccessPair &Pair) {
10870   OverloadExpr::FindResult R = OverloadExpr::find(E);
10871   OverloadExpr *Ovl = R.Expression;
10872   FunctionDecl *Result = nullptr;
10873   DeclAccessPair DAP;
10874   // Don't use the AddressOfResolver because we're specifically looking for
10875   // cases where we have one overload candidate that lacks
10876   // enable_if/pass_object_size/...
10877   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10878     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10879     if (!FD)
10880       return nullptr;
10881 
10882     if (!checkAddressOfFunctionIsAvailable(FD))
10883       continue;
10884 
10885     // We have more than one result; quit.
10886     if (Result)
10887       return nullptr;
10888     DAP = I.getPair();
10889     Result = FD;
10890   }
10891 
10892   if (Result)
10893     Pair = DAP;
10894   return Result;
10895 }
10896 
10897 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10898 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10899 /// will perform access checks, diagnose the use of the resultant decl, and, if
10900 /// necessary, perform a function-to-pointer decay.
10901 ///
10902 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10903 /// Otherwise, returns true. This may emit diagnostics and return true.
10904 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10905     ExprResult &SrcExpr) {
10906   Expr *E = SrcExpr.get();
10907   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10908 
10909   DeclAccessPair DAP;
10910   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10911   if (!Found)
10912     return false;
10913 
10914   // Emitting multiple diagnostics for a function that is both inaccessible and
10915   // unavailable is consistent with our behavior elsewhere. So, always check
10916   // for both.
10917   DiagnoseUseOfDecl(Found, E->getExprLoc());
10918   CheckAddressOfMemberAccess(E, DAP);
10919   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10920   if (Fixed->getType()->isFunctionType())
10921     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10922   else
10923     SrcExpr = Fixed;
10924   return true;
10925 }
10926 
10927 /// \brief Given an expression that refers to an overloaded function, try to
10928 /// resolve that overloaded function expression down to a single function.
10929 ///
10930 /// This routine can only resolve template-ids that refer to a single function
10931 /// template, where that template-id refers to a single template whose template
10932 /// arguments are either provided by the template-id or have defaults,
10933 /// as described in C++0x [temp.arg.explicit]p3.
10934 ///
10935 /// If no template-ids are found, no diagnostics are emitted and NULL is
10936 /// returned.
10937 FunctionDecl *
10938 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10939                                                   bool Complain,
10940                                                   DeclAccessPair *FoundResult) {
10941   // C++ [over.over]p1:
10942   //   [...] [Note: any redundant set of parentheses surrounding the
10943   //   overloaded function name is ignored (5.1). ]
10944   // C++ [over.over]p1:
10945   //   [...] The overloaded function name can be preceded by the &
10946   //   operator.
10947 
10948   // If we didn't actually find any template-ids, we're done.
10949   if (!ovl->hasExplicitTemplateArgs())
10950     return nullptr;
10951 
10952   TemplateArgumentListInfo ExplicitTemplateArgs;
10953   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10954   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10955 
10956   // Look through all of the overloaded functions, searching for one
10957   // whose type matches exactly.
10958   FunctionDecl *Matched = nullptr;
10959   for (UnresolvedSetIterator I = ovl->decls_begin(),
10960          E = ovl->decls_end(); I != E; ++I) {
10961     // C++0x [temp.arg.explicit]p3:
10962     //   [...] In contexts where deduction is done and fails, or in contexts
10963     //   where deduction is not done, if a template argument list is
10964     //   specified and it, along with any default template arguments,
10965     //   identifies a single function template specialization, then the
10966     //   template-id is an lvalue for the function template specialization.
10967     FunctionTemplateDecl *FunctionTemplate
10968       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10969 
10970     // C++ [over.over]p2:
10971     //   If the name is a function template, template argument deduction is
10972     //   done (14.8.2.2), and if the argument deduction succeeds, the
10973     //   resulting template argument list is used to generate a single
10974     //   function template specialization, which is added to the set of
10975     //   overloaded functions considered.
10976     FunctionDecl *Specialization = nullptr;
10977     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10978     if (TemplateDeductionResult Result
10979           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10980                                     Specialization, Info,
10981                                     /*IsAddressOfFunction*/true)) {
10982       // Make a note of the failed deduction for diagnostics.
10983       // TODO: Actually use the failed-deduction info?
10984       FailedCandidates.addCandidate()
10985           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10986                MakeDeductionFailureInfo(Context, Result, Info));
10987       continue;
10988     }
10989 
10990     assert(Specialization && "no specialization and no error?");
10991 
10992     // Multiple matches; we can't resolve to a single declaration.
10993     if (Matched) {
10994       if (Complain) {
10995         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10996           << ovl->getName();
10997         NoteAllOverloadCandidates(ovl);
10998       }
10999       return nullptr;
11000     }
11001 
11002     Matched = Specialization;
11003     if (FoundResult) *FoundResult = I.getPair();
11004   }
11005 
11006   if (Matched &&
11007       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11008     return nullptr;
11009 
11010   return Matched;
11011 }
11012 
11013 
11014 
11015 
11016 // Resolve and fix an overloaded expression that can be resolved
11017 // because it identifies a single function template specialization.
11018 //
11019 // Last three arguments should only be supplied if Complain = true
11020 //
11021 // Return true if it was logically possible to so resolve the
11022 // expression, regardless of whether or not it succeeded.  Always
11023 // returns true if 'complain' is set.
11024 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11025                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11026                       bool complain, SourceRange OpRangeForComplaining,
11027                                            QualType DestTypeForComplaining,
11028                                             unsigned DiagIDForComplaining) {
11029   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11030 
11031   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11032 
11033   DeclAccessPair found;
11034   ExprResult SingleFunctionExpression;
11035   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11036                            ovl.Expression, /*complain*/ false, &found)) {
11037     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11038       SrcExpr = ExprError();
11039       return true;
11040     }
11041 
11042     // It is only correct to resolve to an instance method if we're
11043     // resolving a form that's permitted to be a pointer to member.
11044     // Otherwise we'll end up making a bound member expression, which
11045     // is illegal in all the contexts we resolve like this.
11046     if (!ovl.HasFormOfMemberPointer &&
11047         isa<CXXMethodDecl>(fn) &&
11048         cast<CXXMethodDecl>(fn)->isInstance()) {
11049       if (!complain) return false;
11050 
11051       Diag(ovl.Expression->getExprLoc(),
11052            diag::err_bound_member_function)
11053         << 0 << ovl.Expression->getSourceRange();
11054 
11055       // TODO: I believe we only end up here if there's a mix of
11056       // static and non-static candidates (otherwise the expression
11057       // would have 'bound member' type, not 'overload' type).
11058       // Ideally we would note which candidate was chosen and why
11059       // the static candidates were rejected.
11060       SrcExpr = ExprError();
11061       return true;
11062     }
11063 
11064     // Fix the expression to refer to 'fn'.
11065     SingleFunctionExpression =
11066         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11067 
11068     // If desired, do function-to-pointer decay.
11069     if (doFunctionPointerConverion) {
11070       SingleFunctionExpression =
11071         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11072       if (SingleFunctionExpression.isInvalid()) {
11073         SrcExpr = ExprError();
11074         return true;
11075       }
11076     }
11077   }
11078 
11079   if (!SingleFunctionExpression.isUsable()) {
11080     if (complain) {
11081       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11082         << ovl.Expression->getName()
11083         << DestTypeForComplaining
11084         << OpRangeForComplaining
11085         << ovl.Expression->getQualifierLoc().getSourceRange();
11086       NoteAllOverloadCandidates(SrcExpr.get());
11087 
11088       SrcExpr = ExprError();
11089       return true;
11090     }
11091 
11092     return false;
11093   }
11094 
11095   SrcExpr = SingleFunctionExpression;
11096   return true;
11097 }
11098 
11099 /// \brief Add a single candidate to the overload set.
11100 static void AddOverloadedCallCandidate(Sema &S,
11101                                        DeclAccessPair FoundDecl,
11102                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11103                                        ArrayRef<Expr *> Args,
11104                                        OverloadCandidateSet &CandidateSet,
11105                                        bool PartialOverloading,
11106                                        bool KnownValid) {
11107   NamedDecl *Callee = FoundDecl.getDecl();
11108   if (isa<UsingShadowDecl>(Callee))
11109     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11110 
11111   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11112     if (ExplicitTemplateArgs) {
11113       assert(!KnownValid && "Explicit template arguments?");
11114       return;
11115     }
11116     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11117                            /*SuppressUsedConversions=*/false,
11118                            PartialOverloading);
11119     return;
11120   }
11121 
11122   if (FunctionTemplateDecl *FuncTemplate
11123       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11124     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11125                                    ExplicitTemplateArgs, Args, CandidateSet,
11126                                    /*SuppressUsedConversions=*/false,
11127                                    PartialOverloading);
11128     return;
11129   }
11130 
11131   assert(!KnownValid && "unhandled case in overloaded call candidate");
11132 }
11133 
11134 /// \brief Add the overload candidates named by callee and/or found by argument
11135 /// dependent lookup to the given overload set.
11136 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11137                                        ArrayRef<Expr *> Args,
11138                                        OverloadCandidateSet &CandidateSet,
11139                                        bool PartialOverloading) {
11140 
11141 #ifndef NDEBUG
11142   // Verify that ArgumentDependentLookup is consistent with the rules
11143   // in C++0x [basic.lookup.argdep]p3:
11144   //
11145   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11146   //   and let Y be the lookup set produced by argument dependent
11147   //   lookup (defined as follows). If X contains
11148   //
11149   //     -- a declaration of a class member, or
11150   //
11151   //     -- a block-scope function declaration that is not a
11152   //        using-declaration, or
11153   //
11154   //     -- a declaration that is neither a function or a function
11155   //        template
11156   //
11157   //   then Y is empty.
11158 
11159   if (ULE->requiresADL()) {
11160     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11161            E = ULE->decls_end(); I != E; ++I) {
11162       assert(!(*I)->getDeclContext()->isRecord());
11163       assert(isa<UsingShadowDecl>(*I) ||
11164              !(*I)->getDeclContext()->isFunctionOrMethod());
11165       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11166     }
11167   }
11168 #endif
11169 
11170   // It would be nice to avoid this copy.
11171   TemplateArgumentListInfo TABuffer;
11172   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11173   if (ULE->hasExplicitTemplateArgs()) {
11174     ULE->copyTemplateArgumentsInto(TABuffer);
11175     ExplicitTemplateArgs = &TABuffer;
11176   }
11177 
11178   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11179          E = ULE->decls_end(); I != E; ++I)
11180     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11181                                CandidateSet, PartialOverloading,
11182                                /*KnownValid*/ true);
11183 
11184   if (ULE->requiresADL())
11185     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11186                                          Args, ExplicitTemplateArgs,
11187                                          CandidateSet, PartialOverloading);
11188 }
11189 
11190 /// Determine whether a declaration with the specified name could be moved into
11191 /// a different namespace.
11192 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11193   switch (Name.getCXXOverloadedOperator()) {
11194   case OO_New: case OO_Array_New:
11195   case OO_Delete: case OO_Array_Delete:
11196     return false;
11197 
11198   default:
11199     return true;
11200   }
11201 }
11202 
11203 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11204 /// template, where the non-dependent name was declared after the template
11205 /// was defined. This is common in code written for a compilers which do not
11206 /// correctly implement two-stage name lookup.
11207 ///
11208 /// Returns true if a viable candidate was found and a diagnostic was issued.
11209 static bool
11210 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11211                        const CXXScopeSpec &SS, LookupResult &R,
11212                        OverloadCandidateSet::CandidateSetKind CSK,
11213                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11214                        ArrayRef<Expr *> Args,
11215                        bool *DoDiagnoseEmptyLookup = nullptr) {
11216   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11217     return false;
11218 
11219   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11220     if (DC->isTransparentContext())
11221       continue;
11222 
11223     SemaRef.LookupQualifiedName(R, DC);
11224 
11225     if (!R.empty()) {
11226       R.suppressDiagnostics();
11227 
11228       if (isa<CXXRecordDecl>(DC)) {
11229         // Don't diagnose names we find in classes; we get much better
11230         // diagnostics for these from DiagnoseEmptyLookup.
11231         R.clear();
11232         if (DoDiagnoseEmptyLookup)
11233           *DoDiagnoseEmptyLookup = true;
11234         return false;
11235       }
11236 
11237       OverloadCandidateSet Candidates(FnLoc, CSK);
11238       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11239         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11240                                    ExplicitTemplateArgs, Args,
11241                                    Candidates, false, /*KnownValid*/ false);
11242 
11243       OverloadCandidateSet::iterator Best;
11244       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11245         // No viable functions. Don't bother the user with notes for functions
11246         // which don't work and shouldn't be found anyway.
11247         R.clear();
11248         return false;
11249       }
11250 
11251       // Find the namespaces where ADL would have looked, and suggest
11252       // declaring the function there instead.
11253       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11254       Sema::AssociatedClassSet AssociatedClasses;
11255       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11256                                                  AssociatedNamespaces,
11257                                                  AssociatedClasses);
11258       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11259       if (canBeDeclaredInNamespace(R.getLookupName())) {
11260         DeclContext *Std = SemaRef.getStdNamespace();
11261         for (Sema::AssociatedNamespaceSet::iterator
11262                it = AssociatedNamespaces.begin(),
11263                end = AssociatedNamespaces.end(); it != end; ++it) {
11264           // Never suggest declaring a function within namespace 'std'.
11265           if (Std && Std->Encloses(*it))
11266             continue;
11267 
11268           // Never suggest declaring a function within a namespace with a
11269           // reserved name, like __gnu_cxx.
11270           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11271           if (NS &&
11272               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11273             continue;
11274 
11275           SuggestedNamespaces.insert(*it);
11276         }
11277       }
11278 
11279       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11280         << R.getLookupName();
11281       if (SuggestedNamespaces.empty()) {
11282         SemaRef.Diag(Best->Function->getLocation(),
11283                      diag::note_not_found_by_two_phase_lookup)
11284           << R.getLookupName() << 0;
11285       } else if (SuggestedNamespaces.size() == 1) {
11286         SemaRef.Diag(Best->Function->getLocation(),
11287                      diag::note_not_found_by_two_phase_lookup)
11288           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11289       } else {
11290         // FIXME: It would be useful to list the associated namespaces here,
11291         // but the diagnostics infrastructure doesn't provide a way to produce
11292         // a localized representation of a list of items.
11293         SemaRef.Diag(Best->Function->getLocation(),
11294                      diag::note_not_found_by_two_phase_lookup)
11295           << R.getLookupName() << 2;
11296       }
11297 
11298       // Try to recover by calling this function.
11299       return true;
11300     }
11301 
11302     R.clear();
11303   }
11304 
11305   return false;
11306 }
11307 
11308 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11309 /// template, where the non-dependent operator was declared after the template
11310 /// was defined.
11311 ///
11312 /// Returns true if a viable candidate was found and a diagnostic was issued.
11313 static bool
11314 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11315                                SourceLocation OpLoc,
11316                                ArrayRef<Expr *> Args) {
11317   DeclarationName OpName =
11318     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11319   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11320   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11321                                 OverloadCandidateSet::CSK_Operator,
11322                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11323 }
11324 
11325 namespace {
11326 class BuildRecoveryCallExprRAII {
11327   Sema &SemaRef;
11328 public:
11329   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11330     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11331     SemaRef.IsBuildingRecoveryCallExpr = true;
11332   }
11333 
11334   ~BuildRecoveryCallExprRAII() {
11335     SemaRef.IsBuildingRecoveryCallExpr = false;
11336   }
11337 };
11338 
11339 }
11340 
11341 static std::unique_ptr<CorrectionCandidateCallback>
11342 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11343               bool HasTemplateArgs, bool AllowTypoCorrection) {
11344   if (!AllowTypoCorrection)
11345     return llvm::make_unique<NoTypoCorrectionCCC>();
11346   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11347                                                   HasTemplateArgs, ME);
11348 }
11349 
11350 /// Attempts to recover from a call where no functions were found.
11351 ///
11352 /// Returns true if new candidates were found.
11353 static ExprResult
11354 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11355                       UnresolvedLookupExpr *ULE,
11356                       SourceLocation LParenLoc,
11357                       MutableArrayRef<Expr *> Args,
11358                       SourceLocation RParenLoc,
11359                       bool EmptyLookup, bool AllowTypoCorrection) {
11360   // Do not try to recover if it is already building a recovery call.
11361   // This stops infinite loops for template instantiations like
11362   //
11363   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11364   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11365   //
11366   if (SemaRef.IsBuildingRecoveryCallExpr)
11367     return ExprError();
11368   BuildRecoveryCallExprRAII RCE(SemaRef);
11369 
11370   CXXScopeSpec SS;
11371   SS.Adopt(ULE->getQualifierLoc());
11372   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11373 
11374   TemplateArgumentListInfo TABuffer;
11375   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11376   if (ULE->hasExplicitTemplateArgs()) {
11377     ULE->copyTemplateArgumentsInto(TABuffer);
11378     ExplicitTemplateArgs = &TABuffer;
11379   }
11380 
11381   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11382                  Sema::LookupOrdinaryName);
11383   bool DoDiagnoseEmptyLookup = EmptyLookup;
11384   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11385                               OverloadCandidateSet::CSK_Normal,
11386                               ExplicitTemplateArgs, Args,
11387                               &DoDiagnoseEmptyLookup) &&
11388     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11389         S, SS, R,
11390         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11391                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11392         ExplicitTemplateArgs, Args)))
11393     return ExprError();
11394 
11395   assert(!R.empty() && "lookup results empty despite recovery");
11396 
11397   // Build an implicit member call if appropriate.  Just drop the
11398   // casts and such from the call, we don't really care.
11399   ExprResult NewFn = ExprError();
11400   if ((*R.begin())->isCXXClassMember())
11401     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11402                                                     ExplicitTemplateArgs, S);
11403   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11404     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11405                                         ExplicitTemplateArgs);
11406   else
11407     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11408 
11409   if (NewFn.isInvalid())
11410     return ExprError();
11411 
11412   // This shouldn't cause an infinite loop because we're giving it
11413   // an expression with viable lookup results, which should never
11414   // end up here.
11415   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11416                                MultiExprArg(Args.data(), Args.size()),
11417                                RParenLoc);
11418 }
11419 
11420 /// \brief Constructs and populates an OverloadedCandidateSet from
11421 /// the given function.
11422 /// \returns true when an the ExprResult output parameter has been set.
11423 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11424                                   UnresolvedLookupExpr *ULE,
11425                                   MultiExprArg Args,
11426                                   SourceLocation RParenLoc,
11427                                   OverloadCandidateSet *CandidateSet,
11428                                   ExprResult *Result) {
11429 #ifndef NDEBUG
11430   if (ULE->requiresADL()) {
11431     // To do ADL, we must have found an unqualified name.
11432     assert(!ULE->getQualifier() && "qualified name with ADL");
11433 
11434     // We don't perform ADL for implicit declarations of builtins.
11435     // Verify that this was correctly set up.
11436     FunctionDecl *F;
11437     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11438         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11439         F->getBuiltinID() && F->isImplicit())
11440       llvm_unreachable("performing ADL for builtin");
11441 
11442     // We don't perform ADL in C.
11443     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11444   }
11445 #endif
11446 
11447   UnbridgedCastsSet UnbridgedCasts;
11448   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11449     *Result = ExprError();
11450     return true;
11451   }
11452 
11453   // Add the functions denoted by the callee to the set of candidate
11454   // functions, including those from argument-dependent lookup.
11455   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11456 
11457   if (getLangOpts().MSVCCompat &&
11458       CurContext->isDependentContext() && !isSFINAEContext() &&
11459       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11460 
11461     OverloadCandidateSet::iterator Best;
11462     if (CandidateSet->empty() ||
11463         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11464             OR_No_Viable_Function) {
11465       // In Microsoft mode, if we are inside a template class member function then
11466       // create a type dependent CallExpr. The goal is to postpone name lookup
11467       // to instantiation time to be able to search into type dependent base
11468       // classes.
11469       CallExpr *CE = new (Context) CallExpr(
11470           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11471       CE->setTypeDependent(true);
11472       CE->setValueDependent(true);
11473       CE->setInstantiationDependent(true);
11474       *Result = CE;
11475       return true;
11476     }
11477   }
11478 
11479   if (CandidateSet->empty())
11480     return false;
11481 
11482   UnbridgedCasts.restore();
11483   return false;
11484 }
11485 
11486 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11487 /// the completed call expression. If overload resolution fails, emits
11488 /// diagnostics and returns ExprError()
11489 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11490                                            UnresolvedLookupExpr *ULE,
11491                                            SourceLocation LParenLoc,
11492                                            MultiExprArg Args,
11493                                            SourceLocation RParenLoc,
11494                                            Expr *ExecConfig,
11495                                            OverloadCandidateSet *CandidateSet,
11496                                            OverloadCandidateSet::iterator *Best,
11497                                            OverloadingResult OverloadResult,
11498                                            bool AllowTypoCorrection) {
11499   if (CandidateSet->empty())
11500     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11501                                  RParenLoc, /*EmptyLookup=*/true,
11502                                  AllowTypoCorrection);
11503 
11504   switch (OverloadResult) {
11505   case OR_Success: {
11506     FunctionDecl *FDecl = (*Best)->Function;
11507     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11508     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11509       return ExprError();
11510     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11511     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11512                                          ExecConfig);
11513   }
11514 
11515   case OR_No_Viable_Function: {
11516     // Try to recover by looking for viable functions which the user might
11517     // have meant to call.
11518     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11519                                                 Args, RParenLoc,
11520                                                 /*EmptyLookup=*/false,
11521                                                 AllowTypoCorrection);
11522     if (!Recovery.isInvalid())
11523       return Recovery;
11524 
11525     // If the user passes in a function that we can't take the address of, we
11526     // generally end up emitting really bad error messages. Here, we attempt to
11527     // emit better ones.
11528     for (const Expr *Arg : Args) {
11529       if (!Arg->getType()->isFunctionType())
11530         continue;
11531       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11532         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11533         if (FD &&
11534             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11535                                                        Arg->getExprLoc()))
11536           return ExprError();
11537       }
11538     }
11539 
11540     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11541         << ULE->getName() << Fn->getSourceRange();
11542     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11543     break;
11544   }
11545 
11546   case OR_Ambiguous:
11547     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11548       << ULE->getName() << Fn->getSourceRange();
11549     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11550     break;
11551 
11552   case OR_Deleted: {
11553     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11554       << (*Best)->Function->isDeleted()
11555       << ULE->getName()
11556       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11557       << Fn->getSourceRange();
11558     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11559 
11560     // We emitted an error for the unvailable/deleted function call but keep
11561     // the call in the AST.
11562     FunctionDecl *FDecl = (*Best)->Function;
11563     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11564     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11565                                          ExecConfig);
11566   }
11567   }
11568 
11569   // Overload resolution failed.
11570   return ExprError();
11571 }
11572 
11573 static void markUnaddressableCandidatesUnviable(Sema &S,
11574                                                 OverloadCandidateSet &CS) {
11575   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11576     if (I->Viable &&
11577         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11578       I->Viable = false;
11579       I->FailureKind = ovl_fail_addr_not_available;
11580     }
11581   }
11582 }
11583 
11584 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11585 /// (which eventually refers to the declaration Func) and the call
11586 /// arguments Args/NumArgs, attempt to resolve the function call down
11587 /// to a specific function. If overload resolution succeeds, returns
11588 /// the call expression produced by overload resolution.
11589 /// Otherwise, emits diagnostics and returns ExprError.
11590 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11591                                          UnresolvedLookupExpr *ULE,
11592                                          SourceLocation LParenLoc,
11593                                          MultiExprArg Args,
11594                                          SourceLocation RParenLoc,
11595                                          Expr *ExecConfig,
11596                                          bool AllowTypoCorrection,
11597                                          bool CalleesAddressIsTaken) {
11598   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11599                                     OverloadCandidateSet::CSK_Normal);
11600   ExprResult result;
11601 
11602   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11603                              &result))
11604     return result;
11605 
11606   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11607   // functions that aren't addressible are considered unviable.
11608   if (CalleesAddressIsTaken)
11609     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11610 
11611   OverloadCandidateSet::iterator Best;
11612   OverloadingResult OverloadResult =
11613       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11614 
11615   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11616                                   RParenLoc, ExecConfig, &CandidateSet,
11617                                   &Best, OverloadResult,
11618                                   AllowTypoCorrection);
11619 }
11620 
11621 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11622   return Functions.size() > 1 ||
11623     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11624 }
11625 
11626 /// \brief Create a unary operation that may resolve to an overloaded
11627 /// operator.
11628 ///
11629 /// \param OpLoc The location of the operator itself (e.g., '*').
11630 ///
11631 /// \param Opc The UnaryOperatorKind that describes this operator.
11632 ///
11633 /// \param Fns The set of non-member functions that will be
11634 /// considered by overload resolution. The caller needs to build this
11635 /// set based on the context using, e.g.,
11636 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11637 /// set should not contain any member functions; those will be added
11638 /// by CreateOverloadedUnaryOp().
11639 ///
11640 /// \param Input The input argument.
11641 ExprResult
11642 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11643                               const UnresolvedSetImpl &Fns,
11644                               Expr *Input) {
11645   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11646   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11647   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11648   // TODO: provide better source location info.
11649   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11650 
11651   if (checkPlaceholderForOverload(*this, Input))
11652     return ExprError();
11653 
11654   Expr *Args[2] = { Input, nullptr };
11655   unsigned NumArgs = 1;
11656 
11657   // For post-increment and post-decrement, add the implicit '0' as
11658   // the second argument, so that we know this is a post-increment or
11659   // post-decrement.
11660   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11661     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11662     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11663                                      SourceLocation());
11664     NumArgs = 2;
11665   }
11666 
11667   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11668 
11669   if (Input->isTypeDependent()) {
11670     if (Fns.empty())
11671       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11672                                          VK_RValue, OK_Ordinary, OpLoc);
11673 
11674     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11675     UnresolvedLookupExpr *Fn
11676       = UnresolvedLookupExpr::Create(Context, NamingClass,
11677                                      NestedNameSpecifierLoc(), OpNameInfo,
11678                                      /*ADL*/ true, IsOverloaded(Fns),
11679                                      Fns.begin(), Fns.end());
11680     return new (Context)
11681         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11682                             VK_RValue, OpLoc, false);
11683   }
11684 
11685   // Build an empty overload set.
11686   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11687 
11688   // Add the candidates from the given function set.
11689   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11690 
11691   // Add operator candidates that are member functions.
11692   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11693 
11694   // Add candidates from ADL.
11695   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11696                                        /*ExplicitTemplateArgs*/nullptr,
11697                                        CandidateSet);
11698 
11699   // Add builtin operator candidates.
11700   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11701 
11702   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11703 
11704   // Perform overload resolution.
11705   OverloadCandidateSet::iterator Best;
11706   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11707   case OR_Success: {
11708     // We found a built-in operator or an overloaded operator.
11709     FunctionDecl *FnDecl = Best->Function;
11710 
11711     if (FnDecl) {
11712       // We matched an overloaded operator. Build a call to that
11713       // operator.
11714 
11715       // Convert the arguments.
11716       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11717         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11718 
11719         ExprResult InputRes =
11720           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11721                                               Best->FoundDecl, Method);
11722         if (InputRes.isInvalid())
11723           return ExprError();
11724         Input = InputRes.get();
11725       } else {
11726         // Convert the arguments.
11727         ExprResult InputInit
11728           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11729                                                       Context,
11730                                                       FnDecl->getParamDecl(0)),
11731                                       SourceLocation(),
11732                                       Input);
11733         if (InputInit.isInvalid())
11734           return ExprError();
11735         Input = InputInit.get();
11736       }
11737 
11738       // Build the actual expression node.
11739       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11740                                                 HadMultipleCandidates, OpLoc);
11741       if (FnExpr.isInvalid())
11742         return ExprError();
11743 
11744       // Determine the result type.
11745       QualType ResultTy = FnDecl->getReturnType();
11746       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11747       ResultTy = ResultTy.getNonLValueExprType(Context);
11748 
11749       Args[0] = Input;
11750       CallExpr *TheCall =
11751         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11752                                           ResultTy, VK, OpLoc, false);
11753 
11754       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11755         return ExprError();
11756 
11757       return MaybeBindToTemporary(TheCall);
11758     } else {
11759       // We matched a built-in operator. Convert the arguments, then
11760       // break out so that we will build the appropriate built-in
11761       // operator node.
11762       ExprResult InputRes =
11763         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11764                                   Best->Conversions[0], AA_Passing);
11765       if (InputRes.isInvalid())
11766         return ExprError();
11767       Input = InputRes.get();
11768       break;
11769     }
11770   }
11771 
11772   case OR_No_Viable_Function:
11773     // This is an erroneous use of an operator which can be overloaded by
11774     // a non-member function. Check for non-member operators which were
11775     // defined too late to be candidates.
11776     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11777       // FIXME: Recover by calling the found function.
11778       return ExprError();
11779 
11780     // No viable function; fall through to handling this as a
11781     // built-in operator, which will produce an error message for us.
11782     break;
11783 
11784   case OR_Ambiguous:
11785     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11786         << UnaryOperator::getOpcodeStr(Opc)
11787         << Input->getType()
11788         << Input->getSourceRange();
11789     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11790                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11791     return ExprError();
11792 
11793   case OR_Deleted:
11794     Diag(OpLoc, diag::err_ovl_deleted_oper)
11795       << Best->Function->isDeleted()
11796       << UnaryOperator::getOpcodeStr(Opc)
11797       << getDeletedOrUnavailableSuffix(Best->Function)
11798       << Input->getSourceRange();
11799     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11800                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11801     return ExprError();
11802   }
11803 
11804   // Either we found no viable overloaded operator or we matched a
11805   // built-in operator. In either case, fall through to trying to
11806   // build a built-in operation.
11807   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11808 }
11809 
11810 /// \brief Create a binary operation that may resolve to an overloaded
11811 /// operator.
11812 ///
11813 /// \param OpLoc The location of the operator itself (e.g., '+').
11814 ///
11815 /// \param Opc The BinaryOperatorKind that describes this operator.
11816 ///
11817 /// \param Fns The set of non-member functions that will be
11818 /// considered by overload resolution. The caller needs to build this
11819 /// set based on the context using, e.g.,
11820 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11821 /// set should not contain any member functions; those will be added
11822 /// by CreateOverloadedBinOp().
11823 ///
11824 /// \param LHS Left-hand argument.
11825 /// \param RHS Right-hand argument.
11826 ExprResult
11827 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11828                             BinaryOperatorKind Opc,
11829                             const UnresolvedSetImpl &Fns,
11830                             Expr *LHS, Expr *RHS) {
11831   Expr *Args[2] = { LHS, RHS };
11832   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11833 
11834   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11835   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11836 
11837   // If either side is type-dependent, create an appropriate dependent
11838   // expression.
11839   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11840     if (Fns.empty()) {
11841       // If there are no functions to store, just build a dependent
11842       // BinaryOperator or CompoundAssignment.
11843       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11844         return new (Context) BinaryOperator(
11845             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11846             OpLoc, FPFeatures.fp_contract);
11847 
11848       return new (Context) CompoundAssignOperator(
11849           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11850           Context.DependentTy, Context.DependentTy, OpLoc,
11851           FPFeatures.fp_contract);
11852     }
11853 
11854     // FIXME: save results of ADL from here?
11855     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11856     // TODO: provide better source location info in DNLoc component.
11857     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11858     UnresolvedLookupExpr *Fn
11859       = UnresolvedLookupExpr::Create(Context, NamingClass,
11860                                      NestedNameSpecifierLoc(), OpNameInfo,
11861                                      /*ADL*/ true, IsOverloaded(Fns),
11862                                      Fns.begin(), Fns.end());
11863     return new (Context)
11864         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11865                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11866   }
11867 
11868   // Always do placeholder-like conversions on the RHS.
11869   if (checkPlaceholderForOverload(*this, Args[1]))
11870     return ExprError();
11871 
11872   // Do placeholder-like conversion on the LHS; note that we should
11873   // not get here with a PseudoObject LHS.
11874   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11875   if (checkPlaceholderForOverload(*this, Args[0]))
11876     return ExprError();
11877 
11878   // If this is the assignment operator, we only perform overload resolution
11879   // if the left-hand side is a class or enumeration type. This is actually
11880   // a hack. The standard requires that we do overload resolution between the
11881   // various built-in candidates, but as DR507 points out, this can lead to
11882   // problems. So we do it this way, which pretty much follows what GCC does.
11883   // Note that we go the traditional code path for compound assignment forms.
11884   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11885     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11886 
11887   // If this is the .* operator, which is not overloadable, just
11888   // create a built-in binary operator.
11889   if (Opc == BO_PtrMemD)
11890     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11891 
11892   // Build an empty overload set.
11893   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11894 
11895   // Add the candidates from the given function set.
11896   AddFunctionCandidates(Fns, Args, CandidateSet);
11897 
11898   // Add operator candidates that are member functions.
11899   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11900 
11901   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11902   // performed for an assignment operator (nor for operator[] nor operator->,
11903   // which don't get here).
11904   if (Opc != BO_Assign)
11905     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11906                                          /*ExplicitTemplateArgs*/ nullptr,
11907                                          CandidateSet);
11908 
11909   // Add builtin operator candidates.
11910   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11911 
11912   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11913 
11914   // Perform overload resolution.
11915   OverloadCandidateSet::iterator Best;
11916   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11917     case OR_Success: {
11918       // We found a built-in operator or an overloaded operator.
11919       FunctionDecl *FnDecl = Best->Function;
11920 
11921       if (FnDecl) {
11922         // We matched an overloaded operator. Build a call to that
11923         // operator.
11924 
11925         // Convert the arguments.
11926         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11927           // Best->Access is only meaningful for class members.
11928           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11929 
11930           ExprResult Arg1 =
11931             PerformCopyInitialization(
11932               InitializedEntity::InitializeParameter(Context,
11933                                                      FnDecl->getParamDecl(0)),
11934               SourceLocation(), Args[1]);
11935           if (Arg1.isInvalid())
11936             return ExprError();
11937 
11938           ExprResult Arg0 =
11939             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11940                                                 Best->FoundDecl, Method);
11941           if (Arg0.isInvalid())
11942             return ExprError();
11943           Args[0] = Arg0.getAs<Expr>();
11944           Args[1] = RHS = Arg1.getAs<Expr>();
11945         } else {
11946           // Convert the arguments.
11947           ExprResult Arg0 = PerformCopyInitialization(
11948             InitializedEntity::InitializeParameter(Context,
11949                                                    FnDecl->getParamDecl(0)),
11950             SourceLocation(), Args[0]);
11951           if (Arg0.isInvalid())
11952             return ExprError();
11953 
11954           ExprResult Arg1 =
11955             PerformCopyInitialization(
11956               InitializedEntity::InitializeParameter(Context,
11957                                                      FnDecl->getParamDecl(1)),
11958               SourceLocation(), Args[1]);
11959           if (Arg1.isInvalid())
11960             return ExprError();
11961           Args[0] = LHS = Arg0.getAs<Expr>();
11962           Args[1] = RHS = Arg1.getAs<Expr>();
11963         }
11964 
11965         // Build the actual expression node.
11966         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11967                                                   Best->FoundDecl,
11968                                                   HadMultipleCandidates, OpLoc);
11969         if (FnExpr.isInvalid())
11970           return ExprError();
11971 
11972         // Determine the result type.
11973         QualType ResultTy = FnDecl->getReturnType();
11974         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11975         ResultTy = ResultTy.getNonLValueExprType(Context);
11976 
11977         CXXOperatorCallExpr *TheCall =
11978           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11979                                             Args, ResultTy, VK, OpLoc,
11980                                             FPFeatures.fp_contract);
11981 
11982         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11983                                 FnDecl))
11984           return ExprError();
11985 
11986         ArrayRef<const Expr *> ArgsArray(Args, 2);
11987         // Cut off the implicit 'this'.
11988         if (isa<CXXMethodDecl>(FnDecl))
11989           ArgsArray = ArgsArray.slice(1);
11990 
11991         // Check for a self move.
11992         if (Op == OO_Equal)
11993           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11994 
11995         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11996                   TheCall->getSourceRange(), VariadicDoesNotApply);
11997 
11998         return MaybeBindToTemporary(TheCall);
11999       } else {
12000         // We matched a built-in operator. Convert the arguments, then
12001         // break out so that we will build the appropriate built-in
12002         // operator node.
12003         ExprResult ArgsRes0 =
12004           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12005                                     Best->Conversions[0], AA_Passing);
12006         if (ArgsRes0.isInvalid())
12007           return ExprError();
12008         Args[0] = ArgsRes0.get();
12009 
12010         ExprResult ArgsRes1 =
12011           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12012                                     Best->Conversions[1], AA_Passing);
12013         if (ArgsRes1.isInvalid())
12014           return ExprError();
12015         Args[1] = ArgsRes1.get();
12016         break;
12017       }
12018     }
12019 
12020     case OR_No_Viable_Function: {
12021       // C++ [over.match.oper]p9:
12022       //   If the operator is the operator , [...] and there are no
12023       //   viable functions, then the operator is assumed to be the
12024       //   built-in operator and interpreted according to clause 5.
12025       if (Opc == BO_Comma)
12026         break;
12027 
12028       // For class as left operand for assignment or compound assigment
12029       // operator do not fall through to handling in built-in, but report that
12030       // no overloaded assignment operator found
12031       ExprResult Result = ExprError();
12032       if (Args[0]->getType()->isRecordType() &&
12033           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12034         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12035              << BinaryOperator::getOpcodeStr(Opc)
12036              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12037         if (Args[0]->getType()->isIncompleteType()) {
12038           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12039             << Args[0]->getType()
12040             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12041         }
12042       } else {
12043         // This is an erroneous use of an operator which can be overloaded by
12044         // a non-member function. Check for non-member operators which were
12045         // defined too late to be candidates.
12046         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12047           // FIXME: Recover by calling the found function.
12048           return ExprError();
12049 
12050         // No viable function; try to create a built-in operation, which will
12051         // produce an error. Then, show the non-viable candidates.
12052         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12053       }
12054       assert(Result.isInvalid() &&
12055              "C++ binary operator overloading is missing candidates!");
12056       if (Result.isInvalid())
12057         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12058                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12059       return Result;
12060     }
12061 
12062     case OR_Ambiguous:
12063       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12064           << BinaryOperator::getOpcodeStr(Opc)
12065           << Args[0]->getType() << Args[1]->getType()
12066           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12067       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12068                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12069       return ExprError();
12070 
12071     case OR_Deleted:
12072       if (isImplicitlyDeleted(Best->Function)) {
12073         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12074         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12075           << Context.getRecordType(Method->getParent())
12076           << getSpecialMember(Method);
12077 
12078         // The user probably meant to call this special member. Just
12079         // explain why it's deleted.
12080         NoteDeletedFunction(Method);
12081         return ExprError();
12082       } else {
12083         Diag(OpLoc, diag::err_ovl_deleted_oper)
12084           << Best->Function->isDeleted()
12085           << BinaryOperator::getOpcodeStr(Opc)
12086           << getDeletedOrUnavailableSuffix(Best->Function)
12087           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12088       }
12089       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12090                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12091       return ExprError();
12092   }
12093 
12094   // We matched a built-in operator; build it.
12095   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12096 }
12097 
12098 ExprResult
12099 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12100                                          SourceLocation RLoc,
12101                                          Expr *Base, Expr *Idx) {
12102   Expr *Args[2] = { Base, Idx };
12103   DeclarationName OpName =
12104       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12105 
12106   // If either side is type-dependent, create an appropriate dependent
12107   // expression.
12108   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12109 
12110     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12111     // CHECKME: no 'operator' keyword?
12112     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12113     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12114     UnresolvedLookupExpr *Fn
12115       = UnresolvedLookupExpr::Create(Context, NamingClass,
12116                                      NestedNameSpecifierLoc(), OpNameInfo,
12117                                      /*ADL*/ true, /*Overloaded*/ false,
12118                                      UnresolvedSetIterator(),
12119                                      UnresolvedSetIterator());
12120     // Can't add any actual overloads yet
12121 
12122     return new (Context)
12123         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12124                             Context.DependentTy, VK_RValue, RLoc, false);
12125   }
12126 
12127   // Handle placeholders on both operands.
12128   if (checkPlaceholderForOverload(*this, Args[0]))
12129     return ExprError();
12130   if (checkPlaceholderForOverload(*this, Args[1]))
12131     return ExprError();
12132 
12133   // Build an empty overload set.
12134   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12135 
12136   // Subscript can only be overloaded as a member function.
12137 
12138   // Add operator candidates that are member functions.
12139   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12140 
12141   // Add builtin operator candidates.
12142   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12143 
12144   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12145 
12146   // Perform overload resolution.
12147   OverloadCandidateSet::iterator Best;
12148   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12149     case OR_Success: {
12150       // We found a built-in operator or an overloaded operator.
12151       FunctionDecl *FnDecl = Best->Function;
12152 
12153       if (FnDecl) {
12154         // We matched an overloaded operator. Build a call to that
12155         // operator.
12156 
12157         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12158 
12159         // Convert the arguments.
12160         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12161         ExprResult Arg0 =
12162           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12163                                               Best->FoundDecl, Method);
12164         if (Arg0.isInvalid())
12165           return ExprError();
12166         Args[0] = Arg0.get();
12167 
12168         // Convert the arguments.
12169         ExprResult InputInit
12170           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12171                                                       Context,
12172                                                       FnDecl->getParamDecl(0)),
12173                                       SourceLocation(),
12174                                       Args[1]);
12175         if (InputInit.isInvalid())
12176           return ExprError();
12177 
12178         Args[1] = InputInit.getAs<Expr>();
12179 
12180         // Build the actual expression node.
12181         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12182         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12183         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12184                                                   Best->FoundDecl,
12185                                                   HadMultipleCandidates,
12186                                                   OpLocInfo.getLoc(),
12187                                                   OpLocInfo.getInfo());
12188         if (FnExpr.isInvalid())
12189           return ExprError();
12190 
12191         // Determine the result type
12192         QualType ResultTy = FnDecl->getReturnType();
12193         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12194         ResultTy = ResultTy.getNonLValueExprType(Context);
12195 
12196         CXXOperatorCallExpr *TheCall =
12197           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12198                                             FnExpr.get(), Args,
12199                                             ResultTy, VK, RLoc,
12200                                             false);
12201 
12202         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12203           return ExprError();
12204 
12205         return MaybeBindToTemporary(TheCall);
12206       } else {
12207         // We matched a built-in operator. Convert the arguments, then
12208         // break out so that we will build the appropriate built-in
12209         // operator node.
12210         ExprResult ArgsRes0 =
12211           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12212                                     Best->Conversions[0], AA_Passing);
12213         if (ArgsRes0.isInvalid())
12214           return ExprError();
12215         Args[0] = ArgsRes0.get();
12216 
12217         ExprResult ArgsRes1 =
12218           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12219                                     Best->Conversions[1], AA_Passing);
12220         if (ArgsRes1.isInvalid())
12221           return ExprError();
12222         Args[1] = ArgsRes1.get();
12223 
12224         break;
12225       }
12226     }
12227 
12228     case OR_No_Viable_Function: {
12229       if (CandidateSet.empty())
12230         Diag(LLoc, diag::err_ovl_no_oper)
12231           << Args[0]->getType() << /*subscript*/ 0
12232           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12233       else
12234         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12235           << Args[0]->getType()
12236           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12237       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12238                                   "[]", LLoc);
12239       return ExprError();
12240     }
12241 
12242     case OR_Ambiguous:
12243       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12244           << "[]"
12245           << Args[0]->getType() << Args[1]->getType()
12246           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12247       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12248                                   "[]", LLoc);
12249       return ExprError();
12250 
12251     case OR_Deleted:
12252       Diag(LLoc, diag::err_ovl_deleted_oper)
12253         << Best->Function->isDeleted() << "[]"
12254         << getDeletedOrUnavailableSuffix(Best->Function)
12255         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12256       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12257                                   "[]", LLoc);
12258       return ExprError();
12259     }
12260 
12261   // We matched a built-in operator; build it.
12262   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12263 }
12264 
12265 /// BuildCallToMemberFunction - Build a call to a member
12266 /// function. MemExpr is the expression that refers to the member
12267 /// function (and includes the object parameter), Args/NumArgs are the
12268 /// arguments to the function call (not including the object
12269 /// parameter). The caller needs to validate that the member
12270 /// expression refers to a non-static member function or an overloaded
12271 /// member function.
12272 ExprResult
12273 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12274                                 SourceLocation LParenLoc,
12275                                 MultiExprArg Args,
12276                                 SourceLocation RParenLoc) {
12277   assert(MemExprE->getType() == Context.BoundMemberTy ||
12278          MemExprE->getType() == Context.OverloadTy);
12279 
12280   // Dig out the member expression. This holds both the object
12281   // argument and the member function we're referring to.
12282   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12283 
12284   // Determine whether this is a call to a pointer-to-member function.
12285   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12286     assert(op->getType() == Context.BoundMemberTy);
12287     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12288 
12289     QualType fnType =
12290       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12291 
12292     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12293     QualType resultType = proto->getCallResultType(Context);
12294     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12295 
12296     // Check that the object type isn't more qualified than the
12297     // member function we're calling.
12298     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12299 
12300     QualType objectType = op->getLHS()->getType();
12301     if (op->getOpcode() == BO_PtrMemI)
12302       objectType = objectType->castAs<PointerType>()->getPointeeType();
12303     Qualifiers objectQuals = objectType.getQualifiers();
12304 
12305     Qualifiers difference = objectQuals - funcQuals;
12306     difference.removeObjCGCAttr();
12307     difference.removeAddressSpace();
12308     if (difference) {
12309       std::string qualsString = difference.getAsString();
12310       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12311         << fnType.getUnqualifiedType()
12312         << qualsString
12313         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12314     }
12315 
12316     CXXMemberCallExpr *call
12317       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12318                                         resultType, valueKind, RParenLoc);
12319 
12320     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12321                             call, nullptr))
12322       return ExprError();
12323 
12324     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12325       return ExprError();
12326 
12327     if (CheckOtherCall(call, proto))
12328       return ExprError();
12329 
12330     return MaybeBindToTemporary(call);
12331   }
12332 
12333   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12334     return new (Context)
12335         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12336 
12337   UnbridgedCastsSet UnbridgedCasts;
12338   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12339     return ExprError();
12340 
12341   MemberExpr *MemExpr;
12342   CXXMethodDecl *Method = nullptr;
12343   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12344   NestedNameSpecifier *Qualifier = nullptr;
12345   if (isa<MemberExpr>(NakedMemExpr)) {
12346     MemExpr = cast<MemberExpr>(NakedMemExpr);
12347     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12348     FoundDecl = MemExpr->getFoundDecl();
12349     Qualifier = MemExpr->getQualifier();
12350     UnbridgedCasts.restore();
12351   } else {
12352     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12353     Qualifier = UnresExpr->getQualifier();
12354 
12355     QualType ObjectType = UnresExpr->getBaseType();
12356     Expr::Classification ObjectClassification
12357       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12358                             : UnresExpr->getBase()->Classify(Context);
12359 
12360     // Add overload candidates
12361     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12362                                       OverloadCandidateSet::CSK_Normal);
12363 
12364     // FIXME: avoid copy.
12365     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12366     if (UnresExpr->hasExplicitTemplateArgs()) {
12367       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12368       TemplateArgs = &TemplateArgsBuffer;
12369     }
12370 
12371     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12372            E = UnresExpr->decls_end(); I != E; ++I) {
12373 
12374       NamedDecl *Func = *I;
12375       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12376       if (isa<UsingShadowDecl>(Func))
12377         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12378 
12379 
12380       // Microsoft supports direct constructor calls.
12381       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12382         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12383                              Args, CandidateSet);
12384       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12385         // If explicit template arguments were provided, we can't call a
12386         // non-template member function.
12387         if (TemplateArgs)
12388           continue;
12389 
12390         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12391                            ObjectClassification, Args, CandidateSet,
12392                            /*SuppressUserConversions=*/false);
12393       } else {
12394         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12395                                    I.getPair(), ActingDC, TemplateArgs,
12396                                    ObjectType,  ObjectClassification,
12397                                    Args, CandidateSet,
12398                                    /*SuppressUsedConversions=*/false);
12399       }
12400     }
12401 
12402     DeclarationName DeclName = UnresExpr->getMemberName();
12403 
12404     UnbridgedCasts.restore();
12405 
12406     OverloadCandidateSet::iterator Best;
12407     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12408                                             Best)) {
12409     case OR_Success:
12410       Method = cast<CXXMethodDecl>(Best->Function);
12411       FoundDecl = Best->FoundDecl;
12412       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12413       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12414         return ExprError();
12415       // If FoundDecl is different from Method (such as if one is a template
12416       // and the other a specialization), make sure DiagnoseUseOfDecl is
12417       // called on both.
12418       // FIXME: This would be more comprehensively addressed by modifying
12419       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12420       // being used.
12421       if (Method != FoundDecl.getDecl() &&
12422                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12423         return ExprError();
12424       break;
12425 
12426     case OR_No_Viable_Function:
12427       Diag(UnresExpr->getMemberLoc(),
12428            diag::err_ovl_no_viable_member_function_in_call)
12429         << DeclName << MemExprE->getSourceRange();
12430       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12431       // FIXME: Leaking incoming expressions!
12432       return ExprError();
12433 
12434     case OR_Ambiguous:
12435       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12436         << DeclName << MemExprE->getSourceRange();
12437       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12438       // FIXME: Leaking incoming expressions!
12439       return ExprError();
12440 
12441     case OR_Deleted:
12442       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12443         << Best->Function->isDeleted()
12444         << DeclName
12445         << getDeletedOrUnavailableSuffix(Best->Function)
12446         << MemExprE->getSourceRange();
12447       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12448       // FIXME: Leaking incoming expressions!
12449       return ExprError();
12450     }
12451 
12452     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12453 
12454     // If overload resolution picked a static member, build a
12455     // non-member call based on that function.
12456     if (Method->isStatic()) {
12457       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12458                                    RParenLoc);
12459     }
12460 
12461     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12462   }
12463 
12464   QualType ResultType = Method->getReturnType();
12465   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12466   ResultType = ResultType.getNonLValueExprType(Context);
12467 
12468   assert(Method && "Member call to something that isn't a method?");
12469   CXXMemberCallExpr *TheCall =
12470     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12471                                     ResultType, VK, RParenLoc);
12472 
12473   // Check for a valid return type.
12474   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12475                           TheCall, Method))
12476     return ExprError();
12477 
12478   // Convert the object argument (for a non-static member function call).
12479   // We only need to do this if there was actually an overload; otherwise
12480   // it was done at lookup.
12481   if (!Method->isStatic()) {
12482     ExprResult ObjectArg =
12483       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12484                                           FoundDecl, Method);
12485     if (ObjectArg.isInvalid())
12486       return ExprError();
12487     MemExpr->setBase(ObjectArg.get());
12488   }
12489 
12490   // Convert the rest of the arguments
12491   const FunctionProtoType *Proto =
12492     Method->getType()->getAs<FunctionProtoType>();
12493   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12494                               RParenLoc))
12495     return ExprError();
12496 
12497   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12498 
12499   if (CheckFunctionCall(Method, TheCall, Proto))
12500     return ExprError();
12501 
12502   // In the case the method to call was not selected by the overloading
12503   // resolution process, we still need to handle the enable_if attribute. Do
12504   // that here, so it will not hide previous -- and more relevant -- errors.
12505   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12506     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12507       Diag(MemE->getMemberLoc(),
12508            diag::err_ovl_no_viable_member_function_in_call)
12509           << Method << Method->getSourceRange();
12510       Diag(Method->getLocation(),
12511            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12512           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12513       return ExprError();
12514     }
12515   }
12516 
12517   if ((isa<CXXConstructorDecl>(CurContext) ||
12518        isa<CXXDestructorDecl>(CurContext)) &&
12519       TheCall->getMethodDecl()->isPure()) {
12520     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12521 
12522     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12523         MemExpr->performsVirtualDispatch(getLangOpts())) {
12524       Diag(MemExpr->getLocStart(),
12525            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12526         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12527         << MD->getParent()->getDeclName();
12528 
12529       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12530       if (getLangOpts().AppleKext)
12531         Diag(MemExpr->getLocStart(),
12532              diag::note_pure_qualified_call_kext)
12533              << MD->getParent()->getDeclName()
12534              << MD->getDeclName();
12535     }
12536   }
12537 
12538   if (CXXDestructorDecl *DD =
12539           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12540     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12541     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12542     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12543                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12544                          MemExpr->getMemberLoc());
12545   }
12546 
12547   return MaybeBindToTemporary(TheCall);
12548 }
12549 
12550 /// BuildCallToObjectOfClassType - Build a call to an object of class
12551 /// type (C++ [over.call.object]), which can end up invoking an
12552 /// overloaded function call operator (@c operator()) or performing a
12553 /// user-defined conversion on the object argument.
12554 ExprResult
12555 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12556                                    SourceLocation LParenLoc,
12557                                    MultiExprArg Args,
12558                                    SourceLocation RParenLoc) {
12559   if (checkPlaceholderForOverload(*this, Obj))
12560     return ExprError();
12561   ExprResult Object = Obj;
12562 
12563   UnbridgedCastsSet UnbridgedCasts;
12564   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12565     return ExprError();
12566 
12567   assert(Object.get()->getType()->isRecordType() &&
12568          "Requires object type argument");
12569   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12570 
12571   // C++ [over.call.object]p1:
12572   //  If the primary-expression E in the function call syntax
12573   //  evaluates to a class object of type "cv T", then the set of
12574   //  candidate functions includes at least the function call
12575   //  operators of T. The function call operators of T are obtained by
12576   //  ordinary lookup of the name operator() in the context of
12577   //  (E).operator().
12578   OverloadCandidateSet CandidateSet(LParenLoc,
12579                                     OverloadCandidateSet::CSK_Operator);
12580   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12581 
12582   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12583                           diag::err_incomplete_object_call, Object.get()))
12584     return true;
12585 
12586   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12587   LookupQualifiedName(R, Record->getDecl());
12588   R.suppressDiagnostics();
12589 
12590   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12591        Oper != OperEnd; ++Oper) {
12592     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12593                        Object.get()->Classify(Context),
12594                        Args, CandidateSet,
12595                        /*SuppressUserConversions=*/ false);
12596   }
12597 
12598   // C++ [over.call.object]p2:
12599   //   In addition, for each (non-explicit in C++0x) conversion function
12600   //   declared in T of the form
12601   //
12602   //        operator conversion-type-id () cv-qualifier;
12603   //
12604   //   where cv-qualifier is the same cv-qualification as, or a
12605   //   greater cv-qualification than, cv, and where conversion-type-id
12606   //   denotes the type "pointer to function of (P1,...,Pn) returning
12607   //   R", or the type "reference to pointer to function of
12608   //   (P1,...,Pn) returning R", or the type "reference to function
12609   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12610   //   is also considered as a candidate function. Similarly,
12611   //   surrogate call functions are added to the set of candidate
12612   //   functions for each conversion function declared in an
12613   //   accessible base class provided the function is not hidden
12614   //   within T by another intervening declaration.
12615   const auto &Conversions =
12616       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12617   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12618     NamedDecl *D = *I;
12619     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12620     if (isa<UsingShadowDecl>(D))
12621       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12622 
12623     // Skip over templated conversion functions; they aren't
12624     // surrogates.
12625     if (isa<FunctionTemplateDecl>(D))
12626       continue;
12627 
12628     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12629     if (!Conv->isExplicit()) {
12630       // Strip the reference type (if any) and then the pointer type (if
12631       // any) to get down to what might be a function type.
12632       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12633       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12634         ConvType = ConvPtrType->getPointeeType();
12635 
12636       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12637       {
12638         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12639                               Object.get(), Args, CandidateSet);
12640       }
12641     }
12642   }
12643 
12644   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12645 
12646   // Perform overload resolution.
12647   OverloadCandidateSet::iterator Best;
12648   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12649                              Best)) {
12650   case OR_Success:
12651     // Overload resolution succeeded; we'll build the appropriate call
12652     // below.
12653     break;
12654 
12655   case OR_No_Viable_Function:
12656     if (CandidateSet.empty())
12657       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12658         << Object.get()->getType() << /*call*/ 1
12659         << Object.get()->getSourceRange();
12660     else
12661       Diag(Object.get()->getLocStart(),
12662            diag::err_ovl_no_viable_object_call)
12663         << Object.get()->getType() << Object.get()->getSourceRange();
12664     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12665     break;
12666 
12667   case OR_Ambiguous:
12668     Diag(Object.get()->getLocStart(),
12669          diag::err_ovl_ambiguous_object_call)
12670       << Object.get()->getType() << Object.get()->getSourceRange();
12671     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12672     break;
12673 
12674   case OR_Deleted:
12675     Diag(Object.get()->getLocStart(),
12676          diag::err_ovl_deleted_object_call)
12677       << Best->Function->isDeleted()
12678       << Object.get()->getType()
12679       << getDeletedOrUnavailableSuffix(Best->Function)
12680       << Object.get()->getSourceRange();
12681     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12682     break;
12683   }
12684 
12685   if (Best == CandidateSet.end())
12686     return true;
12687 
12688   UnbridgedCasts.restore();
12689 
12690   if (Best->Function == nullptr) {
12691     // Since there is no function declaration, this is one of the
12692     // surrogate candidates. Dig out the conversion function.
12693     CXXConversionDecl *Conv
12694       = cast<CXXConversionDecl>(
12695                          Best->Conversions[0].UserDefined.ConversionFunction);
12696 
12697     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12698                               Best->FoundDecl);
12699     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12700       return ExprError();
12701     assert(Conv == Best->FoundDecl.getDecl() &&
12702              "Found Decl & conversion-to-functionptr should be same, right?!");
12703     // We selected one of the surrogate functions that converts the
12704     // object parameter to a function pointer. Perform the conversion
12705     // on the object argument, then let ActOnCallExpr finish the job.
12706 
12707     // Create an implicit member expr to refer to the conversion operator.
12708     // and then call it.
12709     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12710                                              Conv, HadMultipleCandidates);
12711     if (Call.isInvalid())
12712       return ExprError();
12713     // Record usage of conversion in an implicit cast.
12714     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12715                                     CK_UserDefinedConversion, Call.get(),
12716                                     nullptr, VK_RValue);
12717 
12718     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12719   }
12720 
12721   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12722 
12723   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12724   // that calls this method, using Object for the implicit object
12725   // parameter and passing along the remaining arguments.
12726   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12727 
12728   // An error diagnostic has already been printed when parsing the declaration.
12729   if (Method->isInvalidDecl())
12730     return ExprError();
12731 
12732   const FunctionProtoType *Proto =
12733     Method->getType()->getAs<FunctionProtoType>();
12734 
12735   unsigned NumParams = Proto->getNumParams();
12736 
12737   DeclarationNameInfo OpLocInfo(
12738                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12739   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12740   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12741                                            HadMultipleCandidates,
12742                                            OpLocInfo.getLoc(),
12743                                            OpLocInfo.getInfo());
12744   if (NewFn.isInvalid())
12745     return true;
12746 
12747   // Build the full argument list for the method call (the implicit object
12748   // parameter is placed at the beginning of the list).
12749   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12750   MethodArgs[0] = Object.get();
12751   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12752 
12753   // Once we've built TheCall, all of the expressions are properly
12754   // owned.
12755   QualType ResultTy = Method->getReturnType();
12756   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12757   ResultTy = ResultTy.getNonLValueExprType(Context);
12758 
12759   CXXOperatorCallExpr *TheCall = new (Context)
12760       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12761                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12762                           ResultTy, VK, RParenLoc, false);
12763   MethodArgs.reset();
12764 
12765   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12766     return true;
12767 
12768   // We may have default arguments. If so, we need to allocate more
12769   // slots in the call for them.
12770   if (Args.size() < NumParams)
12771     TheCall->setNumArgs(Context, NumParams + 1);
12772 
12773   bool IsError = false;
12774 
12775   // Initialize the implicit object parameter.
12776   ExprResult ObjRes =
12777     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12778                                         Best->FoundDecl, Method);
12779   if (ObjRes.isInvalid())
12780     IsError = true;
12781   else
12782     Object = ObjRes;
12783   TheCall->setArg(0, Object.get());
12784 
12785   // Check the argument types.
12786   for (unsigned i = 0; i != NumParams; i++) {
12787     Expr *Arg;
12788     if (i < Args.size()) {
12789       Arg = Args[i];
12790 
12791       // Pass the argument.
12792 
12793       ExprResult InputInit
12794         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12795                                                     Context,
12796                                                     Method->getParamDecl(i)),
12797                                     SourceLocation(), Arg);
12798 
12799       IsError |= InputInit.isInvalid();
12800       Arg = InputInit.getAs<Expr>();
12801     } else {
12802       ExprResult DefArg
12803         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12804       if (DefArg.isInvalid()) {
12805         IsError = true;
12806         break;
12807       }
12808 
12809       Arg = DefArg.getAs<Expr>();
12810     }
12811 
12812     TheCall->setArg(i + 1, Arg);
12813   }
12814 
12815   // If this is a variadic call, handle args passed through "...".
12816   if (Proto->isVariadic()) {
12817     // Promote the arguments (C99 6.5.2.2p7).
12818     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12819       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12820                                                         nullptr);
12821       IsError |= Arg.isInvalid();
12822       TheCall->setArg(i + 1, Arg.get());
12823     }
12824   }
12825 
12826   if (IsError) return true;
12827 
12828   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12829 
12830   if (CheckFunctionCall(Method, TheCall, Proto))
12831     return true;
12832 
12833   return MaybeBindToTemporary(TheCall);
12834 }
12835 
12836 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12837 ///  (if one exists), where @c Base is an expression of class type and
12838 /// @c Member is the name of the member we're trying to find.
12839 ExprResult
12840 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12841                                bool *NoArrowOperatorFound) {
12842   assert(Base->getType()->isRecordType() &&
12843          "left-hand side must have class type");
12844 
12845   if (checkPlaceholderForOverload(*this, Base))
12846     return ExprError();
12847 
12848   SourceLocation Loc = Base->getExprLoc();
12849 
12850   // C++ [over.ref]p1:
12851   //
12852   //   [...] An expression x->m is interpreted as (x.operator->())->m
12853   //   for a class object x of type T if T::operator->() exists and if
12854   //   the operator is selected as the best match function by the
12855   //   overload resolution mechanism (13.3).
12856   DeclarationName OpName =
12857     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12858   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12859   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12860 
12861   if (RequireCompleteType(Loc, Base->getType(),
12862                           diag::err_typecheck_incomplete_tag, Base))
12863     return ExprError();
12864 
12865   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12866   LookupQualifiedName(R, BaseRecord->getDecl());
12867   R.suppressDiagnostics();
12868 
12869   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12870        Oper != OperEnd; ++Oper) {
12871     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12872                        None, CandidateSet, /*SuppressUserConversions=*/false);
12873   }
12874 
12875   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12876 
12877   // Perform overload resolution.
12878   OverloadCandidateSet::iterator Best;
12879   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12880   case OR_Success:
12881     // Overload resolution succeeded; we'll build the call below.
12882     break;
12883 
12884   case OR_No_Viable_Function:
12885     if (CandidateSet.empty()) {
12886       QualType BaseType = Base->getType();
12887       if (NoArrowOperatorFound) {
12888         // Report this specific error to the caller instead of emitting a
12889         // diagnostic, as requested.
12890         *NoArrowOperatorFound = true;
12891         return ExprError();
12892       }
12893       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12894         << BaseType << Base->getSourceRange();
12895       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12896         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12897           << FixItHint::CreateReplacement(OpLoc, ".");
12898       }
12899     } else
12900       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12901         << "operator->" << Base->getSourceRange();
12902     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12903     return ExprError();
12904 
12905   case OR_Ambiguous:
12906     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12907       << "->" << Base->getType() << Base->getSourceRange();
12908     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12909     return ExprError();
12910 
12911   case OR_Deleted:
12912     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12913       << Best->Function->isDeleted()
12914       << "->"
12915       << getDeletedOrUnavailableSuffix(Best->Function)
12916       << Base->getSourceRange();
12917     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12918     return ExprError();
12919   }
12920 
12921   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12922 
12923   // Convert the object parameter.
12924   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12925   ExprResult BaseResult =
12926     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12927                                         Best->FoundDecl, Method);
12928   if (BaseResult.isInvalid())
12929     return ExprError();
12930   Base = BaseResult.get();
12931 
12932   // Build the operator call.
12933   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12934                                             HadMultipleCandidates, OpLoc);
12935   if (FnExpr.isInvalid())
12936     return ExprError();
12937 
12938   QualType ResultTy = Method->getReturnType();
12939   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12940   ResultTy = ResultTy.getNonLValueExprType(Context);
12941   CXXOperatorCallExpr *TheCall =
12942     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12943                                       Base, ResultTy, VK, OpLoc, false);
12944 
12945   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12946           return ExprError();
12947 
12948   return MaybeBindToTemporary(TheCall);
12949 }
12950 
12951 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12952 /// a literal operator described by the provided lookup results.
12953 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12954                                           DeclarationNameInfo &SuffixInfo,
12955                                           ArrayRef<Expr*> Args,
12956                                           SourceLocation LitEndLoc,
12957                                        TemplateArgumentListInfo *TemplateArgs) {
12958   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12959 
12960   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12961                                     OverloadCandidateSet::CSK_Normal);
12962   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12963                         /*SuppressUserConversions=*/true);
12964 
12965   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12966 
12967   // Perform overload resolution. This will usually be trivial, but might need
12968   // to perform substitutions for a literal operator template.
12969   OverloadCandidateSet::iterator Best;
12970   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12971   case OR_Success:
12972   case OR_Deleted:
12973     break;
12974 
12975   case OR_No_Viable_Function:
12976     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12977       << R.getLookupName();
12978     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12979     return ExprError();
12980 
12981   case OR_Ambiguous:
12982     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12983     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12984     return ExprError();
12985   }
12986 
12987   FunctionDecl *FD = Best->Function;
12988   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12989                                         HadMultipleCandidates,
12990                                         SuffixInfo.getLoc(),
12991                                         SuffixInfo.getInfo());
12992   if (Fn.isInvalid())
12993     return true;
12994 
12995   // Check the argument types. This should almost always be a no-op, except
12996   // that array-to-pointer decay is applied to string literals.
12997   Expr *ConvArgs[2];
12998   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12999     ExprResult InputInit = PerformCopyInitialization(
13000       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13001       SourceLocation(), Args[ArgIdx]);
13002     if (InputInit.isInvalid())
13003       return true;
13004     ConvArgs[ArgIdx] = InputInit.get();
13005   }
13006 
13007   QualType ResultTy = FD->getReturnType();
13008   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13009   ResultTy = ResultTy.getNonLValueExprType(Context);
13010 
13011   UserDefinedLiteral *UDL =
13012     new (Context) UserDefinedLiteral(Context, Fn.get(),
13013                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13014                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13015 
13016   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13017     return ExprError();
13018 
13019   if (CheckFunctionCall(FD, UDL, nullptr))
13020     return ExprError();
13021 
13022   return MaybeBindToTemporary(UDL);
13023 }
13024 
13025 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13026 /// given LookupResult is non-empty, it is assumed to describe a member which
13027 /// will be invoked. Otherwise, the function will be found via argument
13028 /// dependent lookup.
13029 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13030 /// otherwise CallExpr is set to ExprError() and some non-success value
13031 /// is returned.
13032 Sema::ForRangeStatus
13033 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13034                                 SourceLocation RangeLoc,
13035                                 const DeclarationNameInfo &NameInfo,
13036                                 LookupResult &MemberLookup,
13037                                 OverloadCandidateSet *CandidateSet,
13038                                 Expr *Range, ExprResult *CallExpr) {
13039   Scope *S = nullptr;
13040 
13041   CandidateSet->clear();
13042   if (!MemberLookup.empty()) {
13043     ExprResult MemberRef =
13044         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13045                                  /*IsPtr=*/false, CXXScopeSpec(),
13046                                  /*TemplateKWLoc=*/SourceLocation(),
13047                                  /*FirstQualifierInScope=*/nullptr,
13048                                  MemberLookup,
13049                                  /*TemplateArgs=*/nullptr, S);
13050     if (MemberRef.isInvalid()) {
13051       *CallExpr = ExprError();
13052       return FRS_DiagnosticIssued;
13053     }
13054     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13055     if (CallExpr->isInvalid()) {
13056       *CallExpr = ExprError();
13057       return FRS_DiagnosticIssued;
13058     }
13059   } else {
13060     UnresolvedSet<0> FoundNames;
13061     UnresolvedLookupExpr *Fn =
13062       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13063                                    NestedNameSpecifierLoc(), NameInfo,
13064                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13065                                    FoundNames.begin(), FoundNames.end());
13066 
13067     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13068                                                     CandidateSet, CallExpr);
13069     if (CandidateSet->empty() || CandidateSetError) {
13070       *CallExpr = ExprError();
13071       return FRS_NoViableFunction;
13072     }
13073     OverloadCandidateSet::iterator Best;
13074     OverloadingResult OverloadResult =
13075         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13076 
13077     if (OverloadResult == OR_No_Viable_Function) {
13078       *CallExpr = ExprError();
13079       return FRS_NoViableFunction;
13080     }
13081     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13082                                          Loc, nullptr, CandidateSet, &Best,
13083                                          OverloadResult,
13084                                          /*AllowTypoCorrection=*/false);
13085     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13086       *CallExpr = ExprError();
13087       return FRS_DiagnosticIssued;
13088     }
13089   }
13090   return FRS_Success;
13091 }
13092 
13093 
13094 /// FixOverloadedFunctionReference - E is an expression that refers to
13095 /// a C++ overloaded function (possibly with some parentheses and
13096 /// perhaps a '&' around it). We have resolved the overloaded function
13097 /// to the function declaration Fn, so patch up the expression E to
13098 /// refer (possibly indirectly) to Fn. Returns the new expr.
13099 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13100                                            FunctionDecl *Fn) {
13101   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13102     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13103                                                    Found, Fn);
13104     if (SubExpr == PE->getSubExpr())
13105       return PE;
13106 
13107     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13108   }
13109 
13110   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13111     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13112                                                    Found, Fn);
13113     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13114                                SubExpr->getType()) &&
13115            "Implicit cast type cannot be determined from overload");
13116     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13117     if (SubExpr == ICE->getSubExpr())
13118       return ICE;
13119 
13120     return ImplicitCastExpr::Create(Context, ICE->getType(),
13121                                     ICE->getCastKind(),
13122                                     SubExpr, nullptr,
13123                                     ICE->getValueKind());
13124   }
13125 
13126   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13127     if (!GSE->isResultDependent()) {
13128       Expr *SubExpr =
13129           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13130       if (SubExpr == GSE->getResultExpr())
13131         return GSE;
13132 
13133       // Replace the resulting type information before rebuilding the generic
13134       // selection expression.
13135       ArrayRef<Expr *> A = GSE->getAssocExprs();
13136       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13137       unsigned ResultIdx = GSE->getResultIndex();
13138       AssocExprs[ResultIdx] = SubExpr;
13139 
13140       return new (Context) GenericSelectionExpr(
13141           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13142           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13143           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13144           ResultIdx);
13145     }
13146     // Rather than fall through to the unreachable, return the original generic
13147     // selection expression.
13148     return GSE;
13149   }
13150 
13151   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13152     assert(UnOp->getOpcode() == UO_AddrOf &&
13153            "Can only take the address of an overloaded function");
13154     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13155       if (Method->isStatic()) {
13156         // Do nothing: static member functions aren't any different
13157         // from non-member functions.
13158       } else {
13159         // Fix the subexpression, which really has to be an
13160         // UnresolvedLookupExpr holding an overloaded member function
13161         // or template.
13162         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13163                                                        Found, Fn);
13164         if (SubExpr == UnOp->getSubExpr())
13165           return UnOp;
13166 
13167         assert(isa<DeclRefExpr>(SubExpr)
13168                && "fixed to something other than a decl ref");
13169         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13170                && "fixed to a member ref with no nested name qualifier");
13171 
13172         // We have taken the address of a pointer to member
13173         // function. Perform the computation here so that we get the
13174         // appropriate pointer to member type.
13175         QualType ClassType
13176           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13177         QualType MemPtrType
13178           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13179         // Under the MS ABI, lock down the inheritance model now.
13180         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13181           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13182 
13183         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13184                                            VK_RValue, OK_Ordinary,
13185                                            UnOp->getOperatorLoc());
13186       }
13187     }
13188     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13189                                                    Found, Fn);
13190     if (SubExpr == UnOp->getSubExpr())
13191       return UnOp;
13192 
13193     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13194                                      Context.getPointerType(SubExpr->getType()),
13195                                        VK_RValue, OK_Ordinary,
13196                                        UnOp->getOperatorLoc());
13197   }
13198 
13199   // C++ [except.spec]p17:
13200   //   An exception-specification is considered to be needed when:
13201   //   - in an expression the function is the unique lookup result or the
13202   //     selected member of a set of overloaded functions
13203   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13204     ResolveExceptionSpec(E->getExprLoc(), FPT);
13205 
13206   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13207     // FIXME: avoid copy.
13208     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13209     if (ULE->hasExplicitTemplateArgs()) {
13210       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13211       TemplateArgs = &TemplateArgsBuffer;
13212     }
13213 
13214     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13215                                            ULE->getQualifierLoc(),
13216                                            ULE->getTemplateKeywordLoc(),
13217                                            Fn,
13218                                            /*enclosing*/ false, // FIXME?
13219                                            ULE->getNameLoc(),
13220                                            Fn->getType(),
13221                                            VK_LValue,
13222                                            Found.getDecl(),
13223                                            TemplateArgs);
13224     MarkDeclRefReferenced(DRE);
13225     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13226     return DRE;
13227   }
13228 
13229   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13230     // FIXME: avoid copy.
13231     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13232     if (MemExpr->hasExplicitTemplateArgs()) {
13233       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13234       TemplateArgs = &TemplateArgsBuffer;
13235     }
13236 
13237     Expr *Base;
13238 
13239     // If we're filling in a static method where we used to have an
13240     // implicit member access, rewrite to a simple decl ref.
13241     if (MemExpr->isImplicitAccess()) {
13242       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13243         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13244                                                MemExpr->getQualifierLoc(),
13245                                                MemExpr->getTemplateKeywordLoc(),
13246                                                Fn,
13247                                                /*enclosing*/ false,
13248                                                MemExpr->getMemberLoc(),
13249                                                Fn->getType(),
13250                                                VK_LValue,
13251                                                Found.getDecl(),
13252                                                TemplateArgs);
13253         MarkDeclRefReferenced(DRE);
13254         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13255         return DRE;
13256       } else {
13257         SourceLocation Loc = MemExpr->getMemberLoc();
13258         if (MemExpr->getQualifier())
13259           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13260         CheckCXXThisCapture(Loc);
13261         Base = new (Context) CXXThisExpr(Loc,
13262                                          MemExpr->getBaseType(),
13263                                          /*isImplicit=*/true);
13264       }
13265     } else
13266       Base = MemExpr->getBase();
13267 
13268     ExprValueKind valueKind;
13269     QualType type;
13270     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13271       valueKind = VK_LValue;
13272       type = Fn->getType();
13273     } else {
13274       valueKind = VK_RValue;
13275       type = Context.BoundMemberTy;
13276     }
13277 
13278     MemberExpr *ME = MemberExpr::Create(
13279         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13280         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13281         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13282         OK_Ordinary);
13283     ME->setHadMultipleCandidates(true);
13284     MarkMemberReferenced(ME);
13285     return ME;
13286   }
13287 
13288   llvm_unreachable("Invalid reference to overloaded function");
13289 }
13290 
13291 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13292                                                 DeclAccessPair Found,
13293                                                 FunctionDecl *Fn) {
13294   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13295 }
13296