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     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4777     // need to call into the initialization code here; overload resolution
4778     // should not be doing that.
4779     InitializedEntity Entity =
4780         InitializedEntity::InitializeParameter(S.Context, ToType,
4781                                                /*Consumed=*/false);
4782     if (S.CanPerformCopyInitialization(Entity, From)) {
4783       Result.setUserDefined();
4784       Result.UserDefined.Before.setAsIdentityConversion();
4785       // Initializer lists don't have a type.
4786       Result.UserDefined.Before.setFromType(QualType());
4787       Result.UserDefined.Before.setAllToTypes(QualType());
4788 
4789       Result.UserDefined.After.setAsIdentityConversion();
4790       Result.UserDefined.After.setFromType(ToType);
4791       Result.UserDefined.After.setAllToTypes(ToType);
4792       Result.UserDefined.ConversionFunction = nullptr;
4793     }
4794     return Result;
4795   }
4796 
4797   // C++14 [over.ics.list]p6:
4798   // C++11 [over.ics.list]p5:
4799   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4800   if (ToType->isReferenceType()) {
4801     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4802     // mention initializer lists in any way. So we go by what list-
4803     // initialization would do and try to extrapolate from that.
4804 
4805     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4806 
4807     // If the initializer list has a single element that is reference-related
4808     // to the parameter type, we initialize the reference from that.
4809     if (From->getNumInits() == 1) {
4810       Expr *Init = From->getInit(0);
4811 
4812       QualType T2 = Init->getType();
4813 
4814       // If the initializer is the address of an overloaded function, try
4815       // to resolve the overloaded function. If all goes well, T2 is the
4816       // type of the resulting function.
4817       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4818         DeclAccessPair Found;
4819         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4820                                    Init, ToType, false, Found))
4821           T2 = Fn->getType();
4822       }
4823 
4824       // Compute some basic properties of the types and the initializer.
4825       bool dummy1 = false;
4826       bool dummy2 = false;
4827       bool dummy3 = false;
4828       Sema::ReferenceCompareResult RefRelationship
4829         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4830                                          dummy2, dummy3);
4831 
4832       if (RefRelationship >= Sema::Ref_Related) {
4833         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4834                                 SuppressUserConversions,
4835                                 /*AllowExplicit=*/false);
4836       }
4837     }
4838 
4839     // Otherwise, we bind the reference to a temporary created from the
4840     // initializer list.
4841     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4842                                InOverloadResolution,
4843                                AllowObjCWritebackConversion);
4844     if (Result.isFailure())
4845       return Result;
4846     assert(!Result.isEllipsis() &&
4847            "Sub-initialization cannot result in ellipsis conversion.");
4848 
4849     // Can we even bind to a temporary?
4850     if (ToType->isRValueReferenceType() ||
4851         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4852       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4853                                             Result.UserDefined.After;
4854       SCS.ReferenceBinding = true;
4855       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4856       SCS.BindsToRvalue = true;
4857       SCS.BindsToFunctionLvalue = false;
4858       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4859       SCS.ObjCLifetimeConversionBinding = false;
4860     } else
4861       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4862                     From, ToType);
4863     return Result;
4864   }
4865 
4866   // C++14 [over.ics.list]p7:
4867   // C++11 [over.ics.list]p6:
4868   //   Otherwise, if the parameter type is not a class:
4869   if (!ToType->isRecordType()) {
4870     //    - if the initializer list has one element that is not itself an
4871     //      initializer list, the implicit conversion sequence is the one
4872     //      required to convert the element to the parameter type.
4873     unsigned NumInits = From->getNumInits();
4874     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4875       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4876                                      SuppressUserConversions,
4877                                      InOverloadResolution,
4878                                      AllowObjCWritebackConversion);
4879     //    - if the initializer list has no elements, the implicit conversion
4880     //      sequence is the identity conversion.
4881     else if (NumInits == 0) {
4882       Result.setStandard();
4883       Result.Standard.setAsIdentityConversion();
4884       Result.Standard.setFromType(ToType);
4885       Result.Standard.setAllToTypes(ToType);
4886     }
4887     return Result;
4888   }
4889 
4890   // C++14 [over.ics.list]p8:
4891   // C++11 [over.ics.list]p7:
4892   //   In all cases other than those enumerated above, no conversion is possible
4893   return Result;
4894 }
4895 
4896 /// TryCopyInitialization - Try to copy-initialize a value of type
4897 /// ToType from the expression From. Return the implicit conversion
4898 /// sequence required to pass this argument, which may be a bad
4899 /// conversion sequence (meaning that the argument cannot be passed to
4900 /// a parameter of this type). If @p SuppressUserConversions, then we
4901 /// do not permit any user-defined conversion sequences.
4902 static ImplicitConversionSequence
4903 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4904                       bool SuppressUserConversions,
4905                       bool InOverloadResolution,
4906                       bool AllowObjCWritebackConversion,
4907                       bool AllowExplicit) {
4908   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4909     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4910                              InOverloadResolution,AllowObjCWritebackConversion);
4911 
4912   if (ToType->isReferenceType())
4913     return TryReferenceInit(S, From, ToType,
4914                             /*FIXME:*/From->getLocStart(),
4915                             SuppressUserConversions,
4916                             AllowExplicit);
4917 
4918   return TryImplicitConversion(S, From, ToType,
4919                                SuppressUserConversions,
4920                                /*AllowExplicit=*/false,
4921                                InOverloadResolution,
4922                                /*CStyle=*/false,
4923                                AllowObjCWritebackConversion,
4924                                /*AllowObjCConversionOnExplicit=*/false);
4925 }
4926 
4927 static bool TryCopyInitialization(const CanQualType FromQTy,
4928                                   const CanQualType ToQTy,
4929                                   Sema &S,
4930                                   SourceLocation Loc,
4931                                   ExprValueKind FromVK) {
4932   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4933   ImplicitConversionSequence ICS =
4934     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4935 
4936   return !ICS.isBad();
4937 }
4938 
4939 /// TryObjectArgumentInitialization - Try to initialize the object
4940 /// parameter of the given member function (@c Method) from the
4941 /// expression @p From.
4942 static ImplicitConversionSequence
4943 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4944                                 Expr::Classification FromClassification,
4945                                 CXXMethodDecl *Method,
4946                                 CXXRecordDecl *ActingContext) {
4947   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4948   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4949   //                 const volatile object.
4950   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4951     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4952   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4953 
4954   // Set up the conversion sequence as a "bad" conversion, to allow us
4955   // to exit early.
4956   ImplicitConversionSequence ICS;
4957 
4958   // We need to have an object of class type.
4959   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4960     FromType = PT->getPointeeType();
4961 
4962     // When we had a pointer, it's implicitly dereferenced, so we
4963     // better have an lvalue.
4964     assert(FromClassification.isLValue());
4965   }
4966 
4967   assert(FromType->isRecordType());
4968 
4969   // C++0x [over.match.funcs]p4:
4970   //   For non-static member functions, the type of the implicit object
4971   //   parameter is
4972   //
4973   //     - "lvalue reference to cv X" for functions declared without a
4974   //        ref-qualifier or with the & ref-qualifier
4975   //     - "rvalue reference to cv X" for functions declared with the &&
4976   //        ref-qualifier
4977   //
4978   // where X is the class of which the function is a member and cv is the
4979   // cv-qualification on the member function declaration.
4980   //
4981   // However, when finding an implicit conversion sequence for the argument, we
4982   // are not allowed to perform user-defined conversions
4983   // (C++ [over.match.funcs]p5). We perform a simplified version of
4984   // reference binding here, that allows class rvalues to bind to
4985   // non-constant references.
4986 
4987   // First check the qualifiers.
4988   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4989   if (ImplicitParamType.getCVRQualifiers()
4990                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4991       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4992     ICS.setBad(BadConversionSequence::bad_qualifiers,
4993                FromType, ImplicitParamType);
4994     return ICS;
4995   }
4996 
4997   // Check that we have either the same type or a derived type. It
4998   // affects the conversion rank.
4999   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5000   ImplicitConversionKind SecondKind;
5001   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5002     SecondKind = ICK_Identity;
5003   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5004     SecondKind = ICK_Derived_To_Base;
5005   else {
5006     ICS.setBad(BadConversionSequence::unrelated_class,
5007                FromType, ImplicitParamType);
5008     return ICS;
5009   }
5010 
5011   // Check the ref-qualifier.
5012   switch (Method->getRefQualifier()) {
5013   case RQ_None:
5014     // Do nothing; we don't care about lvalueness or rvalueness.
5015     break;
5016 
5017   case RQ_LValue:
5018     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5019       // non-const lvalue reference cannot bind to an rvalue
5020       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5021                  ImplicitParamType);
5022       return ICS;
5023     }
5024     break;
5025 
5026   case RQ_RValue:
5027     if (!FromClassification.isRValue()) {
5028       // rvalue reference cannot bind to an lvalue
5029       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5030                  ImplicitParamType);
5031       return ICS;
5032     }
5033     break;
5034   }
5035 
5036   // Success. Mark this as a reference binding.
5037   ICS.setStandard();
5038   ICS.Standard.setAsIdentityConversion();
5039   ICS.Standard.Second = SecondKind;
5040   ICS.Standard.setFromType(FromType);
5041   ICS.Standard.setAllToTypes(ImplicitParamType);
5042   ICS.Standard.ReferenceBinding = true;
5043   ICS.Standard.DirectBinding = true;
5044   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5045   ICS.Standard.BindsToFunctionLvalue = false;
5046   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5047   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5048     = (Method->getRefQualifier() == RQ_None);
5049   return ICS;
5050 }
5051 
5052 /// PerformObjectArgumentInitialization - Perform initialization of
5053 /// the implicit object parameter for the given Method with the given
5054 /// expression.
5055 ExprResult
5056 Sema::PerformObjectArgumentInitialization(Expr *From,
5057                                           NestedNameSpecifier *Qualifier,
5058                                           NamedDecl *FoundDecl,
5059                                           CXXMethodDecl *Method) {
5060   QualType FromRecordType, DestType;
5061   QualType ImplicitParamRecordType  =
5062     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5063 
5064   Expr::Classification FromClassification;
5065   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5066     FromRecordType = PT->getPointeeType();
5067     DestType = Method->getThisType(Context);
5068     FromClassification = Expr::Classification::makeSimpleLValue();
5069   } else {
5070     FromRecordType = From->getType();
5071     DestType = ImplicitParamRecordType;
5072     FromClassification = From->Classify(Context);
5073   }
5074 
5075   // Note that we always use the true parent context when performing
5076   // the actual argument initialization.
5077   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5078       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5079       Method->getParent());
5080   if (ICS.isBad()) {
5081     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5082       Qualifiers FromQs = FromRecordType.getQualifiers();
5083       Qualifiers ToQs = DestType.getQualifiers();
5084       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5085       if (CVR) {
5086         Diag(From->getLocStart(),
5087              diag::err_member_function_call_bad_cvr)
5088           << Method->getDeclName() << FromRecordType << (CVR - 1)
5089           << From->getSourceRange();
5090         Diag(Method->getLocation(), diag::note_previous_decl)
5091           << Method->getDeclName();
5092         return ExprError();
5093       }
5094     }
5095 
5096     return Diag(From->getLocStart(),
5097                 diag::err_implicit_object_parameter_init)
5098        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5099   }
5100 
5101   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5102     ExprResult FromRes =
5103       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5104     if (FromRes.isInvalid())
5105       return ExprError();
5106     From = FromRes.get();
5107   }
5108 
5109   if (!Context.hasSameType(From->getType(), DestType))
5110     From = ImpCastExprToType(From, DestType, CK_NoOp,
5111                              From->getValueKind()).get();
5112   return From;
5113 }
5114 
5115 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5116 /// expression From to bool (C++0x [conv]p3).
5117 static ImplicitConversionSequence
5118 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5119   return TryImplicitConversion(S, From, S.Context.BoolTy,
5120                                /*SuppressUserConversions=*/false,
5121                                /*AllowExplicit=*/true,
5122                                /*InOverloadResolution=*/false,
5123                                /*CStyle=*/false,
5124                                /*AllowObjCWritebackConversion=*/false,
5125                                /*AllowObjCConversionOnExplicit=*/false);
5126 }
5127 
5128 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5129 /// of the expression From to bool (C++0x [conv]p3).
5130 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5131   if (checkPlaceholderForOverload(*this, From))
5132     return ExprError();
5133 
5134   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5135   if (!ICS.isBad())
5136     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5137 
5138   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5139     return Diag(From->getLocStart(),
5140                 diag::err_typecheck_bool_condition)
5141                   << From->getType() << From->getSourceRange();
5142   return ExprError();
5143 }
5144 
5145 /// Check that the specified conversion is permitted in a converted constant
5146 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5147 /// is acceptable.
5148 static bool CheckConvertedConstantConversions(Sema &S,
5149                                               StandardConversionSequence &SCS) {
5150   // Since we know that the target type is an integral or unscoped enumeration
5151   // type, most conversion kinds are impossible. All possible First and Third
5152   // conversions are fine.
5153   switch (SCS.Second) {
5154   case ICK_Identity:
5155   case ICK_Function_Conversion:
5156   case ICK_Integral_Promotion:
5157   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5158     return true;
5159 
5160   case ICK_Boolean_Conversion:
5161     // Conversion from an integral or unscoped enumeration type to bool is
5162     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5163     // conversion, so we allow it in a converted constant expression.
5164     //
5165     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5166     // a lot of popular code. We should at least add a warning for this
5167     // (non-conforming) extension.
5168     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5169            SCS.getToType(2)->isBooleanType();
5170 
5171   case ICK_Pointer_Conversion:
5172   case ICK_Pointer_Member:
5173     // C++1z: null pointer conversions and null member pointer conversions are
5174     // only permitted if the source type is std::nullptr_t.
5175     return SCS.getFromType()->isNullPtrType();
5176 
5177   case ICK_Floating_Promotion:
5178   case ICK_Complex_Promotion:
5179   case ICK_Floating_Conversion:
5180   case ICK_Complex_Conversion:
5181   case ICK_Floating_Integral:
5182   case ICK_Compatible_Conversion:
5183   case ICK_Derived_To_Base:
5184   case ICK_Vector_Conversion:
5185   case ICK_Vector_Splat:
5186   case ICK_Complex_Real:
5187   case ICK_Block_Pointer_Conversion:
5188   case ICK_TransparentUnionConversion:
5189   case ICK_Writeback_Conversion:
5190   case ICK_Zero_Event_Conversion:
5191   case ICK_C_Only_Conversion:
5192   case ICK_Incompatible_Pointer_Conversion:
5193     return false;
5194 
5195   case ICK_Lvalue_To_Rvalue:
5196   case ICK_Array_To_Pointer:
5197   case ICK_Function_To_Pointer:
5198     llvm_unreachable("found a first conversion kind in Second");
5199 
5200   case ICK_Qualification:
5201     llvm_unreachable("found a third conversion kind in Second");
5202 
5203   case ICK_Num_Conversion_Kinds:
5204     break;
5205   }
5206 
5207   llvm_unreachable("unknown conversion kind");
5208 }
5209 
5210 /// CheckConvertedConstantExpression - Check that the expression From is a
5211 /// converted constant expression of type T, perform the conversion and produce
5212 /// the converted expression, per C++11 [expr.const]p3.
5213 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5214                                                    QualType T, APValue &Value,
5215                                                    Sema::CCEKind CCE,
5216                                                    bool RequireInt) {
5217   assert(S.getLangOpts().CPlusPlus11 &&
5218          "converted constant expression outside C++11");
5219 
5220   if (checkPlaceholderForOverload(S, From))
5221     return ExprError();
5222 
5223   // C++1z [expr.const]p3:
5224   //  A converted constant expression of type T is an expression,
5225   //  implicitly converted to type T, where the converted
5226   //  expression is a constant expression and the implicit conversion
5227   //  sequence contains only [... list of conversions ...].
5228   // C++1z [stmt.if]p2:
5229   //  If the if statement is of the form if constexpr, the value of the
5230   //  condition shall be a contextually converted constant expression of type
5231   //  bool.
5232   ImplicitConversionSequence ICS =
5233       CCE == Sema::CCEK_ConstexprIf
5234           ? TryContextuallyConvertToBool(S, From)
5235           : TryCopyInitialization(S, From, T,
5236                                   /*SuppressUserConversions=*/false,
5237                                   /*InOverloadResolution=*/false,
5238                                   /*AllowObjcWritebackConversion=*/false,
5239                                   /*AllowExplicit=*/false);
5240   StandardConversionSequence *SCS = nullptr;
5241   switch (ICS.getKind()) {
5242   case ImplicitConversionSequence::StandardConversion:
5243     SCS = &ICS.Standard;
5244     break;
5245   case ImplicitConversionSequence::UserDefinedConversion:
5246     // We are converting to a non-class type, so the Before sequence
5247     // must be trivial.
5248     SCS = &ICS.UserDefined.After;
5249     break;
5250   case ImplicitConversionSequence::AmbiguousConversion:
5251   case ImplicitConversionSequence::BadConversion:
5252     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5253       return S.Diag(From->getLocStart(),
5254                     diag::err_typecheck_converted_constant_expression)
5255                 << From->getType() << From->getSourceRange() << T;
5256     return ExprError();
5257 
5258   case ImplicitConversionSequence::EllipsisConversion:
5259     llvm_unreachable("ellipsis conversion in converted constant expression");
5260   }
5261 
5262   // Check that we would only use permitted conversions.
5263   if (!CheckConvertedConstantConversions(S, *SCS)) {
5264     return S.Diag(From->getLocStart(),
5265                   diag::err_typecheck_converted_constant_expression_disallowed)
5266              << From->getType() << From->getSourceRange() << T;
5267   }
5268   // [...] and where the reference binding (if any) binds directly.
5269   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5270     return S.Diag(From->getLocStart(),
5271                   diag::err_typecheck_converted_constant_expression_indirect)
5272              << From->getType() << From->getSourceRange() << T;
5273   }
5274 
5275   ExprResult Result =
5276       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5277   if (Result.isInvalid())
5278     return Result;
5279 
5280   // Check for a narrowing implicit conversion.
5281   APValue PreNarrowingValue;
5282   QualType PreNarrowingType;
5283   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5284                                 PreNarrowingType)) {
5285   case NK_Variable_Narrowing:
5286     // Implicit conversion to a narrower type, and the value is not a constant
5287     // expression. We'll diagnose this in a moment.
5288   case NK_Not_Narrowing:
5289     break;
5290 
5291   case NK_Constant_Narrowing:
5292     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5293       << CCE << /*Constant*/1
5294       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5295     break;
5296 
5297   case NK_Type_Narrowing:
5298     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5299       << CCE << /*Constant*/0 << From->getType() << T;
5300     break;
5301   }
5302 
5303   // Check the expression is a constant expression.
5304   SmallVector<PartialDiagnosticAt, 8> Notes;
5305   Expr::EvalResult Eval;
5306   Eval.Diag = &Notes;
5307 
5308   if ((T->isReferenceType()
5309            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5310            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5311       (RequireInt && !Eval.Val.isInt())) {
5312     // The expression can't be folded, so we can't keep it at this position in
5313     // the AST.
5314     Result = ExprError();
5315   } else {
5316     Value = Eval.Val;
5317 
5318     if (Notes.empty()) {
5319       // It's a constant expression.
5320       return Result;
5321     }
5322   }
5323 
5324   // It's not a constant expression. Produce an appropriate diagnostic.
5325   if (Notes.size() == 1 &&
5326       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5327     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5328   else {
5329     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5330       << CCE << From->getSourceRange();
5331     for (unsigned I = 0; I < Notes.size(); ++I)
5332       S.Diag(Notes[I].first, Notes[I].second);
5333   }
5334   return ExprError();
5335 }
5336 
5337 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5338                                                   APValue &Value, CCEKind CCE) {
5339   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5340 }
5341 
5342 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5343                                                   llvm::APSInt &Value,
5344                                                   CCEKind CCE) {
5345   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5346 
5347   APValue V;
5348   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5349   if (!R.isInvalid())
5350     Value = V.getInt();
5351   return R;
5352 }
5353 
5354 
5355 /// dropPointerConversions - If the given standard conversion sequence
5356 /// involves any pointer conversions, remove them.  This may change
5357 /// the result type of the conversion sequence.
5358 static void dropPointerConversion(StandardConversionSequence &SCS) {
5359   if (SCS.Second == ICK_Pointer_Conversion) {
5360     SCS.Second = ICK_Identity;
5361     SCS.Third = ICK_Identity;
5362     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5363   }
5364 }
5365 
5366 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5367 /// convert the expression From to an Objective-C pointer type.
5368 static ImplicitConversionSequence
5369 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5370   // Do an implicit conversion to 'id'.
5371   QualType Ty = S.Context.getObjCIdType();
5372   ImplicitConversionSequence ICS
5373     = TryImplicitConversion(S, From, Ty,
5374                             // FIXME: Are these flags correct?
5375                             /*SuppressUserConversions=*/false,
5376                             /*AllowExplicit=*/true,
5377                             /*InOverloadResolution=*/false,
5378                             /*CStyle=*/false,
5379                             /*AllowObjCWritebackConversion=*/false,
5380                             /*AllowObjCConversionOnExplicit=*/true);
5381 
5382   // Strip off any final conversions to 'id'.
5383   switch (ICS.getKind()) {
5384   case ImplicitConversionSequence::BadConversion:
5385   case ImplicitConversionSequence::AmbiguousConversion:
5386   case ImplicitConversionSequence::EllipsisConversion:
5387     break;
5388 
5389   case ImplicitConversionSequence::UserDefinedConversion:
5390     dropPointerConversion(ICS.UserDefined.After);
5391     break;
5392 
5393   case ImplicitConversionSequence::StandardConversion:
5394     dropPointerConversion(ICS.Standard);
5395     break;
5396   }
5397 
5398   return ICS;
5399 }
5400 
5401 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5402 /// conversion of the expression From to an Objective-C pointer type.
5403 /// Returns a valid but null ExprResult if no conversion sequence exists.
5404 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5405   if (checkPlaceholderForOverload(*this, From))
5406     return ExprError();
5407 
5408   QualType Ty = Context.getObjCIdType();
5409   ImplicitConversionSequence ICS =
5410     TryContextuallyConvertToObjCPointer(*this, From);
5411   if (!ICS.isBad())
5412     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5413   return ExprResult();
5414 }
5415 
5416 /// Determine whether the provided type is an integral type, or an enumeration
5417 /// type of a permitted flavor.
5418 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5419   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5420                                  : T->isIntegralOrUnscopedEnumerationType();
5421 }
5422 
5423 static ExprResult
5424 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5425                             Sema::ContextualImplicitConverter &Converter,
5426                             QualType T, UnresolvedSetImpl &ViableConversions) {
5427 
5428   if (Converter.Suppress)
5429     return ExprError();
5430 
5431   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5432   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5433     CXXConversionDecl *Conv =
5434         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5435     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5436     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5437   }
5438   return From;
5439 }
5440 
5441 static bool
5442 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5443                            Sema::ContextualImplicitConverter &Converter,
5444                            QualType T, bool HadMultipleCandidates,
5445                            UnresolvedSetImpl &ExplicitConversions) {
5446   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5447     DeclAccessPair Found = ExplicitConversions[0];
5448     CXXConversionDecl *Conversion =
5449         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5450 
5451     // The user probably meant to invoke the given explicit
5452     // conversion; use it.
5453     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5454     std::string TypeStr;
5455     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5456 
5457     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5458         << FixItHint::CreateInsertion(From->getLocStart(),
5459                                       "static_cast<" + TypeStr + ">(")
5460         << FixItHint::CreateInsertion(
5461                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5462     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5463 
5464     // If we aren't in a SFINAE context, build a call to the
5465     // explicit conversion function.
5466     if (SemaRef.isSFINAEContext())
5467       return true;
5468 
5469     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5470     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5471                                                        HadMultipleCandidates);
5472     if (Result.isInvalid())
5473       return true;
5474     // Record usage of conversion in an implicit cast.
5475     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5476                                     CK_UserDefinedConversion, Result.get(),
5477                                     nullptr, Result.get()->getValueKind());
5478   }
5479   return false;
5480 }
5481 
5482 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5483                              Sema::ContextualImplicitConverter &Converter,
5484                              QualType T, bool HadMultipleCandidates,
5485                              DeclAccessPair &Found) {
5486   CXXConversionDecl *Conversion =
5487       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5488   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5489 
5490   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5491   if (!Converter.SuppressConversion) {
5492     if (SemaRef.isSFINAEContext())
5493       return true;
5494 
5495     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5496         << From->getSourceRange();
5497   }
5498 
5499   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5500                                                      HadMultipleCandidates);
5501   if (Result.isInvalid())
5502     return true;
5503   // Record usage of conversion in an implicit cast.
5504   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5505                                   CK_UserDefinedConversion, Result.get(),
5506                                   nullptr, Result.get()->getValueKind());
5507   return false;
5508 }
5509 
5510 static ExprResult finishContextualImplicitConversion(
5511     Sema &SemaRef, SourceLocation Loc, Expr *From,
5512     Sema::ContextualImplicitConverter &Converter) {
5513   if (!Converter.match(From->getType()) && !Converter.Suppress)
5514     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5515         << From->getSourceRange();
5516 
5517   return SemaRef.DefaultLvalueConversion(From);
5518 }
5519 
5520 static void
5521 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5522                                   UnresolvedSetImpl &ViableConversions,
5523                                   OverloadCandidateSet &CandidateSet) {
5524   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5525     DeclAccessPair FoundDecl = ViableConversions[I];
5526     NamedDecl *D = FoundDecl.getDecl();
5527     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5528     if (isa<UsingShadowDecl>(D))
5529       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5530 
5531     CXXConversionDecl *Conv;
5532     FunctionTemplateDecl *ConvTemplate;
5533     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5534       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5535     else
5536       Conv = cast<CXXConversionDecl>(D);
5537 
5538     if (ConvTemplate)
5539       SemaRef.AddTemplateConversionCandidate(
5540         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5541         /*AllowObjCConversionOnExplicit=*/false);
5542     else
5543       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5544                                      ToType, CandidateSet,
5545                                      /*AllowObjCConversionOnExplicit=*/false);
5546   }
5547 }
5548 
5549 /// \brief Attempt to convert the given expression to a type which is accepted
5550 /// by the given converter.
5551 ///
5552 /// This routine will attempt to convert an expression of class type to a
5553 /// type accepted by the specified converter. In C++11 and before, the class
5554 /// must have a single non-explicit conversion function converting to a matching
5555 /// type. In C++1y, there can be multiple such conversion functions, but only
5556 /// one target type.
5557 ///
5558 /// \param Loc The source location of the construct that requires the
5559 /// conversion.
5560 ///
5561 /// \param From The expression we're converting from.
5562 ///
5563 /// \param Converter Used to control and diagnose the conversion process.
5564 ///
5565 /// \returns The expression, converted to an integral or enumeration type if
5566 /// successful.
5567 ExprResult Sema::PerformContextualImplicitConversion(
5568     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5569   // We can't perform any more checking for type-dependent expressions.
5570   if (From->isTypeDependent())
5571     return From;
5572 
5573   // Process placeholders immediately.
5574   if (From->hasPlaceholderType()) {
5575     ExprResult result = CheckPlaceholderExpr(From);
5576     if (result.isInvalid())
5577       return result;
5578     From = result.get();
5579   }
5580 
5581   // If the expression already has a matching type, we're golden.
5582   QualType T = From->getType();
5583   if (Converter.match(T))
5584     return DefaultLvalueConversion(From);
5585 
5586   // FIXME: Check for missing '()' if T is a function type?
5587 
5588   // We can only perform contextual implicit conversions on objects of class
5589   // type.
5590   const RecordType *RecordTy = T->getAs<RecordType>();
5591   if (!RecordTy || !getLangOpts().CPlusPlus) {
5592     if (!Converter.Suppress)
5593       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5594     return From;
5595   }
5596 
5597   // We must have a complete class type.
5598   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5599     ContextualImplicitConverter &Converter;
5600     Expr *From;
5601 
5602     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5603         : Converter(Converter), From(From) {}
5604 
5605     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5606       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5607     }
5608   } IncompleteDiagnoser(Converter, From);
5609 
5610   if (Converter.Suppress ? !isCompleteType(Loc, T)
5611                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5612     return From;
5613 
5614   // Look for a conversion to an integral or enumeration type.
5615   UnresolvedSet<4>
5616       ViableConversions; // These are *potentially* viable in C++1y.
5617   UnresolvedSet<4> ExplicitConversions;
5618   const auto &Conversions =
5619       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5620 
5621   bool HadMultipleCandidates =
5622       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5623 
5624   // To check that there is only one target type, in C++1y:
5625   QualType ToType;
5626   bool HasUniqueTargetType = true;
5627 
5628   // Collect explicit or viable (potentially in C++1y) conversions.
5629   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5630     NamedDecl *D = (*I)->getUnderlyingDecl();
5631     CXXConversionDecl *Conversion;
5632     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5633     if (ConvTemplate) {
5634       if (getLangOpts().CPlusPlus14)
5635         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5636       else
5637         continue; // C++11 does not consider conversion operator templates(?).
5638     } else
5639       Conversion = cast<CXXConversionDecl>(D);
5640 
5641     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5642            "Conversion operator templates are considered potentially "
5643            "viable in C++1y");
5644 
5645     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5646     if (Converter.match(CurToType) || ConvTemplate) {
5647 
5648       if (Conversion->isExplicit()) {
5649         // FIXME: For C++1y, do we need this restriction?
5650         // cf. diagnoseNoViableConversion()
5651         if (!ConvTemplate)
5652           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5653       } else {
5654         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5655           if (ToType.isNull())
5656             ToType = CurToType.getUnqualifiedType();
5657           else if (HasUniqueTargetType &&
5658                    (CurToType.getUnqualifiedType() != ToType))
5659             HasUniqueTargetType = false;
5660         }
5661         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5662       }
5663     }
5664   }
5665 
5666   if (getLangOpts().CPlusPlus14) {
5667     // C++1y [conv]p6:
5668     // ... An expression e of class type E appearing in such a context
5669     // is said to be contextually implicitly converted to a specified
5670     // type T and is well-formed if and only if e can be implicitly
5671     // converted to a type T that is determined as follows: E is searched
5672     // for conversion functions whose return type is cv T or reference to
5673     // cv T such that T is allowed by the context. There shall be
5674     // exactly one such T.
5675 
5676     // If no unique T is found:
5677     if (ToType.isNull()) {
5678       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5679                                      HadMultipleCandidates,
5680                                      ExplicitConversions))
5681         return ExprError();
5682       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5683     }
5684 
5685     // If more than one unique Ts are found:
5686     if (!HasUniqueTargetType)
5687       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5688                                          ViableConversions);
5689 
5690     // If one unique T is found:
5691     // First, build a candidate set from the previously recorded
5692     // potentially viable conversions.
5693     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5694     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5695                                       CandidateSet);
5696 
5697     // Then, perform overload resolution over the candidate set.
5698     OverloadCandidateSet::iterator Best;
5699     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5700     case OR_Success: {
5701       // Apply this conversion.
5702       DeclAccessPair Found =
5703           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5704       if (recordConversion(*this, Loc, From, Converter, T,
5705                            HadMultipleCandidates, Found))
5706         return ExprError();
5707       break;
5708     }
5709     case OR_Ambiguous:
5710       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5711                                          ViableConversions);
5712     case OR_No_Viable_Function:
5713       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5714                                      HadMultipleCandidates,
5715                                      ExplicitConversions))
5716         return ExprError();
5717     // fall through 'OR_Deleted' case.
5718     case OR_Deleted:
5719       // We'll complain below about a non-integral condition type.
5720       break;
5721     }
5722   } else {
5723     switch (ViableConversions.size()) {
5724     case 0: {
5725       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5726                                      HadMultipleCandidates,
5727                                      ExplicitConversions))
5728         return ExprError();
5729 
5730       // We'll complain below about a non-integral condition type.
5731       break;
5732     }
5733     case 1: {
5734       // Apply this conversion.
5735       DeclAccessPair Found = ViableConversions[0];
5736       if (recordConversion(*this, Loc, From, Converter, T,
5737                            HadMultipleCandidates, Found))
5738         return ExprError();
5739       break;
5740     }
5741     default:
5742       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5743                                          ViableConversions);
5744     }
5745   }
5746 
5747   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5748 }
5749 
5750 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5751 /// an acceptable non-member overloaded operator for a call whose
5752 /// arguments have types T1 (and, if non-empty, T2). This routine
5753 /// implements the check in C++ [over.match.oper]p3b2 concerning
5754 /// enumeration types.
5755 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5756                                                    FunctionDecl *Fn,
5757                                                    ArrayRef<Expr *> Args) {
5758   QualType T1 = Args[0]->getType();
5759   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5760 
5761   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5762     return true;
5763 
5764   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5765     return true;
5766 
5767   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5768   if (Proto->getNumParams() < 1)
5769     return false;
5770 
5771   if (T1->isEnumeralType()) {
5772     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5773     if (Context.hasSameUnqualifiedType(T1, ArgType))
5774       return true;
5775   }
5776 
5777   if (Proto->getNumParams() < 2)
5778     return false;
5779 
5780   if (!T2.isNull() && T2->isEnumeralType()) {
5781     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5782     if (Context.hasSameUnqualifiedType(T2, ArgType))
5783       return true;
5784   }
5785 
5786   return false;
5787 }
5788 
5789 /// AddOverloadCandidate - Adds the given function to the set of
5790 /// candidate functions, using the given function call arguments.  If
5791 /// @p SuppressUserConversions, then don't allow user-defined
5792 /// conversions via constructors or conversion operators.
5793 ///
5794 /// \param PartialOverloading true if we are performing "partial" overloading
5795 /// based on an incomplete set of function arguments. This feature is used by
5796 /// code completion.
5797 void
5798 Sema::AddOverloadCandidate(FunctionDecl *Function,
5799                            DeclAccessPair FoundDecl,
5800                            ArrayRef<Expr *> Args,
5801                            OverloadCandidateSet &CandidateSet,
5802                            bool SuppressUserConversions,
5803                            bool PartialOverloading,
5804                            bool AllowExplicit) {
5805   const FunctionProtoType *Proto
5806     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5807   assert(Proto && "Functions without a prototype cannot be overloaded");
5808   assert(!Function->getDescribedFunctionTemplate() &&
5809          "Use AddTemplateOverloadCandidate for function templates");
5810 
5811   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5812     if (!isa<CXXConstructorDecl>(Method)) {
5813       // If we get here, it's because we're calling a member function
5814       // that is named without a member access expression (e.g.,
5815       // "this->f") that was either written explicitly or created
5816       // implicitly. This can happen with a qualified call to a member
5817       // function, e.g., X::f(). We use an empty type for the implied
5818       // object argument (C++ [over.call.func]p3), and the acting context
5819       // is irrelevant.
5820       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5821                          QualType(), Expr::Classification::makeSimpleLValue(),
5822                          Args, CandidateSet, SuppressUserConversions,
5823                          PartialOverloading);
5824       return;
5825     }
5826     // We treat a constructor like a non-member function, since its object
5827     // argument doesn't participate in overload resolution.
5828   }
5829 
5830   if (!CandidateSet.isNewCandidate(Function))
5831     return;
5832 
5833   // C++ [over.match.oper]p3:
5834   //   if no operand has a class type, only those non-member functions in the
5835   //   lookup set that have a first parameter of type T1 or "reference to
5836   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5837   //   is a right operand) a second parameter of type T2 or "reference to
5838   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5839   //   candidate functions.
5840   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5841       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5842     return;
5843 
5844   // C++11 [class.copy]p11: [DR1402]
5845   //   A defaulted move constructor that is defined as deleted is ignored by
5846   //   overload resolution.
5847   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5848   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5849       Constructor->isMoveConstructor())
5850     return;
5851 
5852   // Overload resolution is always an unevaluated context.
5853   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5854 
5855   // Add this candidate
5856   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5857   Candidate.FoundDecl = FoundDecl;
5858   Candidate.Function = Function;
5859   Candidate.Viable = true;
5860   Candidate.IsSurrogate = false;
5861   Candidate.IgnoreObjectArgument = false;
5862   Candidate.ExplicitCallArguments = Args.size();
5863 
5864   if (Constructor) {
5865     // C++ [class.copy]p3:
5866     //   A member function template is never instantiated to perform the copy
5867     //   of a class object to an object of its class type.
5868     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5869     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5870         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5871          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5872                        ClassType))) {
5873       Candidate.Viable = false;
5874       Candidate.FailureKind = ovl_fail_illegal_constructor;
5875       return;
5876     }
5877   }
5878 
5879   unsigned NumParams = Proto->getNumParams();
5880 
5881   // (C++ 13.3.2p2): A candidate function having fewer than m
5882   // parameters is viable only if it has an ellipsis in its parameter
5883   // list (8.3.5).
5884   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5885       !Proto->isVariadic()) {
5886     Candidate.Viable = false;
5887     Candidate.FailureKind = ovl_fail_too_many_arguments;
5888     return;
5889   }
5890 
5891   // (C++ 13.3.2p2): A candidate function having more than m parameters
5892   // is viable only if the (m+1)st parameter has a default argument
5893   // (8.3.6). For the purposes of overload resolution, the
5894   // parameter list is truncated on the right, so that there are
5895   // exactly m parameters.
5896   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5897   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5898     // Not enough arguments.
5899     Candidate.Viable = false;
5900     Candidate.FailureKind = ovl_fail_too_few_arguments;
5901     return;
5902   }
5903 
5904   // (CUDA B.1): Check for invalid calls between targets.
5905   if (getLangOpts().CUDA)
5906     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5907       // Skip the check for callers that are implicit members, because in this
5908       // case we may not yet know what the member's target is; the target is
5909       // inferred for the member automatically, based on the bases and fields of
5910       // the class.
5911       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5912         Candidate.Viable = false;
5913         Candidate.FailureKind = ovl_fail_bad_target;
5914         return;
5915       }
5916 
5917   // Determine the implicit conversion sequences for each of the
5918   // arguments.
5919   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5920     if (ArgIdx < NumParams) {
5921       // (C++ 13.3.2p3): for F to be a viable function, there shall
5922       // exist for each argument an implicit conversion sequence
5923       // (13.3.3.1) that converts that argument to the corresponding
5924       // parameter of F.
5925       QualType ParamType = Proto->getParamType(ArgIdx);
5926       Candidate.Conversions[ArgIdx]
5927         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5928                                 SuppressUserConversions,
5929                                 /*InOverloadResolution=*/true,
5930                                 /*AllowObjCWritebackConversion=*/
5931                                   getLangOpts().ObjCAutoRefCount,
5932                                 AllowExplicit);
5933       if (Candidate.Conversions[ArgIdx].isBad()) {
5934         Candidate.Viable = false;
5935         Candidate.FailureKind = ovl_fail_bad_conversion;
5936         return;
5937       }
5938     } else {
5939       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5940       // argument for which there is no corresponding parameter is
5941       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5942       Candidate.Conversions[ArgIdx].setEllipsis();
5943     }
5944   }
5945 
5946   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5947     Candidate.Viable = false;
5948     Candidate.FailureKind = ovl_fail_enable_if;
5949     Candidate.DeductionFailure.Data = FailedAttr;
5950     return;
5951   }
5952 }
5953 
5954 ObjCMethodDecl *
5955 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5956                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5957   if (Methods.size() <= 1)
5958     return nullptr;
5959 
5960   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5961     bool Match = true;
5962     ObjCMethodDecl *Method = Methods[b];
5963     unsigned NumNamedArgs = Sel.getNumArgs();
5964     // Method might have more arguments than selector indicates. This is due
5965     // to addition of c-style arguments in method.
5966     if (Method->param_size() > NumNamedArgs)
5967       NumNamedArgs = Method->param_size();
5968     if (Args.size() < NumNamedArgs)
5969       continue;
5970 
5971     for (unsigned i = 0; i < NumNamedArgs; i++) {
5972       // We can't do any type-checking on a type-dependent argument.
5973       if (Args[i]->isTypeDependent()) {
5974         Match = false;
5975         break;
5976       }
5977 
5978       ParmVarDecl *param = Method->parameters()[i];
5979       Expr *argExpr = Args[i];
5980       assert(argExpr && "SelectBestMethod(): missing expression");
5981 
5982       // Strip the unbridged-cast placeholder expression off unless it's
5983       // a consumed argument.
5984       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5985           !param->hasAttr<CFConsumedAttr>())
5986         argExpr = stripARCUnbridgedCast(argExpr);
5987 
5988       // If the parameter is __unknown_anytype, move on to the next method.
5989       if (param->getType() == Context.UnknownAnyTy) {
5990         Match = false;
5991         break;
5992       }
5993 
5994       ImplicitConversionSequence ConversionState
5995         = TryCopyInitialization(*this, argExpr, param->getType(),
5996                                 /*SuppressUserConversions*/false,
5997                                 /*InOverloadResolution=*/true,
5998                                 /*AllowObjCWritebackConversion=*/
5999                                 getLangOpts().ObjCAutoRefCount,
6000                                 /*AllowExplicit*/false);
6001       // This function looks for a reasonably-exact match, so we consider
6002       // incompatible pointer conversions to be a failure here.
6003       if (ConversionState.isBad() ||
6004           (ConversionState.isStandard() &&
6005            ConversionState.Standard.Second ==
6006                ICK_Incompatible_Pointer_Conversion)) {
6007         Match = false;
6008         break;
6009       }
6010     }
6011     // Promote additional arguments to variadic methods.
6012     if (Match && Method->isVariadic()) {
6013       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6014         if (Args[i]->isTypeDependent()) {
6015           Match = false;
6016           break;
6017         }
6018         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6019                                                           nullptr);
6020         if (Arg.isInvalid()) {
6021           Match = false;
6022           break;
6023         }
6024       }
6025     } else {
6026       // Check for extra arguments to non-variadic methods.
6027       if (Args.size() != NumNamedArgs)
6028         Match = false;
6029       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6030         // Special case when selectors have no argument. In this case, select
6031         // one with the most general result type of 'id'.
6032         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6033           QualType ReturnT = Methods[b]->getReturnType();
6034           if (ReturnT->isObjCIdType())
6035             return Methods[b];
6036         }
6037       }
6038     }
6039 
6040     if (Match)
6041       return Method;
6042   }
6043   return nullptr;
6044 }
6045 
6046 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6047 // enable_if is order-sensitive. As a result, we need to reverse things
6048 // sometimes. Size of 4 elements is arbitrary.
6049 static SmallVector<EnableIfAttr *, 4>
6050 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6051   SmallVector<EnableIfAttr *, 4> Result;
6052   if (!Function->hasAttrs())
6053     return Result;
6054 
6055   const auto &FuncAttrs = Function->getAttrs();
6056   for (Attr *Attr : FuncAttrs)
6057     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6058       Result.push_back(EnableIf);
6059 
6060   std::reverse(Result.begin(), Result.end());
6061   return Result;
6062 }
6063 
6064 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6065                                   bool MissingImplicitThis) {
6066   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6067   if (EnableIfAttrs.empty())
6068     return nullptr;
6069 
6070   SFINAETrap Trap(*this);
6071   SmallVector<Expr *, 16> ConvertedArgs;
6072   bool InitializationFailed = false;
6073 
6074   // Ignore any variadic arguments. Converting them is pointless, since the
6075   // user can't refer to them in the enable_if condition.
6076   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6077 
6078   // Convert the arguments.
6079   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6080     ExprResult R;
6081     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
6082         !cast<CXXMethodDecl>(Function)->isStatic() &&
6083         !isa<CXXConstructorDecl>(Function)) {
6084       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6085       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6086                                               Method, Method);
6087     } else {
6088       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6089                                         Context, Function->getParamDecl(I)),
6090                                     SourceLocation(), Args[I]);
6091     }
6092 
6093     if (R.isInvalid()) {
6094       InitializationFailed = true;
6095       break;
6096     }
6097 
6098     ConvertedArgs.push_back(R.get());
6099   }
6100 
6101   if (InitializationFailed || Trap.hasErrorOccurred())
6102     return EnableIfAttrs[0];
6103 
6104   // Push default arguments if needed.
6105   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6106     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6107       ParmVarDecl *P = Function->getParamDecl(i);
6108       ExprResult R = PerformCopyInitialization(
6109           InitializedEntity::InitializeParameter(Context,
6110                                                  Function->getParamDecl(i)),
6111           SourceLocation(),
6112           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6113                                            : P->getDefaultArg());
6114       if (R.isInvalid()) {
6115         InitializationFailed = true;
6116         break;
6117       }
6118       ConvertedArgs.push_back(R.get());
6119     }
6120 
6121     if (InitializationFailed || Trap.hasErrorOccurred())
6122       return EnableIfAttrs[0];
6123   }
6124 
6125   for (auto *EIA : EnableIfAttrs) {
6126     APValue Result;
6127     // FIXME: This doesn't consider value-dependent cases, because doing so is
6128     // very difficult. Ideally, we should handle them more gracefully.
6129     if (!EIA->getCond()->EvaluateWithSubstitution(
6130             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6131       return EIA;
6132 
6133     if (!Result.isInt() || !Result.getInt().getBoolValue())
6134       return EIA;
6135   }
6136   return nullptr;
6137 }
6138 
6139 /// \brief Add all of the function declarations in the given function set to
6140 /// the overload candidate set.
6141 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6142                                  ArrayRef<Expr *> Args,
6143                                  OverloadCandidateSet& CandidateSet,
6144                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6145                                  bool SuppressUserConversions,
6146                                  bool PartialOverloading) {
6147   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6148     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6149     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6150       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6151         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6152                            cast<CXXMethodDecl>(FD)->getParent(),
6153                            Args[0]->getType(), Args[0]->Classify(Context),
6154                            Args.slice(1), CandidateSet,
6155                            SuppressUserConversions, PartialOverloading);
6156       else
6157         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6158                              SuppressUserConversions, PartialOverloading);
6159     } else {
6160       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6161       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6162           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6163         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6164                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6165                                    ExplicitTemplateArgs,
6166                                    Args[0]->getType(),
6167                                    Args[0]->Classify(Context), Args.slice(1),
6168                                    CandidateSet, SuppressUserConversions,
6169                                    PartialOverloading);
6170       else
6171         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6172                                      ExplicitTemplateArgs, Args,
6173                                      CandidateSet, SuppressUserConversions,
6174                                      PartialOverloading);
6175     }
6176   }
6177 }
6178 
6179 /// AddMethodCandidate - Adds a named decl (which is some kind of
6180 /// method) as a method candidate to the given overload set.
6181 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6182                               QualType ObjectType,
6183                               Expr::Classification ObjectClassification,
6184                               ArrayRef<Expr *> Args,
6185                               OverloadCandidateSet& CandidateSet,
6186                               bool SuppressUserConversions) {
6187   NamedDecl *Decl = FoundDecl.getDecl();
6188   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6189 
6190   if (isa<UsingShadowDecl>(Decl))
6191     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6192 
6193   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6194     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6195            "Expected a member function template");
6196     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6197                                /*ExplicitArgs*/ nullptr,
6198                                ObjectType, ObjectClassification,
6199                                Args, CandidateSet,
6200                                SuppressUserConversions);
6201   } else {
6202     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6203                        ObjectType, ObjectClassification,
6204                        Args,
6205                        CandidateSet, SuppressUserConversions);
6206   }
6207 }
6208 
6209 /// AddMethodCandidate - Adds the given C++ member function to the set
6210 /// of candidate functions, using the given function call arguments
6211 /// and the object argument (@c Object). For example, in a call
6212 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6213 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6214 /// allow user-defined conversions via constructors or conversion
6215 /// operators.
6216 void
6217 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6218                          CXXRecordDecl *ActingContext, QualType ObjectType,
6219                          Expr::Classification ObjectClassification,
6220                          ArrayRef<Expr *> Args,
6221                          OverloadCandidateSet &CandidateSet,
6222                          bool SuppressUserConversions,
6223                          bool PartialOverloading) {
6224   const FunctionProtoType *Proto
6225     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6226   assert(Proto && "Methods without a prototype cannot be overloaded");
6227   assert(!isa<CXXConstructorDecl>(Method) &&
6228          "Use AddOverloadCandidate for constructors");
6229 
6230   if (!CandidateSet.isNewCandidate(Method))
6231     return;
6232 
6233   // C++11 [class.copy]p23: [DR1402]
6234   //   A defaulted move assignment operator that is defined as deleted is
6235   //   ignored by overload resolution.
6236   if (Method->isDefaulted() && Method->isDeleted() &&
6237       Method->isMoveAssignmentOperator())
6238     return;
6239 
6240   // Overload resolution is always an unevaluated context.
6241   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6242 
6243   // Add this candidate
6244   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6245   Candidate.FoundDecl = FoundDecl;
6246   Candidate.Function = Method;
6247   Candidate.IsSurrogate = false;
6248   Candidate.IgnoreObjectArgument = false;
6249   Candidate.ExplicitCallArguments = Args.size();
6250 
6251   unsigned NumParams = Proto->getNumParams();
6252 
6253   // (C++ 13.3.2p2): A candidate function having fewer than m
6254   // parameters is viable only if it has an ellipsis in its parameter
6255   // list (8.3.5).
6256   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6257       !Proto->isVariadic()) {
6258     Candidate.Viable = false;
6259     Candidate.FailureKind = ovl_fail_too_many_arguments;
6260     return;
6261   }
6262 
6263   // (C++ 13.3.2p2): A candidate function having more than m parameters
6264   // is viable only if the (m+1)st parameter has a default argument
6265   // (8.3.6). For the purposes of overload resolution, the
6266   // parameter list is truncated on the right, so that there are
6267   // exactly m parameters.
6268   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6269   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6270     // Not enough arguments.
6271     Candidate.Viable = false;
6272     Candidate.FailureKind = ovl_fail_too_few_arguments;
6273     return;
6274   }
6275 
6276   Candidate.Viable = true;
6277 
6278   if (Method->isStatic() || ObjectType.isNull())
6279     // The implicit object argument is ignored.
6280     Candidate.IgnoreObjectArgument = true;
6281   else {
6282     // Determine the implicit conversion sequence for the object
6283     // parameter.
6284     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6285         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6286         Method, ActingContext);
6287     if (Candidate.Conversions[0].isBad()) {
6288       Candidate.Viable = false;
6289       Candidate.FailureKind = ovl_fail_bad_conversion;
6290       return;
6291     }
6292   }
6293 
6294   // (CUDA B.1): Check for invalid calls between targets.
6295   if (getLangOpts().CUDA)
6296     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6297       if (!IsAllowedCUDACall(Caller, Method)) {
6298         Candidate.Viable = false;
6299         Candidate.FailureKind = ovl_fail_bad_target;
6300         return;
6301       }
6302 
6303   // Determine the implicit conversion sequences for each of the
6304   // arguments.
6305   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6306     if (ArgIdx < NumParams) {
6307       // (C++ 13.3.2p3): for F to be a viable function, there shall
6308       // exist for each argument an implicit conversion sequence
6309       // (13.3.3.1) that converts that argument to the corresponding
6310       // parameter of F.
6311       QualType ParamType = Proto->getParamType(ArgIdx);
6312       Candidate.Conversions[ArgIdx + 1]
6313         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6314                                 SuppressUserConversions,
6315                                 /*InOverloadResolution=*/true,
6316                                 /*AllowObjCWritebackConversion=*/
6317                                   getLangOpts().ObjCAutoRefCount);
6318       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6319         Candidate.Viable = false;
6320         Candidate.FailureKind = ovl_fail_bad_conversion;
6321         return;
6322       }
6323     } else {
6324       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6325       // argument for which there is no corresponding parameter is
6326       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6327       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6328     }
6329   }
6330 
6331   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6332     Candidate.Viable = false;
6333     Candidate.FailureKind = ovl_fail_enable_if;
6334     Candidate.DeductionFailure.Data = FailedAttr;
6335     return;
6336   }
6337 }
6338 
6339 /// \brief Add a C++ member function template as a candidate to the candidate
6340 /// set, using template argument deduction to produce an appropriate member
6341 /// function template specialization.
6342 void
6343 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6344                                  DeclAccessPair FoundDecl,
6345                                  CXXRecordDecl *ActingContext,
6346                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6347                                  QualType ObjectType,
6348                                  Expr::Classification ObjectClassification,
6349                                  ArrayRef<Expr *> Args,
6350                                  OverloadCandidateSet& CandidateSet,
6351                                  bool SuppressUserConversions,
6352                                  bool PartialOverloading) {
6353   if (!CandidateSet.isNewCandidate(MethodTmpl))
6354     return;
6355 
6356   // C++ [over.match.funcs]p7:
6357   //   In each case where a candidate is a function template, candidate
6358   //   function template specializations are generated using template argument
6359   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6360   //   candidate functions in the usual way.113) A given name can refer to one
6361   //   or more function templates and also to a set of overloaded non-template
6362   //   functions. In such a case, the candidate functions generated from each
6363   //   function template are combined with the set of non-template candidate
6364   //   functions.
6365   TemplateDeductionInfo Info(CandidateSet.getLocation());
6366   FunctionDecl *Specialization = nullptr;
6367   if (TemplateDeductionResult Result
6368       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6369                                 Specialization, Info, PartialOverloading)) {
6370     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6371     Candidate.FoundDecl = FoundDecl;
6372     Candidate.Function = MethodTmpl->getTemplatedDecl();
6373     Candidate.Viable = false;
6374     Candidate.FailureKind = ovl_fail_bad_deduction;
6375     Candidate.IsSurrogate = false;
6376     Candidate.IgnoreObjectArgument = false;
6377     Candidate.ExplicitCallArguments = Args.size();
6378     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6379                                                           Info);
6380     return;
6381   }
6382 
6383   // Add the function template specialization produced by template argument
6384   // deduction as a candidate.
6385   assert(Specialization && "Missing member function template specialization?");
6386   assert(isa<CXXMethodDecl>(Specialization) &&
6387          "Specialization is not a member function?");
6388   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6389                      ActingContext, ObjectType, ObjectClassification, Args,
6390                      CandidateSet, SuppressUserConversions, PartialOverloading);
6391 }
6392 
6393 /// \brief Add a C++ function template specialization as a candidate
6394 /// in the candidate set, using template argument deduction to produce
6395 /// an appropriate function template specialization.
6396 void
6397 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6398                                    DeclAccessPair FoundDecl,
6399                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6400                                    ArrayRef<Expr *> Args,
6401                                    OverloadCandidateSet& CandidateSet,
6402                                    bool SuppressUserConversions,
6403                                    bool PartialOverloading) {
6404   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6405     return;
6406 
6407   // C++ [over.match.funcs]p7:
6408   //   In each case where a candidate is a function template, candidate
6409   //   function template specializations are generated using template argument
6410   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6411   //   candidate functions in the usual way.113) A given name can refer to one
6412   //   or more function templates and also to a set of overloaded non-template
6413   //   functions. In such a case, the candidate functions generated from each
6414   //   function template are combined with the set of non-template candidate
6415   //   functions.
6416   TemplateDeductionInfo Info(CandidateSet.getLocation());
6417   FunctionDecl *Specialization = nullptr;
6418   if (TemplateDeductionResult Result
6419         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6420                                   Specialization, Info, PartialOverloading)) {
6421     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6422     Candidate.FoundDecl = FoundDecl;
6423     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6424     Candidate.Viable = false;
6425     Candidate.FailureKind = ovl_fail_bad_deduction;
6426     Candidate.IsSurrogate = false;
6427     Candidate.IgnoreObjectArgument = false;
6428     Candidate.ExplicitCallArguments = Args.size();
6429     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6430                                                           Info);
6431     return;
6432   }
6433 
6434   // Add the function template specialization produced by template argument
6435   // deduction as a candidate.
6436   assert(Specialization && "Missing function template specialization?");
6437   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6438                        SuppressUserConversions, PartialOverloading);
6439 }
6440 
6441 /// Determine whether this is an allowable conversion from the result
6442 /// of an explicit conversion operator to the expected type, per C++
6443 /// [over.match.conv]p1 and [over.match.ref]p1.
6444 ///
6445 /// \param ConvType The return type of the conversion function.
6446 ///
6447 /// \param ToType The type we are converting to.
6448 ///
6449 /// \param AllowObjCPointerConversion Allow a conversion from one
6450 /// Objective-C pointer to another.
6451 ///
6452 /// \returns true if the conversion is allowable, false otherwise.
6453 static bool isAllowableExplicitConversion(Sema &S,
6454                                           QualType ConvType, QualType ToType,
6455                                           bool AllowObjCPointerConversion) {
6456   QualType ToNonRefType = ToType.getNonReferenceType();
6457 
6458   // Easy case: the types are the same.
6459   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6460     return true;
6461 
6462   // Allow qualification conversions.
6463   bool ObjCLifetimeConversion;
6464   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6465                                   ObjCLifetimeConversion))
6466     return true;
6467 
6468   // If we're not allowed to consider Objective-C pointer conversions,
6469   // we're done.
6470   if (!AllowObjCPointerConversion)
6471     return false;
6472 
6473   // Is this an Objective-C pointer conversion?
6474   bool IncompatibleObjC = false;
6475   QualType ConvertedType;
6476   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6477                                    IncompatibleObjC);
6478 }
6479 
6480 /// AddConversionCandidate - Add a C++ conversion function as a
6481 /// candidate in the candidate set (C++ [over.match.conv],
6482 /// C++ [over.match.copy]). From is the expression we're converting from,
6483 /// and ToType is the type that we're eventually trying to convert to
6484 /// (which may or may not be the same type as the type that the
6485 /// conversion function produces).
6486 void
6487 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6488                              DeclAccessPair FoundDecl,
6489                              CXXRecordDecl *ActingContext,
6490                              Expr *From, QualType ToType,
6491                              OverloadCandidateSet& CandidateSet,
6492                              bool AllowObjCConversionOnExplicit) {
6493   assert(!Conversion->getDescribedFunctionTemplate() &&
6494          "Conversion function templates use AddTemplateConversionCandidate");
6495   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6496   if (!CandidateSet.isNewCandidate(Conversion))
6497     return;
6498 
6499   // If the conversion function has an undeduced return type, trigger its
6500   // deduction now.
6501   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6502     if (DeduceReturnType(Conversion, From->getExprLoc()))
6503       return;
6504     ConvType = Conversion->getConversionType().getNonReferenceType();
6505   }
6506 
6507   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6508   // operator is only a candidate if its return type is the target type or
6509   // can be converted to the target type with a qualification conversion.
6510   if (Conversion->isExplicit() &&
6511       !isAllowableExplicitConversion(*this, ConvType, ToType,
6512                                      AllowObjCConversionOnExplicit))
6513     return;
6514 
6515   // Overload resolution is always an unevaluated context.
6516   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6517 
6518   // Add this candidate
6519   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6520   Candidate.FoundDecl = FoundDecl;
6521   Candidate.Function = Conversion;
6522   Candidate.IsSurrogate = false;
6523   Candidate.IgnoreObjectArgument = false;
6524   Candidate.FinalConversion.setAsIdentityConversion();
6525   Candidate.FinalConversion.setFromType(ConvType);
6526   Candidate.FinalConversion.setAllToTypes(ToType);
6527   Candidate.Viable = true;
6528   Candidate.ExplicitCallArguments = 1;
6529 
6530   // C++ [over.match.funcs]p4:
6531   //   For conversion functions, the function is considered to be a member of
6532   //   the class of the implicit implied object argument for the purpose of
6533   //   defining the type of the implicit object parameter.
6534   //
6535   // Determine the implicit conversion sequence for the implicit
6536   // object parameter.
6537   QualType ImplicitParamType = From->getType();
6538   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6539     ImplicitParamType = FromPtrType->getPointeeType();
6540   CXXRecordDecl *ConversionContext
6541     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6542 
6543   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6544       *this, CandidateSet.getLocation(), From->getType(),
6545       From->Classify(Context), Conversion, ConversionContext);
6546 
6547   if (Candidate.Conversions[0].isBad()) {
6548     Candidate.Viable = false;
6549     Candidate.FailureKind = ovl_fail_bad_conversion;
6550     return;
6551   }
6552 
6553   // We won't go through a user-defined type conversion function to convert a
6554   // derived to base as such conversions are given Conversion Rank. They only
6555   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6556   QualType FromCanon
6557     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6558   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6559   if (FromCanon == ToCanon ||
6560       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6561     Candidate.Viable = false;
6562     Candidate.FailureKind = ovl_fail_trivial_conversion;
6563     return;
6564   }
6565 
6566   // To determine what the conversion from the result of calling the
6567   // conversion function to the type we're eventually trying to
6568   // convert to (ToType), we need to synthesize a call to the
6569   // conversion function and attempt copy initialization from it. This
6570   // makes sure that we get the right semantics with respect to
6571   // lvalues/rvalues and the type. Fortunately, we can allocate this
6572   // call on the stack and we don't need its arguments to be
6573   // well-formed.
6574   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6575                             VK_LValue, From->getLocStart());
6576   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6577                                 Context.getPointerType(Conversion->getType()),
6578                                 CK_FunctionToPointerDecay,
6579                                 &ConversionRef, VK_RValue);
6580 
6581   QualType ConversionType = Conversion->getConversionType();
6582   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6583     Candidate.Viable = false;
6584     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6585     return;
6586   }
6587 
6588   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6589 
6590   // Note that it is safe to allocate CallExpr on the stack here because
6591   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6592   // allocator).
6593   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6594   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6595                 From->getLocStart());
6596   ImplicitConversionSequence ICS =
6597     TryCopyInitialization(*this, &Call, ToType,
6598                           /*SuppressUserConversions=*/true,
6599                           /*InOverloadResolution=*/false,
6600                           /*AllowObjCWritebackConversion=*/false);
6601 
6602   switch (ICS.getKind()) {
6603   case ImplicitConversionSequence::StandardConversion:
6604     Candidate.FinalConversion = ICS.Standard;
6605 
6606     // C++ [over.ics.user]p3:
6607     //   If the user-defined conversion is specified by a specialization of a
6608     //   conversion function template, the second standard conversion sequence
6609     //   shall have exact match rank.
6610     if (Conversion->getPrimaryTemplate() &&
6611         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6612       Candidate.Viable = false;
6613       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6614       return;
6615     }
6616 
6617     // C++0x [dcl.init.ref]p5:
6618     //    In the second case, if the reference is an rvalue reference and
6619     //    the second standard conversion sequence of the user-defined
6620     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6621     //    program is ill-formed.
6622     if (ToType->isRValueReferenceType() &&
6623         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6624       Candidate.Viable = false;
6625       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6626       return;
6627     }
6628     break;
6629 
6630   case ImplicitConversionSequence::BadConversion:
6631     Candidate.Viable = false;
6632     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6633     return;
6634 
6635   default:
6636     llvm_unreachable(
6637            "Can only end up with a standard conversion sequence or failure");
6638   }
6639 
6640   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6641     Candidate.Viable = false;
6642     Candidate.FailureKind = ovl_fail_enable_if;
6643     Candidate.DeductionFailure.Data = FailedAttr;
6644     return;
6645   }
6646 }
6647 
6648 /// \brief Adds a conversion function template specialization
6649 /// candidate to the overload set, using template argument deduction
6650 /// to deduce the template arguments of the conversion function
6651 /// template from the type that we are converting to (C++
6652 /// [temp.deduct.conv]).
6653 void
6654 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6655                                      DeclAccessPair FoundDecl,
6656                                      CXXRecordDecl *ActingDC,
6657                                      Expr *From, QualType ToType,
6658                                      OverloadCandidateSet &CandidateSet,
6659                                      bool AllowObjCConversionOnExplicit) {
6660   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6661          "Only conversion function templates permitted here");
6662 
6663   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6664     return;
6665 
6666   TemplateDeductionInfo Info(CandidateSet.getLocation());
6667   CXXConversionDecl *Specialization = nullptr;
6668   if (TemplateDeductionResult Result
6669         = DeduceTemplateArguments(FunctionTemplate, ToType,
6670                                   Specialization, Info)) {
6671     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6672     Candidate.FoundDecl = FoundDecl;
6673     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6674     Candidate.Viable = false;
6675     Candidate.FailureKind = ovl_fail_bad_deduction;
6676     Candidate.IsSurrogate = false;
6677     Candidate.IgnoreObjectArgument = false;
6678     Candidate.ExplicitCallArguments = 1;
6679     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6680                                                           Info);
6681     return;
6682   }
6683 
6684   // Add the conversion function template specialization produced by
6685   // template argument deduction as a candidate.
6686   assert(Specialization && "Missing function template specialization?");
6687   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6688                          CandidateSet, AllowObjCConversionOnExplicit);
6689 }
6690 
6691 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6692 /// converts the given @c Object to a function pointer via the
6693 /// conversion function @c Conversion, and then attempts to call it
6694 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6695 /// the type of function that we'll eventually be calling.
6696 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6697                                  DeclAccessPair FoundDecl,
6698                                  CXXRecordDecl *ActingContext,
6699                                  const FunctionProtoType *Proto,
6700                                  Expr *Object,
6701                                  ArrayRef<Expr *> Args,
6702                                  OverloadCandidateSet& CandidateSet) {
6703   if (!CandidateSet.isNewCandidate(Conversion))
6704     return;
6705 
6706   // Overload resolution is always an unevaluated context.
6707   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6708 
6709   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6710   Candidate.FoundDecl = FoundDecl;
6711   Candidate.Function = nullptr;
6712   Candidate.Surrogate = Conversion;
6713   Candidate.Viable = true;
6714   Candidate.IsSurrogate = true;
6715   Candidate.IgnoreObjectArgument = false;
6716   Candidate.ExplicitCallArguments = Args.size();
6717 
6718   // Determine the implicit conversion sequence for the implicit
6719   // object parameter.
6720   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6721       *this, CandidateSet.getLocation(), Object->getType(),
6722       Object->Classify(Context), Conversion, ActingContext);
6723   if (ObjectInit.isBad()) {
6724     Candidate.Viable = false;
6725     Candidate.FailureKind = ovl_fail_bad_conversion;
6726     Candidate.Conversions[0] = ObjectInit;
6727     return;
6728   }
6729 
6730   // The first conversion is actually a user-defined conversion whose
6731   // first conversion is ObjectInit's standard conversion (which is
6732   // effectively a reference binding). Record it as such.
6733   Candidate.Conversions[0].setUserDefined();
6734   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6735   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6736   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6737   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6738   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6739   Candidate.Conversions[0].UserDefined.After
6740     = Candidate.Conversions[0].UserDefined.Before;
6741   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6742 
6743   // Find the
6744   unsigned NumParams = Proto->getNumParams();
6745 
6746   // (C++ 13.3.2p2): A candidate function having fewer than m
6747   // parameters is viable only if it has an ellipsis in its parameter
6748   // list (8.3.5).
6749   if (Args.size() > NumParams && !Proto->isVariadic()) {
6750     Candidate.Viable = false;
6751     Candidate.FailureKind = ovl_fail_too_many_arguments;
6752     return;
6753   }
6754 
6755   // Function types don't have any default arguments, so just check if
6756   // we have enough arguments.
6757   if (Args.size() < NumParams) {
6758     // Not enough arguments.
6759     Candidate.Viable = false;
6760     Candidate.FailureKind = ovl_fail_too_few_arguments;
6761     return;
6762   }
6763 
6764   // Determine the implicit conversion sequences for each of the
6765   // arguments.
6766   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6767     if (ArgIdx < NumParams) {
6768       // (C++ 13.3.2p3): for F to be a viable function, there shall
6769       // exist for each argument an implicit conversion sequence
6770       // (13.3.3.1) that converts that argument to the corresponding
6771       // parameter of F.
6772       QualType ParamType = Proto->getParamType(ArgIdx);
6773       Candidate.Conversions[ArgIdx + 1]
6774         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6775                                 /*SuppressUserConversions=*/false,
6776                                 /*InOverloadResolution=*/false,
6777                                 /*AllowObjCWritebackConversion=*/
6778                                   getLangOpts().ObjCAutoRefCount);
6779       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6780         Candidate.Viable = false;
6781         Candidate.FailureKind = ovl_fail_bad_conversion;
6782         return;
6783       }
6784     } else {
6785       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6786       // argument for which there is no corresponding parameter is
6787       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6788       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6789     }
6790   }
6791 
6792   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6793     Candidate.Viable = false;
6794     Candidate.FailureKind = ovl_fail_enable_if;
6795     Candidate.DeductionFailure.Data = FailedAttr;
6796     return;
6797   }
6798 }
6799 
6800 /// \brief Add overload candidates for overloaded operators that are
6801 /// member functions.
6802 ///
6803 /// Add the overloaded operator candidates that are member functions
6804 /// for the operator Op that was used in an operator expression such
6805 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6806 /// CandidateSet will store the added overload candidates. (C++
6807 /// [over.match.oper]).
6808 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6809                                        SourceLocation OpLoc,
6810                                        ArrayRef<Expr *> Args,
6811                                        OverloadCandidateSet& CandidateSet,
6812                                        SourceRange OpRange) {
6813   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6814 
6815   // C++ [over.match.oper]p3:
6816   //   For a unary operator @ with an operand of a type whose
6817   //   cv-unqualified version is T1, and for a binary operator @ with
6818   //   a left operand of a type whose cv-unqualified version is T1 and
6819   //   a right operand of a type whose cv-unqualified version is T2,
6820   //   three sets of candidate functions, designated member
6821   //   candidates, non-member candidates and built-in candidates, are
6822   //   constructed as follows:
6823   QualType T1 = Args[0]->getType();
6824 
6825   //     -- If T1 is a complete class type or a class currently being
6826   //        defined, the set of member candidates is the result of the
6827   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6828   //        the set of member candidates is empty.
6829   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6830     // Complete the type if it can be completed.
6831     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6832       return;
6833     // If the type is neither complete nor being defined, bail out now.
6834     if (!T1Rec->getDecl()->getDefinition())
6835       return;
6836 
6837     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6838     LookupQualifiedName(Operators, T1Rec->getDecl());
6839     Operators.suppressDiagnostics();
6840 
6841     for (LookupResult::iterator Oper = Operators.begin(),
6842                              OperEnd = Operators.end();
6843          Oper != OperEnd;
6844          ++Oper)
6845       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6846                          Args[0]->Classify(Context),
6847                          Args.slice(1),
6848                          CandidateSet,
6849                          /* SuppressUserConversions = */ false);
6850   }
6851 }
6852 
6853 /// AddBuiltinCandidate - Add a candidate for a built-in
6854 /// operator. ResultTy and ParamTys are the result and parameter types
6855 /// of the built-in candidate, respectively. Args and NumArgs are the
6856 /// arguments being passed to the candidate. IsAssignmentOperator
6857 /// should be true when this built-in candidate is an assignment
6858 /// operator. NumContextualBoolArguments is the number of arguments
6859 /// (at the beginning of the argument list) that will be contextually
6860 /// converted to bool.
6861 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6862                                ArrayRef<Expr *> Args,
6863                                OverloadCandidateSet& CandidateSet,
6864                                bool IsAssignmentOperator,
6865                                unsigned NumContextualBoolArguments) {
6866   // Overload resolution is always an unevaluated context.
6867   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6868 
6869   // Add this candidate
6870   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6871   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6872   Candidate.Function = nullptr;
6873   Candidate.IsSurrogate = false;
6874   Candidate.IgnoreObjectArgument = false;
6875   Candidate.BuiltinTypes.ResultTy = ResultTy;
6876   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6877     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6878 
6879   // Determine the implicit conversion sequences for each of the
6880   // arguments.
6881   Candidate.Viable = true;
6882   Candidate.ExplicitCallArguments = Args.size();
6883   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6884     // C++ [over.match.oper]p4:
6885     //   For the built-in assignment operators, conversions of the
6886     //   left operand are restricted as follows:
6887     //     -- no temporaries are introduced to hold the left operand, and
6888     //     -- no user-defined conversions are applied to the left
6889     //        operand to achieve a type match with the left-most
6890     //        parameter of a built-in candidate.
6891     //
6892     // We block these conversions by turning off user-defined
6893     // conversions, since that is the only way that initialization of
6894     // a reference to a non-class type can occur from something that
6895     // is not of the same type.
6896     if (ArgIdx < NumContextualBoolArguments) {
6897       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6898              "Contextual conversion to bool requires bool type");
6899       Candidate.Conversions[ArgIdx]
6900         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6901     } else {
6902       Candidate.Conversions[ArgIdx]
6903         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6904                                 ArgIdx == 0 && IsAssignmentOperator,
6905                                 /*InOverloadResolution=*/false,
6906                                 /*AllowObjCWritebackConversion=*/
6907                                   getLangOpts().ObjCAutoRefCount);
6908     }
6909     if (Candidate.Conversions[ArgIdx].isBad()) {
6910       Candidate.Viable = false;
6911       Candidate.FailureKind = ovl_fail_bad_conversion;
6912       break;
6913     }
6914   }
6915 }
6916 
6917 namespace {
6918 
6919 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6920 /// candidate operator functions for built-in operators (C++
6921 /// [over.built]). The types are separated into pointer types and
6922 /// enumeration types.
6923 class BuiltinCandidateTypeSet  {
6924   /// TypeSet - A set of types.
6925   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6926                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6927 
6928   /// PointerTypes - The set of pointer types that will be used in the
6929   /// built-in candidates.
6930   TypeSet PointerTypes;
6931 
6932   /// MemberPointerTypes - The set of member pointer types that will be
6933   /// used in the built-in candidates.
6934   TypeSet MemberPointerTypes;
6935 
6936   /// EnumerationTypes - The set of enumeration types that will be
6937   /// used in the built-in candidates.
6938   TypeSet EnumerationTypes;
6939 
6940   /// \brief The set of vector types that will be used in the built-in
6941   /// candidates.
6942   TypeSet VectorTypes;
6943 
6944   /// \brief A flag indicating non-record types are viable candidates
6945   bool HasNonRecordTypes;
6946 
6947   /// \brief A flag indicating whether either arithmetic or enumeration types
6948   /// were present in the candidate set.
6949   bool HasArithmeticOrEnumeralTypes;
6950 
6951   /// \brief A flag indicating whether the nullptr type was present in the
6952   /// candidate set.
6953   bool HasNullPtrType;
6954 
6955   /// Sema - The semantic analysis instance where we are building the
6956   /// candidate type set.
6957   Sema &SemaRef;
6958 
6959   /// Context - The AST context in which we will build the type sets.
6960   ASTContext &Context;
6961 
6962   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6963                                                const Qualifiers &VisibleQuals);
6964   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6965 
6966 public:
6967   /// iterator - Iterates through the types that are part of the set.
6968   typedef TypeSet::iterator iterator;
6969 
6970   BuiltinCandidateTypeSet(Sema &SemaRef)
6971     : HasNonRecordTypes(false),
6972       HasArithmeticOrEnumeralTypes(false),
6973       HasNullPtrType(false),
6974       SemaRef(SemaRef),
6975       Context(SemaRef.Context) { }
6976 
6977   void AddTypesConvertedFrom(QualType Ty,
6978                              SourceLocation Loc,
6979                              bool AllowUserConversions,
6980                              bool AllowExplicitConversions,
6981                              const Qualifiers &VisibleTypeConversionsQuals);
6982 
6983   /// pointer_begin - First pointer type found;
6984   iterator pointer_begin() { return PointerTypes.begin(); }
6985 
6986   /// pointer_end - Past the last pointer type found;
6987   iterator pointer_end() { return PointerTypes.end(); }
6988 
6989   /// member_pointer_begin - First member pointer type found;
6990   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6991 
6992   /// member_pointer_end - Past the last member pointer type found;
6993   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6994 
6995   /// enumeration_begin - First enumeration type found;
6996   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6997 
6998   /// enumeration_end - Past the last enumeration type found;
6999   iterator enumeration_end() { return EnumerationTypes.end(); }
7000 
7001   iterator vector_begin() { return VectorTypes.begin(); }
7002   iterator vector_end() { return VectorTypes.end(); }
7003 
7004   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7005   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7006   bool hasNullPtrType() const { return HasNullPtrType; }
7007 };
7008 
7009 } // end anonymous namespace
7010 
7011 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7012 /// the set of pointer types along with any more-qualified variants of
7013 /// that type. For example, if @p Ty is "int const *", this routine
7014 /// will add "int const *", "int const volatile *", "int const
7015 /// restrict *", and "int const volatile restrict *" to the set of
7016 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7017 /// false otherwise.
7018 ///
7019 /// FIXME: what to do about extended qualifiers?
7020 bool
7021 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7022                                              const Qualifiers &VisibleQuals) {
7023 
7024   // Insert this type.
7025   if (!PointerTypes.insert(Ty))
7026     return false;
7027 
7028   QualType PointeeTy;
7029   const PointerType *PointerTy = Ty->getAs<PointerType>();
7030   bool buildObjCPtr = false;
7031   if (!PointerTy) {
7032     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7033     PointeeTy = PTy->getPointeeType();
7034     buildObjCPtr = true;
7035   } else {
7036     PointeeTy = PointerTy->getPointeeType();
7037   }
7038 
7039   // Don't add qualified variants of arrays. For one, they're not allowed
7040   // (the qualifier would sink to the element type), and for another, the
7041   // only overload situation where it matters is subscript or pointer +- int,
7042   // and those shouldn't have qualifier variants anyway.
7043   if (PointeeTy->isArrayType())
7044     return true;
7045 
7046   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7047   bool hasVolatile = VisibleQuals.hasVolatile();
7048   bool hasRestrict = VisibleQuals.hasRestrict();
7049 
7050   // Iterate through all strict supersets of BaseCVR.
7051   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7052     if ((CVR | BaseCVR) != CVR) continue;
7053     // Skip over volatile if no volatile found anywhere in the types.
7054     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7055 
7056     // Skip over restrict if no restrict found anywhere in the types, or if
7057     // the type cannot be restrict-qualified.
7058     if ((CVR & Qualifiers::Restrict) &&
7059         (!hasRestrict ||
7060          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7061       continue;
7062 
7063     // Build qualified pointee type.
7064     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7065 
7066     // Build qualified pointer type.
7067     QualType QPointerTy;
7068     if (!buildObjCPtr)
7069       QPointerTy = Context.getPointerType(QPointeeTy);
7070     else
7071       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7072 
7073     // Insert qualified pointer type.
7074     PointerTypes.insert(QPointerTy);
7075   }
7076 
7077   return true;
7078 }
7079 
7080 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7081 /// to the set of pointer types along with any more-qualified variants of
7082 /// that type. For example, if @p Ty is "int const *", this routine
7083 /// will add "int const *", "int const volatile *", "int const
7084 /// restrict *", and "int const volatile restrict *" to the set of
7085 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7086 /// false otherwise.
7087 ///
7088 /// FIXME: what to do about extended qualifiers?
7089 bool
7090 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7091     QualType Ty) {
7092   // Insert this type.
7093   if (!MemberPointerTypes.insert(Ty))
7094     return false;
7095 
7096   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7097   assert(PointerTy && "type was not a member pointer type!");
7098 
7099   QualType PointeeTy = PointerTy->getPointeeType();
7100   // Don't add qualified variants of arrays. For one, they're not allowed
7101   // (the qualifier would sink to the element type), and for another, the
7102   // only overload situation where it matters is subscript or pointer +- int,
7103   // and those shouldn't have qualifier variants anyway.
7104   if (PointeeTy->isArrayType())
7105     return true;
7106   const Type *ClassTy = PointerTy->getClass();
7107 
7108   // Iterate through all strict supersets of the pointee type's CVR
7109   // qualifiers.
7110   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7111   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7112     if ((CVR | BaseCVR) != CVR) continue;
7113 
7114     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7115     MemberPointerTypes.insert(
7116       Context.getMemberPointerType(QPointeeTy, ClassTy));
7117   }
7118 
7119   return true;
7120 }
7121 
7122 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7123 /// Ty can be implicit converted to the given set of @p Types. We're
7124 /// primarily interested in pointer types and enumeration types. We also
7125 /// take member pointer types, for the conditional operator.
7126 /// AllowUserConversions is true if we should look at the conversion
7127 /// functions of a class type, and AllowExplicitConversions if we
7128 /// should also include the explicit conversion functions of a class
7129 /// type.
7130 void
7131 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7132                                                SourceLocation Loc,
7133                                                bool AllowUserConversions,
7134                                                bool AllowExplicitConversions,
7135                                                const Qualifiers &VisibleQuals) {
7136   // Only deal with canonical types.
7137   Ty = Context.getCanonicalType(Ty);
7138 
7139   // Look through reference types; they aren't part of the type of an
7140   // expression for the purposes of conversions.
7141   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7142     Ty = RefTy->getPointeeType();
7143 
7144   // If we're dealing with an array type, decay to the pointer.
7145   if (Ty->isArrayType())
7146     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7147 
7148   // Otherwise, we don't care about qualifiers on the type.
7149   Ty = Ty.getLocalUnqualifiedType();
7150 
7151   // Flag if we ever add a non-record type.
7152   const RecordType *TyRec = Ty->getAs<RecordType>();
7153   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7154 
7155   // Flag if we encounter an arithmetic type.
7156   HasArithmeticOrEnumeralTypes =
7157     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7158 
7159   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7160     PointerTypes.insert(Ty);
7161   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7162     // Insert our type, and its more-qualified variants, into the set
7163     // of types.
7164     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7165       return;
7166   } else if (Ty->isMemberPointerType()) {
7167     // Member pointers are far easier, since the pointee can't be converted.
7168     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7169       return;
7170   } else if (Ty->isEnumeralType()) {
7171     HasArithmeticOrEnumeralTypes = true;
7172     EnumerationTypes.insert(Ty);
7173   } else if (Ty->isVectorType()) {
7174     // We treat vector types as arithmetic types in many contexts as an
7175     // extension.
7176     HasArithmeticOrEnumeralTypes = true;
7177     VectorTypes.insert(Ty);
7178   } else if (Ty->isNullPtrType()) {
7179     HasNullPtrType = true;
7180   } else if (AllowUserConversions && TyRec) {
7181     // No conversion functions in incomplete types.
7182     if (!SemaRef.isCompleteType(Loc, Ty))
7183       return;
7184 
7185     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7186     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7187       if (isa<UsingShadowDecl>(D))
7188         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7189 
7190       // Skip conversion function templates; they don't tell us anything
7191       // about which builtin types we can convert to.
7192       if (isa<FunctionTemplateDecl>(D))
7193         continue;
7194 
7195       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7196       if (AllowExplicitConversions || !Conv->isExplicit()) {
7197         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7198                               VisibleQuals);
7199       }
7200     }
7201   }
7202 }
7203 
7204 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7205 /// the volatile- and non-volatile-qualified assignment operators for the
7206 /// given type to the candidate set.
7207 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7208                                                    QualType T,
7209                                                    ArrayRef<Expr *> Args,
7210                                     OverloadCandidateSet &CandidateSet) {
7211   QualType ParamTypes[2];
7212 
7213   // T& operator=(T&, T)
7214   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7215   ParamTypes[1] = T;
7216   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7217                         /*IsAssignmentOperator=*/true);
7218 
7219   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7220     // volatile T& operator=(volatile T&, T)
7221     ParamTypes[0]
7222       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7223     ParamTypes[1] = T;
7224     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7225                           /*IsAssignmentOperator=*/true);
7226   }
7227 }
7228 
7229 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7230 /// if any, found in visible type conversion functions found in ArgExpr's type.
7231 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7232     Qualifiers VRQuals;
7233     const RecordType *TyRec;
7234     if (const MemberPointerType *RHSMPType =
7235         ArgExpr->getType()->getAs<MemberPointerType>())
7236       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7237     else
7238       TyRec = ArgExpr->getType()->getAs<RecordType>();
7239     if (!TyRec) {
7240       // Just to be safe, assume the worst case.
7241       VRQuals.addVolatile();
7242       VRQuals.addRestrict();
7243       return VRQuals;
7244     }
7245 
7246     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7247     if (!ClassDecl->hasDefinition())
7248       return VRQuals;
7249 
7250     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7251       if (isa<UsingShadowDecl>(D))
7252         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7253       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7254         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7255         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7256           CanTy = ResTypeRef->getPointeeType();
7257         // Need to go down the pointer/mempointer chain and add qualifiers
7258         // as see them.
7259         bool done = false;
7260         while (!done) {
7261           if (CanTy.isRestrictQualified())
7262             VRQuals.addRestrict();
7263           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7264             CanTy = ResTypePtr->getPointeeType();
7265           else if (const MemberPointerType *ResTypeMPtr =
7266                 CanTy->getAs<MemberPointerType>())
7267             CanTy = ResTypeMPtr->getPointeeType();
7268           else
7269             done = true;
7270           if (CanTy.isVolatileQualified())
7271             VRQuals.addVolatile();
7272           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7273             return VRQuals;
7274         }
7275       }
7276     }
7277     return VRQuals;
7278 }
7279 
7280 namespace {
7281 
7282 /// \brief Helper class to manage the addition of builtin operator overload
7283 /// candidates. It provides shared state and utility methods used throughout
7284 /// the process, as well as a helper method to add each group of builtin
7285 /// operator overloads from the standard to a candidate set.
7286 class BuiltinOperatorOverloadBuilder {
7287   // Common instance state available to all overload candidate addition methods.
7288   Sema &S;
7289   ArrayRef<Expr *> Args;
7290   Qualifiers VisibleTypeConversionsQuals;
7291   bool HasArithmeticOrEnumeralCandidateType;
7292   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7293   OverloadCandidateSet &CandidateSet;
7294 
7295   // Define some constants used to index and iterate over the arithemetic types
7296   // provided via the getArithmeticType() method below.
7297   // The "promoted arithmetic types" are the arithmetic
7298   // types are that preserved by promotion (C++ [over.built]p2).
7299   static const unsigned FirstIntegralType = 4;
7300   static const unsigned LastIntegralType = 21;
7301   static const unsigned FirstPromotedIntegralType = 4,
7302                         LastPromotedIntegralType = 12;
7303   static const unsigned FirstPromotedArithmeticType = 0,
7304                         LastPromotedArithmeticType = 12;
7305   static const unsigned NumArithmeticTypes = 21;
7306 
7307   /// \brief Get the canonical type for a given arithmetic type index.
7308   CanQualType getArithmeticType(unsigned index) {
7309     assert(index < NumArithmeticTypes);
7310     static CanQualType ASTContext::* const
7311       ArithmeticTypes[NumArithmeticTypes] = {
7312       // Start of promoted types.
7313       &ASTContext::FloatTy,
7314       &ASTContext::DoubleTy,
7315       &ASTContext::LongDoubleTy,
7316       &ASTContext::Float128Ty,
7317 
7318       // Start of integral types.
7319       &ASTContext::IntTy,
7320       &ASTContext::LongTy,
7321       &ASTContext::LongLongTy,
7322       &ASTContext::Int128Ty,
7323       &ASTContext::UnsignedIntTy,
7324       &ASTContext::UnsignedLongTy,
7325       &ASTContext::UnsignedLongLongTy,
7326       &ASTContext::UnsignedInt128Ty,
7327       // End of promoted types.
7328 
7329       &ASTContext::BoolTy,
7330       &ASTContext::CharTy,
7331       &ASTContext::WCharTy,
7332       &ASTContext::Char16Ty,
7333       &ASTContext::Char32Ty,
7334       &ASTContext::SignedCharTy,
7335       &ASTContext::ShortTy,
7336       &ASTContext::UnsignedCharTy,
7337       &ASTContext::UnsignedShortTy,
7338       // End of integral types.
7339       // FIXME: What about complex? What about half?
7340     };
7341     return S.Context.*ArithmeticTypes[index];
7342   }
7343 
7344   /// \brief Gets the canonical type resulting from the usual arithemetic
7345   /// converions for the given arithmetic types.
7346   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7347     // Accelerator table for performing the usual arithmetic conversions.
7348     // The rules are basically:
7349     //   - if either is floating-point, use the wider floating-point
7350     //   - if same signedness, use the higher rank
7351     //   - if same size, use unsigned of the higher rank
7352     //   - use the larger type
7353     // These rules, together with the axiom that higher ranks are
7354     // never smaller, are sufficient to precompute all of these results
7355     // *except* when dealing with signed types of higher rank.
7356     // (we could precompute SLL x UI for all known platforms, but it's
7357     // better not to make any assumptions).
7358     // We assume that int128 has a higher rank than long long on all platforms.
7359     enum PromotedType : int8_t {
7360             Dep=-1,
7361             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7362     };
7363     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7364                                         [LastPromotedArithmeticType] = {
7365 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7366 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7367 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7368 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7369 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7370 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7371 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7372 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7373 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7374 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7375 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7376     };
7377 
7378     assert(L < LastPromotedArithmeticType);
7379     assert(R < LastPromotedArithmeticType);
7380     int Idx = ConversionsTable[L][R];
7381 
7382     // Fast path: the table gives us a concrete answer.
7383     if (Idx != Dep) return getArithmeticType(Idx);
7384 
7385     // Slow path: we need to compare widths.
7386     // An invariant is that the signed type has higher rank.
7387     CanQualType LT = getArithmeticType(L),
7388                 RT = getArithmeticType(R);
7389     unsigned LW = S.Context.getIntWidth(LT),
7390              RW = S.Context.getIntWidth(RT);
7391 
7392     // If they're different widths, use the signed type.
7393     if (LW > RW) return LT;
7394     else if (LW < RW) return RT;
7395 
7396     // Otherwise, use the unsigned type of the signed type's rank.
7397     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7398     assert(L == SLL || R == SLL);
7399     return S.Context.UnsignedLongLongTy;
7400   }
7401 
7402   /// \brief Helper method to factor out the common pattern of adding overloads
7403   /// for '++' and '--' builtin operators.
7404   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7405                                            bool HasVolatile,
7406                                            bool HasRestrict) {
7407     QualType ParamTypes[2] = {
7408       S.Context.getLValueReferenceType(CandidateTy),
7409       S.Context.IntTy
7410     };
7411 
7412     // Non-volatile version.
7413     if (Args.size() == 1)
7414       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7415     else
7416       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7417 
7418     // Use a heuristic to reduce number of builtin candidates in the set:
7419     // add volatile version only if there are conversions to a volatile type.
7420     if (HasVolatile) {
7421       ParamTypes[0] =
7422         S.Context.getLValueReferenceType(
7423           S.Context.getVolatileType(CandidateTy));
7424       if (Args.size() == 1)
7425         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7426       else
7427         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7428     }
7429 
7430     // Add restrict version only if there are conversions to a restrict type
7431     // and our candidate type is a non-restrict-qualified pointer.
7432     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7433         !CandidateTy.isRestrictQualified()) {
7434       ParamTypes[0]
7435         = S.Context.getLValueReferenceType(
7436             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7437       if (Args.size() == 1)
7438         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7439       else
7440         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7441 
7442       if (HasVolatile) {
7443         ParamTypes[0]
7444           = S.Context.getLValueReferenceType(
7445               S.Context.getCVRQualifiedType(CandidateTy,
7446                                             (Qualifiers::Volatile |
7447                                              Qualifiers::Restrict)));
7448         if (Args.size() == 1)
7449           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7450         else
7451           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7452       }
7453     }
7454 
7455   }
7456 
7457 public:
7458   BuiltinOperatorOverloadBuilder(
7459     Sema &S, ArrayRef<Expr *> Args,
7460     Qualifiers VisibleTypeConversionsQuals,
7461     bool HasArithmeticOrEnumeralCandidateType,
7462     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7463     OverloadCandidateSet &CandidateSet)
7464     : S(S), Args(Args),
7465       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7466       HasArithmeticOrEnumeralCandidateType(
7467         HasArithmeticOrEnumeralCandidateType),
7468       CandidateTypes(CandidateTypes),
7469       CandidateSet(CandidateSet) {
7470     // Validate some of our static helper constants in debug builds.
7471     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7472            "Invalid first promoted integral type");
7473     assert(getArithmeticType(LastPromotedIntegralType - 1)
7474              == S.Context.UnsignedInt128Ty &&
7475            "Invalid last promoted integral type");
7476     assert(getArithmeticType(FirstPromotedArithmeticType)
7477              == S.Context.FloatTy &&
7478            "Invalid first promoted arithmetic type");
7479     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7480              == S.Context.UnsignedInt128Ty &&
7481            "Invalid last promoted arithmetic type");
7482   }
7483 
7484   // C++ [over.built]p3:
7485   //
7486   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7487   //   is either volatile or empty, there exist candidate operator
7488   //   functions of the form
7489   //
7490   //       VQ T&      operator++(VQ T&);
7491   //       T          operator++(VQ T&, int);
7492   //
7493   // C++ [over.built]p4:
7494   //
7495   //   For every pair (T, VQ), where T is an arithmetic type other
7496   //   than bool, and VQ is either volatile or empty, there exist
7497   //   candidate operator functions of the form
7498   //
7499   //       VQ T&      operator--(VQ T&);
7500   //       T          operator--(VQ T&, int);
7501   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7502     if (!HasArithmeticOrEnumeralCandidateType)
7503       return;
7504 
7505     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7506          Arith < NumArithmeticTypes; ++Arith) {
7507       addPlusPlusMinusMinusStyleOverloads(
7508         getArithmeticType(Arith),
7509         VisibleTypeConversionsQuals.hasVolatile(),
7510         VisibleTypeConversionsQuals.hasRestrict());
7511     }
7512   }
7513 
7514   // C++ [over.built]p5:
7515   //
7516   //   For every pair (T, VQ), where T is a cv-qualified or
7517   //   cv-unqualified object type, and VQ is either volatile or
7518   //   empty, there exist candidate operator functions of the form
7519   //
7520   //       T*VQ&      operator++(T*VQ&);
7521   //       T*VQ&      operator--(T*VQ&);
7522   //       T*         operator++(T*VQ&, int);
7523   //       T*         operator--(T*VQ&, int);
7524   void addPlusPlusMinusMinusPointerOverloads() {
7525     for (BuiltinCandidateTypeSet::iterator
7526               Ptr = CandidateTypes[0].pointer_begin(),
7527            PtrEnd = CandidateTypes[0].pointer_end();
7528          Ptr != PtrEnd; ++Ptr) {
7529       // Skip pointer types that aren't pointers to object types.
7530       if (!(*Ptr)->getPointeeType()->isObjectType())
7531         continue;
7532 
7533       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7534         (!(*Ptr).isVolatileQualified() &&
7535          VisibleTypeConversionsQuals.hasVolatile()),
7536         (!(*Ptr).isRestrictQualified() &&
7537          VisibleTypeConversionsQuals.hasRestrict()));
7538     }
7539   }
7540 
7541   // C++ [over.built]p6:
7542   //   For every cv-qualified or cv-unqualified object type T, there
7543   //   exist candidate operator functions of the form
7544   //
7545   //       T&         operator*(T*);
7546   //
7547   // C++ [over.built]p7:
7548   //   For every function type T that does not have cv-qualifiers or a
7549   //   ref-qualifier, there exist candidate operator functions of the form
7550   //       T&         operator*(T*);
7551   void addUnaryStarPointerOverloads() {
7552     for (BuiltinCandidateTypeSet::iterator
7553               Ptr = CandidateTypes[0].pointer_begin(),
7554            PtrEnd = CandidateTypes[0].pointer_end();
7555          Ptr != PtrEnd; ++Ptr) {
7556       QualType ParamTy = *Ptr;
7557       QualType PointeeTy = ParamTy->getPointeeType();
7558       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7559         continue;
7560 
7561       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7562         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7563           continue;
7564 
7565       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7566                             &ParamTy, Args, CandidateSet);
7567     }
7568   }
7569 
7570   // C++ [over.built]p9:
7571   //  For every promoted arithmetic type T, there exist candidate
7572   //  operator functions of the form
7573   //
7574   //       T         operator+(T);
7575   //       T         operator-(T);
7576   void addUnaryPlusOrMinusArithmeticOverloads() {
7577     if (!HasArithmeticOrEnumeralCandidateType)
7578       return;
7579 
7580     for (unsigned Arith = FirstPromotedArithmeticType;
7581          Arith < LastPromotedArithmeticType; ++Arith) {
7582       QualType ArithTy = getArithmeticType(Arith);
7583       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7584     }
7585 
7586     // Extension: We also add these operators for vector types.
7587     for (BuiltinCandidateTypeSet::iterator
7588               Vec = CandidateTypes[0].vector_begin(),
7589            VecEnd = CandidateTypes[0].vector_end();
7590          Vec != VecEnd; ++Vec) {
7591       QualType VecTy = *Vec;
7592       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7593     }
7594   }
7595 
7596   // C++ [over.built]p8:
7597   //   For every type T, there exist candidate operator functions of
7598   //   the form
7599   //
7600   //       T*         operator+(T*);
7601   void addUnaryPlusPointerOverloads() {
7602     for (BuiltinCandidateTypeSet::iterator
7603               Ptr = CandidateTypes[0].pointer_begin(),
7604            PtrEnd = CandidateTypes[0].pointer_end();
7605          Ptr != PtrEnd; ++Ptr) {
7606       QualType ParamTy = *Ptr;
7607       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7608     }
7609   }
7610 
7611   // C++ [over.built]p10:
7612   //   For every promoted integral type T, there exist candidate
7613   //   operator functions of the form
7614   //
7615   //        T         operator~(T);
7616   void addUnaryTildePromotedIntegralOverloads() {
7617     if (!HasArithmeticOrEnumeralCandidateType)
7618       return;
7619 
7620     for (unsigned Int = FirstPromotedIntegralType;
7621          Int < LastPromotedIntegralType; ++Int) {
7622       QualType IntTy = getArithmeticType(Int);
7623       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7624     }
7625 
7626     // Extension: We also add this operator for vector types.
7627     for (BuiltinCandidateTypeSet::iterator
7628               Vec = CandidateTypes[0].vector_begin(),
7629            VecEnd = CandidateTypes[0].vector_end();
7630          Vec != VecEnd; ++Vec) {
7631       QualType VecTy = *Vec;
7632       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7633     }
7634   }
7635 
7636   // C++ [over.match.oper]p16:
7637   //   For every pointer to member type T or type std::nullptr_t, there
7638   //   exist candidate operator functions of the form
7639   //
7640   //        bool operator==(T,T);
7641   //        bool operator!=(T,T);
7642   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7643     /// Set of (canonical) types that we've already handled.
7644     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7645 
7646     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7647       for (BuiltinCandidateTypeSet::iterator
7648                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7649              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7650            MemPtr != MemPtrEnd;
7651            ++MemPtr) {
7652         // Don't add the same builtin candidate twice.
7653         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7654           continue;
7655 
7656         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7657         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7658       }
7659 
7660       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7661         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7662         if (AddedTypes.insert(NullPtrTy).second) {
7663           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7664           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7665                                 CandidateSet);
7666         }
7667       }
7668     }
7669   }
7670 
7671   // C++ [over.built]p15:
7672   //
7673   //   For every T, where T is an enumeration type or a pointer type,
7674   //   there exist candidate operator functions of the form
7675   //
7676   //        bool       operator<(T, T);
7677   //        bool       operator>(T, T);
7678   //        bool       operator<=(T, T);
7679   //        bool       operator>=(T, T);
7680   //        bool       operator==(T, T);
7681   //        bool       operator!=(T, T);
7682   void addRelationalPointerOrEnumeralOverloads() {
7683     // C++ [over.match.oper]p3:
7684     //   [...]the built-in candidates include all of the candidate operator
7685     //   functions defined in 13.6 that, compared to the given operator, [...]
7686     //   do not have the same parameter-type-list as any non-template non-member
7687     //   candidate.
7688     //
7689     // Note that in practice, this only affects enumeration types because there
7690     // aren't any built-in candidates of record type, and a user-defined operator
7691     // must have an operand of record or enumeration type. Also, the only other
7692     // overloaded operator with enumeration arguments, operator=,
7693     // cannot be overloaded for enumeration types, so this is the only place
7694     // where we must suppress candidates like this.
7695     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7696       UserDefinedBinaryOperators;
7697 
7698     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7699       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7700           CandidateTypes[ArgIdx].enumeration_end()) {
7701         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7702                                          CEnd = CandidateSet.end();
7703              C != CEnd; ++C) {
7704           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7705             continue;
7706 
7707           if (C->Function->isFunctionTemplateSpecialization())
7708             continue;
7709 
7710           QualType FirstParamType =
7711             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7712           QualType SecondParamType =
7713             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7714 
7715           // Skip if either parameter isn't of enumeral type.
7716           if (!FirstParamType->isEnumeralType() ||
7717               !SecondParamType->isEnumeralType())
7718             continue;
7719 
7720           // Add this operator to the set of known user-defined operators.
7721           UserDefinedBinaryOperators.insert(
7722             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7723                            S.Context.getCanonicalType(SecondParamType)));
7724         }
7725       }
7726     }
7727 
7728     /// Set of (canonical) types that we've already handled.
7729     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7730 
7731     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7732       for (BuiltinCandidateTypeSet::iterator
7733                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7734              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7735            Ptr != PtrEnd; ++Ptr) {
7736         // Don't add the same builtin candidate twice.
7737         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7738           continue;
7739 
7740         QualType ParamTypes[2] = { *Ptr, *Ptr };
7741         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7742       }
7743       for (BuiltinCandidateTypeSet::iterator
7744                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7745              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7746            Enum != EnumEnd; ++Enum) {
7747         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7748 
7749         // Don't add the same builtin candidate twice, or if a user defined
7750         // candidate exists.
7751         if (!AddedTypes.insert(CanonType).second ||
7752             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7753                                                             CanonType)))
7754           continue;
7755 
7756         QualType ParamTypes[2] = { *Enum, *Enum };
7757         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7758       }
7759     }
7760   }
7761 
7762   // C++ [over.built]p13:
7763   //
7764   //   For every cv-qualified or cv-unqualified object type T
7765   //   there exist candidate operator functions of the form
7766   //
7767   //      T*         operator+(T*, ptrdiff_t);
7768   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7769   //      T*         operator-(T*, ptrdiff_t);
7770   //      T*         operator+(ptrdiff_t, T*);
7771   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7772   //
7773   // C++ [over.built]p14:
7774   //
7775   //   For every T, where T is a pointer to object type, there
7776   //   exist candidate operator functions of the form
7777   //
7778   //      ptrdiff_t  operator-(T, T);
7779   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7780     /// Set of (canonical) types that we've already handled.
7781     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7782 
7783     for (int Arg = 0; Arg < 2; ++Arg) {
7784       QualType AsymmetricParamTypes[2] = {
7785         S.Context.getPointerDiffType(),
7786         S.Context.getPointerDiffType(),
7787       };
7788       for (BuiltinCandidateTypeSet::iterator
7789                 Ptr = CandidateTypes[Arg].pointer_begin(),
7790              PtrEnd = CandidateTypes[Arg].pointer_end();
7791            Ptr != PtrEnd; ++Ptr) {
7792         QualType PointeeTy = (*Ptr)->getPointeeType();
7793         if (!PointeeTy->isObjectType())
7794           continue;
7795 
7796         AsymmetricParamTypes[Arg] = *Ptr;
7797         if (Arg == 0 || Op == OO_Plus) {
7798           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7799           // T* operator+(ptrdiff_t, T*);
7800           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7801         }
7802         if (Op == OO_Minus) {
7803           // ptrdiff_t operator-(T, T);
7804           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7805             continue;
7806 
7807           QualType ParamTypes[2] = { *Ptr, *Ptr };
7808           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7809                                 Args, CandidateSet);
7810         }
7811       }
7812     }
7813   }
7814 
7815   // C++ [over.built]p12:
7816   //
7817   //   For every pair of promoted arithmetic types L and R, there
7818   //   exist candidate operator functions of the form
7819   //
7820   //        LR         operator*(L, R);
7821   //        LR         operator/(L, R);
7822   //        LR         operator+(L, R);
7823   //        LR         operator-(L, R);
7824   //        bool       operator<(L, R);
7825   //        bool       operator>(L, R);
7826   //        bool       operator<=(L, R);
7827   //        bool       operator>=(L, R);
7828   //        bool       operator==(L, R);
7829   //        bool       operator!=(L, R);
7830   //
7831   //   where LR is the result of the usual arithmetic conversions
7832   //   between types L and R.
7833   //
7834   // C++ [over.built]p24:
7835   //
7836   //   For every pair of promoted arithmetic types L and R, there exist
7837   //   candidate operator functions of the form
7838   //
7839   //        LR       operator?(bool, L, R);
7840   //
7841   //   where LR is the result of the usual arithmetic conversions
7842   //   between types L and R.
7843   // Our candidates ignore the first parameter.
7844   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7845     if (!HasArithmeticOrEnumeralCandidateType)
7846       return;
7847 
7848     for (unsigned Left = FirstPromotedArithmeticType;
7849          Left < LastPromotedArithmeticType; ++Left) {
7850       for (unsigned Right = FirstPromotedArithmeticType;
7851            Right < LastPromotedArithmeticType; ++Right) {
7852         QualType LandR[2] = { getArithmeticType(Left),
7853                               getArithmeticType(Right) };
7854         QualType Result =
7855           isComparison ? S.Context.BoolTy
7856                        : getUsualArithmeticConversions(Left, Right);
7857         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7858       }
7859     }
7860 
7861     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7862     // conditional operator for vector types.
7863     for (BuiltinCandidateTypeSet::iterator
7864               Vec1 = CandidateTypes[0].vector_begin(),
7865            Vec1End = CandidateTypes[0].vector_end();
7866          Vec1 != Vec1End; ++Vec1) {
7867       for (BuiltinCandidateTypeSet::iterator
7868                 Vec2 = CandidateTypes[1].vector_begin(),
7869              Vec2End = CandidateTypes[1].vector_end();
7870            Vec2 != Vec2End; ++Vec2) {
7871         QualType LandR[2] = { *Vec1, *Vec2 };
7872         QualType Result = S.Context.BoolTy;
7873         if (!isComparison) {
7874           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7875             Result = *Vec1;
7876           else
7877             Result = *Vec2;
7878         }
7879 
7880         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7881       }
7882     }
7883   }
7884 
7885   // C++ [over.built]p17:
7886   //
7887   //   For every pair of promoted integral types L and R, there
7888   //   exist candidate operator functions of the form
7889   //
7890   //      LR         operator%(L, R);
7891   //      LR         operator&(L, R);
7892   //      LR         operator^(L, R);
7893   //      LR         operator|(L, R);
7894   //      L          operator<<(L, R);
7895   //      L          operator>>(L, R);
7896   //
7897   //   where LR is the result of the usual arithmetic conversions
7898   //   between types L and R.
7899   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7900     if (!HasArithmeticOrEnumeralCandidateType)
7901       return;
7902 
7903     for (unsigned Left = FirstPromotedIntegralType;
7904          Left < LastPromotedIntegralType; ++Left) {
7905       for (unsigned Right = FirstPromotedIntegralType;
7906            Right < LastPromotedIntegralType; ++Right) {
7907         QualType LandR[2] = { getArithmeticType(Left),
7908                               getArithmeticType(Right) };
7909         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7910             ? LandR[0]
7911             : getUsualArithmeticConversions(Left, Right);
7912         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7913       }
7914     }
7915   }
7916 
7917   // C++ [over.built]p20:
7918   //
7919   //   For every pair (T, VQ), where T is an enumeration or
7920   //   pointer to member type and VQ is either volatile or
7921   //   empty, there exist candidate operator functions of the form
7922   //
7923   //        VQ T&      operator=(VQ T&, T);
7924   void addAssignmentMemberPointerOrEnumeralOverloads() {
7925     /// Set of (canonical) types that we've already handled.
7926     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7927 
7928     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7929       for (BuiltinCandidateTypeSet::iterator
7930                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7931              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7932            Enum != EnumEnd; ++Enum) {
7933         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7934           continue;
7935 
7936         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7937       }
7938 
7939       for (BuiltinCandidateTypeSet::iterator
7940                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7941              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7942            MemPtr != MemPtrEnd; ++MemPtr) {
7943         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7944           continue;
7945 
7946         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7947       }
7948     }
7949   }
7950 
7951   // C++ [over.built]p19:
7952   //
7953   //   For every pair (T, VQ), where T is any type and VQ is either
7954   //   volatile or empty, there exist candidate operator functions
7955   //   of the form
7956   //
7957   //        T*VQ&      operator=(T*VQ&, T*);
7958   //
7959   // C++ [over.built]p21:
7960   //
7961   //   For every pair (T, VQ), where T is a cv-qualified or
7962   //   cv-unqualified object type and VQ is either volatile or
7963   //   empty, there exist candidate operator functions of the form
7964   //
7965   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7966   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7967   void addAssignmentPointerOverloads(bool isEqualOp) {
7968     /// Set of (canonical) types that we've already handled.
7969     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7970 
7971     for (BuiltinCandidateTypeSet::iterator
7972               Ptr = CandidateTypes[0].pointer_begin(),
7973            PtrEnd = CandidateTypes[0].pointer_end();
7974          Ptr != PtrEnd; ++Ptr) {
7975       // If this is operator=, keep track of the builtin candidates we added.
7976       if (isEqualOp)
7977         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7978       else if (!(*Ptr)->getPointeeType()->isObjectType())
7979         continue;
7980 
7981       // non-volatile version
7982       QualType ParamTypes[2] = {
7983         S.Context.getLValueReferenceType(*Ptr),
7984         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7985       };
7986       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7987                             /*IsAssigmentOperator=*/ isEqualOp);
7988 
7989       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7990                           VisibleTypeConversionsQuals.hasVolatile();
7991       if (NeedVolatile) {
7992         // volatile version
7993         ParamTypes[0] =
7994           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7995         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7996                               /*IsAssigmentOperator=*/isEqualOp);
7997       }
7998 
7999       if (!(*Ptr).isRestrictQualified() &&
8000           VisibleTypeConversionsQuals.hasRestrict()) {
8001         // restrict version
8002         ParamTypes[0]
8003           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8004         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8005                               /*IsAssigmentOperator=*/isEqualOp);
8006 
8007         if (NeedVolatile) {
8008           // volatile restrict version
8009           ParamTypes[0]
8010             = S.Context.getLValueReferenceType(
8011                 S.Context.getCVRQualifiedType(*Ptr,
8012                                               (Qualifiers::Volatile |
8013                                                Qualifiers::Restrict)));
8014           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8015                                 /*IsAssigmentOperator=*/isEqualOp);
8016         }
8017       }
8018     }
8019 
8020     if (isEqualOp) {
8021       for (BuiltinCandidateTypeSet::iterator
8022                 Ptr = CandidateTypes[1].pointer_begin(),
8023              PtrEnd = CandidateTypes[1].pointer_end();
8024            Ptr != PtrEnd; ++Ptr) {
8025         // Make sure we don't add the same candidate twice.
8026         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8027           continue;
8028 
8029         QualType ParamTypes[2] = {
8030           S.Context.getLValueReferenceType(*Ptr),
8031           *Ptr,
8032         };
8033 
8034         // non-volatile version
8035         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8036                               /*IsAssigmentOperator=*/true);
8037 
8038         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8039                            VisibleTypeConversionsQuals.hasVolatile();
8040         if (NeedVolatile) {
8041           // volatile version
8042           ParamTypes[0] =
8043             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8044           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8045                                 /*IsAssigmentOperator=*/true);
8046         }
8047 
8048         if (!(*Ptr).isRestrictQualified() &&
8049             VisibleTypeConversionsQuals.hasRestrict()) {
8050           // restrict version
8051           ParamTypes[0]
8052             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8053           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8054                                 /*IsAssigmentOperator=*/true);
8055 
8056           if (NeedVolatile) {
8057             // volatile restrict version
8058             ParamTypes[0]
8059               = S.Context.getLValueReferenceType(
8060                   S.Context.getCVRQualifiedType(*Ptr,
8061                                                 (Qualifiers::Volatile |
8062                                                  Qualifiers::Restrict)));
8063             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8064                                   /*IsAssigmentOperator=*/true);
8065           }
8066         }
8067       }
8068     }
8069   }
8070 
8071   // C++ [over.built]p18:
8072   //
8073   //   For every triple (L, VQ, R), where L is an arithmetic type,
8074   //   VQ is either volatile or empty, and R is a promoted
8075   //   arithmetic type, there exist candidate operator functions of
8076   //   the form
8077   //
8078   //        VQ L&      operator=(VQ L&, R);
8079   //        VQ L&      operator*=(VQ L&, R);
8080   //        VQ L&      operator/=(VQ L&, R);
8081   //        VQ L&      operator+=(VQ L&, R);
8082   //        VQ L&      operator-=(VQ L&, R);
8083   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8084     if (!HasArithmeticOrEnumeralCandidateType)
8085       return;
8086 
8087     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8088       for (unsigned Right = FirstPromotedArithmeticType;
8089            Right < LastPromotedArithmeticType; ++Right) {
8090         QualType ParamTypes[2];
8091         ParamTypes[1] = getArithmeticType(Right);
8092 
8093         // Add this built-in operator as a candidate (VQ is empty).
8094         ParamTypes[0] =
8095           S.Context.getLValueReferenceType(getArithmeticType(Left));
8096         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8097                               /*IsAssigmentOperator=*/isEqualOp);
8098 
8099         // Add this built-in operator as a candidate (VQ is 'volatile').
8100         if (VisibleTypeConversionsQuals.hasVolatile()) {
8101           ParamTypes[0] =
8102             S.Context.getVolatileType(getArithmeticType(Left));
8103           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8104           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8105                                 /*IsAssigmentOperator=*/isEqualOp);
8106         }
8107       }
8108     }
8109 
8110     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8111     for (BuiltinCandidateTypeSet::iterator
8112               Vec1 = CandidateTypes[0].vector_begin(),
8113            Vec1End = CandidateTypes[0].vector_end();
8114          Vec1 != Vec1End; ++Vec1) {
8115       for (BuiltinCandidateTypeSet::iterator
8116                 Vec2 = CandidateTypes[1].vector_begin(),
8117              Vec2End = CandidateTypes[1].vector_end();
8118            Vec2 != Vec2End; ++Vec2) {
8119         QualType ParamTypes[2];
8120         ParamTypes[1] = *Vec2;
8121         // Add this built-in operator as a candidate (VQ is empty).
8122         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8123         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8124                               /*IsAssigmentOperator=*/isEqualOp);
8125 
8126         // Add this built-in operator as a candidate (VQ is 'volatile').
8127         if (VisibleTypeConversionsQuals.hasVolatile()) {
8128           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8129           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8130           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8131                                 /*IsAssigmentOperator=*/isEqualOp);
8132         }
8133       }
8134     }
8135   }
8136 
8137   // C++ [over.built]p22:
8138   //
8139   //   For every triple (L, VQ, R), where L is an integral type, VQ
8140   //   is either volatile or empty, and R is a promoted integral
8141   //   type, there exist candidate operator functions of the form
8142   //
8143   //        VQ L&       operator%=(VQ L&, R);
8144   //        VQ L&       operator<<=(VQ L&, R);
8145   //        VQ L&       operator>>=(VQ L&, R);
8146   //        VQ L&       operator&=(VQ L&, R);
8147   //        VQ L&       operator^=(VQ L&, R);
8148   //        VQ L&       operator|=(VQ L&, R);
8149   void addAssignmentIntegralOverloads() {
8150     if (!HasArithmeticOrEnumeralCandidateType)
8151       return;
8152 
8153     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8154       for (unsigned Right = FirstPromotedIntegralType;
8155            Right < LastPromotedIntegralType; ++Right) {
8156         QualType ParamTypes[2];
8157         ParamTypes[1] = getArithmeticType(Right);
8158 
8159         // Add this built-in operator as a candidate (VQ is empty).
8160         ParamTypes[0] =
8161           S.Context.getLValueReferenceType(getArithmeticType(Left));
8162         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8163         if (VisibleTypeConversionsQuals.hasVolatile()) {
8164           // Add this built-in operator as a candidate (VQ is 'volatile').
8165           ParamTypes[0] = getArithmeticType(Left);
8166           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8167           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8168           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8169         }
8170       }
8171     }
8172   }
8173 
8174   // C++ [over.operator]p23:
8175   //
8176   //   There also exist candidate operator functions of the form
8177   //
8178   //        bool        operator!(bool);
8179   //        bool        operator&&(bool, bool);
8180   //        bool        operator||(bool, bool);
8181   void addExclaimOverload() {
8182     QualType ParamTy = S.Context.BoolTy;
8183     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8184                           /*IsAssignmentOperator=*/false,
8185                           /*NumContextualBoolArguments=*/1);
8186   }
8187   void addAmpAmpOrPipePipeOverload() {
8188     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8189     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8190                           /*IsAssignmentOperator=*/false,
8191                           /*NumContextualBoolArguments=*/2);
8192   }
8193 
8194   // C++ [over.built]p13:
8195   //
8196   //   For every cv-qualified or cv-unqualified object type T there
8197   //   exist candidate operator functions of the form
8198   //
8199   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8200   //        T&         operator[](T*, ptrdiff_t);
8201   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8202   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8203   //        T&         operator[](ptrdiff_t, T*);
8204   void addSubscriptOverloads() {
8205     for (BuiltinCandidateTypeSet::iterator
8206               Ptr = CandidateTypes[0].pointer_begin(),
8207            PtrEnd = CandidateTypes[0].pointer_end();
8208          Ptr != PtrEnd; ++Ptr) {
8209       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8210       QualType PointeeType = (*Ptr)->getPointeeType();
8211       if (!PointeeType->isObjectType())
8212         continue;
8213 
8214       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8215 
8216       // T& operator[](T*, ptrdiff_t)
8217       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8218     }
8219 
8220     for (BuiltinCandidateTypeSet::iterator
8221               Ptr = CandidateTypes[1].pointer_begin(),
8222            PtrEnd = CandidateTypes[1].pointer_end();
8223          Ptr != PtrEnd; ++Ptr) {
8224       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8225       QualType PointeeType = (*Ptr)->getPointeeType();
8226       if (!PointeeType->isObjectType())
8227         continue;
8228 
8229       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8230 
8231       // T& operator[](ptrdiff_t, T*)
8232       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8233     }
8234   }
8235 
8236   // C++ [over.built]p11:
8237   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8238   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8239   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8240   //    there exist candidate operator functions of the form
8241   //
8242   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8243   //
8244   //    where CV12 is the union of CV1 and CV2.
8245   void addArrowStarOverloads() {
8246     for (BuiltinCandidateTypeSet::iterator
8247              Ptr = CandidateTypes[0].pointer_begin(),
8248            PtrEnd = CandidateTypes[0].pointer_end();
8249          Ptr != PtrEnd; ++Ptr) {
8250       QualType C1Ty = (*Ptr);
8251       QualType C1;
8252       QualifierCollector Q1;
8253       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8254       if (!isa<RecordType>(C1))
8255         continue;
8256       // heuristic to reduce number of builtin candidates in the set.
8257       // Add volatile/restrict version only if there are conversions to a
8258       // volatile/restrict type.
8259       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8260         continue;
8261       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8262         continue;
8263       for (BuiltinCandidateTypeSet::iterator
8264                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8265              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8266            MemPtr != MemPtrEnd; ++MemPtr) {
8267         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8268         QualType C2 = QualType(mptr->getClass(), 0);
8269         C2 = C2.getUnqualifiedType();
8270         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8271           break;
8272         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8273         // build CV12 T&
8274         QualType T = mptr->getPointeeType();
8275         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8276             T.isVolatileQualified())
8277           continue;
8278         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8279             T.isRestrictQualified())
8280           continue;
8281         T = Q1.apply(S.Context, T);
8282         QualType ResultTy = S.Context.getLValueReferenceType(T);
8283         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8284       }
8285     }
8286   }
8287 
8288   // Note that we don't consider the first argument, since it has been
8289   // contextually converted to bool long ago. The candidates below are
8290   // therefore added as binary.
8291   //
8292   // C++ [over.built]p25:
8293   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8294   //   enumeration type, there exist candidate operator functions of the form
8295   //
8296   //        T        operator?(bool, T, T);
8297   //
8298   void addConditionalOperatorOverloads() {
8299     /// Set of (canonical) types that we've already handled.
8300     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8301 
8302     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8303       for (BuiltinCandidateTypeSet::iterator
8304                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8305              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8306            Ptr != PtrEnd; ++Ptr) {
8307         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8308           continue;
8309 
8310         QualType ParamTypes[2] = { *Ptr, *Ptr };
8311         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8312       }
8313 
8314       for (BuiltinCandidateTypeSet::iterator
8315                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8316              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8317            MemPtr != MemPtrEnd; ++MemPtr) {
8318         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8319           continue;
8320 
8321         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8322         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8323       }
8324 
8325       if (S.getLangOpts().CPlusPlus11) {
8326         for (BuiltinCandidateTypeSet::iterator
8327                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8328                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8329              Enum != EnumEnd; ++Enum) {
8330           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8331             continue;
8332 
8333           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8334             continue;
8335 
8336           QualType ParamTypes[2] = { *Enum, *Enum };
8337           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8338         }
8339       }
8340     }
8341   }
8342 };
8343 
8344 } // end anonymous namespace
8345 
8346 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8347 /// operator overloads to the candidate set (C++ [over.built]), based
8348 /// on the operator @p Op and the arguments given. For example, if the
8349 /// operator is a binary '+', this routine might add "int
8350 /// operator+(int, int)" to cover integer addition.
8351 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8352                                         SourceLocation OpLoc,
8353                                         ArrayRef<Expr *> Args,
8354                                         OverloadCandidateSet &CandidateSet) {
8355   // Find all of the types that the arguments can convert to, but only
8356   // if the operator we're looking at has built-in operator candidates
8357   // that make use of these types. Also record whether we encounter non-record
8358   // candidate types or either arithmetic or enumeral candidate types.
8359   Qualifiers VisibleTypeConversionsQuals;
8360   VisibleTypeConversionsQuals.addConst();
8361   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8362     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8363 
8364   bool HasNonRecordCandidateType = false;
8365   bool HasArithmeticOrEnumeralCandidateType = false;
8366   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8367   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8368     CandidateTypes.emplace_back(*this);
8369     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8370                                                  OpLoc,
8371                                                  true,
8372                                                  (Op == OO_Exclaim ||
8373                                                   Op == OO_AmpAmp ||
8374                                                   Op == OO_PipePipe),
8375                                                  VisibleTypeConversionsQuals);
8376     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8377         CandidateTypes[ArgIdx].hasNonRecordTypes();
8378     HasArithmeticOrEnumeralCandidateType =
8379         HasArithmeticOrEnumeralCandidateType ||
8380         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8381   }
8382 
8383   // Exit early when no non-record types have been added to the candidate set
8384   // for any of the arguments to the operator.
8385   //
8386   // We can't exit early for !, ||, or &&, since there we have always have
8387   // 'bool' overloads.
8388   if (!HasNonRecordCandidateType &&
8389       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8390     return;
8391 
8392   // Setup an object to manage the common state for building overloads.
8393   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8394                                            VisibleTypeConversionsQuals,
8395                                            HasArithmeticOrEnumeralCandidateType,
8396                                            CandidateTypes, CandidateSet);
8397 
8398   // Dispatch over the operation to add in only those overloads which apply.
8399   switch (Op) {
8400   case OO_None:
8401   case NUM_OVERLOADED_OPERATORS:
8402     llvm_unreachable("Expected an overloaded operator");
8403 
8404   case OO_New:
8405   case OO_Delete:
8406   case OO_Array_New:
8407   case OO_Array_Delete:
8408   case OO_Call:
8409     llvm_unreachable(
8410                     "Special operators don't use AddBuiltinOperatorCandidates");
8411 
8412   case OO_Comma:
8413   case OO_Arrow:
8414   case OO_Coawait:
8415     // C++ [over.match.oper]p3:
8416     //   -- For the operator ',', the unary operator '&', the
8417     //      operator '->', or the operator 'co_await', the
8418     //      built-in candidates set is empty.
8419     break;
8420 
8421   case OO_Plus: // '+' is either unary or binary
8422     if (Args.size() == 1)
8423       OpBuilder.addUnaryPlusPointerOverloads();
8424     // Fall through.
8425 
8426   case OO_Minus: // '-' is either unary or binary
8427     if (Args.size() == 1) {
8428       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8429     } else {
8430       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8431       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8432     }
8433     break;
8434 
8435   case OO_Star: // '*' is either unary or binary
8436     if (Args.size() == 1)
8437       OpBuilder.addUnaryStarPointerOverloads();
8438     else
8439       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8440     break;
8441 
8442   case OO_Slash:
8443     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8444     break;
8445 
8446   case OO_PlusPlus:
8447   case OO_MinusMinus:
8448     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8449     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8450     break;
8451 
8452   case OO_EqualEqual:
8453   case OO_ExclaimEqual:
8454     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8455     // Fall through.
8456 
8457   case OO_Less:
8458   case OO_Greater:
8459   case OO_LessEqual:
8460   case OO_GreaterEqual:
8461     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8462     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8463     break;
8464 
8465   case OO_Percent:
8466   case OO_Caret:
8467   case OO_Pipe:
8468   case OO_LessLess:
8469   case OO_GreaterGreater:
8470     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8471     break;
8472 
8473   case OO_Amp: // '&' is either unary or binary
8474     if (Args.size() == 1)
8475       // C++ [over.match.oper]p3:
8476       //   -- For the operator ',', the unary operator '&', or the
8477       //      operator '->', the built-in candidates set is empty.
8478       break;
8479 
8480     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8481     break;
8482 
8483   case OO_Tilde:
8484     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8485     break;
8486 
8487   case OO_Equal:
8488     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8489     // Fall through.
8490 
8491   case OO_PlusEqual:
8492   case OO_MinusEqual:
8493     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8494     // Fall through.
8495 
8496   case OO_StarEqual:
8497   case OO_SlashEqual:
8498     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8499     break;
8500 
8501   case OO_PercentEqual:
8502   case OO_LessLessEqual:
8503   case OO_GreaterGreaterEqual:
8504   case OO_AmpEqual:
8505   case OO_CaretEqual:
8506   case OO_PipeEqual:
8507     OpBuilder.addAssignmentIntegralOverloads();
8508     break;
8509 
8510   case OO_Exclaim:
8511     OpBuilder.addExclaimOverload();
8512     break;
8513 
8514   case OO_AmpAmp:
8515   case OO_PipePipe:
8516     OpBuilder.addAmpAmpOrPipePipeOverload();
8517     break;
8518 
8519   case OO_Subscript:
8520     OpBuilder.addSubscriptOverloads();
8521     break;
8522 
8523   case OO_ArrowStar:
8524     OpBuilder.addArrowStarOverloads();
8525     break;
8526 
8527   case OO_Conditional:
8528     OpBuilder.addConditionalOperatorOverloads();
8529     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8530     break;
8531   }
8532 }
8533 
8534 /// \brief Add function candidates found via argument-dependent lookup
8535 /// to the set of overloading candidates.
8536 ///
8537 /// This routine performs argument-dependent name lookup based on the
8538 /// given function name (which may also be an operator name) and adds
8539 /// all of the overload candidates found by ADL to the overload
8540 /// candidate set (C++ [basic.lookup.argdep]).
8541 void
8542 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8543                                            SourceLocation Loc,
8544                                            ArrayRef<Expr *> Args,
8545                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8546                                            OverloadCandidateSet& CandidateSet,
8547                                            bool PartialOverloading) {
8548   ADLResult Fns;
8549 
8550   // FIXME: This approach for uniquing ADL results (and removing
8551   // redundant candidates from the set) relies on pointer-equality,
8552   // which means we need to key off the canonical decl.  However,
8553   // always going back to the canonical decl might not get us the
8554   // right set of default arguments.  What default arguments are
8555   // we supposed to consider on ADL candidates, anyway?
8556 
8557   // FIXME: Pass in the explicit template arguments?
8558   ArgumentDependentLookup(Name, Loc, Args, Fns);
8559 
8560   // Erase all of the candidates we already knew about.
8561   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8562                                    CandEnd = CandidateSet.end();
8563        Cand != CandEnd; ++Cand)
8564     if (Cand->Function) {
8565       Fns.erase(Cand->Function);
8566       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8567         Fns.erase(FunTmpl);
8568     }
8569 
8570   // For each of the ADL candidates we found, add it to the overload
8571   // set.
8572   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8573     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8574     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8575       if (ExplicitTemplateArgs)
8576         continue;
8577 
8578       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8579                            PartialOverloading);
8580     } else
8581       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8582                                    FoundDecl, ExplicitTemplateArgs,
8583                                    Args, CandidateSet, PartialOverloading);
8584   }
8585 }
8586 
8587 namespace {
8588 enum class Comparison { Equal, Better, Worse };
8589 }
8590 
8591 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8592 /// overload resolution.
8593 ///
8594 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8595 /// Cand1's first N enable_if attributes have precisely the same conditions as
8596 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8597 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8598 ///
8599 /// Note that you can have a pair of candidates such that Cand1's enable_if
8600 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8601 /// worse than Cand1's.
8602 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8603                                        const FunctionDecl *Cand2) {
8604   // Common case: One (or both) decls don't have enable_if attrs.
8605   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8606   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8607   if (!Cand1Attr || !Cand2Attr) {
8608     if (Cand1Attr == Cand2Attr)
8609       return Comparison::Equal;
8610     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8611   }
8612 
8613   // FIXME: The next several lines are just
8614   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8615   // instead of reverse order which is how they're stored in the AST.
8616   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8617   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8618 
8619   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8620   // has fewer enable_if attributes than Cand2.
8621   if (Cand1Attrs.size() < Cand2Attrs.size())
8622     return Comparison::Worse;
8623 
8624   auto Cand1I = Cand1Attrs.begin();
8625   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8626   for (auto &Cand2A : Cand2Attrs) {
8627     Cand1ID.clear();
8628     Cand2ID.clear();
8629 
8630     auto &Cand1A = *Cand1I++;
8631     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8632     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8633     if (Cand1ID != Cand2ID)
8634       return Comparison::Worse;
8635   }
8636 
8637   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8638 }
8639 
8640 /// isBetterOverloadCandidate - Determines whether the first overload
8641 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8642 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8643                                       const OverloadCandidate &Cand2,
8644                                       SourceLocation Loc,
8645                                       bool UserDefinedConversion) {
8646   // Define viable functions to be better candidates than non-viable
8647   // functions.
8648   if (!Cand2.Viable)
8649     return Cand1.Viable;
8650   else if (!Cand1.Viable)
8651     return false;
8652 
8653   // C++ [over.match.best]p1:
8654   //
8655   //   -- if F is a static member function, ICS1(F) is defined such
8656   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8657   //      any function G, and, symmetrically, ICS1(G) is neither
8658   //      better nor worse than ICS1(F).
8659   unsigned StartArg = 0;
8660   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8661     StartArg = 1;
8662 
8663   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8664     // We don't allow incompatible pointer conversions in C++.
8665     if (!S.getLangOpts().CPlusPlus)
8666       return ICS.isStandard() &&
8667              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8668 
8669     // The only ill-formed conversion we allow in C++ is the string literal to
8670     // char* conversion, which is only considered ill-formed after C++11.
8671     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8672            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8673   };
8674 
8675   // Define functions that don't require ill-formed conversions for a given
8676   // argument to be better candidates than functions that do.
8677   unsigned NumArgs = Cand1.NumConversions;
8678   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8679   bool HasBetterConversion = false;
8680   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8681     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8682     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8683     if (Cand1Bad != Cand2Bad) {
8684       if (Cand1Bad)
8685         return false;
8686       HasBetterConversion = true;
8687     }
8688   }
8689 
8690   if (HasBetterConversion)
8691     return true;
8692 
8693   // C++ [over.match.best]p1:
8694   //   A viable function F1 is defined to be a better function than another
8695   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8696   //   conversion sequence than ICSi(F2), and then...
8697   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8698     switch (CompareImplicitConversionSequences(S, Loc,
8699                                                Cand1.Conversions[ArgIdx],
8700                                                Cand2.Conversions[ArgIdx])) {
8701     case ImplicitConversionSequence::Better:
8702       // Cand1 has a better conversion sequence.
8703       HasBetterConversion = true;
8704       break;
8705 
8706     case ImplicitConversionSequence::Worse:
8707       // Cand1 can't be better than Cand2.
8708       return false;
8709 
8710     case ImplicitConversionSequence::Indistinguishable:
8711       // Do nothing.
8712       break;
8713     }
8714   }
8715 
8716   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8717   //       ICSj(F2), or, if not that,
8718   if (HasBetterConversion)
8719     return true;
8720 
8721   //   -- the context is an initialization by user-defined conversion
8722   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8723   //      from the return type of F1 to the destination type (i.e.,
8724   //      the type of the entity being initialized) is a better
8725   //      conversion sequence than the standard conversion sequence
8726   //      from the return type of F2 to the destination type.
8727   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8728       isa<CXXConversionDecl>(Cand1.Function) &&
8729       isa<CXXConversionDecl>(Cand2.Function)) {
8730     // First check whether we prefer one of the conversion functions over the
8731     // other. This only distinguishes the results in non-standard, extension
8732     // cases such as the conversion from a lambda closure type to a function
8733     // pointer or block.
8734     ImplicitConversionSequence::CompareKind Result =
8735         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8736     if (Result == ImplicitConversionSequence::Indistinguishable)
8737       Result = CompareStandardConversionSequences(S, Loc,
8738                                                   Cand1.FinalConversion,
8739                                                   Cand2.FinalConversion);
8740 
8741     if (Result != ImplicitConversionSequence::Indistinguishable)
8742       return Result == ImplicitConversionSequence::Better;
8743 
8744     // FIXME: Compare kind of reference binding if conversion functions
8745     // convert to a reference type used in direct reference binding, per
8746     // C++14 [over.match.best]p1 section 2 bullet 3.
8747   }
8748 
8749   //    -- F1 is a non-template function and F2 is a function template
8750   //       specialization, or, if not that,
8751   bool Cand1IsSpecialization = Cand1.Function &&
8752                                Cand1.Function->getPrimaryTemplate();
8753   bool Cand2IsSpecialization = Cand2.Function &&
8754                                Cand2.Function->getPrimaryTemplate();
8755   if (Cand1IsSpecialization != Cand2IsSpecialization)
8756     return Cand2IsSpecialization;
8757 
8758   //   -- F1 and F2 are function template specializations, and the function
8759   //      template for F1 is more specialized than the template for F2
8760   //      according to the partial ordering rules described in 14.5.5.2, or,
8761   //      if not that,
8762   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8763     if (FunctionTemplateDecl *BetterTemplate
8764           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8765                                          Cand2.Function->getPrimaryTemplate(),
8766                                          Loc,
8767                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8768                                                              : TPOC_Call,
8769                                          Cand1.ExplicitCallArguments,
8770                                          Cand2.ExplicitCallArguments))
8771       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8772   }
8773 
8774   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8775   // A derived-class constructor beats an (inherited) base class constructor.
8776   bool Cand1IsInherited =
8777       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8778   bool Cand2IsInherited =
8779       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8780   if (Cand1IsInherited != Cand2IsInherited)
8781     return Cand2IsInherited;
8782   else if (Cand1IsInherited) {
8783     assert(Cand2IsInherited);
8784     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8785     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8786     if (Cand1Class->isDerivedFrom(Cand2Class))
8787       return true;
8788     if (Cand2Class->isDerivedFrom(Cand1Class))
8789       return false;
8790     // Inherited from sibling base classes: still ambiguous.
8791   }
8792 
8793   // Check for enable_if value-based overload resolution.
8794   if (Cand1.Function && Cand2.Function) {
8795     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8796     if (Cmp != Comparison::Equal)
8797       return Cmp == Comparison::Better;
8798   }
8799 
8800   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8801     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8802     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8803            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8804   }
8805 
8806   bool HasPS1 = Cand1.Function != nullptr &&
8807                 functionHasPassObjectSizeParams(Cand1.Function);
8808   bool HasPS2 = Cand2.Function != nullptr &&
8809                 functionHasPassObjectSizeParams(Cand2.Function);
8810   return HasPS1 != HasPS2 && HasPS1;
8811 }
8812 
8813 /// Determine whether two declarations are "equivalent" for the purposes of
8814 /// name lookup and overload resolution. This applies when the same internal/no
8815 /// linkage entity is defined by two modules (probably by textually including
8816 /// the same header). In such a case, we don't consider the declarations to
8817 /// declare the same entity, but we also don't want lookups with both
8818 /// declarations visible to be ambiguous in some cases (this happens when using
8819 /// a modularized libstdc++).
8820 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8821                                                   const NamedDecl *B) {
8822   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8823   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8824   if (!VA || !VB)
8825     return false;
8826 
8827   // The declarations must be declaring the same name as an internal linkage
8828   // entity in different modules.
8829   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8830           VB->getDeclContext()->getRedeclContext()) ||
8831       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8832           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8833       VA->isExternallyVisible() || VB->isExternallyVisible())
8834     return false;
8835 
8836   // Check that the declarations appear to be equivalent.
8837   //
8838   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8839   // For constants and functions, we should check the initializer or body is
8840   // the same. For non-constant variables, we shouldn't allow it at all.
8841   if (Context.hasSameType(VA->getType(), VB->getType()))
8842     return true;
8843 
8844   // Enum constants within unnamed enumerations will have different types, but
8845   // may still be similar enough to be interchangeable for our purposes.
8846   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8847     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8848       // Only handle anonymous enums. If the enumerations were named and
8849       // equivalent, they would have been merged to the same type.
8850       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8851       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8852       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8853           !Context.hasSameType(EnumA->getIntegerType(),
8854                                EnumB->getIntegerType()))
8855         return false;
8856       // Allow this only if the value is the same for both enumerators.
8857       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8858     }
8859   }
8860 
8861   // Nothing else is sufficiently similar.
8862   return false;
8863 }
8864 
8865 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8866     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8867   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8868 
8869   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8870   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8871       << !M << (M ? M->getFullModuleName() : "");
8872 
8873   for (auto *E : Equiv) {
8874     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8875     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8876         << !M << (M ? M->getFullModuleName() : "");
8877   }
8878 }
8879 
8880 /// \brief Computes the best viable function (C++ 13.3.3)
8881 /// within an overload candidate set.
8882 ///
8883 /// \param Loc The location of the function name (or operator symbol) for
8884 /// which overload resolution occurs.
8885 ///
8886 /// \param Best If overload resolution was successful or found a deleted
8887 /// function, \p Best points to the candidate function found.
8888 ///
8889 /// \returns The result of overload resolution.
8890 OverloadingResult
8891 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8892                                          iterator &Best,
8893                                          bool UserDefinedConversion) {
8894   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8895   std::transform(begin(), end(), std::back_inserter(Candidates),
8896                  [](OverloadCandidate &Cand) { return &Cand; });
8897 
8898   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8899   // are accepted by both clang and NVCC. However, during a particular
8900   // compilation mode only one call variant is viable. We need to
8901   // exclude non-viable overload candidates from consideration based
8902   // only on their host/device attributes. Specifically, if one
8903   // candidate call is WrongSide and the other is SameSide, we ignore
8904   // the WrongSide candidate.
8905   if (S.getLangOpts().CUDA) {
8906     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8907     bool ContainsSameSideCandidate =
8908         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8909           return Cand->Function &&
8910                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8911                      Sema::CFP_SameSide;
8912         });
8913     if (ContainsSameSideCandidate) {
8914       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8915         return Cand->Function &&
8916                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8917                    Sema::CFP_WrongSide;
8918       };
8919       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8920                                       IsWrongSideCandidate),
8921                        Candidates.end());
8922     }
8923   }
8924 
8925   // Find the best viable function.
8926   Best = end();
8927   for (auto *Cand : Candidates)
8928     if (Cand->Viable)
8929       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8930                                                      UserDefinedConversion))
8931         Best = Cand;
8932 
8933   // If we didn't find any viable functions, abort.
8934   if (Best == end())
8935     return OR_No_Viable_Function;
8936 
8937   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8938 
8939   // Make sure that this function is better than every other viable
8940   // function. If not, we have an ambiguity.
8941   for (auto *Cand : Candidates) {
8942     if (Cand->Viable &&
8943         Cand != Best &&
8944         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8945                                    UserDefinedConversion)) {
8946       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8947                                                    Cand->Function)) {
8948         EquivalentCands.push_back(Cand->Function);
8949         continue;
8950       }
8951 
8952       Best = end();
8953       return OR_Ambiguous;
8954     }
8955   }
8956 
8957   // Best is the best viable function.
8958   if (Best->Function &&
8959       (Best->Function->isDeleted() ||
8960        S.isFunctionConsideredUnavailable(Best->Function)))
8961     return OR_Deleted;
8962 
8963   if (!EquivalentCands.empty())
8964     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8965                                                     EquivalentCands);
8966 
8967   return OR_Success;
8968 }
8969 
8970 namespace {
8971 
8972 enum OverloadCandidateKind {
8973   oc_function,
8974   oc_method,
8975   oc_constructor,
8976   oc_function_template,
8977   oc_method_template,
8978   oc_constructor_template,
8979   oc_implicit_default_constructor,
8980   oc_implicit_copy_constructor,
8981   oc_implicit_move_constructor,
8982   oc_implicit_copy_assignment,
8983   oc_implicit_move_assignment,
8984   oc_inherited_constructor,
8985   oc_inherited_constructor_template
8986 };
8987 
8988 static OverloadCandidateKind
8989 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
8990                           std::string &Description) {
8991   bool isTemplate = false;
8992 
8993   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8994     isTemplate = true;
8995     Description = S.getTemplateArgumentBindingsText(
8996       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8997   }
8998 
8999   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9000     if (!Ctor->isImplicit()) {
9001       if (isa<ConstructorUsingShadowDecl>(Found))
9002         return isTemplate ? oc_inherited_constructor_template
9003                           : oc_inherited_constructor;
9004       else
9005         return isTemplate ? oc_constructor_template : oc_constructor;
9006     }
9007 
9008     if (Ctor->isDefaultConstructor())
9009       return oc_implicit_default_constructor;
9010 
9011     if (Ctor->isMoveConstructor())
9012       return oc_implicit_move_constructor;
9013 
9014     assert(Ctor->isCopyConstructor() &&
9015            "unexpected sort of implicit constructor");
9016     return oc_implicit_copy_constructor;
9017   }
9018 
9019   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9020     // This actually gets spelled 'candidate function' for now, but
9021     // it doesn't hurt to split it out.
9022     if (!Meth->isImplicit())
9023       return isTemplate ? oc_method_template : oc_method;
9024 
9025     if (Meth->isMoveAssignmentOperator())
9026       return oc_implicit_move_assignment;
9027 
9028     if (Meth->isCopyAssignmentOperator())
9029       return oc_implicit_copy_assignment;
9030 
9031     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9032     return oc_method;
9033   }
9034 
9035   return isTemplate ? oc_function_template : oc_function;
9036 }
9037 
9038 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9039   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9040   // set.
9041   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9042     S.Diag(FoundDecl->getLocation(),
9043            diag::note_ovl_candidate_inherited_constructor)
9044       << Shadow->getNominatedBaseClass();
9045 }
9046 
9047 } // end anonymous namespace
9048 
9049 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9050                                     const FunctionDecl *FD) {
9051   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9052     bool AlwaysTrue;
9053     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9054       return false;
9055     if (!AlwaysTrue)
9056       return false;
9057   }
9058   return true;
9059 }
9060 
9061 /// \brief Returns true if we can take the address of the function.
9062 ///
9063 /// \param Complain - If true, we'll emit a diagnostic
9064 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9065 ///   we in overload resolution?
9066 /// \param Loc - The location of the statement we're complaining about. Ignored
9067 ///   if we're not complaining, or if we're in overload resolution.
9068 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9069                                               bool Complain,
9070                                               bool InOverloadResolution,
9071                                               SourceLocation Loc) {
9072   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9073     if (Complain) {
9074       if (InOverloadResolution)
9075         S.Diag(FD->getLocStart(),
9076                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9077       else
9078         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9079     }
9080     return false;
9081   }
9082 
9083   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9084     return P->hasAttr<PassObjectSizeAttr>();
9085   });
9086   if (I == FD->param_end())
9087     return true;
9088 
9089   if (Complain) {
9090     // Add one to ParamNo because it's user-facing
9091     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9092     if (InOverloadResolution)
9093       S.Diag(FD->getLocation(),
9094              diag::note_ovl_candidate_has_pass_object_size_params)
9095           << ParamNo;
9096     else
9097       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9098           << FD << ParamNo;
9099   }
9100   return false;
9101 }
9102 
9103 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9104                                                const FunctionDecl *FD) {
9105   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9106                                            /*InOverloadResolution=*/true,
9107                                            /*Loc=*/SourceLocation());
9108 }
9109 
9110 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9111                                              bool Complain,
9112                                              SourceLocation Loc) {
9113   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9114                                              /*InOverloadResolution=*/false,
9115                                              Loc);
9116 }
9117 
9118 // Notes the location of an overload candidate.
9119 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9120                                  QualType DestType, bool TakingAddress) {
9121   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9122     return;
9123 
9124   std::string FnDesc;
9125   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9126   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9127                              << (unsigned) K << FnDesc;
9128 
9129   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9130   Diag(Fn->getLocation(), PD);
9131   MaybeEmitInheritedConstructorNote(*this, Found);
9132 }
9133 
9134 // Notes the location of all overload candidates designated through
9135 // OverloadedExpr
9136 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9137                                      bool TakingAddress) {
9138   assert(OverloadedExpr->getType() == Context.OverloadTy);
9139 
9140   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9141   OverloadExpr *OvlExpr = Ovl.Expression;
9142 
9143   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9144                             IEnd = OvlExpr->decls_end();
9145        I != IEnd; ++I) {
9146     if (FunctionTemplateDecl *FunTmpl =
9147                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9148       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9149                             TakingAddress);
9150     } else if (FunctionDecl *Fun
9151                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9152       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9153     }
9154   }
9155 }
9156 
9157 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9158 /// "lead" diagnostic; it will be given two arguments, the source and
9159 /// target types of the conversion.
9160 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9161                                  Sema &S,
9162                                  SourceLocation CaretLoc,
9163                                  const PartialDiagnostic &PDiag) const {
9164   S.Diag(CaretLoc, PDiag)
9165     << Ambiguous.getFromType() << Ambiguous.getToType();
9166   // FIXME: The note limiting machinery is borrowed from
9167   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9168   // refactoring here.
9169   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9170   unsigned CandsShown = 0;
9171   AmbiguousConversionSequence::const_iterator I, E;
9172   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9173     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9174       break;
9175     ++CandsShown;
9176     S.NoteOverloadCandidate(I->first, I->second);
9177   }
9178   if (I != E)
9179     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9180 }
9181 
9182 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9183                                   unsigned I, bool TakingCandidateAddress) {
9184   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9185   assert(Conv.isBad());
9186   assert(Cand->Function && "for now, candidate must be a function");
9187   FunctionDecl *Fn = Cand->Function;
9188 
9189   // There's a conversion slot for the object argument if this is a
9190   // non-constructor method.  Note that 'I' corresponds the
9191   // conversion-slot index.
9192   bool isObjectArgument = false;
9193   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9194     if (I == 0)
9195       isObjectArgument = true;
9196     else
9197       I--;
9198   }
9199 
9200   std::string FnDesc;
9201   OverloadCandidateKind FnKind =
9202       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9203 
9204   Expr *FromExpr = Conv.Bad.FromExpr;
9205   QualType FromTy = Conv.Bad.getFromType();
9206   QualType ToTy = Conv.Bad.getToType();
9207 
9208   if (FromTy == S.Context.OverloadTy) {
9209     assert(FromExpr && "overload set argument came from implicit argument?");
9210     Expr *E = FromExpr->IgnoreParens();
9211     if (isa<UnaryOperator>(E))
9212       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9213     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9214 
9215     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9216       << (unsigned) FnKind << FnDesc
9217       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9218       << ToTy << Name << I+1;
9219     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9220     return;
9221   }
9222 
9223   // Do some hand-waving analysis to see if the non-viability is due
9224   // to a qualifier mismatch.
9225   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9226   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9227   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9228     CToTy = RT->getPointeeType();
9229   else {
9230     // TODO: detect and diagnose the full richness of const mismatches.
9231     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9232       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9233         CFromTy = FromPT->getPointeeType();
9234         CToTy = ToPT->getPointeeType();
9235       }
9236   }
9237 
9238   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9239       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9240     Qualifiers FromQs = CFromTy.getQualifiers();
9241     Qualifiers ToQs = CToTy.getQualifiers();
9242 
9243     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9244       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9245         << (unsigned) FnKind << FnDesc
9246         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9247         << FromTy
9248         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9249         << (unsigned) isObjectArgument << I+1;
9250       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9251       return;
9252     }
9253 
9254     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9255       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9256         << (unsigned) FnKind << FnDesc
9257         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9258         << FromTy
9259         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9260         << (unsigned) isObjectArgument << I+1;
9261       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9262       return;
9263     }
9264 
9265     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9266       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9267       << (unsigned) FnKind << FnDesc
9268       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9269       << FromTy
9270       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9271       << (unsigned) isObjectArgument << I+1;
9272       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9273       return;
9274     }
9275 
9276     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9277       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9278         << (unsigned) FnKind << FnDesc
9279         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9280         << FromTy << FromQs.hasUnaligned() << I+1;
9281       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9282       return;
9283     }
9284 
9285     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9286     assert(CVR && "unexpected qualifiers mismatch");
9287 
9288     if (isObjectArgument) {
9289       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9290         << (unsigned) FnKind << FnDesc
9291         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9292         << FromTy << (CVR - 1);
9293     } else {
9294       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9295         << (unsigned) FnKind << FnDesc
9296         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9297         << FromTy << (CVR - 1) << I+1;
9298     }
9299     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9300     return;
9301   }
9302 
9303   // Special diagnostic for failure to convert an initializer list, since
9304   // telling the user that it has type void is not useful.
9305   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9306     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9307       << (unsigned) FnKind << FnDesc
9308       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9309       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9310     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9311     return;
9312   }
9313 
9314   // Diagnose references or pointers to incomplete types differently,
9315   // since it's far from impossible that the incompleteness triggered
9316   // the failure.
9317   QualType TempFromTy = FromTy.getNonReferenceType();
9318   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9319     TempFromTy = PTy->getPointeeType();
9320   if (TempFromTy->isIncompleteType()) {
9321     // Emit the generic diagnostic and, optionally, add the hints to it.
9322     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9323       << (unsigned) FnKind << FnDesc
9324       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9325       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9326       << (unsigned) (Cand->Fix.Kind);
9327 
9328     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9329     return;
9330   }
9331 
9332   // Diagnose base -> derived pointer conversions.
9333   unsigned BaseToDerivedConversion = 0;
9334   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9335     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9336       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9337                                                FromPtrTy->getPointeeType()) &&
9338           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9339           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9340           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9341                           FromPtrTy->getPointeeType()))
9342         BaseToDerivedConversion = 1;
9343     }
9344   } else if (const ObjCObjectPointerType *FromPtrTy
9345                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9346     if (const ObjCObjectPointerType *ToPtrTy
9347                                         = ToTy->getAs<ObjCObjectPointerType>())
9348       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9349         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9350           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9351                                                 FromPtrTy->getPointeeType()) &&
9352               FromIface->isSuperClassOf(ToIface))
9353             BaseToDerivedConversion = 2;
9354   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9355     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9356         !FromTy->isIncompleteType() &&
9357         !ToRefTy->getPointeeType()->isIncompleteType() &&
9358         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9359       BaseToDerivedConversion = 3;
9360     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9361                ToTy.getNonReferenceType().getCanonicalType() ==
9362                FromTy.getNonReferenceType().getCanonicalType()) {
9363       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9364         << (unsigned) FnKind << FnDesc
9365         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9366         << (unsigned) isObjectArgument << I + 1;
9367       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9368       return;
9369     }
9370   }
9371 
9372   if (BaseToDerivedConversion) {
9373     S.Diag(Fn->getLocation(),
9374            diag::note_ovl_candidate_bad_base_to_derived_conv)
9375       << (unsigned) FnKind << FnDesc
9376       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9377       << (BaseToDerivedConversion - 1)
9378       << FromTy << ToTy << I+1;
9379     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9380     return;
9381   }
9382 
9383   if (isa<ObjCObjectPointerType>(CFromTy) &&
9384       isa<PointerType>(CToTy)) {
9385       Qualifiers FromQs = CFromTy.getQualifiers();
9386       Qualifiers ToQs = CToTy.getQualifiers();
9387       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9388         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9389         << (unsigned) FnKind << FnDesc
9390         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9391         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9392         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9393         return;
9394       }
9395   }
9396 
9397   if (TakingCandidateAddress &&
9398       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9399     return;
9400 
9401   // Emit the generic diagnostic and, optionally, add the hints to it.
9402   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9403   FDiag << (unsigned) FnKind << FnDesc
9404     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9405     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9406     << (unsigned) (Cand->Fix.Kind);
9407 
9408   // If we can fix the conversion, suggest the FixIts.
9409   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9410        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9411     FDiag << *HI;
9412   S.Diag(Fn->getLocation(), FDiag);
9413 
9414   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9415 }
9416 
9417 /// Additional arity mismatch diagnosis specific to a function overload
9418 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9419 /// over a candidate in any candidate set.
9420 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9421                                unsigned NumArgs) {
9422   FunctionDecl *Fn = Cand->Function;
9423   unsigned MinParams = Fn->getMinRequiredArguments();
9424 
9425   // With invalid overloaded operators, it's possible that we think we
9426   // have an arity mismatch when in fact it looks like we have the
9427   // right number of arguments, because only overloaded operators have
9428   // the weird behavior of overloading member and non-member functions.
9429   // Just don't report anything.
9430   if (Fn->isInvalidDecl() &&
9431       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9432     return true;
9433 
9434   if (NumArgs < MinParams) {
9435     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9436            (Cand->FailureKind == ovl_fail_bad_deduction &&
9437             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9438   } else {
9439     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9440            (Cand->FailureKind == ovl_fail_bad_deduction &&
9441             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9442   }
9443 
9444   return false;
9445 }
9446 
9447 /// General arity mismatch diagnosis over a candidate in a candidate set.
9448 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9449                                   unsigned NumFormalArgs) {
9450   assert(isa<FunctionDecl>(D) &&
9451       "The templated declaration should at least be a function"
9452       " when diagnosing bad template argument deduction due to too many"
9453       " or too few arguments");
9454 
9455   FunctionDecl *Fn = cast<FunctionDecl>(D);
9456 
9457   // TODO: treat calls to a missing default constructor as a special case
9458   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9459   unsigned MinParams = Fn->getMinRequiredArguments();
9460 
9461   // at least / at most / exactly
9462   unsigned mode, modeCount;
9463   if (NumFormalArgs < MinParams) {
9464     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9465         FnTy->isTemplateVariadic())
9466       mode = 0; // "at least"
9467     else
9468       mode = 2; // "exactly"
9469     modeCount = MinParams;
9470   } else {
9471     if (MinParams != FnTy->getNumParams())
9472       mode = 1; // "at most"
9473     else
9474       mode = 2; // "exactly"
9475     modeCount = FnTy->getNumParams();
9476   }
9477 
9478   std::string Description;
9479   OverloadCandidateKind FnKind =
9480       ClassifyOverloadCandidate(S, Found, Fn, Description);
9481 
9482   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9483     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9484       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9485       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9486   else
9487     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9488       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9489       << mode << modeCount << NumFormalArgs;
9490   MaybeEmitInheritedConstructorNote(S, Found);
9491 }
9492 
9493 /// Arity mismatch diagnosis specific to a function overload candidate.
9494 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9495                                   unsigned NumFormalArgs) {
9496   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9497     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9498 }
9499 
9500 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9501   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9502     return TD;
9503   llvm_unreachable("Unsupported: Getting the described template declaration"
9504                    " for bad deduction diagnosis");
9505 }
9506 
9507 /// Diagnose a failed template-argument deduction.
9508 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9509                                  DeductionFailureInfo &DeductionFailure,
9510                                  unsigned NumArgs,
9511                                  bool TakingCandidateAddress) {
9512   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9513   NamedDecl *ParamD;
9514   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9515   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9516   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9517   switch (DeductionFailure.Result) {
9518   case Sema::TDK_Success:
9519     llvm_unreachable("TDK_success while diagnosing bad deduction");
9520 
9521   case Sema::TDK_Incomplete: {
9522     assert(ParamD && "no parameter found for incomplete deduction result");
9523     S.Diag(Templated->getLocation(),
9524            diag::note_ovl_candidate_incomplete_deduction)
9525         << ParamD->getDeclName();
9526     MaybeEmitInheritedConstructorNote(S, Found);
9527     return;
9528   }
9529 
9530   case Sema::TDK_Underqualified: {
9531     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9532     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9533 
9534     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9535 
9536     // Param will have been canonicalized, but it should just be a
9537     // qualified version of ParamD, so move the qualifiers to that.
9538     QualifierCollector Qs;
9539     Qs.strip(Param);
9540     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9541     assert(S.Context.hasSameType(Param, NonCanonParam));
9542 
9543     // Arg has also been canonicalized, but there's nothing we can do
9544     // about that.  It also doesn't matter as much, because it won't
9545     // have any template parameters in it (because deduction isn't
9546     // done on dependent types).
9547     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9548 
9549     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9550         << ParamD->getDeclName() << Arg << NonCanonParam;
9551     MaybeEmitInheritedConstructorNote(S, Found);
9552     return;
9553   }
9554 
9555   case Sema::TDK_Inconsistent: {
9556     assert(ParamD && "no parameter found for inconsistent deduction result");
9557     int which = 0;
9558     if (isa<TemplateTypeParmDecl>(ParamD))
9559       which = 0;
9560     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9561       which = 1;
9562     else {
9563       which = 2;
9564     }
9565 
9566     S.Diag(Templated->getLocation(),
9567            diag::note_ovl_candidate_inconsistent_deduction)
9568         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9569         << *DeductionFailure.getSecondArg();
9570     MaybeEmitInheritedConstructorNote(S, Found);
9571     return;
9572   }
9573 
9574   case Sema::TDK_InvalidExplicitArguments:
9575     assert(ParamD && "no parameter found for invalid explicit arguments");
9576     if (ParamD->getDeclName())
9577       S.Diag(Templated->getLocation(),
9578              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9579           << ParamD->getDeclName();
9580     else {
9581       int index = 0;
9582       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9583         index = TTP->getIndex();
9584       else if (NonTypeTemplateParmDecl *NTTP
9585                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9586         index = NTTP->getIndex();
9587       else
9588         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9589       S.Diag(Templated->getLocation(),
9590              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9591           << (index + 1);
9592     }
9593     MaybeEmitInheritedConstructorNote(S, Found);
9594     return;
9595 
9596   case Sema::TDK_TooManyArguments:
9597   case Sema::TDK_TooFewArguments:
9598     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9599     return;
9600 
9601   case Sema::TDK_InstantiationDepth:
9602     S.Diag(Templated->getLocation(),
9603            diag::note_ovl_candidate_instantiation_depth);
9604     MaybeEmitInheritedConstructorNote(S, Found);
9605     return;
9606 
9607   case Sema::TDK_SubstitutionFailure: {
9608     // Format the template argument list into the argument string.
9609     SmallString<128> TemplateArgString;
9610     if (TemplateArgumentList *Args =
9611             DeductionFailure.getTemplateArgumentList()) {
9612       TemplateArgString = " ";
9613       TemplateArgString += S.getTemplateArgumentBindingsText(
9614           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9615     }
9616 
9617     // If this candidate was disabled by enable_if, say so.
9618     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9619     if (PDiag && PDiag->second.getDiagID() ==
9620           diag::err_typename_nested_not_found_enable_if) {
9621       // FIXME: Use the source range of the condition, and the fully-qualified
9622       //        name of the enable_if template. These are both present in PDiag.
9623       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9624         << "'enable_if'" << TemplateArgString;
9625       return;
9626     }
9627 
9628     // Format the SFINAE diagnostic into the argument string.
9629     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9630     //        formatted message in another diagnostic.
9631     SmallString<128> SFINAEArgString;
9632     SourceRange R;
9633     if (PDiag) {
9634       SFINAEArgString = ": ";
9635       R = SourceRange(PDiag->first, PDiag->first);
9636       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9637     }
9638 
9639     S.Diag(Templated->getLocation(),
9640            diag::note_ovl_candidate_substitution_failure)
9641         << TemplateArgString << SFINAEArgString << R;
9642     MaybeEmitInheritedConstructorNote(S, Found);
9643     return;
9644   }
9645 
9646   case Sema::TDK_FailedOverloadResolution: {
9647     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9648     S.Diag(Templated->getLocation(),
9649            diag::note_ovl_candidate_failed_overload_resolution)
9650         << R.Expression->getName();
9651     return;
9652   }
9653 
9654   case Sema::TDK_DeducedMismatch: {
9655     // Format the template argument list into the argument string.
9656     SmallString<128> TemplateArgString;
9657     if (TemplateArgumentList *Args =
9658             DeductionFailure.getTemplateArgumentList()) {
9659       TemplateArgString = " ";
9660       TemplateArgString += S.getTemplateArgumentBindingsText(
9661           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9662     }
9663 
9664     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9665         << (*DeductionFailure.getCallArgIndex() + 1)
9666         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9667         << TemplateArgString;
9668     break;
9669   }
9670 
9671   case Sema::TDK_NonDeducedMismatch: {
9672     // FIXME: Provide a source location to indicate what we couldn't match.
9673     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9674     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9675     if (FirstTA.getKind() == TemplateArgument::Template &&
9676         SecondTA.getKind() == TemplateArgument::Template) {
9677       TemplateName FirstTN = FirstTA.getAsTemplate();
9678       TemplateName SecondTN = SecondTA.getAsTemplate();
9679       if (FirstTN.getKind() == TemplateName::Template &&
9680           SecondTN.getKind() == TemplateName::Template) {
9681         if (FirstTN.getAsTemplateDecl()->getName() ==
9682             SecondTN.getAsTemplateDecl()->getName()) {
9683           // FIXME: This fixes a bad diagnostic where both templates are named
9684           // the same.  This particular case is a bit difficult since:
9685           // 1) It is passed as a string to the diagnostic printer.
9686           // 2) The diagnostic printer only attempts to find a better
9687           //    name for types, not decls.
9688           // Ideally, this should folded into the diagnostic printer.
9689           S.Diag(Templated->getLocation(),
9690                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9691               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9692           return;
9693         }
9694       }
9695     }
9696 
9697     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9698         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9699       return;
9700 
9701     // FIXME: For generic lambda parameters, check if the function is a lambda
9702     // call operator, and if so, emit a prettier and more informative
9703     // diagnostic that mentions 'auto' and lambda in addition to
9704     // (or instead of?) the canonical template type parameters.
9705     S.Diag(Templated->getLocation(),
9706            diag::note_ovl_candidate_non_deduced_mismatch)
9707         << FirstTA << SecondTA;
9708     return;
9709   }
9710   // TODO: diagnose these individually, then kill off
9711   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9712   case Sema::TDK_MiscellaneousDeductionFailure:
9713     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9714     MaybeEmitInheritedConstructorNote(S, Found);
9715     return;
9716   case Sema::TDK_CUDATargetMismatch:
9717     S.Diag(Templated->getLocation(),
9718            diag::note_cuda_ovl_candidate_target_mismatch);
9719     return;
9720   }
9721 }
9722 
9723 /// Diagnose a failed template-argument deduction, for function calls.
9724 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9725                                  unsigned NumArgs,
9726                                  bool TakingCandidateAddress) {
9727   unsigned TDK = Cand->DeductionFailure.Result;
9728   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9729     if (CheckArityMismatch(S, Cand, NumArgs))
9730       return;
9731   }
9732   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9733                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9734 }
9735 
9736 /// CUDA: diagnose an invalid call across targets.
9737 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9738   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9739   FunctionDecl *Callee = Cand->Function;
9740 
9741   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9742                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9743 
9744   std::string FnDesc;
9745   OverloadCandidateKind FnKind =
9746       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9747 
9748   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9749       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9750 
9751   // This could be an implicit constructor for which we could not infer the
9752   // target due to a collsion. Diagnose that case.
9753   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9754   if (Meth != nullptr && Meth->isImplicit()) {
9755     CXXRecordDecl *ParentClass = Meth->getParent();
9756     Sema::CXXSpecialMember CSM;
9757 
9758     switch (FnKind) {
9759     default:
9760       return;
9761     case oc_implicit_default_constructor:
9762       CSM = Sema::CXXDefaultConstructor;
9763       break;
9764     case oc_implicit_copy_constructor:
9765       CSM = Sema::CXXCopyConstructor;
9766       break;
9767     case oc_implicit_move_constructor:
9768       CSM = Sema::CXXMoveConstructor;
9769       break;
9770     case oc_implicit_copy_assignment:
9771       CSM = Sema::CXXCopyAssignment;
9772       break;
9773     case oc_implicit_move_assignment:
9774       CSM = Sema::CXXMoveAssignment;
9775       break;
9776     };
9777 
9778     bool ConstRHS = false;
9779     if (Meth->getNumParams()) {
9780       if (const ReferenceType *RT =
9781               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9782         ConstRHS = RT->getPointeeType().isConstQualified();
9783       }
9784     }
9785 
9786     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9787                                               /* ConstRHS */ ConstRHS,
9788                                               /* Diagnose */ true);
9789   }
9790 }
9791 
9792 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9793   FunctionDecl *Callee = Cand->Function;
9794   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9795 
9796   S.Diag(Callee->getLocation(),
9797          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9798       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9799 }
9800 
9801 /// Generates a 'note' diagnostic for an overload candidate.  We've
9802 /// already generated a primary error at the call site.
9803 ///
9804 /// It really does need to be a single diagnostic with its caret
9805 /// pointed at the candidate declaration.  Yes, this creates some
9806 /// major challenges of technical writing.  Yes, this makes pointing
9807 /// out problems with specific arguments quite awkward.  It's still
9808 /// better than generating twenty screens of text for every failed
9809 /// overload.
9810 ///
9811 /// It would be great to be able to express per-candidate problems
9812 /// more richly for those diagnostic clients that cared, but we'd
9813 /// still have to be just as careful with the default diagnostics.
9814 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9815                                   unsigned NumArgs,
9816                                   bool TakingCandidateAddress) {
9817   FunctionDecl *Fn = Cand->Function;
9818 
9819   // Note deleted candidates, but only if they're viable.
9820   if (Cand->Viable && (Fn->isDeleted() ||
9821       S.isFunctionConsideredUnavailable(Fn))) {
9822     std::string FnDesc;
9823     OverloadCandidateKind FnKind =
9824         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9825 
9826     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9827       << FnKind << FnDesc
9828       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9829     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9830     return;
9831   }
9832 
9833   // We don't really have anything else to say about viable candidates.
9834   if (Cand->Viable) {
9835     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9836     return;
9837   }
9838 
9839   switch (Cand->FailureKind) {
9840   case ovl_fail_too_many_arguments:
9841   case ovl_fail_too_few_arguments:
9842     return DiagnoseArityMismatch(S, Cand, NumArgs);
9843 
9844   case ovl_fail_bad_deduction:
9845     return DiagnoseBadDeduction(S, Cand, NumArgs,
9846                                 TakingCandidateAddress);
9847 
9848   case ovl_fail_illegal_constructor: {
9849     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9850       << (Fn->getPrimaryTemplate() ? 1 : 0);
9851     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9852     return;
9853   }
9854 
9855   case ovl_fail_trivial_conversion:
9856   case ovl_fail_bad_final_conversion:
9857   case ovl_fail_final_conversion_not_exact:
9858     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9859 
9860   case ovl_fail_bad_conversion: {
9861     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9862     for (unsigned N = Cand->NumConversions; I != N; ++I)
9863       if (Cand->Conversions[I].isBad())
9864         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9865 
9866     // FIXME: this currently happens when we're called from SemaInit
9867     // when user-conversion overload fails.  Figure out how to handle
9868     // those conditions and diagnose them well.
9869     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9870   }
9871 
9872   case ovl_fail_bad_target:
9873     return DiagnoseBadTarget(S, Cand);
9874 
9875   case ovl_fail_enable_if:
9876     return DiagnoseFailedEnableIfAttr(S, Cand);
9877 
9878   case ovl_fail_addr_not_available: {
9879     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9880     (void)Available;
9881     assert(!Available);
9882     break;
9883   }
9884   }
9885 }
9886 
9887 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9888   // Desugar the type of the surrogate down to a function type,
9889   // retaining as many typedefs as possible while still showing
9890   // the function type (and, therefore, its parameter types).
9891   QualType FnType = Cand->Surrogate->getConversionType();
9892   bool isLValueReference = false;
9893   bool isRValueReference = false;
9894   bool isPointer = false;
9895   if (const LValueReferenceType *FnTypeRef =
9896         FnType->getAs<LValueReferenceType>()) {
9897     FnType = FnTypeRef->getPointeeType();
9898     isLValueReference = true;
9899   } else if (const RValueReferenceType *FnTypeRef =
9900                FnType->getAs<RValueReferenceType>()) {
9901     FnType = FnTypeRef->getPointeeType();
9902     isRValueReference = true;
9903   }
9904   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9905     FnType = FnTypePtr->getPointeeType();
9906     isPointer = true;
9907   }
9908   // Desugar down to a function type.
9909   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9910   // Reconstruct the pointer/reference as appropriate.
9911   if (isPointer) FnType = S.Context.getPointerType(FnType);
9912   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9913   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9914 
9915   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9916     << FnType;
9917 }
9918 
9919 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9920                                          SourceLocation OpLoc,
9921                                          OverloadCandidate *Cand) {
9922   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9923   std::string TypeStr("operator");
9924   TypeStr += Opc;
9925   TypeStr += "(";
9926   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9927   if (Cand->NumConversions == 1) {
9928     TypeStr += ")";
9929     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9930   } else {
9931     TypeStr += ", ";
9932     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9933     TypeStr += ")";
9934     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9935   }
9936 }
9937 
9938 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9939                                          OverloadCandidate *Cand) {
9940   unsigned NoOperands = Cand->NumConversions;
9941   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9942     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9943     if (ICS.isBad()) break; // all meaningless after first invalid
9944     if (!ICS.isAmbiguous()) continue;
9945 
9946     ICS.DiagnoseAmbiguousConversion(
9947         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9948   }
9949 }
9950 
9951 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9952   if (Cand->Function)
9953     return Cand->Function->getLocation();
9954   if (Cand->IsSurrogate)
9955     return Cand->Surrogate->getLocation();
9956   return SourceLocation();
9957 }
9958 
9959 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9960   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9961   case Sema::TDK_Success:
9962     llvm_unreachable("TDK_success while diagnosing bad deduction");
9963 
9964   case Sema::TDK_Invalid:
9965   case Sema::TDK_Incomplete:
9966     return 1;
9967 
9968   case Sema::TDK_Underqualified:
9969   case Sema::TDK_Inconsistent:
9970     return 2;
9971 
9972   case Sema::TDK_SubstitutionFailure:
9973   case Sema::TDK_DeducedMismatch:
9974   case Sema::TDK_NonDeducedMismatch:
9975   case Sema::TDK_MiscellaneousDeductionFailure:
9976   case Sema::TDK_CUDATargetMismatch:
9977     return 3;
9978 
9979   case Sema::TDK_InstantiationDepth:
9980   case Sema::TDK_FailedOverloadResolution:
9981     return 4;
9982 
9983   case Sema::TDK_InvalidExplicitArguments:
9984     return 5;
9985 
9986   case Sema::TDK_TooManyArguments:
9987   case Sema::TDK_TooFewArguments:
9988     return 6;
9989   }
9990   llvm_unreachable("Unhandled deduction result");
9991 }
9992 
9993 namespace {
9994 struct CompareOverloadCandidatesForDisplay {
9995   Sema &S;
9996   SourceLocation Loc;
9997   size_t NumArgs;
9998 
9999   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10000       : S(S), NumArgs(nArgs) {}
10001 
10002   bool operator()(const OverloadCandidate *L,
10003                   const OverloadCandidate *R) {
10004     // Fast-path this check.
10005     if (L == R) return false;
10006 
10007     // Order first by viability.
10008     if (L->Viable) {
10009       if (!R->Viable) return true;
10010 
10011       // TODO: introduce a tri-valued comparison for overload
10012       // candidates.  Would be more worthwhile if we had a sort
10013       // that could exploit it.
10014       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10015       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10016     } else if (R->Viable)
10017       return false;
10018 
10019     assert(L->Viable == R->Viable);
10020 
10021     // Criteria by which we can sort non-viable candidates:
10022     if (!L->Viable) {
10023       // 1. Arity mismatches come after other candidates.
10024       if (L->FailureKind == ovl_fail_too_many_arguments ||
10025           L->FailureKind == ovl_fail_too_few_arguments) {
10026         if (R->FailureKind == ovl_fail_too_many_arguments ||
10027             R->FailureKind == ovl_fail_too_few_arguments) {
10028           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10029           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10030           if (LDist == RDist) {
10031             if (L->FailureKind == R->FailureKind)
10032               // Sort non-surrogates before surrogates.
10033               return !L->IsSurrogate && R->IsSurrogate;
10034             // Sort candidates requiring fewer parameters than there were
10035             // arguments given after candidates requiring more parameters
10036             // than there were arguments given.
10037             return L->FailureKind == ovl_fail_too_many_arguments;
10038           }
10039           return LDist < RDist;
10040         }
10041         return false;
10042       }
10043       if (R->FailureKind == ovl_fail_too_many_arguments ||
10044           R->FailureKind == ovl_fail_too_few_arguments)
10045         return true;
10046 
10047       // 2. Bad conversions come first and are ordered by the number
10048       // of bad conversions and quality of good conversions.
10049       if (L->FailureKind == ovl_fail_bad_conversion) {
10050         if (R->FailureKind != ovl_fail_bad_conversion)
10051           return true;
10052 
10053         // The conversion that can be fixed with a smaller number of changes,
10054         // comes first.
10055         unsigned numLFixes = L->Fix.NumConversionsFixed;
10056         unsigned numRFixes = R->Fix.NumConversionsFixed;
10057         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10058         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10059         if (numLFixes != numRFixes) {
10060           return numLFixes < numRFixes;
10061         }
10062 
10063         // If there's any ordering between the defined conversions...
10064         // FIXME: this might not be transitive.
10065         assert(L->NumConversions == R->NumConversions);
10066 
10067         int leftBetter = 0;
10068         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10069         for (unsigned E = L->NumConversions; I != E; ++I) {
10070           switch (CompareImplicitConversionSequences(S, Loc,
10071                                                      L->Conversions[I],
10072                                                      R->Conversions[I])) {
10073           case ImplicitConversionSequence::Better:
10074             leftBetter++;
10075             break;
10076 
10077           case ImplicitConversionSequence::Worse:
10078             leftBetter--;
10079             break;
10080 
10081           case ImplicitConversionSequence::Indistinguishable:
10082             break;
10083           }
10084         }
10085         if (leftBetter > 0) return true;
10086         if (leftBetter < 0) return false;
10087 
10088       } else if (R->FailureKind == ovl_fail_bad_conversion)
10089         return false;
10090 
10091       if (L->FailureKind == ovl_fail_bad_deduction) {
10092         if (R->FailureKind != ovl_fail_bad_deduction)
10093           return true;
10094 
10095         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10096           return RankDeductionFailure(L->DeductionFailure)
10097                < RankDeductionFailure(R->DeductionFailure);
10098       } else if (R->FailureKind == ovl_fail_bad_deduction)
10099         return false;
10100 
10101       // TODO: others?
10102     }
10103 
10104     // Sort everything else by location.
10105     SourceLocation LLoc = GetLocationForCandidate(L);
10106     SourceLocation RLoc = GetLocationForCandidate(R);
10107 
10108     // Put candidates without locations (e.g. builtins) at the end.
10109     if (LLoc.isInvalid()) return false;
10110     if (RLoc.isInvalid()) return true;
10111 
10112     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10113   }
10114 };
10115 }
10116 
10117 /// CompleteNonViableCandidate - Normally, overload resolution only
10118 /// computes up to the first. Produces the FixIt set if possible.
10119 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10120                                        ArrayRef<Expr *> Args) {
10121   assert(!Cand->Viable);
10122 
10123   // Don't do anything on failures other than bad conversion.
10124   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10125 
10126   // We only want the FixIts if all the arguments can be corrected.
10127   bool Unfixable = false;
10128   // Use a implicit copy initialization to check conversion fixes.
10129   Cand->Fix.setConversionChecker(TryCopyInitialization);
10130 
10131   // Skip forward to the first bad conversion.
10132   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10133   unsigned ConvCount = Cand->NumConversions;
10134   while (true) {
10135     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10136     ConvIdx++;
10137     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10138       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10139       break;
10140     }
10141   }
10142 
10143   if (ConvIdx == ConvCount)
10144     return;
10145 
10146   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10147          "remaining conversion is initialized?");
10148 
10149   // FIXME: this should probably be preserved from the overload
10150   // operation somehow.
10151   bool SuppressUserConversions = false;
10152 
10153   const FunctionProtoType* Proto;
10154   unsigned ArgIdx = ConvIdx;
10155 
10156   if (Cand->IsSurrogate) {
10157     QualType ConvType
10158       = Cand->Surrogate->getConversionType().getNonReferenceType();
10159     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10160       ConvType = ConvPtrType->getPointeeType();
10161     Proto = ConvType->getAs<FunctionProtoType>();
10162     ArgIdx--;
10163   } else if (Cand->Function) {
10164     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10165     if (isa<CXXMethodDecl>(Cand->Function) &&
10166         !isa<CXXConstructorDecl>(Cand->Function))
10167       ArgIdx--;
10168   } else {
10169     // Builtin binary operator with a bad first conversion.
10170     assert(ConvCount <= 3);
10171     for (; ConvIdx != ConvCount; ++ConvIdx)
10172       Cand->Conversions[ConvIdx]
10173         = TryCopyInitialization(S, Args[ConvIdx],
10174                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10175                                 SuppressUserConversions,
10176                                 /*InOverloadResolution*/ true,
10177                                 /*AllowObjCWritebackConversion=*/
10178                                   S.getLangOpts().ObjCAutoRefCount);
10179     return;
10180   }
10181 
10182   // Fill in the rest of the conversions.
10183   unsigned NumParams = Proto->getNumParams();
10184   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10185     if (ArgIdx < NumParams) {
10186       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10187           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10188           /*InOverloadResolution=*/true,
10189           /*AllowObjCWritebackConversion=*/
10190           S.getLangOpts().ObjCAutoRefCount);
10191       // Store the FixIt in the candidate if it exists.
10192       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10193         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10194     }
10195     else
10196       Cand->Conversions[ConvIdx].setEllipsis();
10197   }
10198 }
10199 
10200 /// PrintOverloadCandidates - When overload resolution fails, prints
10201 /// diagnostic messages containing the candidates in the candidate
10202 /// set.
10203 void OverloadCandidateSet::NoteCandidates(
10204     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10205     StringRef Opc, SourceLocation OpLoc,
10206     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10207   // Sort the candidates by viability and position.  Sorting directly would
10208   // be prohibitive, so we make a set of pointers and sort those.
10209   SmallVector<OverloadCandidate*, 32> Cands;
10210   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10211   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10212     if (!Filter(*Cand))
10213       continue;
10214     if (Cand->Viable)
10215       Cands.push_back(Cand);
10216     else if (OCD == OCD_AllCandidates) {
10217       CompleteNonViableCandidate(S, Cand, Args);
10218       if (Cand->Function || Cand->IsSurrogate)
10219         Cands.push_back(Cand);
10220       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10221       // want to list every possible builtin candidate.
10222     }
10223   }
10224 
10225   std::sort(Cands.begin(), Cands.end(),
10226             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10227 
10228   bool ReportedAmbiguousConversions = false;
10229 
10230   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10231   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10232   unsigned CandsShown = 0;
10233   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10234     OverloadCandidate *Cand = *I;
10235 
10236     // Set an arbitrary limit on the number of candidate functions we'll spam
10237     // the user with.  FIXME: This limit should depend on details of the
10238     // candidate list.
10239     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10240       break;
10241     }
10242     ++CandsShown;
10243 
10244     if (Cand->Function)
10245       NoteFunctionCandidate(S, Cand, Args.size(),
10246                             /*TakingCandidateAddress=*/false);
10247     else if (Cand->IsSurrogate)
10248       NoteSurrogateCandidate(S, Cand);
10249     else {
10250       assert(Cand->Viable &&
10251              "Non-viable built-in candidates are not added to Cands.");
10252       // Generally we only see ambiguities including viable builtin
10253       // operators if overload resolution got screwed up by an
10254       // ambiguous user-defined conversion.
10255       //
10256       // FIXME: It's quite possible for different conversions to see
10257       // different ambiguities, though.
10258       if (!ReportedAmbiguousConversions) {
10259         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10260         ReportedAmbiguousConversions = true;
10261       }
10262 
10263       // If this is a viable builtin, print it.
10264       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10265     }
10266   }
10267 
10268   if (I != E)
10269     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10270 }
10271 
10272 static SourceLocation
10273 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10274   return Cand->Specialization ? Cand->Specialization->getLocation()
10275                               : SourceLocation();
10276 }
10277 
10278 namespace {
10279 struct CompareTemplateSpecCandidatesForDisplay {
10280   Sema &S;
10281   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10282 
10283   bool operator()(const TemplateSpecCandidate *L,
10284                   const TemplateSpecCandidate *R) {
10285     // Fast-path this check.
10286     if (L == R)
10287       return false;
10288 
10289     // Assuming that both candidates are not matches...
10290 
10291     // Sort by the ranking of deduction failures.
10292     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10293       return RankDeductionFailure(L->DeductionFailure) <
10294              RankDeductionFailure(R->DeductionFailure);
10295 
10296     // Sort everything else by location.
10297     SourceLocation LLoc = GetLocationForCandidate(L);
10298     SourceLocation RLoc = GetLocationForCandidate(R);
10299 
10300     // Put candidates without locations (e.g. builtins) at the end.
10301     if (LLoc.isInvalid())
10302       return false;
10303     if (RLoc.isInvalid())
10304       return true;
10305 
10306     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10307   }
10308 };
10309 }
10310 
10311 /// Diagnose a template argument deduction failure.
10312 /// We are treating these failures as overload failures due to bad
10313 /// deductions.
10314 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10315                                                  bool ForTakingAddress) {
10316   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10317                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10318 }
10319 
10320 void TemplateSpecCandidateSet::destroyCandidates() {
10321   for (iterator i = begin(), e = end(); i != e; ++i) {
10322     i->DeductionFailure.Destroy();
10323   }
10324 }
10325 
10326 void TemplateSpecCandidateSet::clear() {
10327   destroyCandidates();
10328   Candidates.clear();
10329 }
10330 
10331 /// NoteCandidates - When no template specialization match is found, prints
10332 /// diagnostic messages containing the non-matching specializations that form
10333 /// the candidate set.
10334 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10335 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10336 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10337   // Sort the candidates by position (assuming no candidate is a match).
10338   // Sorting directly would be prohibitive, so we make a set of pointers
10339   // and sort those.
10340   SmallVector<TemplateSpecCandidate *, 32> Cands;
10341   Cands.reserve(size());
10342   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10343     if (Cand->Specialization)
10344       Cands.push_back(Cand);
10345     // Otherwise, this is a non-matching builtin candidate.  We do not,
10346     // in general, want to list every possible builtin candidate.
10347   }
10348 
10349   std::sort(Cands.begin(), Cands.end(),
10350             CompareTemplateSpecCandidatesForDisplay(S));
10351 
10352   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10353   // for generalization purposes (?).
10354   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10355 
10356   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10357   unsigned CandsShown = 0;
10358   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10359     TemplateSpecCandidate *Cand = *I;
10360 
10361     // Set an arbitrary limit on the number of candidates we'll spam
10362     // the user with.  FIXME: This limit should depend on details of the
10363     // candidate list.
10364     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10365       break;
10366     ++CandsShown;
10367 
10368     assert(Cand->Specialization &&
10369            "Non-matching built-in candidates are not added to Cands.");
10370     Cand->NoteDeductionFailure(S, ForTakingAddress);
10371   }
10372 
10373   if (I != E)
10374     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10375 }
10376 
10377 // [PossiblyAFunctionType]  -->   [Return]
10378 // NonFunctionType --> NonFunctionType
10379 // R (A) --> R(A)
10380 // R (*)(A) --> R (A)
10381 // R (&)(A) --> R (A)
10382 // R (S::*)(A) --> R (A)
10383 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10384   QualType Ret = PossiblyAFunctionType;
10385   if (const PointerType *ToTypePtr =
10386     PossiblyAFunctionType->getAs<PointerType>())
10387     Ret = ToTypePtr->getPointeeType();
10388   else if (const ReferenceType *ToTypeRef =
10389     PossiblyAFunctionType->getAs<ReferenceType>())
10390     Ret = ToTypeRef->getPointeeType();
10391   else if (const MemberPointerType *MemTypePtr =
10392     PossiblyAFunctionType->getAs<MemberPointerType>())
10393     Ret = MemTypePtr->getPointeeType();
10394   Ret =
10395     Context.getCanonicalType(Ret).getUnqualifiedType();
10396   return Ret;
10397 }
10398 
10399 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10400                                  bool Complain = true) {
10401   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10402       S.DeduceReturnType(FD, Loc, Complain))
10403     return true;
10404 
10405   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10406   if (S.getLangOpts().CPlusPlus1z &&
10407       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10408       !S.ResolveExceptionSpec(Loc, FPT))
10409     return true;
10410 
10411   return false;
10412 }
10413 
10414 namespace {
10415 // A helper class to help with address of function resolution
10416 // - allows us to avoid passing around all those ugly parameters
10417 class AddressOfFunctionResolver {
10418   Sema& S;
10419   Expr* SourceExpr;
10420   const QualType& TargetType;
10421   QualType TargetFunctionType; // Extracted function type from target type
10422 
10423   bool Complain;
10424   //DeclAccessPair& ResultFunctionAccessPair;
10425   ASTContext& Context;
10426 
10427   bool TargetTypeIsNonStaticMemberFunction;
10428   bool FoundNonTemplateFunction;
10429   bool StaticMemberFunctionFromBoundPointer;
10430   bool HasComplained;
10431 
10432   OverloadExpr::FindResult OvlExprInfo;
10433   OverloadExpr *OvlExpr;
10434   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10435   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10436   TemplateSpecCandidateSet FailedCandidates;
10437 
10438 public:
10439   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10440                             const QualType &TargetType, bool Complain)
10441       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10442         Complain(Complain), Context(S.getASTContext()),
10443         TargetTypeIsNonStaticMemberFunction(
10444             !!TargetType->getAs<MemberPointerType>()),
10445         FoundNonTemplateFunction(false),
10446         StaticMemberFunctionFromBoundPointer(false),
10447         HasComplained(false),
10448         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10449         OvlExpr(OvlExprInfo.Expression),
10450         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10451     ExtractUnqualifiedFunctionTypeFromTargetType();
10452 
10453     if (TargetFunctionType->isFunctionType()) {
10454       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10455         if (!UME->isImplicitAccess() &&
10456             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10457           StaticMemberFunctionFromBoundPointer = true;
10458     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10459       DeclAccessPair dap;
10460       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10461               OvlExpr, false, &dap)) {
10462         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10463           if (!Method->isStatic()) {
10464             // If the target type is a non-function type and the function found
10465             // is a non-static member function, pretend as if that was the
10466             // target, it's the only possible type to end up with.
10467             TargetTypeIsNonStaticMemberFunction = true;
10468 
10469             // And skip adding the function if its not in the proper form.
10470             // We'll diagnose this due to an empty set of functions.
10471             if (!OvlExprInfo.HasFormOfMemberPointer)
10472               return;
10473           }
10474 
10475         Matches.push_back(std::make_pair(dap, Fn));
10476       }
10477       return;
10478     }
10479 
10480     if (OvlExpr->hasExplicitTemplateArgs())
10481       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10482 
10483     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10484       // C++ [over.over]p4:
10485       //   If more than one function is selected, [...]
10486       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10487         if (FoundNonTemplateFunction)
10488           EliminateAllTemplateMatches();
10489         else
10490           EliminateAllExceptMostSpecializedTemplate();
10491       }
10492     }
10493 
10494     if (S.getLangOpts().CUDA && Matches.size() > 1)
10495       EliminateSuboptimalCudaMatches();
10496   }
10497 
10498   bool hasComplained() const { return HasComplained; }
10499 
10500 private:
10501   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10502     QualType Discard;
10503     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10504            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10505   }
10506 
10507   /// \return true if A is considered a better overload candidate for the
10508   /// desired type than B.
10509   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10510     // If A doesn't have exactly the correct type, we don't want to classify it
10511     // as "better" than anything else. This way, the user is required to
10512     // disambiguate for us if there are multiple candidates and no exact match.
10513     return candidateHasExactlyCorrectType(A) &&
10514            (!candidateHasExactlyCorrectType(B) ||
10515             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10516   }
10517 
10518   /// \return true if we were able to eliminate all but one overload candidate,
10519   /// false otherwise.
10520   bool eliminiateSuboptimalOverloadCandidates() {
10521     // Same algorithm as overload resolution -- one pass to pick the "best",
10522     // another pass to be sure that nothing is better than the best.
10523     auto Best = Matches.begin();
10524     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10525       if (isBetterCandidate(I->second, Best->second))
10526         Best = I;
10527 
10528     const FunctionDecl *BestFn = Best->second;
10529     auto IsBestOrInferiorToBest = [this, BestFn](
10530         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10531       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10532     };
10533 
10534     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10535     // option, so we can potentially give the user a better error
10536     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10537       return false;
10538     Matches[0] = *Best;
10539     Matches.resize(1);
10540     return true;
10541   }
10542 
10543   bool isTargetTypeAFunction() const {
10544     return TargetFunctionType->isFunctionType();
10545   }
10546 
10547   // [ToType]     [Return]
10548 
10549   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10550   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10551   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10552   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10553     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10554   }
10555 
10556   // return true if any matching specializations were found
10557   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10558                                    const DeclAccessPair& CurAccessFunPair) {
10559     if (CXXMethodDecl *Method
10560               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10561       // Skip non-static function templates when converting to pointer, and
10562       // static when converting to member pointer.
10563       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10564         return false;
10565     }
10566     else if (TargetTypeIsNonStaticMemberFunction)
10567       return false;
10568 
10569     // C++ [over.over]p2:
10570     //   If the name is a function template, template argument deduction is
10571     //   done (14.8.2.2), and if the argument deduction succeeds, the
10572     //   resulting template argument list is used to generate a single
10573     //   function template specialization, which is added to the set of
10574     //   overloaded functions considered.
10575     FunctionDecl *Specialization = nullptr;
10576     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10577     if (Sema::TemplateDeductionResult Result
10578           = S.DeduceTemplateArguments(FunctionTemplate,
10579                                       &OvlExplicitTemplateArgs,
10580                                       TargetFunctionType, Specialization,
10581                                       Info, /*IsAddressOfFunction*/true)) {
10582       // Make a note of the failed deduction for diagnostics.
10583       FailedCandidates.addCandidate()
10584           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10585                MakeDeductionFailureInfo(Context, Result, Info));
10586       return false;
10587     }
10588 
10589     // Template argument deduction ensures that we have an exact match or
10590     // compatible pointer-to-function arguments that would be adjusted by ICS.
10591     // This function template specicalization works.
10592     assert(S.isSameOrCompatibleFunctionType(
10593               Context.getCanonicalType(Specialization->getType()),
10594               Context.getCanonicalType(TargetFunctionType)));
10595 
10596     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10597       return false;
10598 
10599     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10600     return true;
10601   }
10602 
10603   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10604                                       const DeclAccessPair& CurAccessFunPair) {
10605     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10606       // Skip non-static functions when converting to pointer, and static
10607       // when converting to member pointer.
10608       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10609         return false;
10610     }
10611     else if (TargetTypeIsNonStaticMemberFunction)
10612       return false;
10613 
10614     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10615       if (S.getLangOpts().CUDA)
10616         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10617           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10618             return false;
10619 
10620       // If any candidate has a placeholder return type, trigger its deduction
10621       // now.
10622       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10623                                Complain)) {
10624         HasComplained |= Complain;
10625         return false;
10626       }
10627 
10628       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10629         return false;
10630 
10631       // If we're in C, we need to support types that aren't exactly identical.
10632       if (!S.getLangOpts().CPlusPlus ||
10633           candidateHasExactlyCorrectType(FunDecl)) {
10634         Matches.push_back(std::make_pair(
10635             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10636         FoundNonTemplateFunction = true;
10637         return true;
10638       }
10639     }
10640 
10641     return false;
10642   }
10643 
10644   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10645     bool Ret = false;
10646 
10647     // If the overload expression doesn't have the form of a pointer to
10648     // member, don't try to convert it to a pointer-to-member type.
10649     if (IsInvalidFormOfPointerToMemberFunction())
10650       return false;
10651 
10652     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10653                                E = OvlExpr->decls_end();
10654          I != E; ++I) {
10655       // Look through any using declarations to find the underlying function.
10656       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10657 
10658       // C++ [over.over]p3:
10659       //   Non-member functions and static member functions match
10660       //   targets of type "pointer-to-function" or "reference-to-function."
10661       //   Nonstatic member functions match targets of
10662       //   type "pointer-to-member-function."
10663       // Note that according to DR 247, the containing class does not matter.
10664       if (FunctionTemplateDecl *FunctionTemplate
10665                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10666         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10667           Ret = true;
10668       }
10669       // If we have explicit template arguments supplied, skip non-templates.
10670       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10671                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10672         Ret = true;
10673     }
10674     assert(Ret || Matches.empty());
10675     return Ret;
10676   }
10677 
10678   void EliminateAllExceptMostSpecializedTemplate() {
10679     //   [...] and any given function template specialization F1 is
10680     //   eliminated if the set contains a second function template
10681     //   specialization whose function template is more specialized
10682     //   than the function template of F1 according to the partial
10683     //   ordering rules of 14.5.5.2.
10684 
10685     // The algorithm specified above is quadratic. We instead use a
10686     // two-pass algorithm (similar to the one used to identify the
10687     // best viable function in an overload set) that identifies the
10688     // best function template (if it exists).
10689 
10690     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10691     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10692       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10693 
10694     // TODO: It looks like FailedCandidates does not serve much purpose
10695     // here, since the no_viable diagnostic has index 0.
10696     UnresolvedSetIterator Result = S.getMostSpecialized(
10697         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10698         SourceExpr->getLocStart(), S.PDiag(),
10699         S.PDiag(diag::err_addr_ovl_ambiguous)
10700           << Matches[0].second->getDeclName(),
10701         S.PDiag(diag::note_ovl_candidate)
10702           << (unsigned)oc_function_template,
10703         Complain, TargetFunctionType);
10704 
10705     if (Result != MatchesCopy.end()) {
10706       // Make it the first and only element
10707       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10708       Matches[0].second = cast<FunctionDecl>(*Result);
10709       Matches.resize(1);
10710     } else
10711       HasComplained |= Complain;
10712   }
10713 
10714   void EliminateAllTemplateMatches() {
10715     //   [...] any function template specializations in the set are
10716     //   eliminated if the set also contains a non-template function, [...]
10717     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10718       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10719         ++I;
10720       else {
10721         Matches[I] = Matches[--N];
10722         Matches.resize(N);
10723       }
10724     }
10725   }
10726 
10727   void EliminateSuboptimalCudaMatches() {
10728     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10729   }
10730 
10731 public:
10732   void ComplainNoMatchesFound() const {
10733     assert(Matches.empty());
10734     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10735         << OvlExpr->getName() << TargetFunctionType
10736         << OvlExpr->getSourceRange();
10737     if (FailedCandidates.empty())
10738       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10739                                   /*TakingAddress=*/true);
10740     else {
10741       // We have some deduction failure messages. Use them to diagnose
10742       // the function templates, and diagnose the non-template candidates
10743       // normally.
10744       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10745                                  IEnd = OvlExpr->decls_end();
10746            I != IEnd; ++I)
10747         if (FunctionDecl *Fun =
10748                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10749           if (!functionHasPassObjectSizeParams(Fun))
10750             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10751                                     /*TakingAddress=*/true);
10752       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10753     }
10754   }
10755 
10756   bool IsInvalidFormOfPointerToMemberFunction() const {
10757     return TargetTypeIsNonStaticMemberFunction &&
10758       !OvlExprInfo.HasFormOfMemberPointer;
10759   }
10760 
10761   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10762       // TODO: Should we condition this on whether any functions might
10763       // have matched, or is it more appropriate to do that in callers?
10764       // TODO: a fixit wouldn't hurt.
10765       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10766         << TargetType << OvlExpr->getSourceRange();
10767   }
10768 
10769   bool IsStaticMemberFunctionFromBoundPointer() const {
10770     return StaticMemberFunctionFromBoundPointer;
10771   }
10772 
10773   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10774     S.Diag(OvlExpr->getLocStart(),
10775            diag::err_invalid_form_pointer_member_function)
10776       << OvlExpr->getSourceRange();
10777   }
10778 
10779   void ComplainOfInvalidConversion() const {
10780     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10781       << OvlExpr->getName() << TargetType;
10782   }
10783 
10784   void ComplainMultipleMatchesFound() const {
10785     assert(Matches.size() > 1);
10786     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10787       << OvlExpr->getName()
10788       << OvlExpr->getSourceRange();
10789     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10790                                 /*TakingAddress=*/true);
10791   }
10792 
10793   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10794 
10795   int getNumMatches() const { return Matches.size(); }
10796 
10797   FunctionDecl* getMatchingFunctionDecl() const {
10798     if (Matches.size() != 1) return nullptr;
10799     return Matches[0].second;
10800   }
10801 
10802   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10803     if (Matches.size() != 1) return nullptr;
10804     return &Matches[0].first;
10805   }
10806 };
10807 }
10808 
10809 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10810 /// an overloaded function (C++ [over.over]), where @p From is an
10811 /// expression with overloaded function type and @p ToType is the type
10812 /// we're trying to resolve to. For example:
10813 ///
10814 /// @code
10815 /// int f(double);
10816 /// int f(int);
10817 ///
10818 /// int (*pfd)(double) = f; // selects f(double)
10819 /// @endcode
10820 ///
10821 /// This routine returns the resulting FunctionDecl if it could be
10822 /// resolved, and NULL otherwise. When @p Complain is true, this
10823 /// routine will emit diagnostics if there is an error.
10824 FunctionDecl *
10825 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10826                                          QualType TargetType,
10827                                          bool Complain,
10828                                          DeclAccessPair &FoundResult,
10829                                          bool *pHadMultipleCandidates) {
10830   assert(AddressOfExpr->getType() == Context.OverloadTy);
10831 
10832   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10833                                      Complain);
10834   int NumMatches = Resolver.getNumMatches();
10835   FunctionDecl *Fn = nullptr;
10836   bool ShouldComplain = Complain && !Resolver.hasComplained();
10837   if (NumMatches == 0 && ShouldComplain) {
10838     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10839       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10840     else
10841       Resolver.ComplainNoMatchesFound();
10842   }
10843   else if (NumMatches > 1 && ShouldComplain)
10844     Resolver.ComplainMultipleMatchesFound();
10845   else if (NumMatches == 1) {
10846     Fn = Resolver.getMatchingFunctionDecl();
10847     assert(Fn);
10848     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10849       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
10850     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10851     if (Complain) {
10852       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10853         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10854       else
10855         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10856     }
10857   }
10858 
10859   if (pHadMultipleCandidates)
10860     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10861   return Fn;
10862 }
10863 
10864 /// \brief Given an expression that refers to an overloaded function, try to
10865 /// resolve that function to a single function that can have its address taken.
10866 /// This will modify `Pair` iff it returns non-null.
10867 ///
10868 /// This routine can only realistically succeed if all but one candidates in the
10869 /// overload set for SrcExpr cannot have their addresses taken.
10870 FunctionDecl *
10871 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10872                                                   DeclAccessPair &Pair) {
10873   OverloadExpr::FindResult R = OverloadExpr::find(E);
10874   OverloadExpr *Ovl = R.Expression;
10875   FunctionDecl *Result = nullptr;
10876   DeclAccessPair DAP;
10877   // Don't use the AddressOfResolver because we're specifically looking for
10878   // cases where we have one overload candidate that lacks
10879   // enable_if/pass_object_size/...
10880   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10881     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10882     if (!FD)
10883       return nullptr;
10884 
10885     if (!checkAddressOfFunctionIsAvailable(FD))
10886       continue;
10887 
10888     // We have more than one result; quit.
10889     if (Result)
10890       return nullptr;
10891     DAP = I.getPair();
10892     Result = FD;
10893   }
10894 
10895   if (Result)
10896     Pair = DAP;
10897   return Result;
10898 }
10899 
10900 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10901 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10902 /// will perform access checks, diagnose the use of the resultant decl, and, if
10903 /// necessary, perform a function-to-pointer decay.
10904 ///
10905 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10906 /// Otherwise, returns true. This may emit diagnostics and return true.
10907 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10908     ExprResult &SrcExpr) {
10909   Expr *E = SrcExpr.get();
10910   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10911 
10912   DeclAccessPair DAP;
10913   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10914   if (!Found)
10915     return false;
10916 
10917   // Emitting multiple diagnostics for a function that is both inaccessible and
10918   // unavailable is consistent with our behavior elsewhere. So, always check
10919   // for both.
10920   DiagnoseUseOfDecl(Found, E->getExprLoc());
10921   CheckAddressOfMemberAccess(E, DAP);
10922   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10923   if (Fixed->getType()->isFunctionType())
10924     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10925   else
10926     SrcExpr = Fixed;
10927   return true;
10928 }
10929 
10930 /// \brief Given an expression that refers to an overloaded function, try to
10931 /// resolve that overloaded function expression down to a single function.
10932 ///
10933 /// This routine can only resolve template-ids that refer to a single function
10934 /// template, where that template-id refers to a single template whose template
10935 /// arguments are either provided by the template-id or have defaults,
10936 /// as described in C++0x [temp.arg.explicit]p3.
10937 ///
10938 /// If no template-ids are found, no diagnostics are emitted and NULL is
10939 /// returned.
10940 FunctionDecl *
10941 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10942                                                   bool Complain,
10943                                                   DeclAccessPair *FoundResult) {
10944   // C++ [over.over]p1:
10945   //   [...] [Note: any redundant set of parentheses surrounding the
10946   //   overloaded function name is ignored (5.1). ]
10947   // C++ [over.over]p1:
10948   //   [...] The overloaded function name can be preceded by the &
10949   //   operator.
10950 
10951   // If we didn't actually find any template-ids, we're done.
10952   if (!ovl->hasExplicitTemplateArgs())
10953     return nullptr;
10954 
10955   TemplateArgumentListInfo ExplicitTemplateArgs;
10956   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10957   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10958 
10959   // Look through all of the overloaded functions, searching for one
10960   // whose type matches exactly.
10961   FunctionDecl *Matched = nullptr;
10962   for (UnresolvedSetIterator I = ovl->decls_begin(),
10963          E = ovl->decls_end(); I != E; ++I) {
10964     // C++0x [temp.arg.explicit]p3:
10965     //   [...] In contexts where deduction is done and fails, or in contexts
10966     //   where deduction is not done, if a template argument list is
10967     //   specified and it, along with any default template arguments,
10968     //   identifies a single function template specialization, then the
10969     //   template-id is an lvalue for the function template specialization.
10970     FunctionTemplateDecl *FunctionTemplate
10971       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10972 
10973     // C++ [over.over]p2:
10974     //   If the name is a function template, template argument deduction is
10975     //   done (14.8.2.2), and if the argument deduction succeeds, the
10976     //   resulting template argument list is used to generate a single
10977     //   function template specialization, which is added to the set of
10978     //   overloaded functions considered.
10979     FunctionDecl *Specialization = nullptr;
10980     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10981     if (TemplateDeductionResult Result
10982           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10983                                     Specialization, Info,
10984                                     /*IsAddressOfFunction*/true)) {
10985       // Make a note of the failed deduction for diagnostics.
10986       // TODO: Actually use the failed-deduction info?
10987       FailedCandidates.addCandidate()
10988           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10989                MakeDeductionFailureInfo(Context, Result, Info));
10990       continue;
10991     }
10992 
10993     assert(Specialization && "no specialization and no error?");
10994 
10995     // Multiple matches; we can't resolve to a single declaration.
10996     if (Matched) {
10997       if (Complain) {
10998         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10999           << ovl->getName();
11000         NoteAllOverloadCandidates(ovl);
11001       }
11002       return nullptr;
11003     }
11004 
11005     Matched = Specialization;
11006     if (FoundResult) *FoundResult = I.getPair();
11007   }
11008 
11009   if (Matched &&
11010       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11011     return nullptr;
11012 
11013   return Matched;
11014 }
11015 
11016 
11017 
11018 
11019 // Resolve and fix an overloaded expression that can be resolved
11020 // because it identifies a single function template specialization.
11021 //
11022 // Last three arguments should only be supplied if Complain = true
11023 //
11024 // Return true if it was logically possible to so resolve the
11025 // expression, regardless of whether or not it succeeded.  Always
11026 // returns true if 'complain' is set.
11027 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11028                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11029                       bool complain, SourceRange OpRangeForComplaining,
11030                                            QualType DestTypeForComplaining,
11031                                             unsigned DiagIDForComplaining) {
11032   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11033 
11034   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11035 
11036   DeclAccessPair found;
11037   ExprResult SingleFunctionExpression;
11038   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11039                            ovl.Expression, /*complain*/ false, &found)) {
11040     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11041       SrcExpr = ExprError();
11042       return true;
11043     }
11044 
11045     // It is only correct to resolve to an instance method if we're
11046     // resolving a form that's permitted to be a pointer to member.
11047     // Otherwise we'll end up making a bound member expression, which
11048     // is illegal in all the contexts we resolve like this.
11049     if (!ovl.HasFormOfMemberPointer &&
11050         isa<CXXMethodDecl>(fn) &&
11051         cast<CXXMethodDecl>(fn)->isInstance()) {
11052       if (!complain) return false;
11053 
11054       Diag(ovl.Expression->getExprLoc(),
11055            diag::err_bound_member_function)
11056         << 0 << ovl.Expression->getSourceRange();
11057 
11058       // TODO: I believe we only end up here if there's a mix of
11059       // static and non-static candidates (otherwise the expression
11060       // would have 'bound member' type, not 'overload' type).
11061       // Ideally we would note which candidate was chosen and why
11062       // the static candidates were rejected.
11063       SrcExpr = ExprError();
11064       return true;
11065     }
11066 
11067     // Fix the expression to refer to 'fn'.
11068     SingleFunctionExpression =
11069         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11070 
11071     // If desired, do function-to-pointer decay.
11072     if (doFunctionPointerConverion) {
11073       SingleFunctionExpression =
11074         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11075       if (SingleFunctionExpression.isInvalid()) {
11076         SrcExpr = ExprError();
11077         return true;
11078       }
11079     }
11080   }
11081 
11082   if (!SingleFunctionExpression.isUsable()) {
11083     if (complain) {
11084       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11085         << ovl.Expression->getName()
11086         << DestTypeForComplaining
11087         << OpRangeForComplaining
11088         << ovl.Expression->getQualifierLoc().getSourceRange();
11089       NoteAllOverloadCandidates(SrcExpr.get());
11090 
11091       SrcExpr = ExprError();
11092       return true;
11093     }
11094 
11095     return false;
11096   }
11097 
11098   SrcExpr = SingleFunctionExpression;
11099   return true;
11100 }
11101 
11102 /// \brief Add a single candidate to the overload set.
11103 static void AddOverloadedCallCandidate(Sema &S,
11104                                        DeclAccessPair FoundDecl,
11105                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11106                                        ArrayRef<Expr *> Args,
11107                                        OverloadCandidateSet &CandidateSet,
11108                                        bool PartialOverloading,
11109                                        bool KnownValid) {
11110   NamedDecl *Callee = FoundDecl.getDecl();
11111   if (isa<UsingShadowDecl>(Callee))
11112     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11113 
11114   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11115     if (ExplicitTemplateArgs) {
11116       assert(!KnownValid && "Explicit template arguments?");
11117       return;
11118     }
11119     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11120                            /*SuppressUsedConversions=*/false,
11121                            PartialOverloading);
11122     return;
11123   }
11124 
11125   if (FunctionTemplateDecl *FuncTemplate
11126       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11127     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11128                                    ExplicitTemplateArgs, Args, CandidateSet,
11129                                    /*SuppressUsedConversions=*/false,
11130                                    PartialOverloading);
11131     return;
11132   }
11133 
11134   assert(!KnownValid && "unhandled case in overloaded call candidate");
11135 }
11136 
11137 /// \brief Add the overload candidates named by callee and/or found by argument
11138 /// dependent lookup to the given overload set.
11139 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11140                                        ArrayRef<Expr *> Args,
11141                                        OverloadCandidateSet &CandidateSet,
11142                                        bool PartialOverloading) {
11143 
11144 #ifndef NDEBUG
11145   // Verify that ArgumentDependentLookup is consistent with the rules
11146   // in C++0x [basic.lookup.argdep]p3:
11147   //
11148   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11149   //   and let Y be the lookup set produced by argument dependent
11150   //   lookup (defined as follows). If X contains
11151   //
11152   //     -- a declaration of a class member, or
11153   //
11154   //     -- a block-scope function declaration that is not a
11155   //        using-declaration, or
11156   //
11157   //     -- a declaration that is neither a function or a function
11158   //        template
11159   //
11160   //   then Y is empty.
11161 
11162   if (ULE->requiresADL()) {
11163     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11164            E = ULE->decls_end(); I != E; ++I) {
11165       assert(!(*I)->getDeclContext()->isRecord());
11166       assert(isa<UsingShadowDecl>(*I) ||
11167              !(*I)->getDeclContext()->isFunctionOrMethod());
11168       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11169     }
11170   }
11171 #endif
11172 
11173   // It would be nice to avoid this copy.
11174   TemplateArgumentListInfo TABuffer;
11175   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11176   if (ULE->hasExplicitTemplateArgs()) {
11177     ULE->copyTemplateArgumentsInto(TABuffer);
11178     ExplicitTemplateArgs = &TABuffer;
11179   }
11180 
11181   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11182          E = ULE->decls_end(); I != E; ++I)
11183     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11184                                CandidateSet, PartialOverloading,
11185                                /*KnownValid*/ true);
11186 
11187   if (ULE->requiresADL())
11188     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11189                                          Args, ExplicitTemplateArgs,
11190                                          CandidateSet, PartialOverloading);
11191 }
11192 
11193 /// Determine whether a declaration with the specified name could be moved into
11194 /// a different namespace.
11195 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11196   switch (Name.getCXXOverloadedOperator()) {
11197   case OO_New: case OO_Array_New:
11198   case OO_Delete: case OO_Array_Delete:
11199     return false;
11200 
11201   default:
11202     return true;
11203   }
11204 }
11205 
11206 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11207 /// template, where the non-dependent name was declared after the template
11208 /// was defined. This is common in code written for a compilers which do not
11209 /// correctly implement two-stage name lookup.
11210 ///
11211 /// Returns true if a viable candidate was found and a diagnostic was issued.
11212 static bool
11213 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11214                        const CXXScopeSpec &SS, LookupResult &R,
11215                        OverloadCandidateSet::CandidateSetKind CSK,
11216                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11217                        ArrayRef<Expr *> Args,
11218                        bool *DoDiagnoseEmptyLookup = nullptr) {
11219   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11220     return false;
11221 
11222   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11223     if (DC->isTransparentContext())
11224       continue;
11225 
11226     SemaRef.LookupQualifiedName(R, DC);
11227 
11228     if (!R.empty()) {
11229       R.suppressDiagnostics();
11230 
11231       if (isa<CXXRecordDecl>(DC)) {
11232         // Don't diagnose names we find in classes; we get much better
11233         // diagnostics for these from DiagnoseEmptyLookup.
11234         R.clear();
11235         if (DoDiagnoseEmptyLookup)
11236           *DoDiagnoseEmptyLookup = true;
11237         return false;
11238       }
11239 
11240       OverloadCandidateSet Candidates(FnLoc, CSK);
11241       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11242         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11243                                    ExplicitTemplateArgs, Args,
11244                                    Candidates, false, /*KnownValid*/ false);
11245 
11246       OverloadCandidateSet::iterator Best;
11247       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11248         // No viable functions. Don't bother the user with notes for functions
11249         // which don't work and shouldn't be found anyway.
11250         R.clear();
11251         return false;
11252       }
11253 
11254       // Find the namespaces where ADL would have looked, and suggest
11255       // declaring the function there instead.
11256       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11257       Sema::AssociatedClassSet AssociatedClasses;
11258       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11259                                                  AssociatedNamespaces,
11260                                                  AssociatedClasses);
11261       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11262       if (canBeDeclaredInNamespace(R.getLookupName())) {
11263         DeclContext *Std = SemaRef.getStdNamespace();
11264         for (Sema::AssociatedNamespaceSet::iterator
11265                it = AssociatedNamespaces.begin(),
11266                end = AssociatedNamespaces.end(); it != end; ++it) {
11267           // Never suggest declaring a function within namespace 'std'.
11268           if (Std && Std->Encloses(*it))
11269             continue;
11270 
11271           // Never suggest declaring a function within a namespace with a
11272           // reserved name, like __gnu_cxx.
11273           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11274           if (NS &&
11275               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11276             continue;
11277 
11278           SuggestedNamespaces.insert(*it);
11279         }
11280       }
11281 
11282       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11283         << R.getLookupName();
11284       if (SuggestedNamespaces.empty()) {
11285         SemaRef.Diag(Best->Function->getLocation(),
11286                      diag::note_not_found_by_two_phase_lookup)
11287           << R.getLookupName() << 0;
11288       } else if (SuggestedNamespaces.size() == 1) {
11289         SemaRef.Diag(Best->Function->getLocation(),
11290                      diag::note_not_found_by_two_phase_lookup)
11291           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11292       } else {
11293         // FIXME: It would be useful to list the associated namespaces here,
11294         // but the diagnostics infrastructure doesn't provide a way to produce
11295         // a localized representation of a list of items.
11296         SemaRef.Diag(Best->Function->getLocation(),
11297                      diag::note_not_found_by_two_phase_lookup)
11298           << R.getLookupName() << 2;
11299       }
11300 
11301       // Try to recover by calling this function.
11302       return true;
11303     }
11304 
11305     R.clear();
11306   }
11307 
11308   return false;
11309 }
11310 
11311 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11312 /// template, where the non-dependent operator was declared after the template
11313 /// was defined.
11314 ///
11315 /// Returns true if a viable candidate was found and a diagnostic was issued.
11316 static bool
11317 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11318                                SourceLocation OpLoc,
11319                                ArrayRef<Expr *> Args) {
11320   DeclarationName OpName =
11321     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11322   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11323   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11324                                 OverloadCandidateSet::CSK_Operator,
11325                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11326 }
11327 
11328 namespace {
11329 class BuildRecoveryCallExprRAII {
11330   Sema &SemaRef;
11331 public:
11332   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11333     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11334     SemaRef.IsBuildingRecoveryCallExpr = true;
11335   }
11336 
11337   ~BuildRecoveryCallExprRAII() {
11338     SemaRef.IsBuildingRecoveryCallExpr = false;
11339   }
11340 };
11341 
11342 }
11343 
11344 static std::unique_ptr<CorrectionCandidateCallback>
11345 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11346               bool HasTemplateArgs, bool AllowTypoCorrection) {
11347   if (!AllowTypoCorrection)
11348     return llvm::make_unique<NoTypoCorrectionCCC>();
11349   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11350                                                   HasTemplateArgs, ME);
11351 }
11352 
11353 /// Attempts to recover from a call where no functions were found.
11354 ///
11355 /// Returns true if new candidates were found.
11356 static ExprResult
11357 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11358                       UnresolvedLookupExpr *ULE,
11359                       SourceLocation LParenLoc,
11360                       MutableArrayRef<Expr *> Args,
11361                       SourceLocation RParenLoc,
11362                       bool EmptyLookup, bool AllowTypoCorrection) {
11363   // Do not try to recover if it is already building a recovery call.
11364   // This stops infinite loops for template instantiations like
11365   //
11366   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11367   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11368   //
11369   if (SemaRef.IsBuildingRecoveryCallExpr)
11370     return ExprError();
11371   BuildRecoveryCallExprRAII RCE(SemaRef);
11372 
11373   CXXScopeSpec SS;
11374   SS.Adopt(ULE->getQualifierLoc());
11375   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11376 
11377   TemplateArgumentListInfo TABuffer;
11378   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11379   if (ULE->hasExplicitTemplateArgs()) {
11380     ULE->copyTemplateArgumentsInto(TABuffer);
11381     ExplicitTemplateArgs = &TABuffer;
11382   }
11383 
11384   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11385                  Sema::LookupOrdinaryName);
11386   bool DoDiagnoseEmptyLookup = EmptyLookup;
11387   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11388                               OverloadCandidateSet::CSK_Normal,
11389                               ExplicitTemplateArgs, Args,
11390                               &DoDiagnoseEmptyLookup) &&
11391     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11392         S, SS, R,
11393         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11394                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11395         ExplicitTemplateArgs, Args)))
11396     return ExprError();
11397 
11398   assert(!R.empty() && "lookup results empty despite recovery");
11399 
11400   // Build an implicit member call if appropriate.  Just drop the
11401   // casts and such from the call, we don't really care.
11402   ExprResult NewFn = ExprError();
11403   if ((*R.begin())->isCXXClassMember())
11404     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11405                                                     ExplicitTemplateArgs, S);
11406   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11407     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11408                                         ExplicitTemplateArgs);
11409   else
11410     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11411 
11412   if (NewFn.isInvalid())
11413     return ExprError();
11414 
11415   // This shouldn't cause an infinite loop because we're giving it
11416   // an expression with viable lookup results, which should never
11417   // end up here.
11418   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11419                                MultiExprArg(Args.data(), Args.size()),
11420                                RParenLoc);
11421 }
11422 
11423 /// \brief Constructs and populates an OverloadedCandidateSet from
11424 /// the given function.
11425 /// \returns true when an the ExprResult output parameter has been set.
11426 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11427                                   UnresolvedLookupExpr *ULE,
11428                                   MultiExprArg Args,
11429                                   SourceLocation RParenLoc,
11430                                   OverloadCandidateSet *CandidateSet,
11431                                   ExprResult *Result) {
11432 #ifndef NDEBUG
11433   if (ULE->requiresADL()) {
11434     // To do ADL, we must have found an unqualified name.
11435     assert(!ULE->getQualifier() && "qualified name with ADL");
11436 
11437     // We don't perform ADL for implicit declarations of builtins.
11438     // Verify that this was correctly set up.
11439     FunctionDecl *F;
11440     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11441         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11442         F->getBuiltinID() && F->isImplicit())
11443       llvm_unreachable("performing ADL for builtin");
11444 
11445     // We don't perform ADL in C.
11446     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11447   }
11448 #endif
11449 
11450   UnbridgedCastsSet UnbridgedCasts;
11451   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11452     *Result = ExprError();
11453     return true;
11454   }
11455 
11456   // Add the functions denoted by the callee to the set of candidate
11457   // functions, including those from argument-dependent lookup.
11458   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11459 
11460   if (getLangOpts().MSVCCompat &&
11461       CurContext->isDependentContext() && !isSFINAEContext() &&
11462       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11463 
11464     OverloadCandidateSet::iterator Best;
11465     if (CandidateSet->empty() ||
11466         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11467             OR_No_Viable_Function) {
11468       // In Microsoft mode, if we are inside a template class member function then
11469       // create a type dependent CallExpr. The goal is to postpone name lookup
11470       // to instantiation time to be able to search into type dependent base
11471       // classes.
11472       CallExpr *CE = new (Context) CallExpr(
11473           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11474       CE->setTypeDependent(true);
11475       CE->setValueDependent(true);
11476       CE->setInstantiationDependent(true);
11477       *Result = CE;
11478       return true;
11479     }
11480   }
11481 
11482   if (CandidateSet->empty())
11483     return false;
11484 
11485   UnbridgedCasts.restore();
11486   return false;
11487 }
11488 
11489 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11490 /// the completed call expression. If overload resolution fails, emits
11491 /// diagnostics and returns ExprError()
11492 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11493                                            UnresolvedLookupExpr *ULE,
11494                                            SourceLocation LParenLoc,
11495                                            MultiExprArg Args,
11496                                            SourceLocation RParenLoc,
11497                                            Expr *ExecConfig,
11498                                            OverloadCandidateSet *CandidateSet,
11499                                            OverloadCandidateSet::iterator *Best,
11500                                            OverloadingResult OverloadResult,
11501                                            bool AllowTypoCorrection) {
11502   if (CandidateSet->empty())
11503     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11504                                  RParenLoc, /*EmptyLookup=*/true,
11505                                  AllowTypoCorrection);
11506 
11507   switch (OverloadResult) {
11508   case OR_Success: {
11509     FunctionDecl *FDecl = (*Best)->Function;
11510     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11511     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11512       return ExprError();
11513     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11514     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11515                                          ExecConfig);
11516   }
11517 
11518   case OR_No_Viable_Function: {
11519     // Try to recover by looking for viable functions which the user might
11520     // have meant to call.
11521     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11522                                                 Args, RParenLoc,
11523                                                 /*EmptyLookup=*/false,
11524                                                 AllowTypoCorrection);
11525     if (!Recovery.isInvalid())
11526       return Recovery;
11527 
11528     // If the user passes in a function that we can't take the address of, we
11529     // generally end up emitting really bad error messages. Here, we attempt to
11530     // emit better ones.
11531     for (const Expr *Arg : Args) {
11532       if (!Arg->getType()->isFunctionType())
11533         continue;
11534       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11535         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11536         if (FD &&
11537             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11538                                                        Arg->getExprLoc()))
11539           return ExprError();
11540       }
11541     }
11542 
11543     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11544         << ULE->getName() << Fn->getSourceRange();
11545     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11546     break;
11547   }
11548 
11549   case OR_Ambiguous:
11550     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11551       << ULE->getName() << Fn->getSourceRange();
11552     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11553     break;
11554 
11555   case OR_Deleted: {
11556     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11557       << (*Best)->Function->isDeleted()
11558       << ULE->getName()
11559       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11560       << Fn->getSourceRange();
11561     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11562 
11563     // We emitted an error for the unvailable/deleted function call but keep
11564     // the call in the AST.
11565     FunctionDecl *FDecl = (*Best)->Function;
11566     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11567     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11568                                          ExecConfig);
11569   }
11570   }
11571 
11572   // Overload resolution failed.
11573   return ExprError();
11574 }
11575 
11576 static void markUnaddressableCandidatesUnviable(Sema &S,
11577                                                 OverloadCandidateSet &CS) {
11578   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11579     if (I->Viable &&
11580         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11581       I->Viable = false;
11582       I->FailureKind = ovl_fail_addr_not_available;
11583     }
11584   }
11585 }
11586 
11587 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11588 /// (which eventually refers to the declaration Func) and the call
11589 /// arguments Args/NumArgs, attempt to resolve the function call down
11590 /// to a specific function. If overload resolution succeeds, returns
11591 /// the call expression produced by overload resolution.
11592 /// Otherwise, emits diagnostics and returns ExprError.
11593 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11594                                          UnresolvedLookupExpr *ULE,
11595                                          SourceLocation LParenLoc,
11596                                          MultiExprArg Args,
11597                                          SourceLocation RParenLoc,
11598                                          Expr *ExecConfig,
11599                                          bool AllowTypoCorrection,
11600                                          bool CalleesAddressIsTaken) {
11601   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11602                                     OverloadCandidateSet::CSK_Normal);
11603   ExprResult result;
11604 
11605   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11606                              &result))
11607     return result;
11608 
11609   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11610   // functions that aren't addressible are considered unviable.
11611   if (CalleesAddressIsTaken)
11612     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11613 
11614   OverloadCandidateSet::iterator Best;
11615   OverloadingResult OverloadResult =
11616       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11617 
11618   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11619                                   RParenLoc, ExecConfig, &CandidateSet,
11620                                   &Best, OverloadResult,
11621                                   AllowTypoCorrection);
11622 }
11623 
11624 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11625   return Functions.size() > 1 ||
11626     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11627 }
11628 
11629 /// \brief Create a unary operation that may resolve to an overloaded
11630 /// operator.
11631 ///
11632 /// \param OpLoc The location of the operator itself (e.g., '*').
11633 ///
11634 /// \param Opc The UnaryOperatorKind that describes this operator.
11635 ///
11636 /// \param Fns The set of non-member functions that will be
11637 /// considered by overload resolution. The caller needs to build this
11638 /// set based on the context using, e.g.,
11639 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11640 /// set should not contain any member functions; those will be added
11641 /// by CreateOverloadedUnaryOp().
11642 ///
11643 /// \param Input The input argument.
11644 ExprResult
11645 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11646                               const UnresolvedSetImpl &Fns,
11647                               Expr *Input) {
11648   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11649   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11650   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11651   // TODO: provide better source location info.
11652   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11653 
11654   if (checkPlaceholderForOverload(*this, Input))
11655     return ExprError();
11656 
11657   Expr *Args[2] = { Input, nullptr };
11658   unsigned NumArgs = 1;
11659 
11660   // For post-increment and post-decrement, add the implicit '0' as
11661   // the second argument, so that we know this is a post-increment or
11662   // post-decrement.
11663   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11664     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11665     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11666                                      SourceLocation());
11667     NumArgs = 2;
11668   }
11669 
11670   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11671 
11672   if (Input->isTypeDependent()) {
11673     if (Fns.empty())
11674       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11675                                          VK_RValue, OK_Ordinary, OpLoc);
11676 
11677     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11678     UnresolvedLookupExpr *Fn
11679       = UnresolvedLookupExpr::Create(Context, NamingClass,
11680                                      NestedNameSpecifierLoc(), OpNameInfo,
11681                                      /*ADL*/ true, IsOverloaded(Fns),
11682                                      Fns.begin(), Fns.end());
11683     return new (Context)
11684         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11685                             VK_RValue, OpLoc, false);
11686   }
11687 
11688   // Build an empty overload set.
11689   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11690 
11691   // Add the candidates from the given function set.
11692   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11693 
11694   // Add operator candidates that are member functions.
11695   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11696 
11697   // Add candidates from ADL.
11698   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11699                                        /*ExplicitTemplateArgs*/nullptr,
11700                                        CandidateSet);
11701 
11702   // Add builtin operator candidates.
11703   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11704 
11705   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11706 
11707   // Perform overload resolution.
11708   OverloadCandidateSet::iterator Best;
11709   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11710   case OR_Success: {
11711     // We found a built-in operator or an overloaded operator.
11712     FunctionDecl *FnDecl = Best->Function;
11713 
11714     if (FnDecl) {
11715       // We matched an overloaded operator. Build a call to that
11716       // operator.
11717 
11718       // Convert the arguments.
11719       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11720         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11721 
11722         ExprResult InputRes =
11723           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11724                                               Best->FoundDecl, Method);
11725         if (InputRes.isInvalid())
11726           return ExprError();
11727         Input = InputRes.get();
11728       } else {
11729         // Convert the arguments.
11730         ExprResult InputInit
11731           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11732                                                       Context,
11733                                                       FnDecl->getParamDecl(0)),
11734                                       SourceLocation(),
11735                                       Input);
11736         if (InputInit.isInvalid())
11737           return ExprError();
11738         Input = InputInit.get();
11739       }
11740 
11741       // Build the actual expression node.
11742       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11743                                                 HadMultipleCandidates, OpLoc);
11744       if (FnExpr.isInvalid())
11745         return ExprError();
11746 
11747       // Determine the result type.
11748       QualType ResultTy = FnDecl->getReturnType();
11749       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11750       ResultTy = ResultTy.getNonLValueExprType(Context);
11751 
11752       Args[0] = Input;
11753       CallExpr *TheCall =
11754         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11755                                           ResultTy, VK, OpLoc, false);
11756 
11757       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11758         return ExprError();
11759 
11760       return MaybeBindToTemporary(TheCall);
11761     } else {
11762       // We matched a built-in operator. Convert the arguments, then
11763       // break out so that we will build the appropriate built-in
11764       // operator node.
11765       ExprResult InputRes =
11766         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11767                                   Best->Conversions[0], AA_Passing);
11768       if (InputRes.isInvalid())
11769         return ExprError();
11770       Input = InputRes.get();
11771       break;
11772     }
11773   }
11774 
11775   case OR_No_Viable_Function:
11776     // This is an erroneous use of an operator which can be overloaded by
11777     // a non-member function. Check for non-member operators which were
11778     // defined too late to be candidates.
11779     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11780       // FIXME: Recover by calling the found function.
11781       return ExprError();
11782 
11783     // No viable function; fall through to handling this as a
11784     // built-in operator, which will produce an error message for us.
11785     break;
11786 
11787   case OR_Ambiguous:
11788     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11789         << UnaryOperator::getOpcodeStr(Opc)
11790         << Input->getType()
11791         << Input->getSourceRange();
11792     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11793                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11794     return ExprError();
11795 
11796   case OR_Deleted:
11797     Diag(OpLoc, diag::err_ovl_deleted_oper)
11798       << Best->Function->isDeleted()
11799       << UnaryOperator::getOpcodeStr(Opc)
11800       << getDeletedOrUnavailableSuffix(Best->Function)
11801       << Input->getSourceRange();
11802     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11803                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11804     return ExprError();
11805   }
11806 
11807   // Either we found no viable overloaded operator or we matched a
11808   // built-in operator. In either case, fall through to trying to
11809   // build a built-in operation.
11810   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11811 }
11812 
11813 /// \brief Create a binary operation that may resolve to an overloaded
11814 /// operator.
11815 ///
11816 /// \param OpLoc The location of the operator itself (e.g., '+').
11817 ///
11818 /// \param Opc The BinaryOperatorKind that describes this operator.
11819 ///
11820 /// \param Fns The set of non-member functions that will be
11821 /// considered by overload resolution. The caller needs to build this
11822 /// set based on the context using, e.g.,
11823 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11824 /// set should not contain any member functions; those will be added
11825 /// by CreateOverloadedBinOp().
11826 ///
11827 /// \param LHS Left-hand argument.
11828 /// \param RHS Right-hand argument.
11829 ExprResult
11830 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11831                             BinaryOperatorKind Opc,
11832                             const UnresolvedSetImpl &Fns,
11833                             Expr *LHS, Expr *RHS) {
11834   Expr *Args[2] = { LHS, RHS };
11835   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11836 
11837   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11838   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11839 
11840   // If either side is type-dependent, create an appropriate dependent
11841   // expression.
11842   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11843     if (Fns.empty()) {
11844       // If there are no functions to store, just build a dependent
11845       // BinaryOperator or CompoundAssignment.
11846       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11847         return new (Context) BinaryOperator(
11848             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11849             OpLoc, FPFeatures.fp_contract);
11850 
11851       return new (Context) CompoundAssignOperator(
11852           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11853           Context.DependentTy, Context.DependentTy, OpLoc,
11854           FPFeatures.fp_contract);
11855     }
11856 
11857     // FIXME: save results of ADL from here?
11858     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11859     // TODO: provide better source location info in DNLoc component.
11860     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11861     UnresolvedLookupExpr *Fn
11862       = UnresolvedLookupExpr::Create(Context, NamingClass,
11863                                      NestedNameSpecifierLoc(), OpNameInfo,
11864                                      /*ADL*/ true, IsOverloaded(Fns),
11865                                      Fns.begin(), Fns.end());
11866     return new (Context)
11867         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11868                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11869   }
11870 
11871   // Always do placeholder-like conversions on the RHS.
11872   if (checkPlaceholderForOverload(*this, Args[1]))
11873     return ExprError();
11874 
11875   // Do placeholder-like conversion on the LHS; note that we should
11876   // not get here with a PseudoObject LHS.
11877   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11878   if (checkPlaceholderForOverload(*this, Args[0]))
11879     return ExprError();
11880 
11881   // If this is the assignment operator, we only perform overload resolution
11882   // if the left-hand side is a class or enumeration type. This is actually
11883   // a hack. The standard requires that we do overload resolution between the
11884   // various built-in candidates, but as DR507 points out, this can lead to
11885   // problems. So we do it this way, which pretty much follows what GCC does.
11886   // Note that we go the traditional code path for compound assignment forms.
11887   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11888     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11889 
11890   // If this is the .* operator, which is not overloadable, just
11891   // create a built-in binary operator.
11892   if (Opc == BO_PtrMemD)
11893     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11894 
11895   // Build an empty overload set.
11896   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11897 
11898   // Add the candidates from the given function set.
11899   AddFunctionCandidates(Fns, Args, CandidateSet);
11900 
11901   // Add operator candidates that are member functions.
11902   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11903 
11904   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11905   // performed for an assignment operator (nor for operator[] nor operator->,
11906   // which don't get here).
11907   if (Opc != BO_Assign)
11908     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11909                                          /*ExplicitTemplateArgs*/ nullptr,
11910                                          CandidateSet);
11911 
11912   // Add builtin operator candidates.
11913   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11914 
11915   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11916 
11917   // Perform overload resolution.
11918   OverloadCandidateSet::iterator Best;
11919   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11920     case OR_Success: {
11921       // We found a built-in operator or an overloaded operator.
11922       FunctionDecl *FnDecl = Best->Function;
11923 
11924       if (FnDecl) {
11925         // We matched an overloaded operator. Build a call to that
11926         // operator.
11927 
11928         // Convert the arguments.
11929         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11930           // Best->Access is only meaningful for class members.
11931           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11932 
11933           ExprResult Arg1 =
11934             PerformCopyInitialization(
11935               InitializedEntity::InitializeParameter(Context,
11936                                                      FnDecl->getParamDecl(0)),
11937               SourceLocation(), Args[1]);
11938           if (Arg1.isInvalid())
11939             return ExprError();
11940 
11941           ExprResult Arg0 =
11942             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11943                                                 Best->FoundDecl, Method);
11944           if (Arg0.isInvalid())
11945             return ExprError();
11946           Args[0] = Arg0.getAs<Expr>();
11947           Args[1] = RHS = Arg1.getAs<Expr>();
11948         } else {
11949           // Convert the arguments.
11950           ExprResult Arg0 = PerformCopyInitialization(
11951             InitializedEntity::InitializeParameter(Context,
11952                                                    FnDecl->getParamDecl(0)),
11953             SourceLocation(), Args[0]);
11954           if (Arg0.isInvalid())
11955             return ExprError();
11956 
11957           ExprResult Arg1 =
11958             PerformCopyInitialization(
11959               InitializedEntity::InitializeParameter(Context,
11960                                                      FnDecl->getParamDecl(1)),
11961               SourceLocation(), Args[1]);
11962           if (Arg1.isInvalid())
11963             return ExprError();
11964           Args[0] = LHS = Arg0.getAs<Expr>();
11965           Args[1] = RHS = Arg1.getAs<Expr>();
11966         }
11967 
11968         // Build the actual expression node.
11969         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11970                                                   Best->FoundDecl,
11971                                                   HadMultipleCandidates, OpLoc);
11972         if (FnExpr.isInvalid())
11973           return ExprError();
11974 
11975         // Determine the result type.
11976         QualType ResultTy = FnDecl->getReturnType();
11977         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11978         ResultTy = ResultTy.getNonLValueExprType(Context);
11979 
11980         CXXOperatorCallExpr *TheCall =
11981           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11982                                             Args, ResultTy, VK, OpLoc,
11983                                             FPFeatures.fp_contract);
11984 
11985         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11986                                 FnDecl))
11987           return ExprError();
11988 
11989         ArrayRef<const Expr *> ArgsArray(Args, 2);
11990         // Cut off the implicit 'this'.
11991         if (isa<CXXMethodDecl>(FnDecl))
11992           ArgsArray = ArgsArray.slice(1);
11993 
11994         // Check for a self move.
11995         if (Op == OO_Equal)
11996           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11997 
11998         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11999                   TheCall->getSourceRange(), VariadicDoesNotApply);
12000 
12001         return MaybeBindToTemporary(TheCall);
12002       } else {
12003         // We matched a built-in operator. Convert the arguments, then
12004         // break out so that we will build the appropriate built-in
12005         // operator node.
12006         ExprResult ArgsRes0 =
12007           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12008                                     Best->Conversions[0], AA_Passing);
12009         if (ArgsRes0.isInvalid())
12010           return ExprError();
12011         Args[0] = ArgsRes0.get();
12012 
12013         ExprResult ArgsRes1 =
12014           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12015                                     Best->Conversions[1], AA_Passing);
12016         if (ArgsRes1.isInvalid())
12017           return ExprError();
12018         Args[1] = ArgsRes1.get();
12019         break;
12020       }
12021     }
12022 
12023     case OR_No_Viable_Function: {
12024       // C++ [over.match.oper]p9:
12025       //   If the operator is the operator , [...] and there are no
12026       //   viable functions, then the operator is assumed to be the
12027       //   built-in operator and interpreted according to clause 5.
12028       if (Opc == BO_Comma)
12029         break;
12030 
12031       // For class as left operand for assignment or compound assigment
12032       // operator do not fall through to handling in built-in, but report that
12033       // no overloaded assignment operator found
12034       ExprResult Result = ExprError();
12035       if (Args[0]->getType()->isRecordType() &&
12036           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12037         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12038              << BinaryOperator::getOpcodeStr(Opc)
12039              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12040         if (Args[0]->getType()->isIncompleteType()) {
12041           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12042             << Args[0]->getType()
12043             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12044         }
12045       } else {
12046         // This is an erroneous use of an operator which can be overloaded by
12047         // a non-member function. Check for non-member operators which were
12048         // defined too late to be candidates.
12049         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12050           // FIXME: Recover by calling the found function.
12051           return ExprError();
12052 
12053         // No viable function; try to create a built-in operation, which will
12054         // produce an error. Then, show the non-viable candidates.
12055         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12056       }
12057       assert(Result.isInvalid() &&
12058              "C++ binary operator overloading is missing candidates!");
12059       if (Result.isInvalid())
12060         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12061                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12062       return Result;
12063     }
12064 
12065     case OR_Ambiguous:
12066       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12067           << BinaryOperator::getOpcodeStr(Opc)
12068           << Args[0]->getType() << Args[1]->getType()
12069           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12070       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12071                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12072       return ExprError();
12073 
12074     case OR_Deleted:
12075       if (isImplicitlyDeleted(Best->Function)) {
12076         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12077         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12078           << Context.getRecordType(Method->getParent())
12079           << getSpecialMember(Method);
12080 
12081         // The user probably meant to call this special member. Just
12082         // explain why it's deleted.
12083         NoteDeletedFunction(Method);
12084         return ExprError();
12085       } else {
12086         Diag(OpLoc, diag::err_ovl_deleted_oper)
12087           << Best->Function->isDeleted()
12088           << BinaryOperator::getOpcodeStr(Opc)
12089           << getDeletedOrUnavailableSuffix(Best->Function)
12090           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12091       }
12092       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12093                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12094       return ExprError();
12095   }
12096 
12097   // We matched a built-in operator; build it.
12098   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12099 }
12100 
12101 ExprResult
12102 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12103                                          SourceLocation RLoc,
12104                                          Expr *Base, Expr *Idx) {
12105   Expr *Args[2] = { Base, Idx };
12106   DeclarationName OpName =
12107       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12108 
12109   // If either side is type-dependent, create an appropriate dependent
12110   // expression.
12111   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12112 
12113     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12114     // CHECKME: no 'operator' keyword?
12115     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12116     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12117     UnresolvedLookupExpr *Fn
12118       = UnresolvedLookupExpr::Create(Context, NamingClass,
12119                                      NestedNameSpecifierLoc(), OpNameInfo,
12120                                      /*ADL*/ true, /*Overloaded*/ false,
12121                                      UnresolvedSetIterator(),
12122                                      UnresolvedSetIterator());
12123     // Can't add any actual overloads yet
12124 
12125     return new (Context)
12126         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12127                             Context.DependentTy, VK_RValue, RLoc, false);
12128   }
12129 
12130   // Handle placeholders on both operands.
12131   if (checkPlaceholderForOverload(*this, Args[0]))
12132     return ExprError();
12133   if (checkPlaceholderForOverload(*this, Args[1]))
12134     return ExprError();
12135 
12136   // Build an empty overload set.
12137   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12138 
12139   // Subscript can only be overloaded as a member function.
12140 
12141   // Add operator candidates that are member functions.
12142   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12143 
12144   // Add builtin operator candidates.
12145   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12146 
12147   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12148 
12149   // Perform overload resolution.
12150   OverloadCandidateSet::iterator Best;
12151   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12152     case OR_Success: {
12153       // We found a built-in operator or an overloaded operator.
12154       FunctionDecl *FnDecl = Best->Function;
12155 
12156       if (FnDecl) {
12157         // We matched an overloaded operator. Build a call to that
12158         // operator.
12159 
12160         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12161 
12162         // Convert the arguments.
12163         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12164         ExprResult Arg0 =
12165           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12166                                               Best->FoundDecl, Method);
12167         if (Arg0.isInvalid())
12168           return ExprError();
12169         Args[0] = Arg0.get();
12170 
12171         // Convert the arguments.
12172         ExprResult InputInit
12173           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12174                                                       Context,
12175                                                       FnDecl->getParamDecl(0)),
12176                                       SourceLocation(),
12177                                       Args[1]);
12178         if (InputInit.isInvalid())
12179           return ExprError();
12180 
12181         Args[1] = InputInit.getAs<Expr>();
12182 
12183         // Build the actual expression node.
12184         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12185         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12186         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12187                                                   Best->FoundDecl,
12188                                                   HadMultipleCandidates,
12189                                                   OpLocInfo.getLoc(),
12190                                                   OpLocInfo.getInfo());
12191         if (FnExpr.isInvalid())
12192           return ExprError();
12193 
12194         // Determine the result type
12195         QualType ResultTy = FnDecl->getReturnType();
12196         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12197         ResultTy = ResultTy.getNonLValueExprType(Context);
12198 
12199         CXXOperatorCallExpr *TheCall =
12200           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12201                                             FnExpr.get(), Args,
12202                                             ResultTy, VK, RLoc,
12203                                             false);
12204 
12205         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12206           return ExprError();
12207 
12208         return MaybeBindToTemporary(TheCall);
12209       } else {
12210         // We matched a built-in operator. Convert the arguments, then
12211         // break out so that we will build the appropriate built-in
12212         // operator node.
12213         ExprResult ArgsRes0 =
12214           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12215                                     Best->Conversions[0], AA_Passing);
12216         if (ArgsRes0.isInvalid())
12217           return ExprError();
12218         Args[0] = ArgsRes0.get();
12219 
12220         ExprResult ArgsRes1 =
12221           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12222                                     Best->Conversions[1], AA_Passing);
12223         if (ArgsRes1.isInvalid())
12224           return ExprError();
12225         Args[1] = ArgsRes1.get();
12226 
12227         break;
12228       }
12229     }
12230 
12231     case OR_No_Viable_Function: {
12232       if (CandidateSet.empty())
12233         Diag(LLoc, diag::err_ovl_no_oper)
12234           << Args[0]->getType() << /*subscript*/ 0
12235           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12236       else
12237         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12238           << Args[0]->getType()
12239           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12240       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12241                                   "[]", LLoc);
12242       return ExprError();
12243     }
12244 
12245     case OR_Ambiguous:
12246       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12247           << "[]"
12248           << Args[0]->getType() << Args[1]->getType()
12249           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12250       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12251                                   "[]", LLoc);
12252       return ExprError();
12253 
12254     case OR_Deleted:
12255       Diag(LLoc, diag::err_ovl_deleted_oper)
12256         << Best->Function->isDeleted() << "[]"
12257         << getDeletedOrUnavailableSuffix(Best->Function)
12258         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12259       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12260                                   "[]", LLoc);
12261       return ExprError();
12262     }
12263 
12264   // We matched a built-in operator; build it.
12265   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12266 }
12267 
12268 /// BuildCallToMemberFunction - Build a call to a member
12269 /// function. MemExpr is the expression that refers to the member
12270 /// function (and includes the object parameter), Args/NumArgs are the
12271 /// arguments to the function call (not including the object
12272 /// parameter). The caller needs to validate that the member
12273 /// expression refers to a non-static member function or an overloaded
12274 /// member function.
12275 ExprResult
12276 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12277                                 SourceLocation LParenLoc,
12278                                 MultiExprArg Args,
12279                                 SourceLocation RParenLoc) {
12280   assert(MemExprE->getType() == Context.BoundMemberTy ||
12281          MemExprE->getType() == Context.OverloadTy);
12282 
12283   // Dig out the member expression. This holds both the object
12284   // argument and the member function we're referring to.
12285   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12286 
12287   // Determine whether this is a call to a pointer-to-member function.
12288   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12289     assert(op->getType() == Context.BoundMemberTy);
12290     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12291 
12292     QualType fnType =
12293       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12294 
12295     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12296     QualType resultType = proto->getCallResultType(Context);
12297     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12298 
12299     // Check that the object type isn't more qualified than the
12300     // member function we're calling.
12301     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12302 
12303     QualType objectType = op->getLHS()->getType();
12304     if (op->getOpcode() == BO_PtrMemI)
12305       objectType = objectType->castAs<PointerType>()->getPointeeType();
12306     Qualifiers objectQuals = objectType.getQualifiers();
12307 
12308     Qualifiers difference = objectQuals - funcQuals;
12309     difference.removeObjCGCAttr();
12310     difference.removeAddressSpace();
12311     if (difference) {
12312       std::string qualsString = difference.getAsString();
12313       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12314         << fnType.getUnqualifiedType()
12315         << qualsString
12316         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12317     }
12318 
12319     CXXMemberCallExpr *call
12320       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12321                                         resultType, valueKind, RParenLoc);
12322 
12323     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12324                             call, nullptr))
12325       return ExprError();
12326 
12327     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12328       return ExprError();
12329 
12330     if (CheckOtherCall(call, proto))
12331       return ExprError();
12332 
12333     return MaybeBindToTemporary(call);
12334   }
12335 
12336   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12337     return new (Context)
12338         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12339 
12340   UnbridgedCastsSet UnbridgedCasts;
12341   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12342     return ExprError();
12343 
12344   MemberExpr *MemExpr;
12345   CXXMethodDecl *Method = nullptr;
12346   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12347   NestedNameSpecifier *Qualifier = nullptr;
12348   if (isa<MemberExpr>(NakedMemExpr)) {
12349     MemExpr = cast<MemberExpr>(NakedMemExpr);
12350     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12351     FoundDecl = MemExpr->getFoundDecl();
12352     Qualifier = MemExpr->getQualifier();
12353     UnbridgedCasts.restore();
12354   } else {
12355     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12356     Qualifier = UnresExpr->getQualifier();
12357 
12358     QualType ObjectType = UnresExpr->getBaseType();
12359     Expr::Classification ObjectClassification
12360       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12361                             : UnresExpr->getBase()->Classify(Context);
12362 
12363     // Add overload candidates
12364     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12365                                       OverloadCandidateSet::CSK_Normal);
12366 
12367     // FIXME: avoid copy.
12368     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12369     if (UnresExpr->hasExplicitTemplateArgs()) {
12370       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12371       TemplateArgs = &TemplateArgsBuffer;
12372     }
12373 
12374     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12375            E = UnresExpr->decls_end(); I != E; ++I) {
12376 
12377       NamedDecl *Func = *I;
12378       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12379       if (isa<UsingShadowDecl>(Func))
12380         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12381 
12382 
12383       // Microsoft supports direct constructor calls.
12384       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12385         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12386                              Args, CandidateSet);
12387       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12388         // If explicit template arguments were provided, we can't call a
12389         // non-template member function.
12390         if (TemplateArgs)
12391           continue;
12392 
12393         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12394                            ObjectClassification, Args, CandidateSet,
12395                            /*SuppressUserConversions=*/false);
12396       } else {
12397         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12398                                    I.getPair(), ActingDC, TemplateArgs,
12399                                    ObjectType,  ObjectClassification,
12400                                    Args, CandidateSet,
12401                                    /*SuppressUsedConversions=*/false);
12402       }
12403     }
12404 
12405     DeclarationName DeclName = UnresExpr->getMemberName();
12406 
12407     UnbridgedCasts.restore();
12408 
12409     OverloadCandidateSet::iterator Best;
12410     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12411                                             Best)) {
12412     case OR_Success:
12413       Method = cast<CXXMethodDecl>(Best->Function);
12414       FoundDecl = Best->FoundDecl;
12415       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12416       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12417         return ExprError();
12418       // If FoundDecl is different from Method (such as if one is a template
12419       // and the other a specialization), make sure DiagnoseUseOfDecl is
12420       // called on both.
12421       // FIXME: This would be more comprehensively addressed by modifying
12422       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12423       // being used.
12424       if (Method != FoundDecl.getDecl() &&
12425                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12426         return ExprError();
12427       break;
12428 
12429     case OR_No_Viable_Function:
12430       Diag(UnresExpr->getMemberLoc(),
12431            diag::err_ovl_no_viable_member_function_in_call)
12432         << DeclName << MemExprE->getSourceRange();
12433       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12434       // FIXME: Leaking incoming expressions!
12435       return ExprError();
12436 
12437     case OR_Ambiguous:
12438       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12439         << DeclName << MemExprE->getSourceRange();
12440       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12441       // FIXME: Leaking incoming expressions!
12442       return ExprError();
12443 
12444     case OR_Deleted:
12445       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12446         << Best->Function->isDeleted()
12447         << DeclName
12448         << getDeletedOrUnavailableSuffix(Best->Function)
12449         << MemExprE->getSourceRange();
12450       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12451       // FIXME: Leaking incoming expressions!
12452       return ExprError();
12453     }
12454 
12455     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12456 
12457     // If overload resolution picked a static member, build a
12458     // non-member call based on that function.
12459     if (Method->isStatic()) {
12460       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12461                                    RParenLoc);
12462     }
12463 
12464     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12465   }
12466 
12467   QualType ResultType = Method->getReturnType();
12468   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12469   ResultType = ResultType.getNonLValueExprType(Context);
12470 
12471   assert(Method && "Member call to something that isn't a method?");
12472   CXXMemberCallExpr *TheCall =
12473     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12474                                     ResultType, VK, RParenLoc);
12475 
12476   // Check for a valid return type.
12477   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12478                           TheCall, Method))
12479     return ExprError();
12480 
12481   // Convert the object argument (for a non-static member function call).
12482   // We only need to do this if there was actually an overload; otherwise
12483   // it was done at lookup.
12484   if (!Method->isStatic()) {
12485     ExprResult ObjectArg =
12486       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12487                                           FoundDecl, Method);
12488     if (ObjectArg.isInvalid())
12489       return ExprError();
12490     MemExpr->setBase(ObjectArg.get());
12491   }
12492 
12493   // Convert the rest of the arguments
12494   const FunctionProtoType *Proto =
12495     Method->getType()->getAs<FunctionProtoType>();
12496   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12497                               RParenLoc))
12498     return ExprError();
12499 
12500   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12501 
12502   if (CheckFunctionCall(Method, TheCall, Proto))
12503     return ExprError();
12504 
12505   // In the case the method to call was not selected by the overloading
12506   // resolution process, we still need to handle the enable_if attribute. Do
12507   // that here, so it will not hide previous -- and more relevant -- errors.
12508   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12509     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12510       Diag(MemE->getMemberLoc(),
12511            diag::err_ovl_no_viable_member_function_in_call)
12512           << Method << Method->getSourceRange();
12513       Diag(Method->getLocation(),
12514            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12515           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12516       return ExprError();
12517     }
12518   }
12519 
12520   if ((isa<CXXConstructorDecl>(CurContext) ||
12521        isa<CXXDestructorDecl>(CurContext)) &&
12522       TheCall->getMethodDecl()->isPure()) {
12523     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12524 
12525     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12526         MemExpr->performsVirtualDispatch(getLangOpts())) {
12527       Diag(MemExpr->getLocStart(),
12528            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12529         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12530         << MD->getParent()->getDeclName();
12531 
12532       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12533       if (getLangOpts().AppleKext)
12534         Diag(MemExpr->getLocStart(),
12535              diag::note_pure_qualified_call_kext)
12536              << MD->getParent()->getDeclName()
12537              << MD->getDeclName();
12538     }
12539   }
12540 
12541   if (CXXDestructorDecl *DD =
12542           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12543     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12544     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12545     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12546                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12547                          MemExpr->getMemberLoc());
12548   }
12549 
12550   return MaybeBindToTemporary(TheCall);
12551 }
12552 
12553 /// BuildCallToObjectOfClassType - Build a call to an object of class
12554 /// type (C++ [over.call.object]), which can end up invoking an
12555 /// overloaded function call operator (@c operator()) or performing a
12556 /// user-defined conversion on the object argument.
12557 ExprResult
12558 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12559                                    SourceLocation LParenLoc,
12560                                    MultiExprArg Args,
12561                                    SourceLocation RParenLoc) {
12562   if (checkPlaceholderForOverload(*this, Obj))
12563     return ExprError();
12564   ExprResult Object = Obj;
12565 
12566   UnbridgedCastsSet UnbridgedCasts;
12567   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12568     return ExprError();
12569 
12570   assert(Object.get()->getType()->isRecordType() &&
12571          "Requires object type argument");
12572   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12573 
12574   // C++ [over.call.object]p1:
12575   //  If the primary-expression E in the function call syntax
12576   //  evaluates to a class object of type "cv T", then the set of
12577   //  candidate functions includes at least the function call
12578   //  operators of T. The function call operators of T are obtained by
12579   //  ordinary lookup of the name operator() in the context of
12580   //  (E).operator().
12581   OverloadCandidateSet CandidateSet(LParenLoc,
12582                                     OverloadCandidateSet::CSK_Operator);
12583   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12584 
12585   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12586                           diag::err_incomplete_object_call, Object.get()))
12587     return true;
12588 
12589   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12590   LookupQualifiedName(R, Record->getDecl());
12591   R.suppressDiagnostics();
12592 
12593   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12594        Oper != OperEnd; ++Oper) {
12595     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12596                        Object.get()->Classify(Context),
12597                        Args, CandidateSet,
12598                        /*SuppressUserConversions=*/ false);
12599   }
12600 
12601   // C++ [over.call.object]p2:
12602   //   In addition, for each (non-explicit in C++0x) conversion function
12603   //   declared in T of the form
12604   //
12605   //        operator conversion-type-id () cv-qualifier;
12606   //
12607   //   where cv-qualifier is the same cv-qualification as, or a
12608   //   greater cv-qualification than, cv, and where conversion-type-id
12609   //   denotes the type "pointer to function of (P1,...,Pn) returning
12610   //   R", or the type "reference to pointer to function of
12611   //   (P1,...,Pn) returning R", or the type "reference to function
12612   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12613   //   is also considered as a candidate function. Similarly,
12614   //   surrogate call functions are added to the set of candidate
12615   //   functions for each conversion function declared in an
12616   //   accessible base class provided the function is not hidden
12617   //   within T by another intervening declaration.
12618   const auto &Conversions =
12619       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12620   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12621     NamedDecl *D = *I;
12622     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12623     if (isa<UsingShadowDecl>(D))
12624       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12625 
12626     // Skip over templated conversion functions; they aren't
12627     // surrogates.
12628     if (isa<FunctionTemplateDecl>(D))
12629       continue;
12630 
12631     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12632     if (!Conv->isExplicit()) {
12633       // Strip the reference type (if any) and then the pointer type (if
12634       // any) to get down to what might be a function type.
12635       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12636       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12637         ConvType = ConvPtrType->getPointeeType();
12638 
12639       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12640       {
12641         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12642                               Object.get(), Args, CandidateSet);
12643       }
12644     }
12645   }
12646 
12647   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12648 
12649   // Perform overload resolution.
12650   OverloadCandidateSet::iterator Best;
12651   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12652                              Best)) {
12653   case OR_Success:
12654     // Overload resolution succeeded; we'll build the appropriate call
12655     // below.
12656     break;
12657 
12658   case OR_No_Viable_Function:
12659     if (CandidateSet.empty())
12660       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12661         << Object.get()->getType() << /*call*/ 1
12662         << Object.get()->getSourceRange();
12663     else
12664       Diag(Object.get()->getLocStart(),
12665            diag::err_ovl_no_viable_object_call)
12666         << Object.get()->getType() << Object.get()->getSourceRange();
12667     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12668     break;
12669 
12670   case OR_Ambiguous:
12671     Diag(Object.get()->getLocStart(),
12672          diag::err_ovl_ambiguous_object_call)
12673       << Object.get()->getType() << Object.get()->getSourceRange();
12674     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12675     break;
12676 
12677   case OR_Deleted:
12678     Diag(Object.get()->getLocStart(),
12679          diag::err_ovl_deleted_object_call)
12680       << Best->Function->isDeleted()
12681       << Object.get()->getType()
12682       << getDeletedOrUnavailableSuffix(Best->Function)
12683       << Object.get()->getSourceRange();
12684     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12685     break;
12686   }
12687 
12688   if (Best == CandidateSet.end())
12689     return true;
12690 
12691   UnbridgedCasts.restore();
12692 
12693   if (Best->Function == nullptr) {
12694     // Since there is no function declaration, this is one of the
12695     // surrogate candidates. Dig out the conversion function.
12696     CXXConversionDecl *Conv
12697       = cast<CXXConversionDecl>(
12698                          Best->Conversions[0].UserDefined.ConversionFunction);
12699 
12700     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12701                               Best->FoundDecl);
12702     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12703       return ExprError();
12704     assert(Conv == Best->FoundDecl.getDecl() &&
12705              "Found Decl & conversion-to-functionptr should be same, right?!");
12706     // We selected one of the surrogate functions that converts the
12707     // object parameter to a function pointer. Perform the conversion
12708     // on the object argument, then let ActOnCallExpr finish the job.
12709 
12710     // Create an implicit member expr to refer to the conversion operator.
12711     // and then call it.
12712     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12713                                              Conv, HadMultipleCandidates);
12714     if (Call.isInvalid())
12715       return ExprError();
12716     // Record usage of conversion in an implicit cast.
12717     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12718                                     CK_UserDefinedConversion, Call.get(),
12719                                     nullptr, VK_RValue);
12720 
12721     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12722   }
12723 
12724   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12725 
12726   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12727   // that calls this method, using Object for the implicit object
12728   // parameter and passing along the remaining arguments.
12729   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12730 
12731   // An error diagnostic has already been printed when parsing the declaration.
12732   if (Method->isInvalidDecl())
12733     return ExprError();
12734 
12735   const FunctionProtoType *Proto =
12736     Method->getType()->getAs<FunctionProtoType>();
12737 
12738   unsigned NumParams = Proto->getNumParams();
12739 
12740   DeclarationNameInfo OpLocInfo(
12741                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12742   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12743   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12744                                            HadMultipleCandidates,
12745                                            OpLocInfo.getLoc(),
12746                                            OpLocInfo.getInfo());
12747   if (NewFn.isInvalid())
12748     return true;
12749 
12750   // Build the full argument list for the method call (the implicit object
12751   // parameter is placed at the beginning of the list).
12752   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
12753   MethodArgs[0] = Object.get();
12754   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
12755 
12756   // Once we've built TheCall, all of the expressions are properly
12757   // owned.
12758   QualType ResultTy = Method->getReturnType();
12759   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12760   ResultTy = ResultTy.getNonLValueExprType(Context);
12761 
12762   CXXOperatorCallExpr *TheCall = new (Context)
12763       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12764                           VK, RParenLoc, false);
12765 
12766   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12767     return true;
12768 
12769   // We may have default arguments. If so, we need to allocate more
12770   // slots in the call for them.
12771   if (Args.size() < NumParams)
12772     TheCall->setNumArgs(Context, NumParams + 1);
12773 
12774   bool IsError = false;
12775 
12776   // Initialize the implicit object parameter.
12777   ExprResult ObjRes =
12778     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12779                                         Best->FoundDecl, Method);
12780   if (ObjRes.isInvalid())
12781     IsError = true;
12782   else
12783     Object = ObjRes;
12784   TheCall->setArg(0, Object.get());
12785 
12786   // Check the argument types.
12787   for (unsigned i = 0; i != NumParams; i++) {
12788     Expr *Arg;
12789     if (i < Args.size()) {
12790       Arg = Args[i];
12791 
12792       // Pass the argument.
12793 
12794       ExprResult InputInit
12795         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12796                                                     Context,
12797                                                     Method->getParamDecl(i)),
12798                                     SourceLocation(), Arg);
12799 
12800       IsError |= InputInit.isInvalid();
12801       Arg = InputInit.getAs<Expr>();
12802     } else {
12803       ExprResult DefArg
12804         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12805       if (DefArg.isInvalid()) {
12806         IsError = true;
12807         break;
12808       }
12809 
12810       Arg = DefArg.getAs<Expr>();
12811     }
12812 
12813     TheCall->setArg(i + 1, Arg);
12814   }
12815 
12816   // If this is a variadic call, handle args passed through "...".
12817   if (Proto->isVariadic()) {
12818     // Promote the arguments (C99 6.5.2.2p7).
12819     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12820       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12821                                                         nullptr);
12822       IsError |= Arg.isInvalid();
12823       TheCall->setArg(i + 1, Arg.get());
12824     }
12825   }
12826 
12827   if (IsError) return true;
12828 
12829   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12830 
12831   if (CheckFunctionCall(Method, TheCall, Proto))
12832     return true;
12833 
12834   return MaybeBindToTemporary(TheCall);
12835 }
12836 
12837 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12838 ///  (if one exists), where @c Base is an expression of class type and
12839 /// @c Member is the name of the member we're trying to find.
12840 ExprResult
12841 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12842                                bool *NoArrowOperatorFound) {
12843   assert(Base->getType()->isRecordType() &&
12844          "left-hand side must have class type");
12845 
12846   if (checkPlaceholderForOverload(*this, Base))
12847     return ExprError();
12848 
12849   SourceLocation Loc = Base->getExprLoc();
12850 
12851   // C++ [over.ref]p1:
12852   //
12853   //   [...] An expression x->m is interpreted as (x.operator->())->m
12854   //   for a class object x of type T if T::operator->() exists and if
12855   //   the operator is selected as the best match function by the
12856   //   overload resolution mechanism (13.3).
12857   DeclarationName OpName =
12858     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12859   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12860   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12861 
12862   if (RequireCompleteType(Loc, Base->getType(),
12863                           diag::err_typecheck_incomplete_tag, Base))
12864     return ExprError();
12865 
12866   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12867   LookupQualifiedName(R, BaseRecord->getDecl());
12868   R.suppressDiagnostics();
12869 
12870   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12871        Oper != OperEnd; ++Oper) {
12872     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12873                        None, CandidateSet, /*SuppressUserConversions=*/false);
12874   }
12875 
12876   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12877 
12878   // Perform overload resolution.
12879   OverloadCandidateSet::iterator Best;
12880   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12881   case OR_Success:
12882     // Overload resolution succeeded; we'll build the call below.
12883     break;
12884 
12885   case OR_No_Viable_Function:
12886     if (CandidateSet.empty()) {
12887       QualType BaseType = Base->getType();
12888       if (NoArrowOperatorFound) {
12889         // Report this specific error to the caller instead of emitting a
12890         // diagnostic, as requested.
12891         *NoArrowOperatorFound = true;
12892         return ExprError();
12893       }
12894       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12895         << BaseType << Base->getSourceRange();
12896       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12897         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12898           << FixItHint::CreateReplacement(OpLoc, ".");
12899       }
12900     } else
12901       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12902         << "operator->" << Base->getSourceRange();
12903     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12904     return ExprError();
12905 
12906   case OR_Ambiguous:
12907     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12908       << "->" << Base->getType() << Base->getSourceRange();
12909     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12910     return ExprError();
12911 
12912   case OR_Deleted:
12913     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12914       << Best->Function->isDeleted()
12915       << "->"
12916       << getDeletedOrUnavailableSuffix(Best->Function)
12917       << Base->getSourceRange();
12918     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12919     return ExprError();
12920   }
12921 
12922   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12923 
12924   // Convert the object parameter.
12925   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12926   ExprResult BaseResult =
12927     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12928                                         Best->FoundDecl, Method);
12929   if (BaseResult.isInvalid())
12930     return ExprError();
12931   Base = BaseResult.get();
12932 
12933   // Build the operator call.
12934   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12935                                             HadMultipleCandidates, OpLoc);
12936   if (FnExpr.isInvalid())
12937     return ExprError();
12938 
12939   QualType ResultTy = Method->getReturnType();
12940   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12941   ResultTy = ResultTy.getNonLValueExprType(Context);
12942   CXXOperatorCallExpr *TheCall =
12943     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12944                                       Base, ResultTy, VK, OpLoc, false);
12945 
12946   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12947           return ExprError();
12948 
12949   return MaybeBindToTemporary(TheCall);
12950 }
12951 
12952 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12953 /// a literal operator described by the provided lookup results.
12954 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12955                                           DeclarationNameInfo &SuffixInfo,
12956                                           ArrayRef<Expr*> Args,
12957                                           SourceLocation LitEndLoc,
12958                                        TemplateArgumentListInfo *TemplateArgs) {
12959   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12960 
12961   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12962                                     OverloadCandidateSet::CSK_Normal);
12963   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12964                         /*SuppressUserConversions=*/true);
12965 
12966   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12967 
12968   // Perform overload resolution. This will usually be trivial, but might need
12969   // to perform substitutions for a literal operator template.
12970   OverloadCandidateSet::iterator Best;
12971   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12972   case OR_Success:
12973   case OR_Deleted:
12974     break;
12975 
12976   case OR_No_Viable_Function:
12977     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12978       << R.getLookupName();
12979     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12980     return ExprError();
12981 
12982   case OR_Ambiguous:
12983     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12984     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12985     return ExprError();
12986   }
12987 
12988   FunctionDecl *FD = Best->Function;
12989   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12990                                         HadMultipleCandidates,
12991                                         SuffixInfo.getLoc(),
12992                                         SuffixInfo.getInfo());
12993   if (Fn.isInvalid())
12994     return true;
12995 
12996   // Check the argument types. This should almost always be a no-op, except
12997   // that array-to-pointer decay is applied to string literals.
12998   Expr *ConvArgs[2];
12999   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13000     ExprResult InputInit = PerformCopyInitialization(
13001       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13002       SourceLocation(), Args[ArgIdx]);
13003     if (InputInit.isInvalid())
13004       return true;
13005     ConvArgs[ArgIdx] = InputInit.get();
13006   }
13007 
13008   QualType ResultTy = FD->getReturnType();
13009   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13010   ResultTy = ResultTy.getNonLValueExprType(Context);
13011 
13012   UserDefinedLiteral *UDL =
13013     new (Context) UserDefinedLiteral(Context, Fn.get(),
13014                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13015                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13016 
13017   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13018     return ExprError();
13019 
13020   if (CheckFunctionCall(FD, UDL, nullptr))
13021     return ExprError();
13022 
13023   return MaybeBindToTemporary(UDL);
13024 }
13025 
13026 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13027 /// given LookupResult is non-empty, it is assumed to describe a member which
13028 /// will be invoked. Otherwise, the function will be found via argument
13029 /// dependent lookup.
13030 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13031 /// otherwise CallExpr is set to ExprError() and some non-success value
13032 /// is returned.
13033 Sema::ForRangeStatus
13034 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13035                                 SourceLocation RangeLoc,
13036                                 const DeclarationNameInfo &NameInfo,
13037                                 LookupResult &MemberLookup,
13038                                 OverloadCandidateSet *CandidateSet,
13039                                 Expr *Range, ExprResult *CallExpr) {
13040   Scope *S = nullptr;
13041 
13042   CandidateSet->clear();
13043   if (!MemberLookup.empty()) {
13044     ExprResult MemberRef =
13045         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13046                                  /*IsPtr=*/false, CXXScopeSpec(),
13047                                  /*TemplateKWLoc=*/SourceLocation(),
13048                                  /*FirstQualifierInScope=*/nullptr,
13049                                  MemberLookup,
13050                                  /*TemplateArgs=*/nullptr, S);
13051     if (MemberRef.isInvalid()) {
13052       *CallExpr = ExprError();
13053       return FRS_DiagnosticIssued;
13054     }
13055     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13056     if (CallExpr->isInvalid()) {
13057       *CallExpr = ExprError();
13058       return FRS_DiagnosticIssued;
13059     }
13060   } else {
13061     UnresolvedSet<0> FoundNames;
13062     UnresolvedLookupExpr *Fn =
13063       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13064                                    NestedNameSpecifierLoc(), NameInfo,
13065                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13066                                    FoundNames.begin(), FoundNames.end());
13067 
13068     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13069                                                     CandidateSet, CallExpr);
13070     if (CandidateSet->empty() || CandidateSetError) {
13071       *CallExpr = ExprError();
13072       return FRS_NoViableFunction;
13073     }
13074     OverloadCandidateSet::iterator Best;
13075     OverloadingResult OverloadResult =
13076         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13077 
13078     if (OverloadResult == OR_No_Viable_Function) {
13079       *CallExpr = ExprError();
13080       return FRS_NoViableFunction;
13081     }
13082     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13083                                          Loc, nullptr, CandidateSet, &Best,
13084                                          OverloadResult,
13085                                          /*AllowTypoCorrection=*/false);
13086     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13087       *CallExpr = ExprError();
13088       return FRS_DiagnosticIssued;
13089     }
13090   }
13091   return FRS_Success;
13092 }
13093 
13094 
13095 /// FixOverloadedFunctionReference - E is an expression that refers to
13096 /// a C++ overloaded function (possibly with some parentheses and
13097 /// perhaps a '&' around it). We have resolved the overloaded function
13098 /// to the function declaration Fn, so patch up the expression E to
13099 /// refer (possibly indirectly) to Fn. Returns the new expr.
13100 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13101                                            FunctionDecl *Fn) {
13102   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13103     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13104                                                    Found, Fn);
13105     if (SubExpr == PE->getSubExpr())
13106       return PE;
13107 
13108     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13109   }
13110 
13111   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13112     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13113                                                    Found, Fn);
13114     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13115                                SubExpr->getType()) &&
13116            "Implicit cast type cannot be determined from overload");
13117     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13118     if (SubExpr == ICE->getSubExpr())
13119       return ICE;
13120 
13121     return ImplicitCastExpr::Create(Context, ICE->getType(),
13122                                     ICE->getCastKind(),
13123                                     SubExpr, nullptr,
13124                                     ICE->getValueKind());
13125   }
13126 
13127   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13128     if (!GSE->isResultDependent()) {
13129       Expr *SubExpr =
13130           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13131       if (SubExpr == GSE->getResultExpr())
13132         return GSE;
13133 
13134       // Replace the resulting type information before rebuilding the generic
13135       // selection expression.
13136       ArrayRef<Expr *> A = GSE->getAssocExprs();
13137       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13138       unsigned ResultIdx = GSE->getResultIndex();
13139       AssocExprs[ResultIdx] = SubExpr;
13140 
13141       return new (Context) GenericSelectionExpr(
13142           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13143           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13144           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13145           ResultIdx);
13146     }
13147     // Rather than fall through to the unreachable, return the original generic
13148     // selection expression.
13149     return GSE;
13150   }
13151 
13152   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13153     assert(UnOp->getOpcode() == UO_AddrOf &&
13154            "Can only take the address of an overloaded function");
13155     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13156       if (Method->isStatic()) {
13157         // Do nothing: static member functions aren't any different
13158         // from non-member functions.
13159       } else {
13160         // Fix the subexpression, which really has to be an
13161         // UnresolvedLookupExpr holding an overloaded member function
13162         // or template.
13163         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13164                                                        Found, Fn);
13165         if (SubExpr == UnOp->getSubExpr())
13166           return UnOp;
13167 
13168         assert(isa<DeclRefExpr>(SubExpr)
13169                && "fixed to something other than a decl ref");
13170         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13171                && "fixed to a member ref with no nested name qualifier");
13172 
13173         // We have taken the address of a pointer to member
13174         // function. Perform the computation here so that we get the
13175         // appropriate pointer to member type.
13176         QualType ClassType
13177           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13178         QualType MemPtrType
13179           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13180         // Under the MS ABI, lock down the inheritance model now.
13181         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13182           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13183 
13184         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13185                                            VK_RValue, OK_Ordinary,
13186                                            UnOp->getOperatorLoc());
13187       }
13188     }
13189     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13190                                                    Found, Fn);
13191     if (SubExpr == UnOp->getSubExpr())
13192       return UnOp;
13193 
13194     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13195                                      Context.getPointerType(SubExpr->getType()),
13196                                        VK_RValue, OK_Ordinary,
13197                                        UnOp->getOperatorLoc());
13198   }
13199 
13200   // C++ [except.spec]p17:
13201   //   An exception-specification is considered to be needed when:
13202   //   - in an expression the function is the unique lookup result or the
13203   //     selected member of a set of overloaded functions
13204   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13205     ResolveExceptionSpec(E->getExprLoc(), FPT);
13206 
13207   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13208     // FIXME: avoid copy.
13209     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13210     if (ULE->hasExplicitTemplateArgs()) {
13211       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13212       TemplateArgs = &TemplateArgsBuffer;
13213     }
13214 
13215     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13216                                            ULE->getQualifierLoc(),
13217                                            ULE->getTemplateKeywordLoc(),
13218                                            Fn,
13219                                            /*enclosing*/ false, // FIXME?
13220                                            ULE->getNameLoc(),
13221                                            Fn->getType(),
13222                                            VK_LValue,
13223                                            Found.getDecl(),
13224                                            TemplateArgs);
13225     MarkDeclRefReferenced(DRE);
13226     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13227     return DRE;
13228   }
13229 
13230   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13231     // FIXME: avoid copy.
13232     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13233     if (MemExpr->hasExplicitTemplateArgs()) {
13234       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13235       TemplateArgs = &TemplateArgsBuffer;
13236     }
13237 
13238     Expr *Base;
13239 
13240     // If we're filling in a static method where we used to have an
13241     // implicit member access, rewrite to a simple decl ref.
13242     if (MemExpr->isImplicitAccess()) {
13243       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13244         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13245                                                MemExpr->getQualifierLoc(),
13246                                                MemExpr->getTemplateKeywordLoc(),
13247                                                Fn,
13248                                                /*enclosing*/ false,
13249                                                MemExpr->getMemberLoc(),
13250                                                Fn->getType(),
13251                                                VK_LValue,
13252                                                Found.getDecl(),
13253                                                TemplateArgs);
13254         MarkDeclRefReferenced(DRE);
13255         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13256         return DRE;
13257       } else {
13258         SourceLocation Loc = MemExpr->getMemberLoc();
13259         if (MemExpr->getQualifier())
13260           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13261         CheckCXXThisCapture(Loc);
13262         Base = new (Context) CXXThisExpr(Loc,
13263                                          MemExpr->getBaseType(),
13264                                          /*isImplicit=*/true);
13265       }
13266     } else
13267       Base = MemExpr->getBase();
13268 
13269     ExprValueKind valueKind;
13270     QualType type;
13271     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13272       valueKind = VK_LValue;
13273       type = Fn->getType();
13274     } else {
13275       valueKind = VK_RValue;
13276       type = Context.BoundMemberTy;
13277     }
13278 
13279     MemberExpr *ME = MemberExpr::Create(
13280         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13281         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13282         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13283         OK_Ordinary);
13284     ME->setHadMultipleCandidates(true);
13285     MarkMemberReferenced(ME);
13286     return ME;
13287   }
13288 
13289   llvm_unreachable("Invalid reference to overloaded function");
13290 }
13291 
13292 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13293                                                 DeclAccessPair Found,
13294                                                 FunctionDecl *Fn) {
13295   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13296 }
13297