1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.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                       const Expr *Base, 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)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
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_OCL_Scalar_Widening,
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()->isMemberPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292 ///        from floating point types to integral types should be ignored.
293 NarrowingKind StandardConversionSequence::getNarrowingKind(
294     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331                ToType->isRealFloatingType()) {
332       if (IgnoreFloatToIntegralConversion)
333         return NK_Not_Narrowing;
334       llvm::APSInt IntConstantValue;
335       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       assert(Initializer && "Unknown conversion expression");
337 
338       // If it's value-dependent, we can't tell whether it's narrowing.
339       if (Initializer->isValueDependent())
340         return NK_Dependent_Narrowing;
341 
342       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343         // Convert the integer to the floating type.
344         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                 llvm::APFloat::rmNearestTiesToEven);
347         // And back.
348         llvm::APSInt ConvertedValue = IntConstantValue;
349         bool ignored;
350         Result.convertToInteger(ConvertedValue,
351                                 llvm::APFloat::rmTowardZero, &ignored);
352         // If the resulting value is different, this was a narrowing conversion.
353         if (IntConstantValue != ConvertedValue) {
354           ConstantValue = APValue(IntConstantValue);
355           ConstantType = Initializer->getType();
356           return NK_Constant_Narrowing;
357         }
358       } else {
359         // Variables are always narrowings.
360         return NK_Variable_Narrowing;
361       }
362     }
363     return NK_Not_Narrowing;
364 
365   // -- from long double to double or float, or from double to float, except
366   //    where the source is a constant expression and the actual value after
367   //    conversion is within the range of values that can be represented (even
368   //    if it cannot be represented exactly), or
369   case ICK_Floating_Conversion:
370     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372       // FromType is larger than ToType.
373       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374 
375       // If it's value-dependent, we can't tell whether it's narrowing.
376       if (Initializer->isValueDependent())
377         return NK_Dependent_Narrowing;
378 
379       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380         // Constant!
381         assert(ConstantValue.isFloat());
382         llvm::APFloat FloatVal = ConstantValue.getFloat();
383         // Convert the source value into the target type.
384         bool ignored;
385         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386           Ctx.getFloatTypeSemantics(ToType),
387           llvm::APFloat::rmNearestTiesToEven, &ignored);
388         // If there was no overflow, the source value is within the range of
389         // values that can be represented.
390         if (ConvertStatus & llvm::APFloat::opOverflow) {
391           ConstantType = Initializer->getType();
392           return NK_Constant_Narrowing;
393         }
394       } else {
395         return NK_Variable_Narrowing;
396       }
397     }
398     return NK_Not_Narrowing;
399 
400   // -- from an integer type or unscoped enumeration type to an integer type
401   //    that cannot represent all the values of the original type, except where
402   //    the source is a constant expression and the actual value after
403   //    conversion will fit into the target type and will produce the original
404   //    value when converted back to the original type.
405   case ICK_Integral_Conversion:
406   IntegralConversion: {
407     assert(FromType->isIntegralOrUnscopedEnumerationType());
408     assert(ToType->isIntegralOrUnscopedEnumerationType());
409     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410     const unsigned FromWidth = Ctx.getIntWidth(FromType);
411     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412     const unsigned ToWidth = Ctx.getIntWidth(ToType);
413 
414     if (FromWidth > ToWidth ||
415         (FromWidth == ToWidth && FromSigned != ToSigned) ||
416         (FromSigned && !ToSigned)) {
417       // Not all values of FromType can be represented in ToType.
418       llvm::APSInt InitializerValue;
419       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420 
421       // If it's value-dependent, we can't tell whether it's narrowing.
422       if (Initializer->isValueDependent())
423         return NK_Dependent_Narrowing;
424 
425       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426         // Such conversions on variables are always narrowing.
427         return NK_Variable_Narrowing;
428       }
429       bool Narrowing = false;
430       if (FromWidth < ToWidth) {
431         // Negative -> unsigned is narrowing. Otherwise, more bits is never
432         // narrowing.
433         if (InitializerValue.isSigned() && InitializerValue.isNegative())
434           Narrowing = true;
435       } else {
436         // Add a bit to the InitializerValue so we don't have to worry about
437         // signed vs. unsigned comparisons.
438         InitializerValue = InitializerValue.extend(
439           InitializerValue.getBitWidth() + 1);
440         // Convert the initializer to and from the target width and signed-ness.
441         llvm::APSInt ConvertedValue = InitializerValue;
442         ConvertedValue = ConvertedValue.trunc(ToWidth);
443         ConvertedValue.setIsSigned(ToSigned);
444         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445         ConvertedValue.setIsSigned(InitializerValue.isSigned());
446         // If the result is different, this was a narrowing conversion.
447         if (ConvertedValue != InitializerValue)
448           Narrowing = true;
449       }
450       if (Narrowing) {
451         ConstantType = Initializer->getType();
452         ConstantValue = APValue(InitializerValue);
453         return NK_Constant_Narrowing;
454       }
455     }
456     return NK_Not_Narrowing;
457   }
458 
459   default:
460     // Other kinds of conversions are not narrowings.
461     return NK_Not_Narrowing;
462   }
463 }
464 
465 /// dump - Print this standard conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   bool PrintedSomething = false;
470   if (First != ICK_Identity) {
471     OS << GetImplicitConversionName(First);
472     PrintedSomething = true;
473   }
474 
475   if (Second != ICK_Identity) {
476     if (PrintedSomething) {
477       OS << " -> ";
478     }
479     OS << GetImplicitConversionName(Second);
480 
481     if (CopyConstructor) {
482       OS << " (by copy constructor)";
483     } else if (DirectBinding) {
484       OS << " (direct reference binding)";
485     } else if (ReferenceBinding) {
486       OS << " (reference binding)";
487     }
488     PrintedSomething = true;
489   }
490 
491   if (Third != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Third);
496     PrintedSomething = true;
497   }
498 
499   if (!PrintedSomething) {
500     OS << "No conversions required";
501   }
502 }
503 
504 /// dump - Print this user-defined conversion sequence to standard
505 /// error. Useful for debugging overloading issues.
506 void UserDefinedConversionSequence::dump() const {
507   raw_ostream &OS = llvm::errs();
508   if (Before.First || Before.Second || Before.Third) {
509     Before.dump();
510     OS << " -> ";
511   }
512   if (ConversionFunction)
513     OS << '\'' << *ConversionFunction << '\'';
514   else
515     OS << "aggregate initialization";
516   if (After.First || After.Second || After.Third) {
517     OS << " -> ";
518     After.dump();
519   }
520 }
521 
522 /// dump - Print this implicit conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void ImplicitConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (isStdInitializerListElement())
527     OS << "Worst std::initializer_list element conversion: ";
528   switch (ConversionKind) {
529   case StandardConversion:
530     OS << "Standard conversion: ";
531     Standard.dump();
532     break;
533   case UserDefinedConversion:
534     OS << "User-defined conversion: ";
535     UserDefined.dump();
536     break;
537   case EllipsisConversion:
538     OS << "Ellipsis conversion";
539     break;
540   case AmbiguousConversion:
541     OS << "Ambiguous conversion";
542     break;
543   case BadConversion:
544     OS << "Bad conversion";
545     break;
546   }
547 
548   OS << "\n";
549 }
550 
551 void AmbiguousConversionSequence::construct() {
552   new (&conversions()) ConversionSet();
553 }
554 
555 void AmbiguousConversionSequence::destruct() {
556   conversions().~ConversionSet();
557 }
558 
559 void
560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561   FromTypePtr = O.FromTypePtr;
562   ToTypePtr = O.ToTypePtr;
563   new (&conversions()) ConversionSet(O.conversions());
564 }
565 
566 namespace {
567   // Structure used by DeductionFailureInfo to store
568   // template argument information.
569   struct DFIArguments {
570     TemplateArgument FirstArg;
571     TemplateArgument SecondArg;
572   };
573   // Structure used by DeductionFailureInfo to store
574   // template parameter and template argument information.
575   struct DFIParamWithArguments : DFIArguments {
576     TemplateParameter Param;
577   };
578   // Structure used by DeductionFailureInfo to store template argument
579   // information and the index of the problematic call argument.
580   struct DFIDeducedMismatchArgs : DFIArguments {
581     TemplateArgumentList *TemplateArgs;
582     unsigned CallArgIndex;
583   };
584 }
585 
586 /// Convert from Sema's representation of template deduction information
587 /// to the form used in overload-candidate information.
588 DeductionFailureInfo
589 clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                 Sema::TemplateDeductionResult TDK,
591                                 TemplateDeductionInfo &Info) {
592   DeductionFailureInfo Result;
593   Result.Result = static_cast<unsigned>(TDK);
594   Result.HasDiagnostic = false;
595   switch (TDK) {
596   case Sema::TDK_Invalid:
597   case Sema::TDK_InstantiationDepth:
598   case Sema::TDK_TooManyArguments:
599   case Sema::TDK_TooFewArguments:
600   case Sema::TDK_MiscellaneousDeductionFailure:
601   case Sema::TDK_CUDATargetMismatch:
602     Result.Data = nullptr;
603     break;
604 
605   case Sema::TDK_Incomplete:
606   case Sema::TDK_InvalidExplicitArguments:
607     Result.Data = Info.Param.getOpaqueValue();
608     break;
609 
610   case Sema::TDK_DeducedMismatch:
611   case Sema::TDK_DeducedMismatchNested: {
612     // FIXME: Should allocate from normal heap so that we can free this later.
613     auto *Saved = new (Context) DFIDeducedMismatchArgs;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Saved->TemplateArgs = Info.take();
617     Saved->CallArgIndex = Info.CallArgIndex;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_NonDeducedMismatch: {
623     // FIXME: Should allocate from normal heap so that we can free this later.
624     DFIArguments *Saved = new (Context) DFIArguments;
625     Saved->FirstArg = Info.FirstArg;
626     Saved->SecondArg = Info.SecondArg;
627     Result.Data = Saved;
628     break;
629   }
630 
631   case Sema::TDK_IncompletePack:
632     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
633   case Sema::TDK_Inconsistent:
634   case Sema::TDK_Underqualified: {
635     // FIXME: Should allocate from normal heap so that we can free this later.
636     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
637     Saved->Param = Info.Param;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Result.Data = Saved;
641     break;
642   }
643 
644   case Sema::TDK_SubstitutionFailure:
645     Result.Data = Info.take();
646     if (Info.hasSFINAEDiagnostic()) {
647       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
648           SourceLocation(), PartialDiagnostic::NullDiagnostic());
649       Info.takeSFINAEDiagnostic(*Diag);
650       Result.HasDiagnostic = true;
651     }
652     break;
653 
654   case Sema::TDK_Success:
655   case Sema::TDK_NonDependentConversionFailure:
656     llvm_unreachable("not a deduction failure");
657   }
658 
659   return Result;
660 }
661 
662 void DeductionFailureInfo::Destroy() {
663   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
664   case Sema::TDK_Success:
665   case Sema::TDK_Invalid:
666   case Sema::TDK_InstantiationDepth:
667   case Sema::TDK_Incomplete:
668   case Sema::TDK_TooManyArguments:
669   case Sema::TDK_TooFewArguments:
670   case Sema::TDK_InvalidExplicitArguments:
671   case Sema::TDK_CUDATargetMismatch:
672   case Sema::TDK_NonDependentConversionFailure:
673     break;
674 
675   case Sema::TDK_IncompletePack:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_DeducedMismatch:
679   case Sema::TDK_DeducedMismatchNested:
680   case Sema::TDK_NonDeducedMismatch:
681     // FIXME: Destroy the data?
682     Data = nullptr;
683     break;
684 
685   case Sema::TDK_SubstitutionFailure:
686     // FIXME: Destroy the template argument list?
687     Data = nullptr;
688     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
689       Diag->~PartialDiagnosticAt();
690       HasDiagnostic = false;
691     }
692     break;
693 
694   // Unhandled
695   case Sema::TDK_MiscellaneousDeductionFailure:
696     break;
697   }
698 }
699 
700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
701   if (HasDiagnostic)
702     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
703   return nullptr;
704 }
705 
706 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
707   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708   case Sema::TDK_Success:
709   case Sema::TDK_Invalid:
710   case Sema::TDK_InstantiationDepth:
711   case Sema::TDK_TooManyArguments:
712   case Sema::TDK_TooFewArguments:
713   case Sema::TDK_SubstitutionFailure:
714   case Sema::TDK_DeducedMismatch:
715   case Sema::TDK_DeducedMismatchNested:
716   case Sema::TDK_NonDeducedMismatch:
717   case Sema::TDK_CUDATargetMismatch:
718   case Sema::TDK_NonDependentConversionFailure:
719     return TemplateParameter();
720 
721   case Sema::TDK_Incomplete:
722   case Sema::TDK_InvalidExplicitArguments:
723     return TemplateParameter::getFromOpaqueValue(Data);
724 
725   case Sema::TDK_IncompletePack:
726   case Sema::TDK_Inconsistent:
727   case Sema::TDK_Underqualified:
728     return static_cast<DFIParamWithArguments*>(Data)->Param;
729 
730   // Unhandled
731   case Sema::TDK_MiscellaneousDeductionFailure:
732     break;
733   }
734 
735   return TemplateParameter();
736 }
737 
738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
739   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
740   case Sema::TDK_Success:
741   case Sema::TDK_Invalid:
742   case Sema::TDK_InstantiationDepth:
743   case Sema::TDK_TooManyArguments:
744   case Sema::TDK_TooFewArguments:
745   case Sema::TDK_Incomplete:
746   case Sema::TDK_IncompletePack:
747   case Sema::TDK_InvalidExplicitArguments:
748   case Sema::TDK_Inconsistent:
749   case Sema::TDK_Underqualified:
750   case Sema::TDK_NonDeducedMismatch:
751   case Sema::TDK_CUDATargetMismatch:
752   case Sema::TDK_NonDependentConversionFailure:
753     return nullptr;
754 
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
758 
759   case Sema::TDK_SubstitutionFailure:
760     return static_cast<TemplateArgumentList*>(Data);
761 
762   // Unhandled
763   case Sema::TDK_MiscellaneousDeductionFailure:
764     break;
765   }
766 
767   return nullptr;
768 }
769 
770 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
771   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
772   case Sema::TDK_Success:
773   case Sema::TDK_Invalid:
774   case Sema::TDK_InstantiationDepth:
775   case Sema::TDK_Incomplete:
776   case Sema::TDK_TooManyArguments:
777   case Sema::TDK_TooFewArguments:
778   case Sema::TDK_InvalidExplicitArguments:
779   case Sema::TDK_SubstitutionFailure:
780   case Sema::TDK_CUDATargetMismatch:
781   case Sema::TDK_NonDependentConversionFailure:
782     return nullptr;
783 
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_Inconsistent:
786   case Sema::TDK_Underqualified:
787   case Sema::TDK_DeducedMismatch:
788   case Sema::TDK_DeducedMismatchNested:
789   case Sema::TDK_NonDeducedMismatch:
790     return &static_cast<DFIArguments*>(Data)->FirstArg;
791 
792   // Unhandled
793   case Sema::TDK_MiscellaneousDeductionFailure:
794     break;
795   }
796 
797   return nullptr;
798 }
799 
800 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
801   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802   case Sema::TDK_Success:
803   case Sema::TDK_Invalid:
804   case Sema::TDK_InstantiationDepth:
805   case Sema::TDK_Incomplete:
806   case Sema::TDK_IncompletePack:
807   case Sema::TDK_TooManyArguments:
808   case Sema::TDK_TooFewArguments:
809   case Sema::TDK_InvalidExplicitArguments:
810   case Sema::TDK_SubstitutionFailure:
811   case Sema::TDK_CUDATargetMismatch:
812   case Sema::TDK_NonDependentConversionFailure:
813     return nullptr;
814 
815   case Sema::TDK_Inconsistent:
816   case Sema::TDK_Underqualified:
817   case Sema::TDK_DeducedMismatch:
818   case Sema::TDK_DeducedMismatchNested:
819   case Sema::TDK_NonDeducedMismatch:
820     return &static_cast<DFIArguments*>(Data)->SecondArg;
821 
822   // Unhandled
823   case Sema::TDK_MiscellaneousDeductionFailure:
824     break;
825   }
826 
827   return nullptr;
828 }
829 
830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
831   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
832   case Sema::TDK_DeducedMismatch:
833   case Sema::TDK_DeducedMismatchNested:
834     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
835 
836   default:
837     return llvm::None;
838   }
839 }
840 
841 void OverloadCandidateSet::destroyCandidates() {
842   for (iterator i = begin(), e = end(); i != e; ++i) {
843     for (auto &C : i->Conversions)
844       C.~ImplicitConversionSequence();
845     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
846       i->DeductionFailure.Destroy();
847   }
848 }
849 
850 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
851   destroyCandidates();
852   SlabAllocator.Reset();
853   NumInlineBytesUsed = 0;
854   Candidates.clear();
855   Functions.clear();
856   Kind = CSK;
857 }
858 
859 namespace {
860   class UnbridgedCastsSet {
861     struct Entry {
862       Expr **Addr;
863       Expr *Saved;
864     };
865     SmallVector<Entry, 2> Entries;
866 
867   public:
868     void save(Sema &S, Expr *&E) {
869       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
870       Entry entry = { &E, E };
871       Entries.push_back(entry);
872       E = S.stripARCUnbridgedCast(E);
873     }
874 
875     void restore() {
876       for (SmallVectorImpl<Entry>::iterator
877              i = Entries.begin(), e = Entries.end(); i != e; ++i)
878         *i->Addr = i->Saved;
879     }
880   };
881 }
882 
883 /// checkPlaceholderForOverload - Do any interesting placeholder-like
884 /// preprocessing on the given expression.
885 ///
886 /// \param unbridgedCasts a collection to which to add unbridged casts;
887 ///   without this, they will be immediately diagnosed as errors
888 ///
889 /// Return true on unrecoverable error.
890 static bool
891 checkPlaceholderForOverload(Sema &S, Expr *&E,
892                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
893   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
894     // We can't handle overloaded expressions here because overload
895     // resolution might reasonably tweak them.
896     if (placeholder->getKind() == BuiltinType::Overload) return false;
897 
898     // If the context potentially accepts unbridged ARC casts, strip
899     // the unbridged cast and add it to the collection for later restoration.
900     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
901         unbridgedCasts) {
902       unbridgedCasts->save(S, E);
903       return false;
904     }
905 
906     // Go ahead and check everything else.
907     ExprResult result = S.CheckPlaceholderExpr(E);
908     if (result.isInvalid())
909       return true;
910 
911     E = result.get();
912     return false;
913   }
914 
915   // Nothing to do.
916   return false;
917 }
918 
919 /// checkArgPlaceholdersForOverload - Check a set of call operands for
920 /// placeholders.
921 static bool checkArgPlaceholdersForOverload(Sema &S,
922                                             MultiExprArg Args,
923                                             UnbridgedCastsSet &unbridged) {
924   for (unsigned i = 0, e = Args.size(); i != e; ++i)
925     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
926       return true;
927 
928   return false;
929 }
930 
931 /// Determine whether the given New declaration is an overload of the
932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
933 /// New and Old cannot be overloaded, e.g., if New has the same signature as
934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
935 /// functions (or function templates) at all. When it does return Ovl_Match or
936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
938 /// declaration.
939 ///
940 /// Example: Given the following input:
941 ///
942 ///   void f(int, float); // #1
943 ///   void f(int, int); // #2
944 ///   int f(int, int); // #3
945 ///
946 /// When we process #1, there is no previous declaration of "f", so IsOverload
947 /// will not be used.
948 ///
949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
950 /// the parameter types, we see that #1 and #2 are overloaded (since they have
951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
952 /// unchanged.
953 ///
954 /// When we process #3, Old is an overload set containing #1 and #2. We compare
955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
957 /// functions are not part of the signature), IsOverload returns Ovl_Match and
958 /// MatchedDecl will be set to point to the FunctionDecl for #2.
959 ///
960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
961 /// by a using declaration. The rules for whether to hide shadow declarations
962 /// ignore some properties which otherwise figure into a function template's
963 /// signature.
964 Sema::OverloadKind
965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
966                     NamedDecl *&Match, bool NewIsUsingDecl) {
967   for (LookupResult::iterator I = Old.begin(), E = Old.end();
968          I != E; ++I) {
969     NamedDecl *OldD = *I;
970 
971     bool OldIsUsingDecl = false;
972     if (isa<UsingShadowDecl>(OldD)) {
973       OldIsUsingDecl = true;
974 
975       // We can always introduce two using declarations into the same
976       // context, even if they have identical signatures.
977       if (NewIsUsingDecl) continue;
978 
979       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980     }
981 
982     // A using-declaration does not conflict with another declaration
983     // if one of them is hidden.
984     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
985       continue;
986 
987     // If either declaration was introduced by a using declaration,
988     // we'll need to use slightly different rules for matching.
989     // Essentially, these rules are the normal rules, except that
990     // function templates hide function templates with different
991     // return types or template parameter lists.
992     bool UseMemberUsingDeclRules =
993       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
994       !New->getFriendObjectKind();
995 
996     if (FunctionDecl *OldF = OldD->getAsFunction()) {
997       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
998         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
999           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1000           continue;
1001         }
1002 
1003         if (!isa<FunctionTemplateDecl>(OldD) &&
1004             !shouldLinkPossiblyHiddenDecl(*I, New))
1005           continue;
1006 
1007         Match = *I;
1008         return Ovl_Match;
1009       }
1010 
1011       // Builtins that have custom typechecking or have a reference should
1012       // not be overloadable or redeclarable.
1013       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1018       // We can overload with these, which can show up when doing
1019       // redeclaration checks for UsingDecls.
1020       assert(Old.getLookupKind() == LookupUsingDeclName);
1021     } else if (isa<TagDecl>(OldD)) {
1022       // We can always overload with tags by hiding them.
1023     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1024       // Optimistically assume that an unresolved using decl will
1025       // overload; if it doesn't, we'll have to diagnose during
1026       // template instantiation.
1027       //
1028       // Exception: if the scope is dependent and this is not a class
1029       // member, the using declaration can only introduce an enumerator.
1030       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1031         Match = *I;
1032         return Ovl_NonFunction;
1033       }
1034     } else {
1035       // (C++ 13p1):
1036       //   Only function declarations can be overloaded; object and type
1037       //   declarations cannot be overloaded.
1038       Match = *I;
1039       return Ovl_NonFunction;
1040     }
1041   }
1042 
1043   // C++ [temp.friend]p1:
1044   //   For a friend function declaration that is not a template declaration:
1045   //    -- if the name of the friend is a qualified or unqualified template-id,
1046   //       [...], otherwise
1047   //    -- if the name of the friend is a qualified-id and a matching
1048   //       non-template function is found in the specified class or namespace,
1049   //       the friend declaration refers to that function, otherwise,
1050   //    -- if the name of the friend is a qualified-id and a matching function
1051   //       template is found in the specified class or namespace, the friend
1052   //       declaration refers to the deduced specialization of that function
1053   //       template, otherwise
1054   //    -- the name shall be an unqualified-id [...]
1055   // If we get here for a qualified friend declaration, we've just reached the
1056   // third bullet. If the type of the friend is dependent, skip this lookup
1057   // until instantiation.
1058   if (New->getFriendObjectKind() && New->getQualifier() &&
1059       !New->getDependentSpecializationInfo() &&
1060       !New->getType()->isDependentType()) {
1061     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1062     TemplateSpecResult.addAllDecls(Old);
1063     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1064                                             /*QualifiedFriend*/true)) {
1065       New->setInvalidDecl();
1066       return Ovl_Overload;
1067     }
1068 
1069     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1070     return Ovl_Match;
1071   }
1072 
1073   return Ovl_Overload;
1074 }
1075 
1076 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1077                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1078   // C++ [basic.start.main]p2: This function shall not be overloaded.
1079   if (New->isMain())
1080     return false;
1081 
1082   // MSVCRT user defined entry points cannot be overloaded.
1083   if (New->isMSVCRTEntryPoint())
1084     return false;
1085 
1086   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1087   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1088 
1089   // C++ [temp.fct]p2:
1090   //   A function template can be overloaded with other function templates
1091   //   and with normal (non-template) functions.
1092   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1093     return true;
1094 
1095   // Is the function New an overload of the function Old?
1096   QualType OldQType = Context.getCanonicalType(Old->getType());
1097   QualType NewQType = Context.getCanonicalType(New->getType());
1098 
1099   // Compare the signatures (C++ 1.3.10) of the two functions to
1100   // determine whether they are overloads. If we find any mismatch
1101   // in the signature, they are overloads.
1102 
1103   // If either of these functions is a K&R-style function (no
1104   // prototype), then we consider them to have matching signatures.
1105   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1106       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1107     return false;
1108 
1109   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1110   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1111 
1112   // The signature of a function includes the types of its
1113   // parameters (C++ 1.3.10), which includes the presence or absence
1114   // of the ellipsis; see C++ DR 357).
1115   if (OldQType != NewQType &&
1116       (OldType->getNumParams() != NewType->getNumParams() ||
1117        OldType->isVariadic() != NewType->isVariadic() ||
1118        !FunctionParamTypesAreEqual(OldType, NewType)))
1119     return true;
1120 
1121   // C++ [temp.over.link]p4:
1122   //   The signature of a function template consists of its function
1123   //   signature, its return type and its template parameter list. The names
1124   //   of the template parameters are significant only for establishing the
1125   //   relationship between the template parameters and the rest of the
1126   //   signature.
1127   //
1128   // We check the return type and template parameter lists for function
1129   // templates first; the remaining checks follow.
1130   //
1131   // However, we don't consider either of these when deciding whether
1132   // a member introduced by a shadow declaration is hidden.
1133   if (!UseMemberUsingDeclRules && NewTemplate &&
1134       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1135                                        OldTemplate->getTemplateParameters(),
1136                                        false, TPL_TemplateMatch) ||
1137        !Context.hasSameType(Old->getDeclaredReturnType(),
1138                             New->getDeclaredReturnType())))
1139     return true;
1140 
1141   // If the function is a class member, its signature includes the
1142   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1143   //
1144   // As part of this, also check whether one of the member functions
1145   // is static, in which case they are not overloads (C++
1146   // 13.1p2). While not part of the definition of the signature,
1147   // this check is important to determine whether these functions
1148   // can be overloaded.
1149   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1150   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1151   if (OldMethod && NewMethod &&
1152       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1153     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1154       if (!UseMemberUsingDeclRules &&
1155           (OldMethod->getRefQualifier() == RQ_None ||
1156            NewMethod->getRefQualifier() == RQ_None)) {
1157         // C++0x [over.load]p2:
1158         //   - Member function declarations with the same name and the same
1159         //     parameter-type-list as well as member function template
1160         //     declarations with the same name, the same parameter-type-list, and
1161         //     the same template parameter lists cannot be overloaded if any of
1162         //     them, but not all, have a ref-qualifier (8.3.5).
1163         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1164           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1165         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1166       }
1167       return true;
1168     }
1169 
1170     // We may not have applied the implicit const for a constexpr member
1171     // function yet (because we haven't yet resolved whether this is a static
1172     // or non-static member function). Add it now, on the assumption that this
1173     // is a redeclaration of OldMethod.
1174     auto OldQuals = OldMethod->getMethodQualifiers();
1175     auto NewQuals = NewMethod->getMethodQualifiers();
1176     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1177         !isa<CXXConstructorDecl>(NewMethod))
1178       NewQuals.addConst();
1179     // We do not allow overloading based off of '__restrict'.
1180     OldQuals.removeRestrict();
1181     NewQuals.removeRestrict();
1182     if (OldQuals != NewQuals)
1183       return true;
1184   }
1185 
1186   // Though pass_object_size is placed on parameters and takes an argument, we
1187   // consider it to be a function-level modifier for the sake of function
1188   // identity. Either the function has one or more parameters with
1189   // pass_object_size or it doesn't.
1190   if (functionHasPassObjectSizeParams(New) !=
1191       functionHasPassObjectSizeParams(Old))
1192     return true;
1193 
1194   // enable_if attributes are an order-sensitive part of the signature.
1195   for (specific_attr_iterator<EnableIfAttr>
1196          NewI = New->specific_attr_begin<EnableIfAttr>(),
1197          NewE = New->specific_attr_end<EnableIfAttr>(),
1198          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1199          OldE = Old->specific_attr_end<EnableIfAttr>();
1200        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1201     if (NewI == NewE || OldI == OldE)
1202       return true;
1203     llvm::FoldingSetNodeID NewID, OldID;
1204     NewI->getCond()->Profile(NewID, Context, true);
1205     OldI->getCond()->Profile(OldID, Context, true);
1206     if (NewID != OldID)
1207       return true;
1208   }
1209 
1210   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1211     // Don't allow overloading of destructors.  (In theory we could, but it
1212     // would be a giant change to clang.)
1213     if (isa<CXXDestructorDecl>(New))
1214       return false;
1215 
1216     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1217                        OldTarget = IdentifyCUDATarget(Old);
1218     if (NewTarget == CFT_InvalidTarget)
1219       return false;
1220 
1221     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1222 
1223     // Allow overloading of functions with same signature and different CUDA
1224     // target attributes.
1225     return NewTarget != OldTarget;
1226   }
1227 
1228   // The signatures match; this is not an overload.
1229   return false;
1230 }
1231 
1232 /// Checks availability of the function depending on the current
1233 /// function context. Inside an unavailable function, unavailability is ignored.
1234 ///
1235 /// \returns true if \arg FD is unavailable and current context is inside
1236 /// an available function, false otherwise.
1237 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1238   if (!FD->isUnavailable())
1239     return false;
1240 
1241   // Walk up the context of the caller.
1242   Decl *C = cast<Decl>(CurContext);
1243   do {
1244     if (C->isUnavailable())
1245       return false;
1246   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1247   return true;
1248 }
1249 
1250 /// Tries a user-defined conversion from From to ToType.
1251 ///
1252 /// Produces an implicit conversion sequence for when a standard conversion
1253 /// is not an option. See TryImplicitConversion for more information.
1254 static ImplicitConversionSequence
1255 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1256                          bool SuppressUserConversions,
1257                          bool AllowExplicit,
1258                          bool InOverloadResolution,
1259                          bool CStyle,
1260                          bool AllowObjCWritebackConversion,
1261                          bool AllowObjCConversionOnExplicit) {
1262   ImplicitConversionSequence ICS;
1263 
1264   if (SuppressUserConversions) {
1265     // We're not in the case above, so there is no conversion that
1266     // we can perform.
1267     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1268     return ICS;
1269   }
1270 
1271   // Attempt user-defined conversion.
1272   OverloadCandidateSet Conversions(From->getExprLoc(),
1273                                    OverloadCandidateSet::CSK_Normal);
1274   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1275                                   Conversions, AllowExplicit,
1276                                   AllowObjCConversionOnExplicit)) {
1277   case OR_Success:
1278   case OR_Deleted:
1279     ICS.setUserDefined();
1280     // C++ [over.ics.user]p4:
1281     //   A conversion of an expression of class type to the same class
1282     //   type is given Exact Match rank, and a conversion of an
1283     //   expression of class type to a base class of that type is
1284     //   given Conversion rank, in spite of the fact that a copy
1285     //   constructor (i.e., a user-defined conversion function) is
1286     //   called for those cases.
1287     if (CXXConstructorDecl *Constructor
1288           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1289       QualType FromCanon
1290         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1291       QualType ToCanon
1292         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1293       if (Constructor->isCopyConstructor() &&
1294           (FromCanon == ToCanon ||
1295            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1296         // Turn this into a "standard" conversion sequence, so that it
1297         // gets ranked with standard conversion sequences.
1298         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1299         ICS.setStandard();
1300         ICS.Standard.setAsIdentityConversion();
1301         ICS.Standard.setFromType(From->getType());
1302         ICS.Standard.setAllToTypes(ToType);
1303         ICS.Standard.CopyConstructor = Constructor;
1304         ICS.Standard.FoundCopyConstructor = Found;
1305         if (ToCanon != FromCanon)
1306           ICS.Standard.Second = ICK_Derived_To_Base;
1307       }
1308     }
1309     break;
1310 
1311   case OR_Ambiguous:
1312     ICS.setAmbiguous();
1313     ICS.Ambiguous.setFromType(From->getType());
1314     ICS.Ambiguous.setToType(ToType);
1315     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1316          Cand != Conversions.end(); ++Cand)
1317       if (Cand->Viable)
1318         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1319     break;
1320 
1321     // Fall through.
1322   case OR_No_Viable_Function:
1323     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1324     break;
1325   }
1326 
1327   return ICS;
1328 }
1329 
1330 /// TryImplicitConversion - Attempt to perform an implicit conversion
1331 /// from the given expression (Expr) to the given type (ToType). This
1332 /// function returns an implicit conversion sequence that can be used
1333 /// to perform the initialization. Given
1334 ///
1335 ///   void f(float f);
1336 ///   void g(int i) { f(i); }
1337 ///
1338 /// this routine would produce an implicit conversion sequence to
1339 /// describe the initialization of f from i, which will be a standard
1340 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1341 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1342 //
1343 /// Note that this routine only determines how the conversion can be
1344 /// performed; it does not actually perform the conversion. As such,
1345 /// it will not produce any diagnostics if no conversion is available,
1346 /// but will instead return an implicit conversion sequence of kind
1347 /// "BadConversion".
1348 ///
1349 /// If @p SuppressUserConversions, then user-defined conversions are
1350 /// not permitted.
1351 /// If @p AllowExplicit, then explicit user-defined conversions are
1352 /// permitted.
1353 ///
1354 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1355 /// writeback conversion, which allows __autoreleasing id* parameters to
1356 /// be initialized with __strong id* or __weak id* arguments.
1357 static ImplicitConversionSequence
1358 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1359                       bool SuppressUserConversions,
1360                       bool AllowExplicit,
1361                       bool InOverloadResolution,
1362                       bool CStyle,
1363                       bool AllowObjCWritebackConversion,
1364                       bool AllowObjCConversionOnExplicit) {
1365   ImplicitConversionSequence ICS;
1366   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1367                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1368     ICS.setStandard();
1369     return ICS;
1370   }
1371 
1372   if (!S.getLangOpts().CPlusPlus) {
1373     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1374     return ICS;
1375   }
1376 
1377   // C++ [over.ics.user]p4:
1378   //   A conversion of an expression of class type to the same class
1379   //   type is given Exact Match rank, and a conversion of an
1380   //   expression of class type to a base class of that type is
1381   //   given Conversion rank, in spite of the fact that a copy/move
1382   //   constructor (i.e., a user-defined conversion function) is
1383   //   called for those cases.
1384   QualType FromType = From->getType();
1385   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1386       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1387        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1388     ICS.setStandard();
1389     ICS.Standard.setAsIdentityConversion();
1390     ICS.Standard.setFromType(FromType);
1391     ICS.Standard.setAllToTypes(ToType);
1392 
1393     // We don't actually check at this point whether there is a valid
1394     // copy/move constructor, since overloading just assumes that it
1395     // exists. When we actually perform initialization, we'll find the
1396     // appropriate constructor to copy the returned object, if needed.
1397     ICS.Standard.CopyConstructor = nullptr;
1398 
1399     // Determine whether this is considered a derived-to-base conversion.
1400     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1401       ICS.Standard.Second = ICK_Derived_To_Base;
1402 
1403     return ICS;
1404   }
1405 
1406   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1407                                   AllowExplicit, InOverloadResolution, CStyle,
1408                                   AllowObjCWritebackConversion,
1409                                   AllowObjCConversionOnExplicit);
1410 }
1411 
1412 ImplicitConversionSequence
1413 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1414                             bool SuppressUserConversions,
1415                             bool AllowExplicit,
1416                             bool InOverloadResolution,
1417                             bool CStyle,
1418                             bool AllowObjCWritebackConversion) {
1419   return ::TryImplicitConversion(*this, From, ToType,
1420                                  SuppressUserConversions, AllowExplicit,
1421                                  InOverloadResolution, CStyle,
1422                                  AllowObjCWritebackConversion,
1423                                  /*AllowObjCConversionOnExplicit=*/false);
1424 }
1425 
1426 /// PerformImplicitConversion - Perform an implicit conversion of the
1427 /// expression From to the type ToType. Returns the
1428 /// converted expression. Flavor is the kind of conversion we're
1429 /// performing, used in the error message. If @p AllowExplicit,
1430 /// explicit user-defined conversions are permitted.
1431 ExprResult
1432 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1433                                 AssignmentAction Action, bool AllowExplicit) {
1434   ImplicitConversionSequence ICS;
1435   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1436 }
1437 
1438 ExprResult
1439 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1440                                 AssignmentAction Action, bool AllowExplicit,
1441                                 ImplicitConversionSequence& ICS) {
1442   if (checkPlaceholderForOverload(*this, From))
1443     return ExprError();
1444 
1445   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1446   bool AllowObjCWritebackConversion
1447     = getLangOpts().ObjCAutoRefCount &&
1448       (Action == AA_Passing || Action == AA_Sending);
1449   if (getLangOpts().ObjC)
1450     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1451                                       From->getType(), From);
1452   ICS = ::TryImplicitConversion(*this, From, ToType,
1453                                 /*SuppressUserConversions=*/false,
1454                                 AllowExplicit,
1455                                 /*InOverloadResolution=*/false,
1456                                 /*CStyle=*/false,
1457                                 AllowObjCWritebackConversion,
1458                                 /*AllowObjCConversionOnExplicit=*/false);
1459   return PerformImplicitConversion(From, ToType, ICS, Action);
1460 }
1461 
1462 /// Determine whether the conversion from FromType to ToType is a valid
1463 /// conversion that strips "noexcept" or "noreturn" off the nested function
1464 /// type.
1465 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1466                                 QualType &ResultTy) {
1467   if (Context.hasSameUnqualifiedType(FromType, ToType))
1468     return false;
1469 
1470   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1471   //                    or F(t noexcept) -> F(t)
1472   // where F adds one of the following at most once:
1473   //   - a pointer
1474   //   - a member pointer
1475   //   - a block pointer
1476   // Changes here need matching changes in FindCompositePointerType.
1477   CanQualType CanTo = Context.getCanonicalType(ToType);
1478   CanQualType CanFrom = Context.getCanonicalType(FromType);
1479   Type::TypeClass TyClass = CanTo->getTypeClass();
1480   if (TyClass != CanFrom->getTypeClass()) return false;
1481   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1482     if (TyClass == Type::Pointer) {
1483       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1484       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1485     } else if (TyClass == Type::BlockPointer) {
1486       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1487       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1488     } else if (TyClass == Type::MemberPointer) {
1489       auto ToMPT = CanTo.getAs<MemberPointerType>();
1490       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1491       // A function pointer conversion cannot change the class of the function.
1492       if (ToMPT->getClass() != FromMPT->getClass())
1493         return false;
1494       CanTo = ToMPT->getPointeeType();
1495       CanFrom = FromMPT->getPointeeType();
1496     } else {
1497       return false;
1498     }
1499 
1500     TyClass = CanTo->getTypeClass();
1501     if (TyClass != CanFrom->getTypeClass()) return false;
1502     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1503       return false;
1504   }
1505 
1506   const auto *FromFn = cast<FunctionType>(CanFrom);
1507   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1508 
1509   const auto *ToFn = cast<FunctionType>(CanTo);
1510   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1511 
1512   bool Changed = false;
1513 
1514   // Drop 'noreturn' if not present in target type.
1515   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1516     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1517     Changed = true;
1518   }
1519 
1520   // Drop 'noexcept' if not present in target type.
1521   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1522     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1523     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1524       FromFn = cast<FunctionType>(
1525           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1526                                                    EST_None)
1527                  .getTypePtr());
1528       Changed = true;
1529     }
1530 
1531     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1532     // only if the ExtParameterInfo lists of the two function prototypes can be
1533     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1534     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1535     bool CanUseToFPT, CanUseFromFPT;
1536     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1537                                       CanUseFromFPT, NewParamInfos) &&
1538         CanUseToFPT && !CanUseFromFPT) {
1539       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1540       ExtInfo.ExtParameterInfos =
1541           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1542       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1543                                             FromFPT->getParamTypes(), ExtInfo);
1544       FromFn = QT->getAs<FunctionType>();
1545       Changed = true;
1546     }
1547   }
1548 
1549   if (!Changed)
1550     return false;
1551 
1552   assert(QualType(FromFn, 0).isCanonical());
1553   if (QualType(FromFn, 0) != CanTo) return false;
1554 
1555   ResultTy = ToType;
1556   return true;
1557 }
1558 
1559 /// Determine whether the conversion from FromType to ToType is a valid
1560 /// vector conversion.
1561 ///
1562 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1563 /// conversion.
1564 static bool IsVectorConversion(Sema &S, QualType FromType,
1565                                QualType ToType, ImplicitConversionKind &ICK) {
1566   // We need at least one of these types to be a vector type to have a vector
1567   // conversion.
1568   if (!ToType->isVectorType() && !FromType->isVectorType())
1569     return false;
1570 
1571   // Identical types require no conversions.
1572   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1573     return false;
1574 
1575   // There are no conversions between extended vector types, only identity.
1576   if (ToType->isExtVectorType()) {
1577     // There are no conversions between extended vector types other than the
1578     // identity conversion.
1579     if (FromType->isExtVectorType())
1580       return false;
1581 
1582     // Vector splat from any arithmetic type to a vector.
1583     if (FromType->isArithmeticType()) {
1584       ICK = ICK_Vector_Splat;
1585       return true;
1586     }
1587   }
1588 
1589   // We can perform the conversion between vector types in the following cases:
1590   // 1)vector types are equivalent AltiVec and GCC vector types
1591   // 2)lax vector conversions are permitted and the vector types are of the
1592   //   same size
1593   if (ToType->isVectorType() && FromType->isVectorType()) {
1594     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1595         S.isLaxVectorConversion(FromType, ToType)) {
1596       ICK = ICK_Vector_Conversion;
1597       return true;
1598     }
1599   }
1600 
1601   return false;
1602 }
1603 
1604 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1605                                 bool InOverloadResolution,
1606                                 StandardConversionSequence &SCS,
1607                                 bool CStyle);
1608 
1609 /// IsStandardConversion - Determines whether there is a standard
1610 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1611 /// expression From to the type ToType. Standard conversion sequences
1612 /// only consider non-class types; for conversions that involve class
1613 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1614 /// contain the standard conversion sequence required to perform this
1615 /// conversion and this routine will return true. Otherwise, this
1616 /// routine will return false and the value of SCS is unspecified.
1617 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1618                                  bool InOverloadResolution,
1619                                  StandardConversionSequence &SCS,
1620                                  bool CStyle,
1621                                  bool AllowObjCWritebackConversion) {
1622   QualType FromType = From->getType();
1623 
1624   // Standard conversions (C++ [conv])
1625   SCS.setAsIdentityConversion();
1626   SCS.IncompatibleObjC = false;
1627   SCS.setFromType(FromType);
1628   SCS.CopyConstructor = nullptr;
1629 
1630   // There are no standard conversions for class types in C++, so
1631   // abort early. When overloading in C, however, we do permit them.
1632   if (S.getLangOpts().CPlusPlus &&
1633       (FromType->isRecordType() || ToType->isRecordType()))
1634     return false;
1635 
1636   // The first conversion can be an lvalue-to-rvalue conversion,
1637   // array-to-pointer conversion, or function-to-pointer conversion
1638   // (C++ 4p1).
1639 
1640   if (FromType == S.Context.OverloadTy) {
1641     DeclAccessPair AccessPair;
1642     if (FunctionDecl *Fn
1643           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1644                                                  AccessPair)) {
1645       // We were able to resolve the address of the overloaded function,
1646       // so we can convert to the type of that function.
1647       FromType = Fn->getType();
1648       SCS.setFromType(FromType);
1649 
1650       // we can sometimes resolve &foo<int> regardless of ToType, so check
1651       // if the type matches (identity) or we are converting to bool
1652       if (!S.Context.hasSameUnqualifiedType(
1653                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1654         QualType resultTy;
1655         // if the function type matches except for [[noreturn]], it's ok
1656         if (!S.IsFunctionConversion(FromType,
1657               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1658           // otherwise, only a boolean conversion is standard
1659           if (!ToType->isBooleanType())
1660             return false;
1661       }
1662 
1663       // Check if the "from" expression is taking the address of an overloaded
1664       // function and recompute the FromType accordingly. Take advantage of the
1665       // fact that non-static member functions *must* have such an address-of
1666       // expression.
1667       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1668       if (Method && !Method->isStatic()) {
1669         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1670                "Non-unary operator on non-static member address");
1671         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1672                == UO_AddrOf &&
1673                "Non-address-of operator on non-static member address");
1674         const Type *ClassType
1675           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1676         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1677       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1678         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1679                UO_AddrOf &&
1680                "Non-address-of operator for overloaded function expression");
1681         FromType = S.Context.getPointerType(FromType);
1682       }
1683 
1684       // Check that we've computed the proper type after overload resolution.
1685       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1686       // be calling it from within an NDEBUG block.
1687       assert(S.Context.hasSameType(
1688         FromType,
1689         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1690     } else {
1691       return false;
1692     }
1693   }
1694   // Lvalue-to-rvalue conversion (C++11 4.1):
1695   //   A glvalue (3.10) of a non-function, non-array type T can
1696   //   be converted to a prvalue.
1697   bool argIsLValue = From->isGLValue();
1698   if (argIsLValue &&
1699       !FromType->isFunctionType() && !FromType->isArrayType() &&
1700       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1701     SCS.First = ICK_Lvalue_To_Rvalue;
1702 
1703     // C11 6.3.2.1p2:
1704     //   ... if the lvalue has atomic type, the value has the non-atomic version
1705     //   of the type of the lvalue ...
1706     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1707       FromType = Atomic->getValueType();
1708 
1709     // If T is a non-class type, the type of the rvalue is the
1710     // cv-unqualified version of T. Otherwise, the type of the rvalue
1711     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1712     // just strip the qualifiers because they don't matter.
1713     FromType = FromType.getUnqualifiedType();
1714   } else if (FromType->isArrayType()) {
1715     // Array-to-pointer conversion (C++ 4.2)
1716     SCS.First = ICK_Array_To_Pointer;
1717 
1718     // An lvalue or rvalue of type "array of N T" or "array of unknown
1719     // bound of T" can be converted to an rvalue of type "pointer to
1720     // T" (C++ 4.2p1).
1721     FromType = S.Context.getArrayDecayedType(FromType);
1722 
1723     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1724       // This conversion is deprecated in C++03 (D.4)
1725       SCS.DeprecatedStringLiteralToCharPtr = true;
1726 
1727       // For the purpose of ranking in overload resolution
1728       // (13.3.3.1.1), this conversion is considered an
1729       // array-to-pointer conversion followed by a qualification
1730       // conversion (4.4). (C++ 4.2p2)
1731       SCS.Second = ICK_Identity;
1732       SCS.Third = ICK_Qualification;
1733       SCS.QualificationIncludesObjCLifetime = false;
1734       SCS.setAllToTypes(FromType);
1735       return true;
1736     }
1737   } else if (FromType->isFunctionType() && argIsLValue) {
1738     // Function-to-pointer conversion (C++ 4.3).
1739     SCS.First = ICK_Function_To_Pointer;
1740 
1741     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1742       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1743         if (!S.checkAddressOfFunctionIsAvailable(FD))
1744           return false;
1745 
1746     // An lvalue of function type T can be converted to an rvalue of
1747     // type "pointer to T." The result is a pointer to the
1748     // function. (C++ 4.3p1).
1749     FromType = S.Context.getPointerType(FromType);
1750   } else {
1751     // We don't require any conversions for the first step.
1752     SCS.First = ICK_Identity;
1753   }
1754   SCS.setToType(0, FromType);
1755 
1756   // The second conversion can be an integral promotion, floating
1757   // point promotion, integral conversion, floating point conversion,
1758   // floating-integral conversion, pointer conversion,
1759   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1760   // For overloading in C, this can also be a "compatible-type"
1761   // conversion.
1762   bool IncompatibleObjC = false;
1763   ImplicitConversionKind SecondICK = ICK_Identity;
1764   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1765     // The unqualified versions of the types are the same: there's no
1766     // conversion to do.
1767     SCS.Second = ICK_Identity;
1768   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1769     // Integral promotion (C++ 4.5).
1770     SCS.Second = ICK_Integral_Promotion;
1771     FromType = ToType.getUnqualifiedType();
1772   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1773     // Floating point promotion (C++ 4.6).
1774     SCS.Second = ICK_Floating_Promotion;
1775     FromType = ToType.getUnqualifiedType();
1776   } else if (S.IsComplexPromotion(FromType, ToType)) {
1777     // Complex promotion (Clang extension)
1778     SCS.Second = ICK_Complex_Promotion;
1779     FromType = ToType.getUnqualifiedType();
1780   } else if (ToType->isBooleanType() &&
1781              (FromType->isArithmeticType() ||
1782               FromType->isAnyPointerType() ||
1783               FromType->isBlockPointerType() ||
1784               FromType->isMemberPointerType() ||
1785               FromType->isNullPtrType())) {
1786     // Boolean conversions (C++ 4.12).
1787     SCS.Second = ICK_Boolean_Conversion;
1788     FromType = S.Context.BoolTy;
1789   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1790              ToType->isIntegralType(S.Context)) {
1791     // Integral conversions (C++ 4.7).
1792     SCS.Second = ICK_Integral_Conversion;
1793     FromType = ToType.getUnqualifiedType();
1794   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1795     // Complex conversions (C99 6.3.1.6)
1796     SCS.Second = ICK_Complex_Conversion;
1797     FromType = ToType.getUnqualifiedType();
1798   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1799              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1800     // Complex-real conversions (C99 6.3.1.7)
1801     SCS.Second = ICK_Complex_Real;
1802     FromType = ToType.getUnqualifiedType();
1803   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1804     // FIXME: disable conversions between long double and __float128 if
1805     // their representation is different until there is back end support
1806     // We of course allow this conversion if long double is really double.
1807     if (&S.Context.getFloatTypeSemantics(FromType) !=
1808         &S.Context.getFloatTypeSemantics(ToType)) {
1809       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1810                                     ToType == S.Context.LongDoubleTy) ||
1811                                    (FromType == S.Context.LongDoubleTy &&
1812                                     ToType == S.Context.Float128Ty));
1813       if (Float128AndLongDouble &&
1814           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1815            &llvm::APFloat::PPCDoubleDouble()))
1816         return false;
1817     }
1818     // Floating point conversions (C++ 4.8).
1819     SCS.Second = ICK_Floating_Conversion;
1820     FromType = ToType.getUnqualifiedType();
1821   } else if ((FromType->isRealFloatingType() &&
1822               ToType->isIntegralType(S.Context)) ||
1823              (FromType->isIntegralOrUnscopedEnumerationType() &&
1824               ToType->isRealFloatingType())) {
1825     // Floating-integral conversions (C++ 4.9).
1826     SCS.Second = ICK_Floating_Integral;
1827     FromType = ToType.getUnqualifiedType();
1828   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1829     SCS.Second = ICK_Block_Pointer_Conversion;
1830   } else if (AllowObjCWritebackConversion &&
1831              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1832     SCS.Second = ICK_Writeback_Conversion;
1833   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1834                                    FromType, IncompatibleObjC)) {
1835     // Pointer conversions (C++ 4.10).
1836     SCS.Second = ICK_Pointer_Conversion;
1837     SCS.IncompatibleObjC = IncompatibleObjC;
1838     FromType = FromType.getUnqualifiedType();
1839   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1840                                          InOverloadResolution, FromType)) {
1841     // Pointer to member conversions (4.11).
1842     SCS.Second = ICK_Pointer_Member;
1843   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1844     SCS.Second = SecondICK;
1845     FromType = ToType.getUnqualifiedType();
1846   } else if (!S.getLangOpts().CPlusPlus &&
1847              S.Context.typesAreCompatible(ToType, FromType)) {
1848     // Compatible conversions (Clang extension for C function overloading)
1849     SCS.Second = ICK_Compatible_Conversion;
1850     FromType = ToType.getUnqualifiedType();
1851   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1852                                              InOverloadResolution,
1853                                              SCS, CStyle)) {
1854     SCS.Second = ICK_TransparentUnionConversion;
1855     FromType = ToType;
1856   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1857                                  CStyle)) {
1858     // tryAtomicConversion has updated the standard conversion sequence
1859     // appropriately.
1860     return true;
1861   } else if (ToType->isEventT() &&
1862              From->isIntegerConstantExpr(S.getASTContext()) &&
1863              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1864     SCS.Second = ICK_Zero_Event_Conversion;
1865     FromType = ToType;
1866   } else if (ToType->isQueueT() &&
1867              From->isIntegerConstantExpr(S.getASTContext()) &&
1868              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1869     SCS.Second = ICK_Zero_Queue_Conversion;
1870     FromType = ToType;
1871   } else {
1872     // No second conversion required.
1873     SCS.Second = ICK_Identity;
1874   }
1875   SCS.setToType(1, FromType);
1876 
1877   // The third conversion can be a function pointer conversion or a
1878   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1879   bool ObjCLifetimeConversion;
1880   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1881     // Function pointer conversions (removing 'noexcept') including removal of
1882     // 'noreturn' (Clang extension).
1883     SCS.Third = ICK_Function_Conversion;
1884   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1885                                          ObjCLifetimeConversion)) {
1886     SCS.Third = ICK_Qualification;
1887     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1888     FromType = ToType;
1889   } else {
1890     // No conversion required
1891     SCS.Third = ICK_Identity;
1892   }
1893 
1894   // C++ [over.best.ics]p6:
1895   //   [...] Any difference in top-level cv-qualification is
1896   //   subsumed by the initialization itself and does not constitute
1897   //   a conversion. [...]
1898   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1899   QualType CanonTo = S.Context.getCanonicalType(ToType);
1900   if (CanonFrom.getLocalUnqualifiedType()
1901                                      == CanonTo.getLocalUnqualifiedType() &&
1902       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1903     FromType = ToType;
1904     CanonFrom = CanonTo;
1905   }
1906 
1907   SCS.setToType(2, FromType);
1908 
1909   if (CanonFrom == CanonTo)
1910     return true;
1911 
1912   // If we have not converted the argument type to the parameter type,
1913   // this is a bad conversion sequence, unless we're resolving an overload in C.
1914   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1915     return false;
1916 
1917   ExprResult ER = ExprResult{From};
1918   Sema::AssignConvertType Conv =
1919       S.CheckSingleAssignmentConstraints(ToType, ER,
1920                                          /*Diagnose=*/false,
1921                                          /*DiagnoseCFAudited=*/false,
1922                                          /*ConvertRHS=*/false);
1923   ImplicitConversionKind SecondConv;
1924   switch (Conv) {
1925   case Sema::Compatible:
1926     SecondConv = ICK_C_Only_Conversion;
1927     break;
1928   // For our purposes, discarding qualifiers is just as bad as using an
1929   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1930   // qualifiers, as well.
1931   case Sema::CompatiblePointerDiscardsQualifiers:
1932   case Sema::IncompatiblePointer:
1933   case Sema::IncompatiblePointerSign:
1934     SecondConv = ICK_Incompatible_Pointer_Conversion;
1935     break;
1936   default:
1937     return false;
1938   }
1939 
1940   // First can only be an lvalue conversion, so we pretend that this was the
1941   // second conversion. First should already be valid from earlier in the
1942   // function.
1943   SCS.Second = SecondConv;
1944   SCS.setToType(1, ToType);
1945 
1946   // Third is Identity, because Second should rank us worse than any other
1947   // conversion. This could also be ICK_Qualification, but it's simpler to just
1948   // lump everything in with the second conversion, and we don't gain anything
1949   // from making this ICK_Qualification.
1950   SCS.Third = ICK_Identity;
1951   SCS.setToType(2, ToType);
1952   return true;
1953 }
1954 
1955 static bool
1956 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1957                                      QualType &ToType,
1958                                      bool InOverloadResolution,
1959                                      StandardConversionSequence &SCS,
1960                                      bool CStyle) {
1961 
1962   const RecordType *UT = ToType->getAsUnionType();
1963   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1964     return false;
1965   // The field to initialize within the transparent union.
1966   RecordDecl *UD = UT->getDecl();
1967   // It's compatible if the expression matches any of the fields.
1968   for (const auto *it : UD->fields()) {
1969     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1970                              CStyle, /*ObjCWritebackConversion=*/false)) {
1971       ToType = it->getType();
1972       return true;
1973     }
1974   }
1975   return false;
1976 }
1977 
1978 /// IsIntegralPromotion - Determines whether the conversion from the
1979 /// expression From (whose potentially-adjusted type is FromType) to
1980 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1981 /// sets PromotedType to the promoted type.
1982 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1983   const BuiltinType *To = ToType->getAs<BuiltinType>();
1984   // All integers are built-in.
1985   if (!To) {
1986     return false;
1987   }
1988 
1989   // An rvalue of type char, signed char, unsigned char, short int, or
1990   // unsigned short int can be converted to an rvalue of type int if
1991   // int can represent all the values of the source type; otherwise,
1992   // the source rvalue can be converted to an rvalue of type unsigned
1993   // int (C++ 4.5p1).
1994   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1995       !FromType->isEnumeralType()) {
1996     if (// We can promote any signed, promotable integer type to an int
1997         (FromType->isSignedIntegerType() ||
1998          // We can promote any unsigned integer type whose size is
1999          // less than int to an int.
2000          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2001       return To->getKind() == BuiltinType::Int;
2002     }
2003 
2004     return To->getKind() == BuiltinType::UInt;
2005   }
2006 
2007   // C++11 [conv.prom]p3:
2008   //   A prvalue of an unscoped enumeration type whose underlying type is not
2009   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2010   //   following types that can represent all the values of the enumeration
2011   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2012   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2013   //   long long int. If none of the types in that list can represent all the
2014   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2015   //   type can be converted to an rvalue a prvalue of the extended integer type
2016   //   with lowest integer conversion rank (4.13) greater than the rank of long
2017   //   long in which all the values of the enumeration can be represented. If
2018   //   there are two such extended types, the signed one is chosen.
2019   // C++11 [conv.prom]p4:
2020   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2021   //   can be converted to a prvalue of its underlying type. Moreover, if
2022   //   integral promotion can be applied to its underlying type, a prvalue of an
2023   //   unscoped enumeration type whose underlying type is fixed can also be
2024   //   converted to a prvalue of the promoted underlying type.
2025   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2026     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2027     // provided for a scoped enumeration.
2028     if (FromEnumType->getDecl()->isScoped())
2029       return false;
2030 
2031     // We can perform an integral promotion to the underlying type of the enum,
2032     // even if that's not the promoted type. Note that the check for promoting
2033     // the underlying type is based on the type alone, and does not consider
2034     // the bitfield-ness of the actual source expression.
2035     if (FromEnumType->getDecl()->isFixed()) {
2036       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2037       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2038              IsIntegralPromotion(nullptr, Underlying, ToType);
2039     }
2040 
2041     // We have already pre-calculated the promotion type, so this is trivial.
2042     if (ToType->isIntegerType() &&
2043         isCompleteType(From->getBeginLoc(), FromType))
2044       return Context.hasSameUnqualifiedType(
2045           ToType, FromEnumType->getDecl()->getPromotionType());
2046 
2047     // C++ [conv.prom]p5:
2048     //   If the bit-field has an enumerated type, it is treated as any other
2049     //   value of that type for promotion purposes.
2050     //
2051     // ... so do not fall through into the bit-field checks below in C++.
2052     if (getLangOpts().CPlusPlus)
2053       return false;
2054   }
2055 
2056   // C++0x [conv.prom]p2:
2057   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2058   //   to an rvalue a prvalue of the first of the following types that can
2059   //   represent all the values of its underlying type: int, unsigned int,
2060   //   long int, unsigned long int, long long int, or unsigned long long int.
2061   //   If none of the types in that list can represent all the values of its
2062   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2063   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2064   //   type.
2065   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2066       ToType->isIntegerType()) {
2067     // Determine whether the type we're converting from is signed or
2068     // unsigned.
2069     bool FromIsSigned = FromType->isSignedIntegerType();
2070     uint64_t FromSize = Context.getTypeSize(FromType);
2071 
2072     // The types we'll try to promote to, in the appropriate
2073     // order. Try each of these types.
2074     QualType PromoteTypes[6] = {
2075       Context.IntTy, Context.UnsignedIntTy,
2076       Context.LongTy, Context.UnsignedLongTy ,
2077       Context.LongLongTy, Context.UnsignedLongLongTy
2078     };
2079     for (int Idx = 0; Idx < 6; ++Idx) {
2080       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2081       if (FromSize < ToSize ||
2082           (FromSize == ToSize &&
2083            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2084         // We found the type that we can promote to. If this is the
2085         // type we wanted, we have a promotion. Otherwise, no
2086         // promotion.
2087         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2088       }
2089     }
2090   }
2091 
2092   // An rvalue for an integral bit-field (9.6) can be converted to an
2093   // rvalue of type int if int can represent all the values of the
2094   // bit-field; otherwise, it can be converted to unsigned int if
2095   // unsigned int can represent all the values of the bit-field. If
2096   // the bit-field is larger yet, no integral promotion applies to
2097   // it. If the bit-field has an enumerated type, it is treated as any
2098   // other value of that type for promotion purposes (C++ 4.5p3).
2099   // FIXME: We should delay checking of bit-fields until we actually perform the
2100   // conversion.
2101   //
2102   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2103   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2104   // bit-fields and those whose underlying type is larger than int) for GCC
2105   // compatibility.
2106   if (From) {
2107     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2108       llvm::APSInt BitWidth;
2109       if (FromType->isIntegralType(Context) &&
2110           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2111         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2112         ToSize = Context.getTypeSize(ToType);
2113 
2114         // Are we promoting to an int from a bitfield that fits in an int?
2115         if (BitWidth < ToSize ||
2116             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2117           return To->getKind() == BuiltinType::Int;
2118         }
2119 
2120         // Are we promoting to an unsigned int from an unsigned bitfield
2121         // that fits into an unsigned int?
2122         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2123           return To->getKind() == BuiltinType::UInt;
2124         }
2125 
2126         return false;
2127       }
2128     }
2129   }
2130 
2131   // An rvalue of type bool can be converted to an rvalue of type int,
2132   // with false becoming zero and true becoming one (C++ 4.5p4).
2133   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2134     return true;
2135   }
2136 
2137   return false;
2138 }
2139 
2140 /// IsFloatingPointPromotion - Determines whether the conversion from
2141 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2142 /// returns true and sets PromotedType to the promoted type.
2143 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2144   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2145     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2146       /// An rvalue of type float can be converted to an rvalue of type
2147       /// double. (C++ 4.6p1).
2148       if (FromBuiltin->getKind() == BuiltinType::Float &&
2149           ToBuiltin->getKind() == BuiltinType::Double)
2150         return true;
2151 
2152       // C99 6.3.1.5p1:
2153       //   When a float is promoted to double or long double, or a
2154       //   double is promoted to long double [...].
2155       if (!getLangOpts().CPlusPlus &&
2156           (FromBuiltin->getKind() == BuiltinType::Float ||
2157            FromBuiltin->getKind() == BuiltinType::Double) &&
2158           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2159            ToBuiltin->getKind() == BuiltinType::Float128))
2160         return true;
2161 
2162       // Half can be promoted to float.
2163       if (!getLangOpts().NativeHalfType &&
2164            FromBuiltin->getKind() == BuiltinType::Half &&
2165           ToBuiltin->getKind() == BuiltinType::Float)
2166         return true;
2167     }
2168 
2169   return false;
2170 }
2171 
2172 /// Determine if a conversion is a complex promotion.
2173 ///
2174 /// A complex promotion is defined as a complex -> complex conversion
2175 /// where the conversion between the underlying real types is a
2176 /// floating-point or integral promotion.
2177 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2178   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2179   if (!FromComplex)
2180     return false;
2181 
2182   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2183   if (!ToComplex)
2184     return false;
2185 
2186   return IsFloatingPointPromotion(FromComplex->getElementType(),
2187                                   ToComplex->getElementType()) ||
2188     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2189                         ToComplex->getElementType());
2190 }
2191 
2192 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2193 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2194 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2195 /// if non-empty, will be a pointer to ToType that may or may not have
2196 /// the right set of qualifiers on its pointee.
2197 ///
2198 static QualType
2199 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2200                                    QualType ToPointee, QualType ToType,
2201                                    ASTContext &Context,
2202                                    bool StripObjCLifetime = false) {
2203   assert((FromPtr->getTypeClass() == Type::Pointer ||
2204           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2205          "Invalid similarly-qualified pointer type");
2206 
2207   /// Conversions to 'id' subsume cv-qualifier conversions.
2208   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2209     return ToType.getUnqualifiedType();
2210 
2211   QualType CanonFromPointee
2212     = Context.getCanonicalType(FromPtr->getPointeeType());
2213   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2214   Qualifiers Quals = CanonFromPointee.getQualifiers();
2215 
2216   if (StripObjCLifetime)
2217     Quals.removeObjCLifetime();
2218 
2219   // Exact qualifier match -> return the pointer type we're converting to.
2220   if (CanonToPointee.getLocalQualifiers() == Quals) {
2221     // ToType is exactly what we need. Return it.
2222     if (!ToType.isNull())
2223       return ToType.getUnqualifiedType();
2224 
2225     // Build a pointer to ToPointee. It has the right qualifiers
2226     // already.
2227     if (isa<ObjCObjectPointerType>(ToType))
2228       return Context.getObjCObjectPointerType(ToPointee);
2229     return Context.getPointerType(ToPointee);
2230   }
2231 
2232   // Just build a canonical type that has the right qualifiers.
2233   QualType QualifiedCanonToPointee
2234     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2235 
2236   if (isa<ObjCObjectPointerType>(ToType))
2237     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2238   return Context.getPointerType(QualifiedCanonToPointee);
2239 }
2240 
2241 static bool isNullPointerConstantForConversion(Expr *Expr,
2242                                                bool InOverloadResolution,
2243                                                ASTContext &Context) {
2244   // Handle value-dependent integral null pointer constants correctly.
2245   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2246   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2247       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2248     return !InOverloadResolution;
2249 
2250   return Expr->isNullPointerConstant(Context,
2251                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2252                                         : Expr::NPC_ValueDependentIsNull);
2253 }
2254 
2255 /// IsPointerConversion - Determines whether the conversion of the
2256 /// expression From, which has the (possibly adjusted) type FromType,
2257 /// can be converted to the type ToType via a pointer conversion (C++
2258 /// 4.10). If so, returns true and places the converted type (that
2259 /// might differ from ToType in its cv-qualifiers at some level) into
2260 /// ConvertedType.
2261 ///
2262 /// This routine also supports conversions to and from block pointers
2263 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2264 /// pointers to interfaces. FIXME: Once we've determined the
2265 /// appropriate overloading rules for Objective-C, we may want to
2266 /// split the Objective-C checks into a different routine; however,
2267 /// GCC seems to consider all of these conversions to be pointer
2268 /// conversions, so for now they live here. IncompatibleObjC will be
2269 /// set if the conversion is an allowed Objective-C conversion that
2270 /// should result in a warning.
2271 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2272                                bool InOverloadResolution,
2273                                QualType& ConvertedType,
2274                                bool &IncompatibleObjC) {
2275   IncompatibleObjC = false;
2276   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2277                               IncompatibleObjC))
2278     return true;
2279 
2280   // Conversion from a null pointer constant to any Objective-C pointer type.
2281   if (ToType->isObjCObjectPointerType() &&
2282       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2283     ConvertedType = ToType;
2284     return true;
2285   }
2286 
2287   // Blocks: Block pointers can be converted to void*.
2288   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2289       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2290     ConvertedType = ToType;
2291     return true;
2292   }
2293   // Blocks: A null pointer constant can be converted to a block
2294   // pointer type.
2295   if (ToType->isBlockPointerType() &&
2296       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2297     ConvertedType = ToType;
2298     return true;
2299   }
2300 
2301   // If the left-hand-side is nullptr_t, the right side can be a null
2302   // pointer constant.
2303   if (ToType->isNullPtrType() &&
2304       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2305     ConvertedType = ToType;
2306     return true;
2307   }
2308 
2309   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2310   if (!ToTypePtr)
2311     return false;
2312 
2313   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2314   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2315     ConvertedType = ToType;
2316     return true;
2317   }
2318 
2319   // Beyond this point, both types need to be pointers
2320   // , including objective-c pointers.
2321   QualType ToPointeeType = ToTypePtr->getPointeeType();
2322   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2323       !getLangOpts().ObjCAutoRefCount) {
2324     ConvertedType = BuildSimilarlyQualifiedPointerType(
2325                                       FromType->getAs<ObjCObjectPointerType>(),
2326                                                        ToPointeeType,
2327                                                        ToType, Context);
2328     return true;
2329   }
2330   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2331   if (!FromTypePtr)
2332     return false;
2333 
2334   QualType FromPointeeType = FromTypePtr->getPointeeType();
2335 
2336   // If the unqualified pointee types are the same, this can't be a
2337   // pointer conversion, so don't do all of the work below.
2338   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2339     return false;
2340 
2341   // An rvalue of type "pointer to cv T," where T is an object type,
2342   // can be converted to an rvalue of type "pointer to cv void" (C++
2343   // 4.10p2).
2344   if (FromPointeeType->isIncompleteOrObjectType() &&
2345       ToPointeeType->isVoidType()) {
2346     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2347                                                        ToPointeeType,
2348                                                        ToType, Context,
2349                                                    /*StripObjCLifetime=*/true);
2350     return true;
2351   }
2352 
2353   // MSVC allows implicit function to void* type conversion.
2354   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2355       ToPointeeType->isVoidType()) {
2356     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2357                                                        ToPointeeType,
2358                                                        ToType, Context);
2359     return true;
2360   }
2361 
2362   // When we're overloading in C, we allow a special kind of pointer
2363   // conversion for compatible-but-not-identical pointee types.
2364   if (!getLangOpts().CPlusPlus &&
2365       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2366     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2367                                                        ToPointeeType,
2368                                                        ToType, Context);
2369     return true;
2370   }
2371 
2372   // C++ [conv.ptr]p3:
2373   //
2374   //   An rvalue of type "pointer to cv D," where D is a class type,
2375   //   can be converted to an rvalue of type "pointer to cv B," where
2376   //   B is a base class (clause 10) of D. If B is an inaccessible
2377   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2378   //   necessitates this conversion is ill-formed. The result of the
2379   //   conversion is a pointer to the base class sub-object of the
2380   //   derived class object. The null pointer value is converted to
2381   //   the null pointer value of the destination type.
2382   //
2383   // Note that we do not check for ambiguity or inaccessibility
2384   // here. That is handled by CheckPointerConversion.
2385   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2386       ToPointeeType->isRecordType() &&
2387       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2388       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2389     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2390                                                        ToPointeeType,
2391                                                        ToType, Context);
2392     return true;
2393   }
2394 
2395   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2396       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2397     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2398                                                        ToPointeeType,
2399                                                        ToType, Context);
2400     return true;
2401   }
2402 
2403   return false;
2404 }
2405 
2406 /// Adopt the given qualifiers for the given type.
2407 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2408   Qualifiers TQs = T.getQualifiers();
2409 
2410   // Check whether qualifiers already match.
2411   if (TQs == Qs)
2412     return T;
2413 
2414   if (Qs.compatiblyIncludes(TQs))
2415     return Context.getQualifiedType(T, Qs);
2416 
2417   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2418 }
2419 
2420 /// isObjCPointerConversion - Determines whether this is an
2421 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2422 /// with the same arguments and return values.
2423 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2424                                    QualType& ConvertedType,
2425                                    bool &IncompatibleObjC) {
2426   if (!getLangOpts().ObjC)
2427     return false;
2428 
2429   // The set of qualifiers on the type we're converting from.
2430   Qualifiers FromQualifiers = FromType.getQualifiers();
2431 
2432   // First, we handle all conversions on ObjC object pointer types.
2433   const ObjCObjectPointerType* ToObjCPtr =
2434     ToType->getAs<ObjCObjectPointerType>();
2435   const ObjCObjectPointerType *FromObjCPtr =
2436     FromType->getAs<ObjCObjectPointerType>();
2437 
2438   if (ToObjCPtr && FromObjCPtr) {
2439     // If the pointee types are the same (ignoring qualifications),
2440     // then this is not a pointer conversion.
2441     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2442                                        FromObjCPtr->getPointeeType()))
2443       return false;
2444 
2445     // Conversion between Objective-C pointers.
2446     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2447       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2448       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2449       if (getLangOpts().CPlusPlus && LHS && RHS &&
2450           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2451                                                 FromObjCPtr->getPointeeType()))
2452         return false;
2453       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2454                                                    ToObjCPtr->getPointeeType(),
2455                                                          ToType, Context);
2456       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2457       return true;
2458     }
2459 
2460     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2461       // Okay: this is some kind of implicit downcast of Objective-C
2462       // interfaces, which is permitted. However, we're going to
2463       // complain about it.
2464       IncompatibleObjC = true;
2465       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2466                                                    ToObjCPtr->getPointeeType(),
2467                                                          ToType, Context);
2468       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2469       return true;
2470     }
2471   }
2472   // Beyond this point, both types need to be C pointers or block pointers.
2473   QualType ToPointeeType;
2474   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2475     ToPointeeType = ToCPtr->getPointeeType();
2476   else if (const BlockPointerType *ToBlockPtr =
2477             ToType->getAs<BlockPointerType>()) {
2478     // Objective C++: We're able to convert from a pointer to any object
2479     // to a block pointer type.
2480     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2481       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2482       return true;
2483     }
2484     ToPointeeType = ToBlockPtr->getPointeeType();
2485   }
2486   else if (FromType->getAs<BlockPointerType>() &&
2487            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2488     // Objective C++: We're able to convert from a block pointer type to a
2489     // pointer to any object.
2490     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2491     return true;
2492   }
2493   else
2494     return false;
2495 
2496   QualType FromPointeeType;
2497   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2498     FromPointeeType = FromCPtr->getPointeeType();
2499   else if (const BlockPointerType *FromBlockPtr =
2500            FromType->getAs<BlockPointerType>())
2501     FromPointeeType = FromBlockPtr->getPointeeType();
2502   else
2503     return false;
2504 
2505   // If we have pointers to pointers, recursively check whether this
2506   // is an Objective-C conversion.
2507   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2508       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2509                               IncompatibleObjC)) {
2510     // We always complain about this conversion.
2511     IncompatibleObjC = true;
2512     ConvertedType = Context.getPointerType(ConvertedType);
2513     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2514     return true;
2515   }
2516   // Allow conversion of pointee being objective-c pointer to another one;
2517   // as in I* to id.
2518   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2519       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2520       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2521                               IncompatibleObjC)) {
2522 
2523     ConvertedType = Context.getPointerType(ConvertedType);
2524     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2525     return true;
2526   }
2527 
2528   // If we have pointers to functions or blocks, check whether the only
2529   // differences in the argument and result types are in Objective-C
2530   // pointer conversions. If so, we permit the conversion (but
2531   // complain about it).
2532   const FunctionProtoType *FromFunctionType
2533     = FromPointeeType->getAs<FunctionProtoType>();
2534   const FunctionProtoType *ToFunctionType
2535     = ToPointeeType->getAs<FunctionProtoType>();
2536   if (FromFunctionType && ToFunctionType) {
2537     // If the function types are exactly the same, this isn't an
2538     // Objective-C pointer conversion.
2539     if (Context.getCanonicalType(FromPointeeType)
2540           == Context.getCanonicalType(ToPointeeType))
2541       return false;
2542 
2543     // Perform the quick checks that will tell us whether these
2544     // function types are obviously different.
2545     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2546         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2547         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2548       return false;
2549 
2550     bool HasObjCConversion = false;
2551     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2552         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2553       // Okay, the types match exactly. Nothing to do.
2554     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2555                                        ToFunctionType->getReturnType(),
2556                                        ConvertedType, IncompatibleObjC)) {
2557       // Okay, we have an Objective-C pointer conversion.
2558       HasObjCConversion = true;
2559     } else {
2560       // Function types are too different. Abort.
2561       return false;
2562     }
2563 
2564     // Check argument types.
2565     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2566          ArgIdx != NumArgs; ++ArgIdx) {
2567       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2568       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2569       if (Context.getCanonicalType(FromArgType)
2570             == Context.getCanonicalType(ToArgType)) {
2571         // Okay, the types match exactly. Nothing to do.
2572       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2573                                          ConvertedType, IncompatibleObjC)) {
2574         // Okay, we have an Objective-C pointer conversion.
2575         HasObjCConversion = true;
2576       } else {
2577         // Argument types are too different. Abort.
2578         return false;
2579       }
2580     }
2581 
2582     if (HasObjCConversion) {
2583       // We had an Objective-C conversion. Allow this pointer
2584       // conversion, but complain about it.
2585       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2586       IncompatibleObjC = true;
2587       return true;
2588     }
2589   }
2590 
2591   return false;
2592 }
2593 
2594 /// Determine whether this is an Objective-C writeback conversion,
2595 /// used for parameter passing when performing automatic reference counting.
2596 ///
2597 /// \param FromType The type we're converting form.
2598 ///
2599 /// \param ToType The type we're converting to.
2600 ///
2601 /// \param ConvertedType The type that will be produced after applying
2602 /// this conversion.
2603 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2604                                      QualType &ConvertedType) {
2605   if (!getLangOpts().ObjCAutoRefCount ||
2606       Context.hasSameUnqualifiedType(FromType, ToType))
2607     return false;
2608 
2609   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2610   QualType ToPointee;
2611   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2612     ToPointee = ToPointer->getPointeeType();
2613   else
2614     return false;
2615 
2616   Qualifiers ToQuals = ToPointee.getQualifiers();
2617   if (!ToPointee->isObjCLifetimeType() ||
2618       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2619       !ToQuals.withoutObjCLifetime().empty())
2620     return false;
2621 
2622   // Argument must be a pointer to __strong to __weak.
2623   QualType FromPointee;
2624   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2625     FromPointee = FromPointer->getPointeeType();
2626   else
2627     return false;
2628 
2629   Qualifiers FromQuals = FromPointee.getQualifiers();
2630   if (!FromPointee->isObjCLifetimeType() ||
2631       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2632        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2633     return false;
2634 
2635   // Make sure that we have compatible qualifiers.
2636   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2637   if (!ToQuals.compatiblyIncludes(FromQuals))
2638     return false;
2639 
2640   // Remove qualifiers from the pointee type we're converting from; they
2641   // aren't used in the compatibility check belong, and we'll be adding back
2642   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2643   FromPointee = FromPointee.getUnqualifiedType();
2644 
2645   // The unqualified form of the pointee types must be compatible.
2646   ToPointee = ToPointee.getUnqualifiedType();
2647   bool IncompatibleObjC;
2648   if (Context.typesAreCompatible(FromPointee, ToPointee))
2649     FromPointee = ToPointee;
2650   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2651                                     IncompatibleObjC))
2652     return false;
2653 
2654   /// Construct the type we're converting to, which is a pointer to
2655   /// __autoreleasing pointee.
2656   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2657   ConvertedType = Context.getPointerType(FromPointee);
2658   return true;
2659 }
2660 
2661 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2662                                     QualType& ConvertedType) {
2663   QualType ToPointeeType;
2664   if (const BlockPointerType *ToBlockPtr =
2665         ToType->getAs<BlockPointerType>())
2666     ToPointeeType = ToBlockPtr->getPointeeType();
2667   else
2668     return false;
2669 
2670   QualType FromPointeeType;
2671   if (const BlockPointerType *FromBlockPtr =
2672       FromType->getAs<BlockPointerType>())
2673     FromPointeeType = FromBlockPtr->getPointeeType();
2674   else
2675     return false;
2676   // We have pointer to blocks, check whether the only
2677   // differences in the argument and result types are in Objective-C
2678   // pointer conversions. If so, we permit the conversion.
2679 
2680   const FunctionProtoType *FromFunctionType
2681     = FromPointeeType->getAs<FunctionProtoType>();
2682   const FunctionProtoType *ToFunctionType
2683     = ToPointeeType->getAs<FunctionProtoType>();
2684 
2685   if (!FromFunctionType || !ToFunctionType)
2686     return false;
2687 
2688   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2689     return true;
2690 
2691   // Perform the quick checks that will tell us whether these
2692   // function types are obviously different.
2693   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2694       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2695     return false;
2696 
2697   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2698   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2699   if (FromEInfo != ToEInfo)
2700     return false;
2701 
2702   bool IncompatibleObjC = false;
2703   if (Context.hasSameType(FromFunctionType->getReturnType(),
2704                           ToFunctionType->getReturnType())) {
2705     // Okay, the types match exactly. Nothing to do.
2706   } else {
2707     QualType RHS = FromFunctionType->getReturnType();
2708     QualType LHS = ToFunctionType->getReturnType();
2709     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2710         !RHS.hasQualifiers() && LHS.hasQualifiers())
2711        LHS = LHS.getUnqualifiedType();
2712 
2713      if (Context.hasSameType(RHS,LHS)) {
2714        // OK exact match.
2715      } else if (isObjCPointerConversion(RHS, LHS,
2716                                         ConvertedType, IncompatibleObjC)) {
2717      if (IncompatibleObjC)
2718        return false;
2719      // Okay, we have an Objective-C pointer conversion.
2720      }
2721      else
2722        return false;
2723    }
2724 
2725    // Check argument types.
2726    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2727         ArgIdx != NumArgs; ++ArgIdx) {
2728      IncompatibleObjC = false;
2729      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2730      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2731      if (Context.hasSameType(FromArgType, ToArgType)) {
2732        // Okay, the types match exactly. Nothing to do.
2733      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2734                                         ConvertedType, IncompatibleObjC)) {
2735        if (IncompatibleObjC)
2736          return false;
2737        // Okay, we have an Objective-C pointer conversion.
2738      } else
2739        // Argument types are too different. Abort.
2740        return false;
2741    }
2742 
2743    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2744    bool CanUseToFPT, CanUseFromFPT;
2745    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2746                                       CanUseToFPT, CanUseFromFPT,
2747                                       NewParamInfos))
2748      return false;
2749 
2750    ConvertedType = ToType;
2751    return true;
2752 }
2753 
2754 enum {
2755   ft_default,
2756   ft_different_class,
2757   ft_parameter_arity,
2758   ft_parameter_mismatch,
2759   ft_return_type,
2760   ft_qualifer_mismatch,
2761   ft_noexcept
2762 };
2763 
2764 /// Attempts to get the FunctionProtoType from a Type. Handles
2765 /// MemberFunctionPointers properly.
2766 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2767   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2768     return FPT;
2769 
2770   if (auto *MPT = FromType->getAs<MemberPointerType>())
2771     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2772 
2773   return nullptr;
2774 }
2775 
2776 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2777 /// function types.  Catches different number of parameter, mismatch in
2778 /// parameter types, and different return types.
2779 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2780                                       QualType FromType, QualType ToType) {
2781   // If either type is not valid, include no extra info.
2782   if (FromType.isNull() || ToType.isNull()) {
2783     PDiag << ft_default;
2784     return;
2785   }
2786 
2787   // Get the function type from the pointers.
2788   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2789     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2790                             *ToMember = ToType->getAs<MemberPointerType>();
2791     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2792       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2793             << QualType(FromMember->getClass(), 0);
2794       return;
2795     }
2796     FromType = FromMember->getPointeeType();
2797     ToType = ToMember->getPointeeType();
2798   }
2799 
2800   if (FromType->isPointerType())
2801     FromType = FromType->getPointeeType();
2802   if (ToType->isPointerType())
2803     ToType = ToType->getPointeeType();
2804 
2805   // Remove references.
2806   FromType = FromType.getNonReferenceType();
2807   ToType = ToType.getNonReferenceType();
2808 
2809   // Don't print extra info for non-specialized template functions.
2810   if (FromType->isInstantiationDependentType() &&
2811       !FromType->getAs<TemplateSpecializationType>()) {
2812     PDiag << ft_default;
2813     return;
2814   }
2815 
2816   // No extra info for same types.
2817   if (Context.hasSameType(FromType, ToType)) {
2818     PDiag << ft_default;
2819     return;
2820   }
2821 
2822   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2823                           *ToFunction = tryGetFunctionProtoType(ToType);
2824 
2825   // Both types need to be function types.
2826   if (!FromFunction || !ToFunction) {
2827     PDiag << ft_default;
2828     return;
2829   }
2830 
2831   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2832     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2833           << FromFunction->getNumParams();
2834     return;
2835   }
2836 
2837   // Handle different parameter types.
2838   unsigned ArgPos;
2839   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2840     PDiag << ft_parameter_mismatch << ArgPos + 1
2841           << ToFunction->getParamType(ArgPos)
2842           << FromFunction->getParamType(ArgPos);
2843     return;
2844   }
2845 
2846   // Handle different return type.
2847   if (!Context.hasSameType(FromFunction->getReturnType(),
2848                            ToFunction->getReturnType())) {
2849     PDiag << ft_return_type << ToFunction->getReturnType()
2850           << FromFunction->getReturnType();
2851     return;
2852   }
2853 
2854   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2855     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2856           << FromFunction->getMethodQuals();
2857     return;
2858   }
2859 
2860   // Handle exception specification differences on canonical type (in C++17
2861   // onwards).
2862   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2863           ->isNothrow() !=
2864       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2865           ->isNothrow()) {
2866     PDiag << ft_noexcept;
2867     return;
2868   }
2869 
2870   // Unable to find a difference, so add no extra info.
2871   PDiag << ft_default;
2872 }
2873 
2874 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2875 /// for equality of their argument types. Caller has already checked that
2876 /// they have same number of arguments.  If the parameters are different,
2877 /// ArgPos will have the parameter index of the first different parameter.
2878 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2879                                       const FunctionProtoType *NewType,
2880                                       unsigned *ArgPos) {
2881   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2882                                               N = NewType->param_type_begin(),
2883                                               E = OldType->param_type_end();
2884        O && (O != E); ++O, ++N) {
2885     if (!Context.hasSameType(O->getUnqualifiedType(),
2886                              N->getUnqualifiedType())) {
2887       if (ArgPos)
2888         *ArgPos = O - OldType->param_type_begin();
2889       return false;
2890     }
2891   }
2892   return true;
2893 }
2894 
2895 /// CheckPointerConversion - Check the pointer conversion from the
2896 /// expression From to the type ToType. This routine checks for
2897 /// ambiguous or inaccessible derived-to-base pointer
2898 /// conversions for which IsPointerConversion has already returned
2899 /// true. It returns true and produces a diagnostic if there was an
2900 /// error, or returns false otherwise.
2901 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2902                                   CastKind &Kind,
2903                                   CXXCastPath& BasePath,
2904                                   bool IgnoreBaseAccess,
2905                                   bool Diagnose) {
2906   QualType FromType = From->getType();
2907   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2908 
2909   Kind = CK_BitCast;
2910 
2911   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2912       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2913           Expr::NPCK_ZeroExpression) {
2914     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2915       DiagRuntimeBehavior(From->getExprLoc(), From,
2916                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2917                             << ToType << From->getSourceRange());
2918     else if (!isUnevaluatedContext())
2919       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2920         << ToType << From->getSourceRange();
2921   }
2922   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2923     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2924       QualType FromPointeeType = FromPtrType->getPointeeType(),
2925                ToPointeeType   = ToPtrType->getPointeeType();
2926 
2927       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2928           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2929         // We must have a derived-to-base conversion. Check an
2930         // ambiguous or inaccessible conversion.
2931         unsigned InaccessibleID = 0;
2932         unsigned AmbigiousID = 0;
2933         if (Diagnose) {
2934           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2935           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2936         }
2937         if (CheckDerivedToBaseConversion(
2938                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2939                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2940                 &BasePath, IgnoreBaseAccess))
2941           return true;
2942 
2943         // The conversion was successful.
2944         Kind = CK_DerivedToBase;
2945       }
2946 
2947       if (Diagnose && !IsCStyleOrFunctionalCast &&
2948           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2949         assert(getLangOpts().MSVCCompat &&
2950                "this should only be possible with MSVCCompat!");
2951         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2952             << From->getSourceRange();
2953       }
2954     }
2955   } else if (const ObjCObjectPointerType *ToPtrType =
2956                ToType->getAs<ObjCObjectPointerType>()) {
2957     if (const ObjCObjectPointerType *FromPtrType =
2958           FromType->getAs<ObjCObjectPointerType>()) {
2959       // Objective-C++ conversions are always okay.
2960       // FIXME: We should have a different class of conversions for the
2961       // Objective-C++ implicit conversions.
2962       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2963         return false;
2964     } else if (FromType->isBlockPointerType()) {
2965       Kind = CK_BlockPointerToObjCPointerCast;
2966     } else {
2967       Kind = CK_CPointerToObjCPointerCast;
2968     }
2969   } else if (ToType->isBlockPointerType()) {
2970     if (!FromType->isBlockPointerType())
2971       Kind = CK_AnyPointerToBlockPointerCast;
2972   }
2973 
2974   // We shouldn't fall into this case unless it's valid for other
2975   // reasons.
2976   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2977     Kind = CK_NullToPointer;
2978 
2979   return false;
2980 }
2981 
2982 /// IsMemberPointerConversion - Determines whether the conversion of the
2983 /// expression From, which has the (possibly adjusted) type FromType, can be
2984 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2985 /// If so, returns true and places the converted type (that might differ from
2986 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2987 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2988                                      QualType ToType,
2989                                      bool InOverloadResolution,
2990                                      QualType &ConvertedType) {
2991   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2992   if (!ToTypePtr)
2993     return false;
2994 
2995   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2996   if (From->isNullPointerConstant(Context,
2997                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2998                                         : Expr::NPC_ValueDependentIsNull)) {
2999     ConvertedType = ToType;
3000     return true;
3001   }
3002 
3003   // Otherwise, both types have to be member pointers.
3004   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3005   if (!FromTypePtr)
3006     return false;
3007 
3008   // A pointer to member of B can be converted to a pointer to member of D,
3009   // where D is derived from B (C++ 4.11p2).
3010   QualType FromClass(FromTypePtr->getClass(), 0);
3011   QualType ToClass(ToTypePtr->getClass(), 0);
3012 
3013   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3014       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3015     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3016                                                  ToClass.getTypePtr());
3017     return true;
3018   }
3019 
3020   return false;
3021 }
3022 
3023 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3024 /// expression From to the type ToType. This routine checks for ambiguous or
3025 /// virtual or inaccessible base-to-derived member pointer conversions
3026 /// for which IsMemberPointerConversion has already returned true. It returns
3027 /// true and produces a diagnostic if there was an error, or returns false
3028 /// otherwise.
3029 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3030                                         CastKind &Kind,
3031                                         CXXCastPath &BasePath,
3032                                         bool IgnoreBaseAccess) {
3033   QualType FromType = From->getType();
3034   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3035   if (!FromPtrType) {
3036     // This must be a null pointer to member pointer conversion
3037     assert(From->isNullPointerConstant(Context,
3038                                        Expr::NPC_ValueDependentIsNull) &&
3039            "Expr must be null pointer constant!");
3040     Kind = CK_NullToMemberPointer;
3041     return false;
3042   }
3043 
3044   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3045   assert(ToPtrType && "No member pointer cast has a target type "
3046                       "that is not a member pointer.");
3047 
3048   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3049   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3050 
3051   // FIXME: What about dependent types?
3052   assert(FromClass->isRecordType() && "Pointer into non-class.");
3053   assert(ToClass->isRecordType() && "Pointer into non-class.");
3054 
3055   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3056                      /*DetectVirtual=*/true);
3057   bool DerivationOkay =
3058       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3059   assert(DerivationOkay &&
3060          "Should not have been called if derivation isn't OK.");
3061   (void)DerivationOkay;
3062 
3063   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3064                                   getUnqualifiedType())) {
3065     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3066     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3067       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3068     return true;
3069   }
3070 
3071   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3072     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3073       << FromClass << ToClass << QualType(VBase, 0)
3074       << From->getSourceRange();
3075     return true;
3076   }
3077 
3078   if (!IgnoreBaseAccess)
3079     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3080                          Paths.front(),
3081                          diag::err_downcast_from_inaccessible_base);
3082 
3083   // Must be a base to derived member conversion.
3084   BuildBasePathArray(Paths, BasePath);
3085   Kind = CK_BaseToDerivedMemberPointer;
3086   return false;
3087 }
3088 
3089 /// Determine whether the lifetime conversion between the two given
3090 /// qualifiers sets is nontrivial.
3091 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3092                                                Qualifiers ToQuals) {
3093   // Converting anything to const __unsafe_unretained is trivial.
3094   if (ToQuals.hasConst() &&
3095       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3096     return false;
3097 
3098   return true;
3099 }
3100 
3101 /// IsQualificationConversion - Determines whether the conversion from
3102 /// an rvalue of type FromType to ToType is a qualification conversion
3103 /// (C++ 4.4).
3104 ///
3105 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3106 /// when the qualification conversion involves a change in the Objective-C
3107 /// object lifetime.
3108 bool
3109 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3110                                 bool CStyle, bool &ObjCLifetimeConversion) {
3111   FromType = Context.getCanonicalType(FromType);
3112   ToType = Context.getCanonicalType(ToType);
3113   ObjCLifetimeConversion = false;
3114 
3115   // If FromType and ToType are the same type, this is not a
3116   // qualification conversion.
3117   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3118     return false;
3119 
3120   // (C++ 4.4p4):
3121   //   A conversion can add cv-qualifiers at levels other than the first
3122   //   in multi-level pointers, subject to the following rules: [...]
3123   bool PreviousToQualsIncludeConst = true;
3124   bool UnwrappedAnyPointer = false;
3125   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3126     // Within each iteration of the loop, we check the qualifiers to
3127     // determine if this still looks like a qualification
3128     // conversion. Then, if all is well, we unwrap one more level of
3129     // pointers or pointers-to-members and do it all again
3130     // until there are no more pointers or pointers-to-members left to
3131     // unwrap.
3132     UnwrappedAnyPointer = true;
3133 
3134     Qualifiers FromQuals = FromType.getQualifiers();
3135     Qualifiers ToQuals = ToType.getQualifiers();
3136 
3137     // Ignore __unaligned qualifier if this type is void.
3138     if (ToType.getUnqualifiedType()->isVoidType())
3139       FromQuals.removeUnaligned();
3140 
3141     // Objective-C ARC:
3142     //   Check Objective-C lifetime conversions.
3143     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3144         UnwrappedAnyPointer) {
3145       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3146         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3147           ObjCLifetimeConversion = true;
3148         FromQuals.removeObjCLifetime();
3149         ToQuals.removeObjCLifetime();
3150       } else {
3151         // Qualification conversions cannot cast between different
3152         // Objective-C lifetime qualifiers.
3153         return false;
3154       }
3155     }
3156 
3157     // Allow addition/removal of GC attributes but not changing GC attributes.
3158     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3159         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3160       FromQuals.removeObjCGCAttr();
3161       ToQuals.removeObjCGCAttr();
3162     }
3163 
3164     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3165     //      2,j, and similarly for volatile.
3166     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3167       return false;
3168 
3169     //   -- if the cv 1,j and cv 2,j are different, then const is in
3170     //      every cv for 0 < k < j.
3171     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3172         && !PreviousToQualsIncludeConst)
3173       return false;
3174 
3175     // Keep track of whether all prior cv-qualifiers in the "to" type
3176     // include const.
3177     PreviousToQualsIncludeConst
3178       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3179   }
3180 
3181   // Allows address space promotion by language rules implemented in
3182   // Type::Qualifiers::isAddressSpaceSupersetOf.
3183   Qualifiers FromQuals = FromType.getQualifiers();
3184   Qualifiers ToQuals = ToType.getQualifiers();
3185   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3186       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3187     return false;
3188   }
3189 
3190   // We are left with FromType and ToType being the pointee types
3191   // after unwrapping the original FromType and ToType the same number
3192   // of types. If we unwrapped any pointers, and if FromType and
3193   // ToType have the same unqualified type (since we checked
3194   // qualifiers above), then this is a qualification conversion.
3195   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3196 }
3197 
3198 /// - Determine whether this is a conversion from a scalar type to an
3199 /// atomic type.
3200 ///
3201 /// If successful, updates \c SCS's second and third steps in the conversion
3202 /// sequence to finish the conversion.
3203 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3204                                 bool InOverloadResolution,
3205                                 StandardConversionSequence &SCS,
3206                                 bool CStyle) {
3207   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3208   if (!ToAtomic)
3209     return false;
3210 
3211   StandardConversionSequence InnerSCS;
3212   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3213                             InOverloadResolution, InnerSCS,
3214                             CStyle, /*AllowObjCWritebackConversion=*/false))
3215     return false;
3216 
3217   SCS.Second = InnerSCS.Second;
3218   SCS.setToType(1, InnerSCS.getToType(1));
3219   SCS.Third = InnerSCS.Third;
3220   SCS.QualificationIncludesObjCLifetime
3221     = InnerSCS.QualificationIncludesObjCLifetime;
3222   SCS.setToType(2, InnerSCS.getToType(2));
3223   return true;
3224 }
3225 
3226 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3227                                               CXXConstructorDecl *Constructor,
3228                                               QualType Type) {
3229   const FunctionProtoType *CtorType =
3230       Constructor->getType()->getAs<FunctionProtoType>();
3231   if (CtorType->getNumParams() > 0) {
3232     QualType FirstArg = CtorType->getParamType(0);
3233     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3234       return true;
3235   }
3236   return false;
3237 }
3238 
3239 static OverloadingResult
3240 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3241                                        CXXRecordDecl *To,
3242                                        UserDefinedConversionSequence &User,
3243                                        OverloadCandidateSet &CandidateSet,
3244                                        bool AllowExplicit) {
3245   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3246   for (auto *D : S.LookupConstructors(To)) {
3247     auto Info = getConstructorInfo(D);
3248     if (!Info)
3249       continue;
3250 
3251     bool Usable = !Info.Constructor->isInvalidDecl() &&
3252                   S.isInitListConstructor(Info.Constructor) &&
3253                   (AllowExplicit || !Info.Constructor->isExplicit());
3254     if (Usable) {
3255       // If the first argument is (a reference to) the target type,
3256       // suppress conversions.
3257       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3258           S.Context, Info.Constructor, ToType);
3259       if (Info.ConstructorTmpl)
3260         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3261                                        /*ExplicitArgs*/ nullptr, From,
3262                                        CandidateSet, SuppressUserConversions);
3263       else
3264         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3265                                CandidateSet, SuppressUserConversions);
3266     }
3267   }
3268 
3269   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3270 
3271   OverloadCandidateSet::iterator Best;
3272   switch (auto Result =
3273               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3274   case OR_Deleted:
3275   case OR_Success: {
3276     // Record the standard conversion we used and the conversion function.
3277     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3278     QualType ThisType = Constructor->getThisType();
3279     // Initializer lists don't have conversions as such.
3280     User.Before.setAsIdentityConversion();
3281     User.HadMultipleCandidates = HadMultipleCandidates;
3282     User.ConversionFunction = Constructor;
3283     User.FoundConversionFunction = Best->FoundDecl;
3284     User.After.setAsIdentityConversion();
3285     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3286     User.After.setAllToTypes(ToType);
3287     return Result;
3288   }
3289 
3290   case OR_No_Viable_Function:
3291     return OR_No_Viable_Function;
3292   case OR_Ambiguous:
3293     return OR_Ambiguous;
3294   }
3295 
3296   llvm_unreachable("Invalid OverloadResult!");
3297 }
3298 
3299 /// Determines whether there is a user-defined conversion sequence
3300 /// (C++ [over.ics.user]) that converts expression From to the type
3301 /// ToType. If such a conversion exists, User will contain the
3302 /// user-defined conversion sequence that performs such a conversion
3303 /// and this routine will return true. Otherwise, this routine returns
3304 /// false and User is unspecified.
3305 ///
3306 /// \param AllowExplicit  true if the conversion should consider C++0x
3307 /// "explicit" conversion functions as well as non-explicit conversion
3308 /// functions (C++0x [class.conv.fct]p2).
3309 ///
3310 /// \param AllowObjCConversionOnExplicit true if the conversion should
3311 /// allow an extra Objective-C pointer conversion on uses of explicit
3312 /// constructors. Requires \c AllowExplicit to also be set.
3313 static OverloadingResult
3314 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3315                         UserDefinedConversionSequence &User,
3316                         OverloadCandidateSet &CandidateSet,
3317                         bool AllowExplicit,
3318                         bool AllowObjCConversionOnExplicit) {
3319   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3320   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3321 
3322   // Whether we will only visit constructors.
3323   bool ConstructorsOnly = false;
3324 
3325   // If the type we are conversion to is a class type, enumerate its
3326   // constructors.
3327   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3328     // C++ [over.match.ctor]p1:
3329     //   When objects of class type are direct-initialized (8.5), or
3330     //   copy-initialized from an expression of the same or a
3331     //   derived class type (8.5), overload resolution selects the
3332     //   constructor. [...] For copy-initialization, the candidate
3333     //   functions are all the converting constructors (12.3.1) of
3334     //   that class. The argument list is the expression-list within
3335     //   the parentheses of the initializer.
3336     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3337         (From->getType()->getAs<RecordType>() &&
3338          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3339       ConstructorsOnly = true;
3340 
3341     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3342       // We're not going to find any constructors.
3343     } else if (CXXRecordDecl *ToRecordDecl
3344                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3345 
3346       Expr **Args = &From;
3347       unsigned NumArgs = 1;
3348       bool ListInitializing = false;
3349       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3350         // But first, see if there is an init-list-constructor that will work.
3351         OverloadingResult Result = IsInitializerListConstructorConversion(
3352             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3353         if (Result != OR_No_Viable_Function)
3354           return Result;
3355         // Never mind.
3356         CandidateSet.clear(
3357             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3358 
3359         // If we're list-initializing, we pass the individual elements as
3360         // arguments, not the entire list.
3361         Args = InitList->getInits();
3362         NumArgs = InitList->getNumInits();
3363         ListInitializing = true;
3364       }
3365 
3366       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3367         auto Info = getConstructorInfo(D);
3368         if (!Info)
3369           continue;
3370 
3371         bool Usable = !Info.Constructor->isInvalidDecl();
3372         if (ListInitializing)
3373           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3374         else
3375           Usable = Usable &&
3376                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3377         if (Usable) {
3378           bool SuppressUserConversions = !ConstructorsOnly;
3379           if (SuppressUserConversions && ListInitializing) {
3380             SuppressUserConversions = false;
3381             if (NumArgs == 1) {
3382               // If the first argument is (a reference to) the target type,
3383               // suppress conversions.
3384               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3385                   S.Context, Info.Constructor, ToType);
3386             }
3387           }
3388           if (Info.ConstructorTmpl)
3389             S.AddTemplateOverloadCandidate(
3390                 Info.ConstructorTmpl, Info.FoundDecl,
3391                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3392                 CandidateSet, SuppressUserConversions);
3393           else
3394             // Allow one user-defined conversion when user specifies a
3395             // From->ToType conversion via an static cast (c-style, etc).
3396             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3397                                    llvm::makeArrayRef(Args, NumArgs),
3398                                    CandidateSet, SuppressUserConversions);
3399         }
3400       }
3401     }
3402   }
3403 
3404   // Enumerate conversion functions, if we're allowed to.
3405   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3406   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3407     // No conversion functions from incomplete types.
3408   } else if (const RecordType *FromRecordType =
3409                  From->getType()->getAs<RecordType>()) {
3410     if (CXXRecordDecl *FromRecordDecl
3411          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3412       // Add all of the conversion functions as candidates.
3413       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3414       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3415         DeclAccessPair FoundDecl = I.getPair();
3416         NamedDecl *D = FoundDecl.getDecl();
3417         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3418         if (isa<UsingShadowDecl>(D))
3419           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3420 
3421         CXXConversionDecl *Conv;
3422         FunctionTemplateDecl *ConvTemplate;
3423         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3424           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3425         else
3426           Conv = cast<CXXConversionDecl>(D);
3427 
3428         if (AllowExplicit || !Conv->isExplicit()) {
3429           if (ConvTemplate)
3430             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3431                                              ActingContext, From, ToType,
3432                                              CandidateSet,
3433                                              AllowObjCConversionOnExplicit);
3434           else
3435             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3436                                      From, ToType, CandidateSet,
3437                                      AllowObjCConversionOnExplicit);
3438         }
3439       }
3440     }
3441   }
3442 
3443   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3444 
3445   OverloadCandidateSet::iterator Best;
3446   switch (auto Result =
3447               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3448   case OR_Success:
3449   case OR_Deleted:
3450     // Record the standard conversion we used and the conversion function.
3451     if (CXXConstructorDecl *Constructor
3452           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3453       // C++ [over.ics.user]p1:
3454       //   If the user-defined conversion is specified by a
3455       //   constructor (12.3.1), the initial standard conversion
3456       //   sequence converts the source type to the type required by
3457       //   the argument of the constructor.
3458       //
3459       QualType ThisType = Constructor->getThisType();
3460       if (isa<InitListExpr>(From)) {
3461         // Initializer lists don't have conversions as such.
3462         User.Before.setAsIdentityConversion();
3463       } else {
3464         if (Best->Conversions[0].isEllipsis())
3465           User.EllipsisConversion = true;
3466         else {
3467           User.Before = Best->Conversions[0].Standard;
3468           User.EllipsisConversion = false;
3469         }
3470       }
3471       User.HadMultipleCandidates = HadMultipleCandidates;
3472       User.ConversionFunction = Constructor;
3473       User.FoundConversionFunction = Best->FoundDecl;
3474       User.After.setAsIdentityConversion();
3475       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3476       User.After.setAllToTypes(ToType);
3477       return Result;
3478     }
3479     if (CXXConversionDecl *Conversion
3480                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3481       // C++ [over.ics.user]p1:
3482       //
3483       //   [...] If the user-defined conversion is specified by a
3484       //   conversion function (12.3.2), the initial standard
3485       //   conversion sequence converts the source type to the
3486       //   implicit object parameter of the conversion function.
3487       User.Before = Best->Conversions[0].Standard;
3488       User.HadMultipleCandidates = HadMultipleCandidates;
3489       User.ConversionFunction = Conversion;
3490       User.FoundConversionFunction = Best->FoundDecl;
3491       User.EllipsisConversion = false;
3492 
3493       // C++ [over.ics.user]p2:
3494       //   The second standard conversion sequence converts the
3495       //   result of the user-defined conversion to the target type
3496       //   for the sequence. Since an implicit conversion sequence
3497       //   is an initialization, the special rules for
3498       //   initialization by user-defined conversion apply when
3499       //   selecting the best user-defined conversion for a
3500       //   user-defined conversion sequence (see 13.3.3 and
3501       //   13.3.3.1).
3502       User.After = Best->FinalConversion;
3503       return Result;
3504     }
3505     llvm_unreachable("Not a constructor or conversion function?");
3506 
3507   case OR_No_Viable_Function:
3508     return OR_No_Viable_Function;
3509 
3510   case OR_Ambiguous:
3511     return OR_Ambiguous;
3512   }
3513 
3514   llvm_unreachable("Invalid OverloadResult!");
3515 }
3516 
3517 bool
3518 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3519   ImplicitConversionSequence ICS;
3520   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3521                                     OverloadCandidateSet::CSK_Normal);
3522   OverloadingResult OvResult =
3523     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3524                             CandidateSet, false, false);
3525   if (OvResult == OR_Ambiguous)
3526     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3527         << From->getType() << ToType << From->getSourceRange();
3528   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3529     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3530                              diag::err_typecheck_nonviable_condition_incomplete,
3531                              From->getType(), From->getSourceRange()))
3532       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3533           << false << From->getType() << From->getSourceRange() << ToType;
3534   } else
3535     return false;
3536   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3537   return true;
3538 }
3539 
3540 /// Compare the user-defined conversion functions or constructors
3541 /// of two user-defined conversion sequences to determine whether any ordering
3542 /// is possible.
3543 static ImplicitConversionSequence::CompareKind
3544 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3545                            FunctionDecl *Function2) {
3546   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3547     return ImplicitConversionSequence::Indistinguishable;
3548 
3549   // Objective-C++:
3550   //   If both conversion functions are implicitly-declared conversions from
3551   //   a lambda closure type to a function pointer and a block pointer,
3552   //   respectively, always prefer the conversion to a function pointer,
3553   //   because the function pointer is more lightweight and is more likely
3554   //   to keep code working.
3555   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3556   if (!Conv1)
3557     return ImplicitConversionSequence::Indistinguishable;
3558 
3559   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3560   if (!Conv2)
3561     return ImplicitConversionSequence::Indistinguishable;
3562 
3563   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3564     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3565     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3566     if (Block1 != Block2)
3567       return Block1 ? ImplicitConversionSequence::Worse
3568                     : ImplicitConversionSequence::Better;
3569   }
3570 
3571   return ImplicitConversionSequence::Indistinguishable;
3572 }
3573 
3574 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3575     const ImplicitConversionSequence &ICS) {
3576   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3577          (ICS.isUserDefined() &&
3578           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3579 }
3580 
3581 /// CompareImplicitConversionSequences - Compare two implicit
3582 /// conversion sequences to determine whether one is better than the
3583 /// other or if they are indistinguishable (C++ 13.3.3.2).
3584 static ImplicitConversionSequence::CompareKind
3585 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3586                                    const ImplicitConversionSequence& ICS1,
3587                                    const ImplicitConversionSequence& ICS2)
3588 {
3589   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3590   // conversion sequences (as defined in 13.3.3.1)
3591   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3592   //      conversion sequence than a user-defined conversion sequence or
3593   //      an ellipsis conversion sequence, and
3594   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3595   //      conversion sequence than an ellipsis conversion sequence
3596   //      (13.3.3.1.3).
3597   //
3598   // C++0x [over.best.ics]p10:
3599   //   For the purpose of ranking implicit conversion sequences as
3600   //   described in 13.3.3.2, the ambiguous conversion sequence is
3601   //   treated as a user-defined sequence that is indistinguishable
3602   //   from any other user-defined conversion sequence.
3603 
3604   // String literal to 'char *' conversion has been deprecated in C++03. It has
3605   // been removed from C++11. We still accept this conversion, if it happens at
3606   // the best viable function. Otherwise, this conversion is considered worse
3607   // than ellipsis conversion. Consider this as an extension; this is not in the
3608   // standard. For example:
3609   //
3610   // int &f(...);    // #1
3611   // void f(char*);  // #2
3612   // void g() { int &r = f("foo"); }
3613   //
3614   // In C++03, we pick #2 as the best viable function.
3615   // In C++11, we pick #1 as the best viable function, because ellipsis
3616   // conversion is better than string-literal to char* conversion (since there
3617   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3618   // convert arguments, #2 would be the best viable function in C++11.
3619   // If the best viable function has this conversion, a warning will be issued
3620   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3621 
3622   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3623       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3624       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3625     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3626                ? ImplicitConversionSequence::Worse
3627                : ImplicitConversionSequence::Better;
3628 
3629   if (ICS1.getKindRank() < ICS2.getKindRank())
3630     return ImplicitConversionSequence::Better;
3631   if (ICS2.getKindRank() < ICS1.getKindRank())
3632     return ImplicitConversionSequence::Worse;
3633 
3634   // The following checks require both conversion sequences to be of
3635   // the same kind.
3636   if (ICS1.getKind() != ICS2.getKind())
3637     return ImplicitConversionSequence::Indistinguishable;
3638 
3639   ImplicitConversionSequence::CompareKind Result =
3640       ImplicitConversionSequence::Indistinguishable;
3641 
3642   // Two implicit conversion sequences of the same form are
3643   // indistinguishable conversion sequences unless one of the
3644   // following rules apply: (C++ 13.3.3.2p3):
3645 
3646   // List-initialization sequence L1 is a better conversion sequence than
3647   // list-initialization sequence L2 if:
3648   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3649   //   if not that,
3650   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3651   //   and N1 is smaller than N2.,
3652   // even if one of the other rules in this paragraph would otherwise apply.
3653   if (!ICS1.isBad()) {
3654     if (ICS1.isStdInitializerListElement() &&
3655         !ICS2.isStdInitializerListElement())
3656       return ImplicitConversionSequence::Better;
3657     if (!ICS1.isStdInitializerListElement() &&
3658         ICS2.isStdInitializerListElement())
3659       return ImplicitConversionSequence::Worse;
3660   }
3661 
3662   if (ICS1.isStandard())
3663     // Standard conversion sequence S1 is a better conversion sequence than
3664     // standard conversion sequence S2 if [...]
3665     Result = CompareStandardConversionSequences(S, Loc,
3666                                                 ICS1.Standard, ICS2.Standard);
3667   else if (ICS1.isUserDefined()) {
3668     // User-defined conversion sequence U1 is a better conversion
3669     // sequence than another user-defined conversion sequence U2 if
3670     // they contain the same user-defined conversion function or
3671     // constructor and if the second standard conversion sequence of
3672     // U1 is better than the second standard conversion sequence of
3673     // U2 (C++ 13.3.3.2p3).
3674     if (ICS1.UserDefined.ConversionFunction ==
3675           ICS2.UserDefined.ConversionFunction)
3676       Result = CompareStandardConversionSequences(S, Loc,
3677                                                   ICS1.UserDefined.After,
3678                                                   ICS2.UserDefined.After);
3679     else
3680       Result = compareConversionFunctions(S,
3681                                           ICS1.UserDefined.ConversionFunction,
3682                                           ICS2.UserDefined.ConversionFunction);
3683   }
3684 
3685   return Result;
3686 }
3687 
3688 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3689 // determine if one is a proper subset of the other.
3690 static ImplicitConversionSequence::CompareKind
3691 compareStandardConversionSubsets(ASTContext &Context,
3692                                  const StandardConversionSequence& SCS1,
3693                                  const StandardConversionSequence& SCS2) {
3694   ImplicitConversionSequence::CompareKind Result
3695     = ImplicitConversionSequence::Indistinguishable;
3696 
3697   // the identity conversion sequence is considered to be a subsequence of
3698   // any non-identity conversion sequence
3699   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3700     return ImplicitConversionSequence::Better;
3701   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3702     return ImplicitConversionSequence::Worse;
3703 
3704   if (SCS1.Second != SCS2.Second) {
3705     if (SCS1.Second == ICK_Identity)
3706       Result = ImplicitConversionSequence::Better;
3707     else if (SCS2.Second == ICK_Identity)
3708       Result = ImplicitConversionSequence::Worse;
3709     else
3710       return ImplicitConversionSequence::Indistinguishable;
3711   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3712     return ImplicitConversionSequence::Indistinguishable;
3713 
3714   if (SCS1.Third == SCS2.Third) {
3715     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3716                              : ImplicitConversionSequence::Indistinguishable;
3717   }
3718 
3719   if (SCS1.Third == ICK_Identity)
3720     return Result == ImplicitConversionSequence::Worse
3721              ? ImplicitConversionSequence::Indistinguishable
3722              : ImplicitConversionSequence::Better;
3723 
3724   if (SCS2.Third == ICK_Identity)
3725     return Result == ImplicitConversionSequence::Better
3726              ? ImplicitConversionSequence::Indistinguishable
3727              : ImplicitConversionSequence::Worse;
3728 
3729   return ImplicitConversionSequence::Indistinguishable;
3730 }
3731 
3732 /// Determine whether one of the given reference bindings is better
3733 /// than the other based on what kind of bindings they are.
3734 static bool
3735 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3736                              const StandardConversionSequence &SCS2) {
3737   // C++0x [over.ics.rank]p3b4:
3738   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3739   //      implicit object parameter of a non-static member function declared
3740   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3741   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3742   //      lvalue reference to a function lvalue and S2 binds an rvalue
3743   //      reference*.
3744   //
3745   // FIXME: Rvalue references. We're going rogue with the above edits,
3746   // because the semantics in the current C++0x working paper (N3225 at the
3747   // time of this writing) break the standard definition of std::forward
3748   // and std::reference_wrapper when dealing with references to functions.
3749   // Proposed wording changes submitted to CWG for consideration.
3750   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3751       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3752     return false;
3753 
3754   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3755           SCS2.IsLvalueReference) ||
3756          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3757           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3758 }
3759 
3760 /// CompareStandardConversionSequences - Compare two standard
3761 /// conversion sequences to determine whether one is better than the
3762 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3763 static ImplicitConversionSequence::CompareKind
3764 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3765                                    const StandardConversionSequence& SCS1,
3766                                    const StandardConversionSequence& SCS2)
3767 {
3768   // Standard conversion sequence S1 is a better conversion sequence
3769   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3770 
3771   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3772   //     sequences in the canonical form defined by 13.3.3.1.1,
3773   //     excluding any Lvalue Transformation; the identity conversion
3774   //     sequence is considered to be a subsequence of any
3775   //     non-identity conversion sequence) or, if not that,
3776   if (ImplicitConversionSequence::CompareKind CK
3777         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3778     return CK;
3779 
3780   //  -- the rank of S1 is better than the rank of S2 (by the rules
3781   //     defined below), or, if not that,
3782   ImplicitConversionRank Rank1 = SCS1.getRank();
3783   ImplicitConversionRank Rank2 = SCS2.getRank();
3784   if (Rank1 < Rank2)
3785     return ImplicitConversionSequence::Better;
3786   else if (Rank2 < Rank1)
3787     return ImplicitConversionSequence::Worse;
3788 
3789   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3790   // are indistinguishable unless one of the following rules
3791   // applies:
3792 
3793   //   A conversion that is not a conversion of a pointer, or
3794   //   pointer to member, to bool is better than another conversion
3795   //   that is such a conversion.
3796   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3797     return SCS2.isPointerConversionToBool()
3798              ? ImplicitConversionSequence::Better
3799              : ImplicitConversionSequence::Worse;
3800 
3801   // C++ [over.ics.rank]p4b2:
3802   //
3803   //   If class B is derived directly or indirectly from class A,
3804   //   conversion of B* to A* is better than conversion of B* to
3805   //   void*, and conversion of A* to void* is better than conversion
3806   //   of B* to void*.
3807   bool SCS1ConvertsToVoid
3808     = SCS1.isPointerConversionToVoidPointer(S.Context);
3809   bool SCS2ConvertsToVoid
3810     = SCS2.isPointerConversionToVoidPointer(S.Context);
3811   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3812     // Exactly one of the conversion sequences is a conversion to
3813     // a void pointer; it's the worse conversion.
3814     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3815                               : ImplicitConversionSequence::Worse;
3816   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3817     // Neither conversion sequence converts to a void pointer; compare
3818     // their derived-to-base conversions.
3819     if (ImplicitConversionSequence::CompareKind DerivedCK
3820           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3821       return DerivedCK;
3822   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3823              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3824     // Both conversion sequences are conversions to void
3825     // pointers. Compare the source types to determine if there's an
3826     // inheritance relationship in their sources.
3827     QualType FromType1 = SCS1.getFromType();
3828     QualType FromType2 = SCS2.getFromType();
3829 
3830     // Adjust the types we're converting from via the array-to-pointer
3831     // conversion, if we need to.
3832     if (SCS1.First == ICK_Array_To_Pointer)
3833       FromType1 = S.Context.getArrayDecayedType(FromType1);
3834     if (SCS2.First == ICK_Array_To_Pointer)
3835       FromType2 = S.Context.getArrayDecayedType(FromType2);
3836 
3837     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3838     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3839 
3840     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3841       return ImplicitConversionSequence::Better;
3842     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3843       return ImplicitConversionSequence::Worse;
3844 
3845     // Objective-C++: If one interface is more specific than the
3846     // other, it is the better one.
3847     const ObjCObjectPointerType* FromObjCPtr1
3848       = FromType1->getAs<ObjCObjectPointerType>();
3849     const ObjCObjectPointerType* FromObjCPtr2
3850       = FromType2->getAs<ObjCObjectPointerType>();
3851     if (FromObjCPtr1 && FromObjCPtr2) {
3852       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3853                                                           FromObjCPtr2);
3854       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3855                                                            FromObjCPtr1);
3856       if (AssignLeft != AssignRight) {
3857         return AssignLeft? ImplicitConversionSequence::Better
3858                          : ImplicitConversionSequence::Worse;
3859       }
3860     }
3861   }
3862 
3863   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3864   // bullet 3).
3865   if (ImplicitConversionSequence::CompareKind QualCK
3866         = CompareQualificationConversions(S, SCS1, SCS2))
3867     return QualCK;
3868 
3869   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3870     // Check for a better reference binding based on the kind of bindings.
3871     if (isBetterReferenceBindingKind(SCS1, SCS2))
3872       return ImplicitConversionSequence::Better;
3873     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3874       return ImplicitConversionSequence::Worse;
3875 
3876     // C++ [over.ics.rank]p3b4:
3877     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3878     //      which the references refer are the same type except for
3879     //      top-level cv-qualifiers, and the type to which the reference
3880     //      initialized by S2 refers is more cv-qualified than the type
3881     //      to which the reference initialized by S1 refers.
3882     QualType T1 = SCS1.getToType(2);
3883     QualType T2 = SCS2.getToType(2);
3884     T1 = S.Context.getCanonicalType(T1);
3885     T2 = S.Context.getCanonicalType(T2);
3886     Qualifiers T1Quals, T2Quals;
3887     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3888     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3889     if (UnqualT1 == UnqualT2) {
3890       // Objective-C++ ARC: If the references refer to objects with different
3891       // lifetimes, prefer bindings that don't change lifetime.
3892       if (SCS1.ObjCLifetimeConversionBinding !=
3893                                           SCS2.ObjCLifetimeConversionBinding) {
3894         return SCS1.ObjCLifetimeConversionBinding
3895                                            ? ImplicitConversionSequence::Worse
3896                                            : ImplicitConversionSequence::Better;
3897       }
3898 
3899       // If the type is an array type, promote the element qualifiers to the
3900       // type for comparison.
3901       if (isa<ArrayType>(T1) && T1Quals)
3902         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3903       if (isa<ArrayType>(T2) && T2Quals)
3904         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3905       if (T2.isMoreQualifiedThan(T1))
3906         return ImplicitConversionSequence::Better;
3907       else if (T1.isMoreQualifiedThan(T2))
3908         return ImplicitConversionSequence::Worse;
3909     }
3910   }
3911 
3912   // In Microsoft mode, prefer an integral conversion to a
3913   // floating-to-integral conversion if the integral conversion
3914   // is between types of the same size.
3915   // For example:
3916   // void f(float);
3917   // void f(int);
3918   // int main {
3919   //    long a;
3920   //    f(a);
3921   // }
3922   // Here, MSVC will call f(int) instead of generating a compile error
3923   // as clang will do in standard mode.
3924   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3925       SCS2.Second == ICK_Floating_Integral &&
3926       S.Context.getTypeSize(SCS1.getFromType()) ==
3927           S.Context.getTypeSize(SCS1.getToType(2)))
3928     return ImplicitConversionSequence::Better;
3929 
3930   // Prefer a compatible vector conversion over a lax vector conversion
3931   // For example:
3932   //
3933   // typedef float __v4sf __attribute__((__vector_size__(16)));
3934   // void f(vector float);
3935   // void f(vector signed int);
3936   // int main() {
3937   //   __v4sf a;
3938   //   f(a);
3939   // }
3940   // Here, we'd like to choose f(vector float) and not
3941   // report an ambiguous call error
3942   if (SCS1.Second == ICK_Vector_Conversion &&
3943       SCS2.Second == ICK_Vector_Conversion) {
3944     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3945         SCS1.getFromType(), SCS1.getToType(2));
3946     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3947         SCS2.getFromType(), SCS2.getToType(2));
3948 
3949     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3950       return SCS1IsCompatibleVectorConversion
3951                  ? ImplicitConversionSequence::Better
3952                  : ImplicitConversionSequence::Worse;
3953   }
3954 
3955   return ImplicitConversionSequence::Indistinguishable;
3956 }
3957 
3958 /// CompareQualificationConversions - Compares two standard conversion
3959 /// sequences to determine whether they can be ranked based on their
3960 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3961 static ImplicitConversionSequence::CompareKind
3962 CompareQualificationConversions(Sema &S,
3963                                 const StandardConversionSequence& SCS1,
3964                                 const StandardConversionSequence& SCS2) {
3965   // C++ 13.3.3.2p3:
3966   //  -- S1 and S2 differ only in their qualification conversion and
3967   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3968   //     cv-qualification signature of type T1 is a proper subset of
3969   //     the cv-qualification signature of type T2, and S1 is not the
3970   //     deprecated string literal array-to-pointer conversion (4.2).
3971   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3972       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3973     return ImplicitConversionSequence::Indistinguishable;
3974 
3975   // FIXME: the example in the standard doesn't use a qualification
3976   // conversion (!)
3977   QualType T1 = SCS1.getToType(2);
3978   QualType T2 = SCS2.getToType(2);
3979   T1 = S.Context.getCanonicalType(T1);
3980   T2 = S.Context.getCanonicalType(T2);
3981   Qualifiers T1Quals, T2Quals;
3982   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3983   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3984 
3985   // If the types are the same, we won't learn anything by unwrapped
3986   // them.
3987   if (UnqualT1 == UnqualT2)
3988     return ImplicitConversionSequence::Indistinguishable;
3989 
3990   // If the type is an array type, promote the element qualifiers to the type
3991   // for comparison.
3992   if (isa<ArrayType>(T1) && T1Quals)
3993     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3994   if (isa<ArrayType>(T2) && T2Quals)
3995     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3996 
3997   ImplicitConversionSequence::CompareKind Result
3998     = ImplicitConversionSequence::Indistinguishable;
3999 
4000   // Objective-C++ ARC:
4001   //   Prefer qualification conversions not involving a change in lifetime
4002   //   to qualification conversions that do not change lifetime.
4003   if (SCS1.QualificationIncludesObjCLifetime !=
4004                                       SCS2.QualificationIncludesObjCLifetime) {
4005     Result = SCS1.QualificationIncludesObjCLifetime
4006                ? ImplicitConversionSequence::Worse
4007                : ImplicitConversionSequence::Better;
4008   }
4009 
4010   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4011     // Within each iteration of the loop, we check the qualifiers to
4012     // determine if this still looks like a qualification
4013     // conversion. Then, if all is well, we unwrap one more level of
4014     // pointers or pointers-to-members and do it all again
4015     // until there are no more pointers or pointers-to-members left
4016     // to unwrap. This essentially mimics what
4017     // IsQualificationConversion does, but here we're checking for a
4018     // strict subset of qualifiers.
4019     if (T1.getQualifiers().withoutObjCLifetime() ==
4020         T2.getQualifiers().withoutObjCLifetime())
4021       // The qualifiers are the same, so this doesn't tell us anything
4022       // about how the sequences rank.
4023       // ObjC ownership quals are omitted above as they interfere with
4024       // the ARC overload rule.
4025       ;
4026     else if (T2.isMoreQualifiedThan(T1)) {
4027       // T1 has fewer qualifiers, so it could be the better sequence.
4028       if (Result == ImplicitConversionSequence::Worse)
4029         // Neither has qualifiers that are a subset of the other's
4030         // qualifiers.
4031         return ImplicitConversionSequence::Indistinguishable;
4032 
4033       Result = ImplicitConversionSequence::Better;
4034     } else if (T1.isMoreQualifiedThan(T2)) {
4035       // T2 has fewer qualifiers, so it could be the better sequence.
4036       if (Result == ImplicitConversionSequence::Better)
4037         // Neither has qualifiers that are a subset of the other's
4038         // qualifiers.
4039         return ImplicitConversionSequence::Indistinguishable;
4040 
4041       Result = ImplicitConversionSequence::Worse;
4042     } else {
4043       // Qualifiers are disjoint.
4044       return ImplicitConversionSequence::Indistinguishable;
4045     }
4046 
4047     // If the types after this point are equivalent, we're done.
4048     if (S.Context.hasSameUnqualifiedType(T1, T2))
4049       break;
4050   }
4051 
4052   // Check that the winning standard conversion sequence isn't using
4053   // the deprecated string literal array to pointer conversion.
4054   switch (Result) {
4055   case ImplicitConversionSequence::Better:
4056     if (SCS1.DeprecatedStringLiteralToCharPtr)
4057       Result = ImplicitConversionSequence::Indistinguishable;
4058     break;
4059 
4060   case ImplicitConversionSequence::Indistinguishable:
4061     break;
4062 
4063   case ImplicitConversionSequence::Worse:
4064     if (SCS2.DeprecatedStringLiteralToCharPtr)
4065       Result = ImplicitConversionSequence::Indistinguishable;
4066     break;
4067   }
4068 
4069   return Result;
4070 }
4071 
4072 /// CompareDerivedToBaseConversions - Compares two standard conversion
4073 /// sequences to determine whether they can be ranked based on their
4074 /// various kinds of derived-to-base conversions (C++
4075 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4076 /// conversions between Objective-C interface types.
4077 static ImplicitConversionSequence::CompareKind
4078 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4079                                 const StandardConversionSequence& SCS1,
4080                                 const StandardConversionSequence& SCS2) {
4081   QualType FromType1 = SCS1.getFromType();
4082   QualType ToType1 = SCS1.getToType(1);
4083   QualType FromType2 = SCS2.getFromType();
4084   QualType ToType2 = SCS2.getToType(1);
4085 
4086   // Adjust the types we're converting from via the array-to-pointer
4087   // conversion, if we need to.
4088   if (SCS1.First == ICK_Array_To_Pointer)
4089     FromType1 = S.Context.getArrayDecayedType(FromType1);
4090   if (SCS2.First == ICK_Array_To_Pointer)
4091     FromType2 = S.Context.getArrayDecayedType(FromType2);
4092 
4093   // Canonicalize all of the types.
4094   FromType1 = S.Context.getCanonicalType(FromType1);
4095   ToType1 = S.Context.getCanonicalType(ToType1);
4096   FromType2 = S.Context.getCanonicalType(FromType2);
4097   ToType2 = S.Context.getCanonicalType(ToType2);
4098 
4099   // C++ [over.ics.rank]p4b3:
4100   //
4101   //   If class B is derived directly or indirectly from class A and
4102   //   class C is derived directly or indirectly from B,
4103   //
4104   // Compare based on pointer conversions.
4105   if (SCS1.Second == ICK_Pointer_Conversion &&
4106       SCS2.Second == ICK_Pointer_Conversion &&
4107       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4108       FromType1->isPointerType() && FromType2->isPointerType() &&
4109       ToType1->isPointerType() && ToType2->isPointerType()) {
4110     QualType FromPointee1
4111       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4112     QualType ToPointee1
4113       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4114     QualType FromPointee2
4115       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4116     QualType ToPointee2
4117       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4118 
4119     //   -- conversion of C* to B* is better than conversion of C* to A*,
4120     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4121       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4122         return ImplicitConversionSequence::Better;
4123       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4124         return ImplicitConversionSequence::Worse;
4125     }
4126 
4127     //   -- conversion of B* to A* is better than conversion of C* to A*,
4128     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4129       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4130         return ImplicitConversionSequence::Better;
4131       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4132         return ImplicitConversionSequence::Worse;
4133     }
4134   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4135              SCS2.Second == ICK_Pointer_Conversion) {
4136     const ObjCObjectPointerType *FromPtr1
4137       = FromType1->getAs<ObjCObjectPointerType>();
4138     const ObjCObjectPointerType *FromPtr2
4139       = FromType2->getAs<ObjCObjectPointerType>();
4140     const ObjCObjectPointerType *ToPtr1
4141       = ToType1->getAs<ObjCObjectPointerType>();
4142     const ObjCObjectPointerType *ToPtr2
4143       = ToType2->getAs<ObjCObjectPointerType>();
4144 
4145     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4146       // Apply the same conversion ranking rules for Objective-C pointer types
4147       // that we do for C++ pointers to class types. However, we employ the
4148       // Objective-C pseudo-subtyping relationship used for assignment of
4149       // Objective-C pointer types.
4150       bool FromAssignLeft
4151         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4152       bool FromAssignRight
4153         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4154       bool ToAssignLeft
4155         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4156       bool ToAssignRight
4157         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4158 
4159       // A conversion to an a non-id object pointer type or qualified 'id'
4160       // type is better than a conversion to 'id'.
4161       if (ToPtr1->isObjCIdType() &&
4162           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4163         return ImplicitConversionSequence::Worse;
4164       if (ToPtr2->isObjCIdType() &&
4165           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4166         return ImplicitConversionSequence::Better;
4167 
4168       // A conversion to a non-id object pointer type is better than a
4169       // conversion to a qualified 'id' type
4170       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4171         return ImplicitConversionSequence::Worse;
4172       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4173         return ImplicitConversionSequence::Better;
4174 
4175       // A conversion to an a non-Class object pointer type or qualified 'Class'
4176       // type is better than a conversion to 'Class'.
4177       if (ToPtr1->isObjCClassType() &&
4178           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4179         return ImplicitConversionSequence::Worse;
4180       if (ToPtr2->isObjCClassType() &&
4181           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4182         return ImplicitConversionSequence::Better;
4183 
4184       // A conversion to a non-Class object pointer type is better than a
4185       // conversion to a qualified 'Class' type.
4186       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4187         return ImplicitConversionSequence::Worse;
4188       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4189         return ImplicitConversionSequence::Better;
4190 
4191       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4192       if (S.Context.hasSameType(FromType1, FromType2) &&
4193           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4194           (ToAssignLeft != ToAssignRight)) {
4195         if (FromPtr1->isSpecialized()) {
4196           // "conversion of B<A> * to B * is better than conversion of B * to
4197           // C *.
4198           bool IsFirstSame =
4199               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4200           bool IsSecondSame =
4201               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4202           if (IsFirstSame) {
4203             if (!IsSecondSame)
4204               return ImplicitConversionSequence::Better;
4205           } else if (IsSecondSame)
4206             return ImplicitConversionSequence::Worse;
4207         }
4208         return ToAssignLeft? ImplicitConversionSequence::Worse
4209                            : ImplicitConversionSequence::Better;
4210       }
4211 
4212       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4213       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4214           (FromAssignLeft != FromAssignRight))
4215         return FromAssignLeft? ImplicitConversionSequence::Better
4216         : ImplicitConversionSequence::Worse;
4217     }
4218   }
4219 
4220   // Ranking of member-pointer types.
4221   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4222       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4223       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4224     const MemberPointerType * FromMemPointer1 =
4225                                         FromType1->getAs<MemberPointerType>();
4226     const MemberPointerType * ToMemPointer1 =
4227                                           ToType1->getAs<MemberPointerType>();
4228     const MemberPointerType * FromMemPointer2 =
4229                                           FromType2->getAs<MemberPointerType>();
4230     const MemberPointerType * ToMemPointer2 =
4231                                           ToType2->getAs<MemberPointerType>();
4232     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4233     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4234     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4235     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4236     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4237     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4238     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4239     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4240     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4241     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4242       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4243         return ImplicitConversionSequence::Worse;
4244       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4245         return ImplicitConversionSequence::Better;
4246     }
4247     // conversion of B::* to C::* is better than conversion of A::* to C::*
4248     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4249       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4250         return ImplicitConversionSequence::Better;
4251       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4252         return ImplicitConversionSequence::Worse;
4253     }
4254   }
4255 
4256   if (SCS1.Second == ICK_Derived_To_Base) {
4257     //   -- conversion of C to B is better than conversion of C to A,
4258     //   -- binding of an expression of type C to a reference of type
4259     //      B& is better than binding an expression of type C to a
4260     //      reference of type A&,
4261     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4262         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4263       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4264         return ImplicitConversionSequence::Better;
4265       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4266         return ImplicitConversionSequence::Worse;
4267     }
4268 
4269     //   -- conversion of B to A is better than conversion of C to A.
4270     //   -- binding of an expression of type B to a reference of type
4271     //      A& is better than binding an expression of type C to a
4272     //      reference of type A&,
4273     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4274         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4275       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4276         return ImplicitConversionSequence::Better;
4277       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4278         return ImplicitConversionSequence::Worse;
4279     }
4280   }
4281 
4282   return ImplicitConversionSequence::Indistinguishable;
4283 }
4284 
4285 /// Determine whether the given type is valid, e.g., it is not an invalid
4286 /// C++ class.
4287 static bool isTypeValid(QualType T) {
4288   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4289     return !Record->isInvalidDecl();
4290 
4291   return true;
4292 }
4293 
4294 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4295 /// determine whether they are reference-related,
4296 /// reference-compatible, reference-compatible with added
4297 /// qualification, or incompatible, for use in C++ initialization by
4298 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4299 /// type, and the first type (T1) is the pointee type of the reference
4300 /// type being initialized.
4301 Sema::ReferenceCompareResult
4302 Sema::CompareReferenceRelationship(SourceLocation Loc,
4303                                    QualType OrigT1, QualType OrigT2,
4304                                    bool &DerivedToBase,
4305                                    bool &ObjCConversion,
4306                                    bool &ObjCLifetimeConversion) {
4307   assert(!OrigT1->isReferenceType() &&
4308     "T1 must be the pointee type of the reference type");
4309   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4310 
4311   QualType T1 = Context.getCanonicalType(OrigT1);
4312   QualType T2 = Context.getCanonicalType(OrigT2);
4313   Qualifiers T1Quals, T2Quals;
4314   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4315   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4316 
4317   // C++ [dcl.init.ref]p4:
4318   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4319   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4320   //   T1 is a base class of T2.
4321   DerivedToBase = false;
4322   ObjCConversion = false;
4323   ObjCLifetimeConversion = false;
4324   QualType ConvertedT2;
4325   if (UnqualT1 == UnqualT2) {
4326     // Nothing to do.
4327   } else if (isCompleteType(Loc, OrigT2) &&
4328              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4329              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4330     DerivedToBase = true;
4331   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4332            UnqualT2->isObjCObjectOrInterfaceType() &&
4333            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4334     ObjCConversion = true;
4335   else if (UnqualT2->isFunctionType() &&
4336            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4337     // C++1z [dcl.init.ref]p4:
4338     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4339     //   function" and T1 is "function"
4340     //
4341     // We extend this to also apply to 'noreturn', so allow any function
4342     // conversion between function types.
4343     return Ref_Compatible;
4344   else
4345     return Ref_Incompatible;
4346 
4347   // At this point, we know that T1 and T2 are reference-related (at
4348   // least).
4349 
4350   // If the type is an array type, promote the element qualifiers to the type
4351   // for comparison.
4352   if (isa<ArrayType>(T1) && T1Quals)
4353     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4354   if (isa<ArrayType>(T2) && T2Quals)
4355     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4356 
4357   // C++ [dcl.init.ref]p4:
4358   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4359   //   reference-related to T2 and cv1 is the same cv-qualification
4360   //   as, or greater cv-qualification than, cv2. For purposes of
4361   //   overload resolution, cases for which cv1 is greater
4362   //   cv-qualification than cv2 are identified as
4363   //   reference-compatible with added qualification (see 13.3.3.2).
4364   //
4365   // Note that we also require equivalence of Objective-C GC and address-space
4366   // qualifiers when performing these computations, so that e.g., an int in
4367   // address space 1 is not reference-compatible with an int in address
4368   // space 2.
4369   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4370       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4371     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4372       ObjCLifetimeConversion = true;
4373 
4374     T1Quals.removeObjCLifetime();
4375     T2Quals.removeObjCLifetime();
4376   }
4377 
4378   // MS compiler ignores __unaligned qualifier for references; do the same.
4379   T1Quals.removeUnaligned();
4380   T2Quals.removeUnaligned();
4381 
4382   if (T1Quals.compatiblyIncludes(T2Quals))
4383     return Ref_Compatible;
4384   else
4385     return Ref_Related;
4386 }
4387 
4388 /// Look for a user-defined conversion to a value reference-compatible
4389 ///        with DeclType. Return true if something definite is found.
4390 static bool
4391 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4392                          QualType DeclType, SourceLocation DeclLoc,
4393                          Expr *Init, QualType T2, bool AllowRvalues,
4394                          bool AllowExplicit) {
4395   assert(T2->isRecordType() && "Can only find conversions of record types.");
4396   CXXRecordDecl *T2RecordDecl
4397     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4398 
4399   OverloadCandidateSet CandidateSet(
4400       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4401   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4402   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4403     NamedDecl *D = *I;
4404     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4405     if (isa<UsingShadowDecl>(D))
4406       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4407 
4408     FunctionTemplateDecl *ConvTemplate
4409       = dyn_cast<FunctionTemplateDecl>(D);
4410     CXXConversionDecl *Conv;
4411     if (ConvTemplate)
4412       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4413     else
4414       Conv = cast<CXXConversionDecl>(D);
4415 
4416     // If this is an explicit conversion, and we're not allowed to consider
4417     // explicit conversions, skip it.
4418     if (!AllowExplicit && Conv->isExplicit())
4419       continue;
4420 
4421     if (AllowRvalues) {
4422       bool DerivedToBase = false;
4423       bool ObjCConversion = false;
4424       bool ObjCLifetimeConversion = false;
4425 
4426       // If we are initializing an rvalue reference, don't permit conversion
4427       // functions that return lvalues.
4428       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4429         const ReferenceType *RefType
4430           = Conv->getConversionType()->getAs<LValueReferenceType>();
4431         if (RefType && !RefType->getPointeeType()->isFunctionType())
4432           continue;
4433       }
4434 
4435       if (!ConvTemplate &&
4436           S.CompareReferenceRelationship(
4437             DeclLoc,
4438             Conv->getConversionType().getNonReferenceType()
4439               .getUnqualifiedType(),
4440             DeclType.getNonReferenceType().getUnqualifiedType(),
4441             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4442           Sema::Ref_Incompatible)
4443         continue;
4444     } else {
4445       // If the conversion function doesn't return a reference type,
4446       // it can't be considered for this conversion. An rvalue reference
4447       // is only acceptable if its referencee is a function type.
4448 
4449       const ReferenceType *RefType =
4450         Conv->getConversionType()->getAs<ReferenceType>();
4451       if (!RefType ||
4452           (!RefType->isLValueReferenceType() &&
4453            !RefType->getPointeeType()->isFunctionType()))
4454         continue;
4455     }
4456 
4457     if (ConvTemplate)
4458       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4459                                        Init, DeclType, CandidateSet,
4460                                        /*AllowObjCConversionOnExplicit=*/false);
4461     else
4462       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4463                                DeclType, CandidateSet,
4464                                /*AllowObjCConversionOnExplicit=*/false);
4465   }
4466 
4467   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4468 
4469   OverloadCandidateSet::iterator Best;
4470   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4471   case OR_Success:
4472     // C++ [over.ics.ref]p1:
4473     //
4474     //   [...] If the parameter binds directly to the result of
4475     //   applying a conversion function to the argument
4476     //   expression, the implicit conversion sequence is a
4477     //   user-defined conversion sequence (13.3.3.1.2), with the
4478     //   second standard conversion sequence either an identity
4479     //   conversion or, if the conversion function returns an
4480     //   entity of a type that is a derived class of the parameter
4481     //   type, a derived-to-base Conversion.
4482     if (!Best->FinalConversion.DirectBinding)
4483       return false;
4484 
4485     ICS.setUserDefined();
4486     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4487     ICS.UserDefined.After = Best->FinalConversion;
4488     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4489     ICS.UserDefined.ConversionFunction = Best->Function;
4490     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4491     ICS.UserDefined.EllipsisConversion = false;
4492     assert(ICS.UserDefined.After.ReferenceBinding &&
4493            ICS.UserDefined.After.DirectBinding &&
4494            "Expected a direct reference binding!");
4495     return true;
4496 
4497   case OR_Ambiguous:
4498     ICS.setAmbiguous();
4499     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4500          Cand != CandidateSet.end(); ++Cand)
4501       if (Cand->Viable)
4502         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4503     return true;
4504 
4505   case OR_No_Viable_Function:
4506   case OR_Deleted:
4507     // There was no suitable conversion, or we found a deleted
4508     // conversion; continue with other checks.
4509     return false;
4510   }
4511 
4512   llvm_unreachable("Invalid OverloadResult!");
4513 }
4514 
4515 /// Compute an implicit conversion sequence for reference
4516 /// initialization.
4517 static ImplicitConversionSequence
4518 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4519                  SourceLocation DeclLoc,
4520                  bool SuppressUserConversions,
4521                  bool AllowExplicit) {
4522   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4523 
4524   // Most paths end in a failed conversion.
4525   ImplicitConversionSequence ICS;
4526   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4527 
4528   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4529   QualType T2 = Init->getType();
4530 
4531   // If the initializer is the address of an overloaded function, try
4532   // to resolve the overloaded function. If all goes well, T2 is the
4533   // type of the resulting function.
4534   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4535     DeclAccessPair Found;
4536     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4537                                                                 false, Found))
4538       T2 = Fn->getType();
4539   }
4540 
4541   // Compute some basic properties of the types and the initializer.
4542   bool isRValRef = DeclType->isRValueReferenceType();
4543   bool DerivedToBase = false;
4544   bool ObjCConversion = false;
4545   bool ObjCLifetimeConversion = false;
4546   Expr::Classification InitCategory = Init->Classify(S.Context);
4547   Sema::ReferenceCompareResult RefRelationship
4548     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4549                                      ObjCConversion, ObjCLifetimeConversion);
4550 
4551 
4552   // C++0x [dcl.init.ref]p5:
4553   //   A reference to type "cv1 T1" is initialized by an expression
4554   //   of type "cv2 T2" as follows:
4555 
4556   //     -- If reference is an lvalue reference and the initializer expression
4557   if (!isRValRef) {
4558     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4559     //        reference-compatible with "cv2 T2," or
4560     //
4561     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4562     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4563       // C++ [over.ics.ref]p1:
4564       //   When a parameter of reference type binds directly (8.5.3)
4565       //   to an argument expression, the implicit conversion sequence
4566       //   is the identity conversion, unless the argument expression
4567       //   has a type that is a derived class of the parameter type,
4568       //   in which case the implicit conversion sequence is a
4569       //   derived-to-base Conversion (13.3.3.1).
4570       ICS.setStandard();
4571       ICS.Standard.First = ICK_Identity;
4572       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4573                          : ObjCConversion? ICK_Compatible_Conversion
4574                          : ICK_Identity;
4575       ICS.Standard.Third = ICK_Identity;
4576       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4577       ICS.Standard.setToType(0, T2);
4578       ICS.Standard.setToType(1, T1);
4579       ICS.Standard.setToType(2, T1);
4580       ICS.Standard.ReferenceBinding = true;
4581       ICS.Standard.DirectBinding = true;
4582       ICS.Standard.IsLvalueReference = !isRValRef;
4583       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4584       ICS.Standard.BindsToRvalue = false;
4585       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4586       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4587       ICS.Standard.CopyConstructor = nullptr;
4588       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4589 
4590       // Nothing more to do: the inaccessibility/ambiguity check for
4591       // derived-to-base conversions is suppressed when we're
4592       // computing the implicit conversion sequence (C++
4593       // [over.best.ics]p2).
4594       return ICS;
4595     }
4596 
4597     //       -- has a class type (i.e., T2 is a class type), where T1 is
4598     //          not reference-related to T2, and can be implicitly
4599     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4600     //          is reference-compatible with "cv3 T3" 92) (this
4601     //          conversion is selected by enumerating the applicable
4602     //          conversion functions (13.3.1.6) and choosing the best
4603     //          one through overload resolution (13.3)),
4604     if (!SuppressUserConversions && T2->isRecordType() &&
4605         S.isCompleteType(DeclLoc, T2) &&
4606         RefRelationship == Sema::Ref_Incompatible) {
4607       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4608                                    Init, T2, /*AllowRvalues=*/false,
4609                                    AllowExplicit))
4610         return ICS;
4611     }
4612   }
4613 
4614   //     -- Otherwise, the reference shall be an lvalue reference to a
4615   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4616   //        shall be an rvalue reference.
4617   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4618     return ICS;
4619 
4620   //       -- If the initializer expression
4621   //
4622   //            -- is an xvalue, class prvalue, array prvalue or function
4623   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4624   if (RefRelationship == Sema::Ref_Compatible &&
4625       (InitCategory.isXValue() ||
4626        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4627        (InitCategory.isLValue() && T2->isFunctionType()))) {
4628     ICS.setStandard();
4629     ICS.Standard.First = ICK_Identity;
4630     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4631                       : ObjCConversion? ICK_Compatible_Conversion
4632                       : ICK_Identity;
4633     ICS.Standard.Third = ICK_Identity;
4634     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4635     ICS.Standard.setToType(0, T2);
4636     ICS.Standard.setToType(1, T1);
4637     ICS.Standard.setToType(2, T1);
4638     ICS.Standard.ReferenceBinding = true;
4639     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4640     // binding unless we're binding to a class prvalue.
4641     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4642     // allow the use of rvalue references in C++98/03 for the benefit of
4643     // standard library implementors; therefore, we need the xvalue check here.
4644     ICS.Standard.DirectBinding =
4645       S.getLangOpts().CPlusPlus11 ||
4646       !(InitCategory.isPRValue() || T2->isRecordType());
4647     ICS.Standard.IsLvalueReference = !isRValRef;
4648     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4649     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4650     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4651     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4652     ICS.Standard.CopyConstructor = nullptr;
4653     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4654     return ICS;
4655   }
4656 
4657   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4658   //               reference-related to T2, and can be implicitly converted to
4659   //               an xvalue, class prvalue, or function lvalue of type
4660   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4661   //               "cv3 T3",
4662   //
4663   //          then the reference is bound to the value of the initializer
4664   //          expression in the first case and to the result of the conversion
4665   //          in the second case (or, in either case, to an appropriate base
4666   //          class subobject).
4667   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4668       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4669       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4670                                Init, T2, /*AllowRvalues=*/true,
4671                                AllowExplicit)) {
4672     // In the second case, if the reference is an rvalue reference
4673     // and the second standard conversion sequence of the
4674     // user-defined conversion sequence includes an lvalue-to-rvalue
4675     // conversion, the program is ill-formed.
4676     if (ICS.isUserDefined() && isRValRef &&
4677         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4678       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4679 
4680     return ICS;
4681   }
4682 
4683   // A temporary of function type cannot be created; don't even try.
4684   if (T1->isFunctionType())
4685     return ICS;
4686 
4687   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4688   //          initialized from the initializer expression using the
4689   //          rules for a non-reference copy initialization (8.5). The
4690   //          reference is then bound to the temporary. If T1 is
4691   //          reference-related to T2, cv1 must be the same
4692   //          cv-qualification as, or greater cv-qualification than,
4693   //          cv2; otherwise, the program is ill-formed.
4694   if (RefRelationship == Sema::Ref_Related) {
4695     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4696     // we would be reference-compatible or reference-compatible with
4697     // added qualification. But that wasn't the case, so the reference
4698     // initialization fails.
4699     //
4700     // Note that we only want to check address spaces and cvr-qualifiers here.
4701     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4702     Qualifiers T1Quals = T1.getQualifiers();
4703     Qualifiers T2Quals = T2.getQualifiers();
4704     T1Quals.removeObjCGCAttr();
4705     T1Quals.removeObjCLifetime();
4706     T2Quals.removeObjCGCAttr();
4707     T2Quals.removeObjCLifetime();
4708     // MS compiler ignores __unaligned qualifier for references; do the same.
4709     T1Quals.removeUnaligned();
4710     T2Quals.removeUnaligned();
4711     if (!T1Quals.compatiblyIncludes(T2Quals))
4712       return ICS;
4713   }
4714 
4715   // If at least one of the types is a class type, the types are not
4716   // related, and we aren't allowed any user conversions, the
4717   // reference binding fails. This case is important for breaking
4718   // recursion, since TryImplicitConversion below will attempt to
4719   // create a temporary through the use of a copy constructor.
4720   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4721       (T1->isRecordType() || T2->isRecordType()))
4722     return ICS;
4723 
4724   // If T1 is reference-related to T2 and the reference is an rvalue
4725   // reference, the initializer expression shall not be an lvalue.
4726   if (RefRelationship >= Sema::Ref_Related &&
4727       isRValRef && Init->Classify(S.Context).isLValue())
4728     return ICS;
4729 
4730   // C++ [over.ics.ref]p2:
4731   //   When a parameter of reference type is not bound directly to
4732   //   an argument expression, the conversion sequence is the one
4733   //   required to convert the argument expression to the
4734   //   underlying type of the reference according to
4735   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4736   //   to copy-initializing a temporary of the underlying type with
4737   //   the argument expression. Any difference in top-level
4738   //   cv-qualification is subsumed by the initialization itself
4739   //   and does not constitute a conversion.
4740   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4741                               /*AllowExplicit=*/false,
4742                               /*InOverloadResolution=*/false,
4743                               /*CStyle=*/false,
4744                               /*AllowObjCWritebackConversion=*/false,
4745                               /*AllowObjCConversionOnExplicit=*/false);
4746 
4747   // Of course, that's still a reference binding.
4748   if (ICS.isStandard()) {
4749     ICS.Standard.ReferenceBinding = true;
4750     ICS.Standard.IsLvalueReference = !isRValRef;
4751     ICS.Standard.BindsToFunctionLvalue = false;
4752     ICS.Standard.BindsToRvalue = true;
4753     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4754     ICS.Standard.ObjCLifetimeConversionBinding = false;
4755   } else if (ICS.isUserDefined()) {
4756     const ReferenceType *LValRefType =
4757         ICS.UserDefined.ConversionFunction->getReturnType()
4758             ->getAs<LValueReferenceType>();
4759 
4760     // C++ [over.ics.ref]p3:
4761     //   Except for an implicit object parameter, for which see 13.3.1, a
4762     //   standard conversion sequence cannot be formed if it requires [...]
4763     //   binding an rvalue reference to an lvalue other than a function
4764     //   lvalue.
4765     // Note that the function case is not possible here.
4766     if (DeclType->isRValueReferenceType() && LValRefType) {
4767       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4768       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4769       // reference to an rvalue!
4770       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4771       return ICS;
4772     }
4773 
4774     ICS.UserDefined.After.ReferenceBinding = true;
4775     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4776     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4777     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4778     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4779     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4780   }
4781 
4782   return ICS;
4783 }
4784 
4785 static ImplicitConversionSequence
4786 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4787                       bool SuppressUserConversions,
4788                       bool InOverloadResolution,
4789                       bool AllowObjCWritebackConversion,
4790                       bool AllowExplicit = false);
4791 
4792 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4793 /// initializer list From.
4794 static ImplicitConversionSequence
4795 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4796                   bool SuppressUserConversions,
4797                   bool InOverloadResolution,
4798                   bool AllowObjCWritebackConversion) {
4799   // C++11 [over.ics.list]p1:
4800   //   When an argument is an initializer list, it is not an expression and
4801   //   special rules apply for converting it to a parameter type.
4802 
4803   ImplicitConversionSequence Result;
4804   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4805 
4806   // We need a complete type for what follows. Incomplete types can never be
4807   // initialized from init lists.
4808   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4809     return Result;
4810 
4811   // Per DR1467:
4812   //   If the parameter type is a class X and the initializer list has a single
4813   //   element of type cv U, where U is X or a class derived from X, the
4814   //   implicit conversion sequence is the one required to convert the element
4815   //   to the parameter type.
4816   //
4817   //   Otherwise, if the parameter type is a character array [... ]
4818   //   and the initializer list has a single element that is an
4819   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4820   //   implicit conversion sequence is the identity conversion.
4821   if (From->getNumInits() == 1) {
4822     if (ToType->isRecordType()) {
4823       QualType InitType = From->getInit(0)->getType();
4824       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4825           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4826         return TryCopyInitialization(S, From->getInit(0), ToType,
4827                                      SuppressUserConversions,
4828                                      InOverloadResolution,
4829                                      AllowObjCWritebackConversion);
4830     }
4831     // FIXME: Check the other conditions here: array of character type,
4832     // initializer is a string literal.
4833     if (ToType->isArrayType()) {
4834       InitializedEntity Entity =
4835         InitializedEntity::InitializeParameter(S.Context, ToType,
4836                                                /*Consumed=*/false);
4837       if (S.CanPerformCopyInitialization(Entity, From)) {
4838         Result.setStandard();
4839         Result.Standard.setAsIdentityConversion();
4840         Result.Standard.setFromType(ToType);
4841         Result.Standard.setAllToTypes(ToType);
4842         return Result;
4843       }
4844     }
4845   }
4846 
4847   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4848   // C++11 [over.ics.list]p2:
4849   //   If the parameter type is std::initializer_list<X> or "array of X" and
4850   //   all the elements can be implicitly converted to X, the implicit
4851   //   conversion sequence is the worst conversion necessary to convert an
4852   //   element of the list to X.
4853   //
4854   // C++14 [over.ics.list]p3:
4855   //   Otherwise, if the parameter type is "array of N X", if the initializer
4856   //   list has exactly N elements or if it has fewer than N elements and X is
4857   //   default-constructible, and if all the elements of the initializer list
4858   //   can be implicitly converted to X, the implicit conversion sequence is
4859   //   the worst conversion necessary to convert an element of the list to X.
4860   //
4861   // FIXME: We're missing a lot of these checks.
4862   bool toStdInitializerList = false;
4863   QualType X;
4864   if (ToType->isArrayType())
4865     X = S.Context.getAsArrayType(ToType)->getElementType();
4866   else
4867     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4868   if (!X.isNull()) {
4869     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4870       Expr *Init = From->getInit(i);
4871       ImplicitConversionSequence ICS =
4872           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4873                                 InOverloadResolution,
4874                                 AllowObjCWritebackConversion);
4875       // If a single element isn't convertible, fail.
4876       if (ICS.isBad()) {
4877         Result = ICS;
4878         break;
4879       }
4880       // Otherwise, look for the worst conversion.
4881       if (Result.isBad() || CompareImplicitConversionSequences(
4882                                 S, From->getBeginLoc(), ICS, Result) ==
4883                                 ImplicitConversionSequence::Worse)
4884         Result = ICS;
4885     }
4886 
4887     // For an empty list, we won't have computed any conversion sequence.
4888     // Introduce the identity conversion sequence.
4889     if (From->getNumInits() == 0) {
4890       Result.setStandard();
4891       Result.Standard.setAsIdentityConversion();
4892       Result.Standard.setFromType(ToType);
4893       Result.Standard.setAllToTypes(ToType);
4894     }
4895 
4896     Result.setStdInitializerListElement(toStdInitializerList);
4897     return Result;
4898   }
4899 
4900   // C++14 [over.ics.list]p4:
4901   // C++11 [over.ics.list]p3:
4902   //   Otherwise, if the parameter is a non-aggregate class X and overload
4903   //   resolution chooses a single best constructor [...] the implicit
4904   //   conversion sequence is a user-defined conversion sequence. If multiple
4905   //   constructors are viable but none is better than the others, the
4906   //   implicit conversion sequence is a user-defined conversion sequence.
4907   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4908     // This function can deal with initializer lists.
4909     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4910                                     /*AllowExplicit=*/false,
4911                                     InOverloadResolution, /*CStyle=*/false,
4912                                     AllowObjCWritebackConversion,
4913                                     /*AllowObjCConversionOnExplicit=*/false);
4914   }
4915 
4916   // C++14 [over.ics.list]p5:
4917   // C++11 [over.ics.list]p4:
4918   //   Otherwise, if the parameter has an aggregate type which can be
4919   //   initialized from the initializer list [...] the implicit conversion
4920   //   sequence is a user-defined conversion sequence.
4921   if (ToType->isAggregateType()) {
4922     // Type is an aggregate, argument is an init list. At this point it comes
4923     // down to checking whether the initialization works.
4924     // FIXME: Find out whether this parameter is consumed or not.
4925     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4926     // need to call into the initialization code here; overload resolution
4927     // should not be doing that.
4928     InitializedEntity Entity =
4929         InitializedEntity::InitializeParameter(S.Context, ToType,
4930                                                /*Consumed=*/false);
4931     if (S.CanPerformCopyInitialization(Entity, From)) {
4932       Result.setUserDefined();
4933       Result.UserDefined.Before.setAsIdentityConversion();
4934       // Initializer lists don't have a type.
4935       Result.UserDefined.Before.setFromType(QualType());
4936       Result.UserDefined.Before.setAllToTypes(QualType());
4937 
4938       Result.UserDefined.After.setAsIdentityConversion();
4939       Result.UserDefined.After.setFromType(ToType);
4940       Result.UserDefined.After.setAllToTypes(ToType);
4941       Result.UserDefined.ConversionFunction = nullptr;
4942     }
4943     return Result;
4944   }
4945 
4946   // C++14 [over.ics.list]p6:
4947   // C++11 [over.ics.list]p5:
4948   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4949   if (ToType->isReferenceType()) {
4950     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4951     // mention initializer lists in any way. So we go by what list-
4952     // initialization would do and try to extrapolate from that.
4953 
4954     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4955 
4956     // If the initializer list has a single element that is reference-related
4957     // to the parameter type, we initialize the reference from that.
4958     if (From->getNumInits() == 1) {
4959       Expr *Init = From->getInit(0);
4960 
4961       QualType T2 = Init->getType();
4962 
4963       // If the initializer is the address of an overloaded function, try
4964       // to resolve the overloaded function. If all goes well, T2 is the
4965       // type of the resulting function.
4966       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4967         DeclAccessPair Found;
4968         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4969                                    Init, ToType, false, Found))
4970           T2 = Fn->getType();
4971       }
4972 
4973       // Compute some basic properties of the types and the initializer.
4974       bool dummy1 = false;
4975       bool dummy2 = false;
4976       bool dummy3 = false;
4977       Sema::ReferenceCompareResult RefRelationship =
4978           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4979                                          dummy2, dummy3);
4980 
4981       if (RefRelationship >= Sema::Ref_Related) {
4982         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4983                                 SuppressUserConversions,
4984                                 /*AllowExplicit=*/false);
4985       }
4986     }
4987 
4988     // Otherwise, we bind the reference to a temporary created from the
4989     // initializer list.
4990     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4991                                InOverloadResolution,
4992                                AllowObjCWritebackConversion);
4993     if (Result.isFailure())
4994       return Result;
4995     assert(!Result.isEllipsis() &&
4996            "Sub-initialization cannot result in ellipsis conversion.");
4997 
4998     // Can we even bind to a temporary?
4999     if (ToType->isRValueReferenceType() ||
5000         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5001       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5002                                             Result.UserDefined.After;
5003       SCS.ReferenceBinding = true;
5004       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5005       SCS.BindsToRvalue = true;
5006       SCS.BindsToFunctionLvalue = false;
5007       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5008       SCS.ObjCLifetimeConversionBinding = false;
5009     } else
5010       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5011                     From, ToType);
5012     return Result;
5013   }
5014 
5015   // C++14 [over.ics.list]p7:
5016   // C++11 [over.ics.list]p6:
5017   //   Otherwise, if the parameter type is not a class:
5018   if (!ToType->isRecordType()) {
5019     //    - if the initializer list has one element that is not itself an
5020     //      initializer list, the implicit conversion sequence is the one
5021     //      required to convert the element to the parameter type.
5022     unsigned NumInits = From->getNumInits();
5023     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5024       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5025                                      SuppressUserConversions,
5026                                      InOverloadResolution,
5027                                      AllowObjCWritebackConversion);
5028     //    - if the initializer list has no elements, the implicit conversion
5029     //      sequence is the identity conversion.
5030     else if (NumInits == 0) {
5031       Result.setStandard();
5032       Result.Standard.setAsIdentityConversion();
5033       Result.Standard.setFromType(ToType);
5034       Result.Standard.setAllToTypes(ToType);
5035     }
5036     return Result;
5037   }
5038 
5039   // C++14 [over.ics.list]p8:
5040   // C++11 [over.ics.list]p7:
5041   //   In all cases other than those enumerated above, no conversion is possible
5042   return Result;
5043 }
5044 
5045 /// TryCopyInitialization - Try to copy-initialize a value of type
5046 /// ToType from the expression From. Return the implicit conversion
5047 /// sequence required to pass this argument, which may be a bad
5048 /// conversion sequence (meaning that the argument cannot be passed to
5049 /// a parameter of this type). If @p SuppressUserConversions, then we
5050 /// do not permit any user-defined conversion sequences.
5051 static ImplicitConversionSequence
5052 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5053                       bool SuppressUserConversions,
5054                       bool InOverloadResolution,
5055                       bool AllowObjCWritebackConversion,
5056                       bool AllowExplicit) {
5057   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5058     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5059                              InOverloadResolution,AllowObjCWritebackConversion);
5060 
5061   if (ToType->isReferenceType())
5062     return TryReferenceInit(S, From, ToType,
5063                             /*FIXME:*/ From->getBeginLoc(),
5064                             SuppressUserConversions, AllowExplicit);
5065 
5066   return TryImplicitConversion(S, From, ToType,
5067                                SuppressUserConversions,
5068                                /*AllowExplicit=*/false,
5069                                InOverloadResolution,
5070                                /*CStyle=*/false,
5071                                AllowObjCWritebackConversion,
5072                                /*AllowObjCConversionOnExplicit=*/false);
5073 }
5074 
5075 static bool TryCopyInitialization(const CanQualType FromQTy,
5076                                   const CanQualType ToQTy,
5077                                   Sema &S,
5078                                   SourceLocation Loc,
5079                                   ExprValueKind FromVK) {
5080   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5081   ImplicitConversionSequence ICS =
5082     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5083 
5084   return !ICS.isBad();
5085 }
5086 
5087 /// TryObjectArgumentInitialization - Try to initialize the object
5088 /// parameter of the given member function (@c Method) from the
5089 /// expression @p From.
5090 static ImplicitConversionSequence
5091 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5092                                 Expr::Classification FromClassification,
5093                                 CXXMethodDecl *Method,
5094                                 CXXRecordDecl *ActingContext) {
5095   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5096   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5097   //                 const volatile object.
5098   Qualifiers Quals;
5099   if (isa<CXXDestructorDecl>(Method)) {
5100     Quals.addConst();
5101     Quals.addVolatile();
5102   } else {
5103     Quals = Method->getMethodQualifiers();
5104   }
5105 
5106   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5107 
5108   // Set up the conversion sequence as a "bad" conversion, to allow us
5109   // to exit early.
5110   ImplicitConversionSequence ICS;
5111 
5112   // We need to have an object of class type.
5113   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5114     FromType = PT->getPointeeType();
5115 
5116     // When we had a pointer, it's implicitly dereferenced, so we
5117     // better have an lvalue.
5118     assert(FromClassification.isLValue());
5119   }
5120 
5121   assert(FromType->isRecordType());
5122 
5123   // C++0x [over.match.funcs]p4:
5124   //   For non-static member functions, the type of the implicit object
5125   //   parameter is
5126   //
5127   //     - "lvalue reference to cv X" for functions declared without a
5128   //        ref-qualifier or with the & ref-qualifier
5129   //     - "rvalue reference to cv X" for functions declared with the &&
5130   //        ref-qualifier
5131   //
5132   // where X is the class of which the function is a member and cv is the
5133   // cv-qualification on the member function declaration.
5134   //
5135   // However, when finding an implicit conversion sequence for the argument, we
5136   // are not allowed to perform user-defined conversions
5137   // (C++ [over.match.funcs]p5). We perform a simplified version of
5138   // reference binding here, that allows class rvalues to bind to
5139   // non-constant references.
5140 
5141   // First check the qualifiers.
5142   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5143   if (ImplicitParamType.getCVRQualifiers()
5144                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5145       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5146     ICS.setBad(BadConversionSequence::bad_qualifiers,
5147                FromType, ImplicitParamType);
5148     return ICS;
5149   }
5150 
5151   if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5152     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5153     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5154     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5155       ICS.setBad(BadConversionSequence::bad_qualifiers,
5156                  FromType, ImplicitParamType);
5157       return ICS;
5158     }
5159   }
5160 
5161   // Check that we have either the same type or a derived type. It
5162   // affects the conversion rank.
5163   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5164   ImplicitConversionKind SecondKind;
5165   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5166     SecondKind = ICK_Identity;
5167   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5168     SecondKind = ICK_Derived_To_Base;
5169   else {
5170     ICS.setBad(BadConversionSequence::unrelated_class,
5171                FromType, ImplicitParamType);
5172     return ICS;
5173   }
5174 
5175   // Check the ref-qualifier.
5176   switch (Method->getRefQualifier()) {
5177   case RQ_None:
5178     // Do nothing; we don't care about lvalueness or rvalueness.
5179     break;
5180 
5181   case RQ_LValue:
5182     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5183       // non-const lvalue reference cannot bind to an rvalue
5184       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5185                  ImplicitParamType);
5186       return ICS;
5187     }
5188     break;
5189 
5190   case RQ_RValue:
5191     if (!FromClassification.isRValue()) {
5192       // rvalue reference cannot bind to an lvalue
5193       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5194                  ImplicitParamType);
5195       return ICS;
5196     }
5197     break;
5198   }
5199 
5200   // Success. Mark this as a reference binding.
5201   ICS.setStandard();
5202   ICS.Standard.setAsIdentityConversion();
5203   ICS.Standard.Second = SecondKind;
5204   ICS.Standard.setFromType(FromType);
5205   ICS.Standard.setAllToTypes(ImplicitParamType);
5206   ICS.Standard.ReferenceBinding = true;
5207   ICS.Standard.DirectBinding = true;
5208   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5209   ICS.Standard.BindsToFunctionLvalue = false;
5210   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5211   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5212     = (Method->getRefQualifier() == RQ_None);
5213   return ICS;
5214 }
5215 
5216 /// PerformObjectArgumentInitialization - Perform initialization of
5217 /// the implicit object parameter for the given Method with the given
5218 /// expression.
5219 ExprResult
5220 Sema::PerformObjectArgumentInitialization(Expr *From,
5221                                           NestedNameSpecifier *Qualifier,
5222                                           NamedDecl *FoundDecl,
5223                                           CXXMethodDecl *Method) {
5224   QualType FromRecordType, DestType;
5225   QualType ImplicitParamRecordType  =
5226     Method->getThisType()->getAs<PointerType>()->getPointeeType();
5227 
5228   Expr::Classification FromClassification;
5229   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5230     FromRecordType = PT->getPointeeType();
5231     DestType = Method->getThisType();
5232     FromClassification = Expr::Classification::makeSimpleLValue();
5233   } else {
5234     FromRecordType = From->getType();
5235     DestType = ImplicitParamRecordType;
5236     FromClassification = From->Classify(Context);
5237 
5238     // When performing member access on an rvalue, materialize a temporary.
5239     if (From->isRValue()) {
5240       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5241                                             Method->getRefQualifier() !=
5242                                                 RefQualifierKind::RQ_RValue);
5243     }
5244   }
5245 
5246   // Note that we always use the true parent context when performing
5247   // the actual argument initialization.
5248   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5249       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5250       Method->getParent());
5251   if (ICS.isBad()) {
5252     switch (ICS.Bad.Kind) {
5253     case BadConversionSequence::bad_qualifiers: {
5254       Qualifiers FromQs = FromRecordType.getQualifiers();
5255       Qualifiers ToQs = DestType.getQualifiers();
5256       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5257       if (CVR) {
5258         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5259             << Method->getDeclName() << FromRecordType << (CVR - 1)
5260             << From->getSourceRange();
5261         Diag(Method->getLocation(), diag::note_previous_decl)
5262           << Method->getDeclName();
5263         return ExprError();
5264       }
5265       break;
5266     }
5267 
5268     case BadConversionSequence::lvalue_ref_to_rvalue:
5269     case BadConversionSequence::rvalue_ref_to_lvalue: {
5270       bool IsRValueQualified =
5271         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5272       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5273           << Method->getDeclName() << FromClassification.isRValue()
5274           << IsRValueQualified;
5275       Diag(Method->getLocation(), diag::note_previous_decl)
5276         << Method->getDeclName();
5277       return ExprError();
5278     }
5279 
5280     case BadConversionSequence::no_conversion:
5281     case BadConversionSequence::unrelated_class:
5282       break;
5283     }
5284 
5285     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5286            << ImplicitParamRecordType << FromRecordType
5287            << From->getSourceRange();
5288   }
5289 
5290   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5291     ExprResult FromRes =
5292       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5293     if (FromRes.isInvalid())
5294       return ExprError();
5295     From = FromRes.get();
5296   }
5297 
5298   if (!Context.hasSameType(From->getType(), DestType)) {
5299     if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5300       From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion,
5301                              From->getValueKind()).get();
5302     else
5303       From = ImpCastExprToType(From, DestType, CK_NoOp,
5304                              From->getValueKind()).get();
5305   }
5306   return From;
5307 }
5308 
5309 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5310 /// expression From to bool (C++0x [conv]p3).
5311 static ImplicitConversionSequence
5312 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5313   return TryImplicitConversion(S, From, S.Context.BoolTy,
5314                                /*SuppressUserConversions=*/false,
5315                                /*AllowExplicit=*/true,
5316                                /*InOverloadResolution=*/false,
5317                                /*CStyle=*/false,
5318                                /*AllowObjCWritebackConversion=*/false,
5319                                /*AllowObjCConversionOnExplicit=*/false);
5320 }
5321 
5322 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5323 /// of the expression From to bool (C++0x [conv]p3).
5324 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5325   if (checkPlaceholderForOverload(*this, From))
5326     return ExprError();
5327 
5328   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5329   if (!ICS.isBad())
5330     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5331 
5332   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5333     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5334            << From->getType() << From->getSourceRange();
5335   return ExprError();
5336 }
5337 
5338 /// Check that the specified conversion is permitted in a converted constant
5339 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5340 /// is acceptable.
5341 static bool CheckConvertedConstantConversions(Sema &S,
5342                                               StandardConversionSequence &SCS) {
5343   // Since we know that the target type is an integral or unscoped enumeration
5344   // type, most conversion kinds are impossible. All possible First and Third
5345   // conversions are fine.
5346   switch (SCS.Second) {
5347   case ICK_Identity:
5348   case ICK_Function_Conversion:
5349   case ICK_Integral_Promotion:
5350   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5351   case ICK_Zero_Queue_Conversion:
5352     return true;
5353 
5354   case ICK_Boolean_Conversion:
5355     // Conversion from an integral or unscoped enumeration type to bool is
5356     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5357     // conversion, so we allow it in a converted constant expression.
5358     //
5359     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5360     // a lot of popular code. We should at least add a warning for this
5361     // (non-conforming) extension.
5362     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5363            SCS.getToType(2)->isBooleanType();
5364 
5365   case ICK_Pointer_Conversion:
5366   case ICK_Pointer_Member:
5367     // C++1z: null pointer conversions and null member pointer conversions are
5368     // only permitted if the source type is std::nullptr_t.
5369     return SCS.getFromType()->isNullPtrType();
5370 
5371   case ICK_Floating_Promotion:
5372   case ICK_Complex_Promotion:
5373   case ICK_Floating_Conversion:
5374   case ICK_Complex_Conversion:
5375   case ICK_Floating_Integral:
5376   case ICK_Compatible_Conversion:
5377   case ICK_Derived_To_Base:
5378   case ICK_Vector_Conversion:
5379   case ICK_Vector_Splat:
5380   case ICK_Complex_Real:
5381   case ICK_Block_Pointer_Conversion:
5382   case ICK_TransparentUnionConversion:
5383   case ICK_Writeback_Conversion:
5384   case ICK_Zero_Event_Conversion:
5385   case ICK_C_Only_Conversion:
5386   case ICK_Incompatible_Pointer_Conversion:
5387     return false;
5388 
5389   case ICK_Lvalue_To_Rvalue:
5390   case ICK_Array_To_Pointer:
5391   case ICK_Function_To_Pointer:
5392     llvm_unreachable("found a first conversion kind in Second");
5393 
5394   case ICK_Qualification:
5395     llvm_unreachable("found a third conversion kind in Second");
5396 
5397   case ICK_Num_Conversion_Kinds:
5398     break;
5399   }
5400 
5401   llvm_unreachable("unknown conversion kind");
5402 }
5403 
5404 /// CheckConvertedConstantExpression - Check that the expression From is a
5405 /// converted constant expression of type T, perform the conversion and produce
5406 /// the converted expression, per C++11 [expr.const]p3.
5407 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5408                                                    QualType T, APValue &Value,
5409                                                    Sema::CCEKind CCE,
5410                                                    bool RequireInt) {
5411   assert(S.getLangOpts().CPlusPlus11 &&
5412          "converted constant expression outside C++11");
5413 
5414   if (checkPlaceholderForOverload(S, From))
5415     return ExprError();
5416 
5417   // C++1z [expr.const]p3:
5418   //  A converted constant expression of type T is an expression,
5419   //  implicitly converted to type T, where the converted
5420   //  expression is a constant expression and the implicit conversion
5421   //  sequence contains only [... list of conversions ...].
5422   // C++1z [stmt.if]p2:
5423   //  If the if statement is of the form if constexpr, the value of the
5424   //  condition shall be a contextually converted constant expression of type
5425   //  bool.
5426   ImplicitConversionSequence ICS =
5427       CCE == Sema::CCEK_ConstexprIf
5428           ? TryContextuallyConvertToBool(S, From)
5429           : TryCopyInitialization(S, From, T,
5430                                   /*SuppressUserConversions=*/false,
5431                                   /*InOverloadResolution=*/false,
5432                                   /*AllowObjcWritebackConversion=*/false,
5433                                   /*AllowExplicit=*/false);
5434   StandardConversionSequence *SCS = nullptr;
5435   switch (ICS.getKind()) {
5436   case ImplicitConversionSequence::StandardConversion:
5437     SCS = &ICS.Standard;
5438     break;
5439   case ImplicitConversionSequence::UserDefinedConversion:
5440     // We are converting to a non-class type, so the Before sequence
5441     // must be trivial.
5442     SCS = &ICS.UserDefined.After;
5443     break;
5444   case ImplicitConversionSequence::AmbiguousConversion:
5445   case ImplicitConversionSequence::BadConversion:
5446     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5447       return S.Diag(From->getBeginLoc(),
5448                     diag::err_typecheck_converted_constant_expression)
5449              << From->getType() << From->getSourceRange() << T;
5450     return ExprError();
5451 
5452   case ImplicitConversionSequence::EllipsisConversion:
5453     llvm_unreachable("ellipsis conversion in converted constant expression");
5454   }
5455 
5456   // Check that we would only use permitted conversions.
5457   if (!CheckConvertedConstantConversions(S, *SCS)) {
5458     return S.Diag(From->getBeginLoc(),
5459                   diag::err_typecheck_converted_constant_expression_disallowed)
5460            << From->getType() << From->getSourceRange() << T;
5461   }
5462   // [...] and where the reference binding (if any) binds directly.
5463   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5464     return S.Diag(From->getBeginLoc(),
5465                   diag::err_typecheck_converted_constant_expression_indirect)
5466            << From->getType() << From->getSourceRange() << T;
5467   }
5468 
5469   ExprResult Result =
5470       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5471   if (Result.isInvalid())
5472     return Result;
5473 
5474   // Check for a narrowing implicit conversion.
5475   APValue PreNarrowingValue;
5476   QualType PreNarrowingType;
5477   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5478                                 PreNarrowingType)) {
5479   case NK_Dependent_Narrowing:
5480     // Implicit conversion to a narrower type, but the expression is
5481     // value-dependent so we can't tell whether it's actually narrowing.
5482   case NK_Variable_Narrowing:
5483     // Implicit conversion to a narrower type, and the value is not a constant
5484     // expression. We'll diagnose this in a moment.
5485   case NK_Not_Narrowing:
5486     break;
5487 
5488   case NK_Constant_Narrowing:
5489     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5490         << CCE << /*Constant*/ 1
5491         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5492     break;
5493 
5494   case NK_Type_Narrowing:
5495     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5496         << CCE << /*Constant*/ 0 << From->getType() << T;
5497     break;
5498   }
5499 
5500   if (Result.get()->isValueDependent()) {
5501     Value = APValue();
5502     return Result;
5503   }
5504 
5505   // Check the expression is a constant expression.
5506   SmallVector<PartialDiagnosticAt, 8> Notes;
5507   Expr::EvalResult Eval;
5508   Eval.Diag = &Notes;
5509   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5510                                    ? Expr::EvaluateForMangling
5511                                    : Expr::EvaluateForCodeGen;
5512 
5513   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5514       (RequireInt && !Eval.Val.isInt())) {
5515     // The expression can't be folded, so we can't keep it at this position in
5516     // the AST.
5517     Result = ExprError();
5518   } else {
5519     Value = Eval.Val;
5520 
5521     if (Notes.empty()) {
5522       // It's a constant expression.
5523       return ConstantExpr::Create(S.Context, Result.get());
5524     }
5525   }
5526 
5527   // It's not a constant expression. Produce an appropriate diagnostic.
5528   if (Notes.size() == 1 &&
5529       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5530     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5531   else {
5532     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5533         << CCE << From->getSourceRange();
5534     for (unsigned I = 0; I < Notes.size(); ++I)
5535       S.Diag(Notes[I].first, Notes[I].second);
5536   }
5537   return ExprError();
5538 }
5539 
5540 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5541                                                   APValue &Value, CCEKind CCE) {
5542   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5543 }
5544 
5545 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5546                                                   llvm::APSInt &Value,
5547                                                   CCEKind CCE) {
5548   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5549 
5550   APValue V;
5551   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5552   if (!R.isInvalid() && !R.get()->isValueDependent())
5553     Value = V.getInt();
5554   return R;
5555 }
5556 
5557 
5558 /// dropPointerConversions - If the given standard conversion sequence
5559 /// involves any pointer conversions, remove them.  This may change
5560 /// the result type of the conversion sequence.
5561 static void dropPointerConversion(StandardConversionSequence &SCS) {
5562   if (SCS.Second == ICK_Pointer_Conversion) {
5563     SCS.Second = ICK_Identity;
5564     SCS.Third = ICK_Identity;
5565     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5566   }
5567 }
5568 
5569 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5570 /// convert the expression From to an Objective-C pointer type.
5571 static ImplicitConversionSequence
5572 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5573   // Do an implicit conversion to 'id'.
5574   QualType Ty = S.Context.getObjCIdType();
5575   ImplicitConversionSequence ICS
5576     = TryImplicitConversion(S, From, Ty,
5577                             // FIXME: Are these flags correct?
5578                             /*SuppressUserConversions=*/false,
5579                             /*AllowExplicit=*/true,
5580                             /*InOverloadResolution=*/false,
5581                             /*CStyle=*/false,
5582                             /*AllowObjCWritebackConversion=*/false,
5583                             /*AllowObjCConversionOnExplicit=*/true);
5584 
5585   // Strip off any final conversions to 'id'.
5586   switch (ICS.getKind()) {
5587   case ImplicitConversionSequence::BadConversion:
5588   case ImplicitConversionSequence::AmbiguousConversion:
5589   case ImplicitConversionSequence::EllipsisConversion:
5590     break;
5591 
5592   case ImplicitConversionSequence::UserDefinedConversion:
5593     dropPointerConversion(ICS.UserDefined.After);
5594     break;
5595 
5596   case ImplicitConversionSequence::StandardConversion:
5597     dropPointerConversion(ICS.Standard);
5598     break;
5599   }
5600 
5601   return ICS;
5602 }
5603 
5604 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5605 /// conversion of the expression From to an Objective-C pointer type.
5606 /// Returns a valid but null ExprResult if no conversion sequence exists.
5607 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5608   if (checkPlaceholderForOverload(*this, From))
5609     return ExprError();
5610 
5611   QualType Ty = Context.getObjCIdType();
5612   ImplicitConversionSequence ICS =
5613     TryContextuallyConvertToObjCPointer(*this, From);
5614   if (!ICS.isBad())
5615     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5616   return ExprResult();
5617 }
5618 
5619 /// Determine whether the provided type is an integral type, or an enumeration
5620 /// type of a permitted flavor.
5621 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5622   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5623                                  : T->isIntegralOrUnscopedEnumerationType();
5624 }
5625 
5626 static ExprResult
5627 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5628                             Sema::ContextualImplicitConverter &Converter,
5629                             QualType T, UnresolvedSetImpl &ViableConversions) {
5630 
5631   if (Converter.Suppress)
5632     return ExprError();
5633 
5634   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5635   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5636     CXXConversionDecl *Conv =
5637         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5638     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5639     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5640   }
5641   return From;
5642 }
5643 
5644 static bool
5645 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5646                            Sema::ContextualImplicitConverter &Converter,
5647                            QualType T, bool HadMultipleCandidates,
5648                            UnresolvedSetImpl &ExplicitConversions) {
5649   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5650     DeclAccessPair Found = ExplicitConversions[0];
5651     CXXConversionDecl *Conversion =
5652         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5653 
5654     // The user probably meant to invoke the given explicit
5655     // conversion; use it.
5656     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5657     std::string TypeStr;
5658     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5659 
5660     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5661         << FixItHint::CreateInsertion(From->getBeginLoc(),
5662                                       "static_cast<" + TypeStr + ">(")
5663         << FixItHint::CreateInsertion(
5664                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5665     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5666 
5667     // If we aren't in a SFINAE context, build a call to the
5668     // explicit conversion function.
5669     if (SemaRef.isSFINAEContext())
5670       return true;
5671 
5672     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5673     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5674                                                        HadMultipleCandidates);
5675     if (Result.isInvalid())
5676       return true;
5677     // Record usage of conversion in an implicit cast.
5678     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5679                                     CK_UserDefinedConversion, Result.get(),
5680                                     nullptr, Result.get()->getValueKind());
5681   }
5682   return false;
5683 }
5684 
5685 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5686                              Sema::ContextualImplicitConverter &Converter,
5687                              QualType T, bool HadMultipleCandidates,
5688                              DeclAccessPair &Found) {
5689   CXXConversionDecl *Conversion =
5690       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5691   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5692 
5693   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5694   if (!Converter.SuppressConversion) {
5695     if (SemaRef.isSFINAEContext())
5696       return true;
5697 
5698     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5699         << From->getSourceRange();
5700   }
5701 
5702   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5703                                                      HadMultipleCandidates);
5704   if (Result.isInvalid())
5705     return true;
5706   // Record usage of conversion in an implicit cast.
5707   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5708                                   CK_UserDefinedConversion, Result.get(),
5709                                   nullptr, Result.get()->getValueKind());
5710   return false;
5711 }
5712 
5713 static ExprResult finishContextualImplicitConversion(
5714     Sema &SemaRef, SourceLocation Loc, Expr *From,
5715     Sema::ContextualImplicitConverter &Converter) {
5716   if (!Converter.match(From->getType()) && !Converter.Suppress)
5717     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5718         << From->getSourceRange();
5719 
5720   return SemaRef.DefaultLvalueConversion(From);
5721 }
5722 
5723 static void
5724 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5725                                   UnresolvedSetImpl &ViableConversions,
5726                                   OverloadCandidateSet &CandidateSet) {
5727   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5728     DeclAccessPair FoundDecl = ViableConversions[I];
5729     NamedDecl *D = FoundDecl.getDecl();
5730     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5731     if (isa<UsingShadowDecl>(D))
5732       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5733 
5734     CXXConversionDecl *Conv;
5735     FunctionTemplateDecl *ConvTemplate;
5736     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5737       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5738     else
5739       Conv = cast<CXXConversionDecl>(D);
5740 
5741     if (ConvTemplate)
5742       SemaRef.AddTemplateConversionCandidate(
5743         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5744         /*AllowObjCConversionOnExplicit=*/false);
5745     else
5746       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5747                                      ToType, CandidateSet,
5748                                      /*AllowObjCConversionOnExplicit=*/false);
5749   }
5750 }
5751 
5752 /// Attempt to convert the given expression to a type which is accepted
5753 /// by the given converter.
5754 ///
5755 /// This routine will attempt to convert an expression of class type to a
5756 /// type accepted by the specified converter. In C++11 and before, the class
5757 /// must have a single non-explicit conversion function converting to a matching
5758 /// type. In C++1y, there can be multiple such conversion functions, but only
5759 /// one target type.
5760 ///
5761 /// \param Loc The source location of the construct that requires the
5762 /// conversion.
5763 ///
5764 /// \param From The expression we're converting from.
5765 ///
5766 /// \param Converter Used to control and diagnose the conversion process.
5767 ///
5768 /// \returns The expression, converted to an integral or enumeration type if
5769 /// successful.
5770 ExprResult Sema::PerformContextualImplicitConversion(
5771     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5772   // We can't perform any more checking for type-dependent expressions.
5773   if (From->isTypeDependent())
5774     return From;
5775 
5776   // Process placeholders immediately.
5777   if (From->hasPlaceholderType()) {
5778     ExprResult result = CheckPlaceholderExpr(From);
5779     if (result.isInvalid())
5780       return result;
5781     From = result.get();
5782   }
5783 
5784   // If the expression already has a matching type, we're golden.
5785   QualType T = From->getType();
5786   if (Converter.match(T))
5787     return DefaultLvalueConversion(From);
5788 
5789   // FIXME: Check for missing '()' if T is a function type?
5790 
5791   // We can only perform contextual implicit conversions on objects of class
5792   // type.
5793   const RecordType *RecordTy = T->getAs<RecordType>();
5794   if (!RecordTy || !getLangOpts().CPlusPlus) {
5795     if (!Converter.Suppress)
5796       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5797     return From;
5798   }
5799 
5800   // We must have a complete class type.
5801   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5802     ContextualImplicitConverter &Converter;
5803     Expr *From;
5804 
5805     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5806         : Converter(Converter), From(From) {}
5807 
5808     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5809       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5810     }
5811   } IncompleteDiagnoser(Converter, From);
5812 
5813   if (Converter.Suppress ? !isCompleteType(Loc, T)
5814                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5815     return From;
5816 
5817   // Look for a conversion to an integral or enumeration type.
5818   UnresolvedSet<4>
5819       ViableConversions; // These are *potentially* viable in C++1y.
5820   UnresolvedSet<4> ExplicitConversions;
5821   const auto &Conversions =
5822       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5823 
5824   bool HadMultipleCandidates =
5825       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5826 
5827   // To check that there is only one target type, in C++1y:
5828   QualType ToType;
5829   bool HasUniqueTargetType = true;
5830 
5831   // Collect explicit or viable (potentially in C++1y) conversions.
5832   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5833     NamedDecl *D = (*I)->getUnderlyingDecl();
5834     CXXConversionDecl *Conversion;
5835     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5836     if (ConvTemplate) {
5837       if (getLangOpts().CPlusPlus14)
5838         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5839       else
5840         continue; // C++11 does not consider conversion operator templates(?).
5841     } else
5842       Conversion = cast<CXXConversionDecl>(D);
5843 
5844     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5845            "Conversion operator templates are considered potentially "
5846            "viable in C++1y");
5847 
5848     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5849     if (Converter.match(CurToType) || ConvTemplate) {
5850 
5851       if (Conversion->isExplicit()) {
5852         // FIXME: For C++1y, do we need this restriction?
5853         // cf. diagnoseNoViableConversion()
5854         if (!ConvTemplate)
5855           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5856       } else {
5857         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5858           if (ToType.isNull())
5859             ToType = CurToType.getUnqualifiedType();
5860           else if (HasUniqueTargetType &&
5861                    (CurToType.getUnqualifiedType() != ToType))
5862             HasUniqueTargetType = false;
5863         }
5864         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5865       }
5866     }
5867   }
5868 
5869   if (getLangOpts().CPlusPlus14) {
5870     // C++1y [conv]p6:
5871     // ... An expression e of class type E appearing in such a context
5872     // is said to be contextually implicitly converted to a specified
5873     // type T and is well-formed if and only if e can be implicitly
5874     // converted to a type T that is determined as follows: E is searched
5875     // for conversion functions whose return type is cv T or reference to
5876     // cv T such that T is allowed by the context. There shall be
5877     // exactly one such T.
5878 
5879     // If no unique T is found:
5880     if (ToType.isNull()) {
5881       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5882                                      HadMultipleCandidates,
5883                                      ExplicitConversions))
5884         return ExprError();
5885       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5886     }
5887 
5888     // If more than one unique Ts are found:
5889     if (!HasUniqueTargetType)
5890       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5891                                          ViableConversions);
5892 
5893     // If one unique T is found:
5894     // First, build a candidate set from the previously recorded
5895     // potentially viable conversions.
5896     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5897     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5898                                       CandidateSet);
5899 
5900     // Then, perform overload resolution over the candidate set.
5901     OverloadCandidateSet::iterator Best;
5902     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5903     case OR_Success: {
5904       // Apply this conversion.
5905       DeclAccessPair Found =
5906           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5907       if (recordConversion(*this, Loc, From, Converter, T,
5908                            HadMultipleCandidates, Found))
5909         return ExprError();
5910       break;
5911     }
5912     case OR_Ambiguous:
5913       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5914                                          ViableConversions);
5915     case OR_No_Viable_Function:
5916       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5917                                      HadMultipleCandidates,
5918                                      ExplicitConversions))
5919         return ExprError();
5920       LLVM_FALLTHROUGH;
5921     case OR_Deleted:
5922       // We'll complain below about a non-integral condition type.
5923       break;
5924     }
5925   } else {
5926     switch (ViableConversions.size()) {
5927     case 0: {
5928       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5929                                      HadMultipleCandidates,
5930                                      ExplicitConversions))
5931         return ExprError();
5932 
5933       // We'll complain below about a non-integral condition type.
5934       break;
5935     }
5936     case 1: {
5937       // Apply this conversion.
5938       DeclAccessPair Found = ViableConversions[0];
5939       if (recordConversion(*this, Loc, From, Converter, T,
5940                            HadMultipleCandidates, Found))
5941         return ExprError();
5942       break;
5943     }
5944     default:
5945       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5946                                          ViableConversions);
5947     }
5948   }
5949 
5950   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5951 }
5952 
5953 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5954 /// an acceptable non-member overloaded operator for a call whose
5955 /// arguments have types T1 (and, if non-empty, T2). This routine
5956 /// implements the check in C++ [over.match.oper]p3b2 concerning
5957 /// enumeration types.
5958 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5959                                                    FunctionDecl *Fn,
5960                                                    ArrayRef<Expr *> Args) {
5961   QualType T1 = Args[0]->getType();
5962   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5963 
5964   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5965     return true;
5966 
5967   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5968     return true;
5969 
5970   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5971   if (Proto->getNumParams() < 1)
5972     return false;
5973 
5974   if (T1->isEnumeralType()) {
5975     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5976     if (Context.hasSameUnqualifiedType(T1, ArgType))
5977       return true;
5978   }
5979 
5980   if (Proto->getNumParams() < 2)
5981     return false;
5982 
5983   if (!T2.isNull() && T2->isEnumeralType()) {
5984     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5985     if (Context.hasSameUnqualifiedType(T2, ArgType))
5986       return true;
5987   }
5988 
5989   return false;
5990 }
5991 
5992 /// AddOverloadCandidate - Adds the given function to the set of
5993 /// candidate functions, using the given function call arguments.  If
5994 /// @p SuppressUserConversions, then don't allow user-defined
5995 /// conversions via constructors or conversion operators.
5996 ///
5997 /// \param PartialOverloading true if we are performing "partial" overloading
5998 /// based on an incomplete set of function arguments. This feature is used by
5999 /// code completion.
6000 void Sema::AddOverloadCandidate(FunctionDecl *Function,
6001                                 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6002                                 OverloadCandidateSet &CandidateSet,
6003                                 bool SuppressUserConversions,
6004                                 bool PartialOverloading, bool AllowExplicit,
6005                                 ADLCallKind IsADLCandidate,
6006                                 ConversionSequenceList EarlyConversions) {
6007   const FunctionProtoType *Proto
6008     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6009   assert(Proto && "Functions without a prototype cannot be overloaded");
6010   assert(!Function->getDescribedFunctionTemplate() &&
6011          "Use AddTemplateOverloadCandidate for function templates");
6012 
6013   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6014     if (!isa<CXXConstructorDecl>(Method)) {
6015       // If we get here, it's because we're calling a member function
6016       // that is named without a member access expression (e.g.,
6017       // "this->f") that was either written explicitly or created
6018       // implicitly. This can happen with a qualified call to a member
6019       // function, e.g., X::f(). We use an empty type for the implied
6020       // object argument (C++ [over.call.func]p3), and the acting context
6021       // is irrelevant.
6022       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6023                          Expr::Classification::makeSimpleLValue(), Args,
6024                          CandidateSet, SuppressUserConversions,
6025                          PartialOverloading, EarlyConversions);
6026       return;
6027     }
6028     // We treat a constructor like a non-member function, since its object
6029     // argument doesn't participate in overload resolution.
6030   }
6031 
6032   if (!CandidateSet.isNewCandidate(Function))
6033     return;
6034 
6035   // C++ [over.match.oper]p3:
6036   //   if no operand has a class type, only those non-member functions in the
6037   //   lookup set that have a first parameter of type T1 or "reference to
6038   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6039   //   is a right operand) a second parameter of type T2 or "reference to
6040   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6041   //   candidate functions.
6042   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6043       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6044     return;
6045 
6046   // C++11 [class.copy]p11: [DR1402]
6047   //   A defaulted move constructor that is defined as deleted is ignored by
6048   //   overload resolution.
6049   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6050   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6051       Constructor->isMoveConstructor())
6052     return;
6053 
6054   // Overload resolution is always an unevaluated context.
6055   EnterExpressionEvaluationContext Unevaluated(
6056       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6057 
6058   // Add this candidate
6059   OverloadCandidate &Candidate =
6060       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6061   Candidate.FoundDecl = FoundDecl;
6062   Candidate.Function = Function;
6063   Candidate.Viable = true;
6064   Candidate.IsSurrogate = false;
6065   Candidate.IsADLCandidate = IsADLCandidate;
6066   Candidate.IgnoreObjectArgument = false;
6067   Candidate.ExplicitCallArguments = Args.size();
6068 
6069   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6070       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6071     Candidate.Viable = false;
6072     Candidate.FailureKind = ovl_non_default_multiversion_function;
6073     return;
6074   }
6075 
6076   if (Constructor) {
6077     // C++ [class.copy]p3:
6078     //   A member function template is never instantiated to perform the copy
6079     //   of a class object to an object of its class type.
6080     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6081     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6082         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6083          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6084                        ClassType))) {
6085       Candidate.Viable = false;
6086       Candidate.FailureKind = ovl_fail_illegal_constructor;
6087       return;
6088     }
6089 
6090     // C++ [over.match.funcs]p8: (proposed DR resolution)
6091     //   A constructor inherited from class type C that has a first parameter
6092     //   of type "reference to P" (including such a constructor instantiated
6093     //   from a template) is excluded from the set of candidate functions when
6094     //   constructing an object of type cv D if the argument list has exactly
6095     //   one argument and D is reference-related to P and P is reference-related
6096     //   to C.
6097     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6098     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6099         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6100       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6101       QualType C = Context.getRecordType(Constructor->getParent());
6102       QualType D = Context.getRecordType(Shadow->getParent());
6103       SourceLocation Loc = Args.front()->getExprLoc();
6104       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6105           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6106         Candidate.Viable = false;
6107         Candidate.FailureKind = ovl_fail_inhctor_slice;
6108         return;
6109       }
6110     }
6111   }
6112 
6113   unsigned NumParams = Proto->getNumParams();
6114 
6115   // (C++ 13.3.2p2): A candidate function having fewer than m
6116   // parameters is viable only if it has an ellipsis in its parameter
6117   // list (8.3.5).
6118   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6119       !Proto->isVariadic()) {
6120     Candidate.Viable = false;
6121     Candidate.FailureKind = ovl_fail_too_many_arguments;
6122     return;
6123   }
6124 
6125   // (C++ 13.3.2p2): A candidate function having more than m parameters
6126   // is viable only if the (m+1)st parameter has a default argument
6127   // (8.3.6). For the purposes of overload resolution, the
6128   // parameter list is truncated on the right, so that there are
6129   // exactly m parameters.
6130   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6131   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6132     // Not enough arguments.
6133     Candidate.Viable = false;
6134     Candidate.FailureKind = ovl_fail_too_few_arguments;
6135     return;
6136   }
6137 
6138   // (CUDA B.1): Check for invalid calls between targets.
6139   if (getLangOpts().CUDA)
6140     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6141       // Skip the check for callers that are implicit members, because in this
6142       // case we may not yet know what the member's target is; the target is
6143       // inferred for the member automatically, based on the bases and fields of
6144       // the class.
6145       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6146         Candidate.Viable = false;
6147         Candidate.FailureKind = ovl_fail_bad_target;
6148         return;
6149       }
6150 
6151   // Determine the implicit conversion sequences for each of the
6152   // arguments.
6153   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6154     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6155       // We already formed a conversion sequence for this parameter during
6156       // template argument deduction.
6157     } else if (ArgIdx < NumParams) {
6158       // (C++ 13.3.2p3): for F to be a viable function, there shall
6159       // exist for each argument an implicit conversion sequence
6160       // (13.3.3.1) that converts that argument to the corresponding
6161       // parameter of F.
6162       QualType ParamType = Proto->getParamType(ArgIdx);
6163       Candidate.Conversions[ArgIdx]
6164         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6165                                 SuppressUserConversions,
6166                                 /*InOverloadResolution=*/true,
6167                                 /*AllowObjCWritebackConversion=*/
6168                                   getLangOpts().ObjCAutoRefCount,
6169                                 AllowExplicit);
6170       if (Candidate.Conversions[ArgIdx].isBad()) {
6171         Candidate.Viable = false;
6172         Candidate.FailureKind = ovl_fail_bad_conversion;
6173         return;
6174       }
6175     } else {
6176       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6177       // argument for which there is no corresponding parameter is
6178       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6179       Candidate.Conversions[ArgIdx].setEllipsis();
6180     }
6181   }
6182 
6183   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6184     Candidate.Viable = false;
6185     Candidate.FailureKind = ovl_fail_enable_if;
6186     Candidate.DeductionFailure.Data = FailedAttr;
6187     return;
6188   }
6189 
6190   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6191     Candidate.Viable = false;
6192     Candidate.FailureKind = ovl_fail_ext_disabled;
6193     return;
6194   }
6195 }
6196 
6197 ObjCMethodDecl *
6198 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6199                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6200   if (Methods.size() <= 1)
6201     return nullptr;
6202 
6203   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6204     bool Match = true;
6205     ObjCMethodDecl *Method = Methods[b];
6206     unsigned NumNamedArgs = Sel.getNumArgs();
6207     // Method might have more arguments than selector indicates. This is due
6208     // to addition of c-style arguments in method.
6209     if (Method->param_size() > NumNamedArgs)
6210       NumNamedArgs = Method->param_size();
6211     if (Args.size() < NumNamedArgs)
6212       continue;
6213 
6214     for (unsigned i = 0; i < NumNamedArgs; i++) {
6215       // We can't do any type-checking on a type-dependent argument.
6216       if (Args[i]->isTypeDependent()) {
6217         Match = false;
6218         break;
6219       }
6220 
6221       ParmVarDecl *param = Method->parameters()[i];
6222       Expr *argExpr = Args[i];
6223       assert(argExpr && "SelectBestMethod(): missing expression");
6224 
6225       // Strip the unbridged-cast placeholder expression off unless it's
6226       // a consumed argument.
6227       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6228           !param->hasAttr<CFConsumedAttr>())
6229         argExpr = stripARCUnbridgedCast(argExpr);
6230 
6231       // If the parameter is __unknown_anytype, move on to the next method.
6232       if (param->getType() == Context.UnknownAnyTy) {
6233         Match = false;
6234         break;
6235       }
6236 
6237       ImplicitConversionSequence ConversionState
6238         = TryCopyInitialization(*this, argExpr, param->getType(),
6239                                 /*SuppressUserConversions*/false,
6240                                 /*InOverloadResolution=*/true,
6241                                 /*AllowObjCWritebackConversion=*/
6242                                 getLangOpts().ObjCAutoRefCount,
6243                                 /*AllowExplicit*/false);
6244       // This function looks for a reasonably-exact match, so we consider
6245       // incompatible pointer conversions to be a failure here.
6246       if (ConversionState.isBad() ||
6247           (ConversionState.isStandard() &&
6248            ConversionState.Standard.Second ==
6249                ICK_Incompatible_Pointer_Conversion)) {
6250         Match = false;
6251         break;
6252       }
6253     }
6254     // Promote additional arguments to variadic methods.
6255     if (Match && Method->isVariadic()) {
6256       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6257         if (Args[i]->isTypeDependent()) {
6258           Match = false;
6259           break;
6260         }
6261         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6262                                                           nullptr);
6263         if (Arg.isInvalid()) {
6264           Match = false;
6265           break;
6266         }
6267       }
6268     } else {
6269       // Check for extra arguments to non-variadic methods.
6270       if (Args.size() != NumNamedArgs)
6271         Match = false;
6272       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6273         // Special case when selectors have no argument. In this case, select
6274         // one with the most general result type of 'id'.
6275         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6276           QualType ReturnT = Methods[b]->getReturnType();
6277           if (ReturnT->isObjCIdType())
6278             return Methods[b];
6279         }
6280       }
6281     }
6282 
6283     if (Match)
6284       return Method;
6285   }
6286   return nullptr;
6287 }
6288 
6289 static bool
6290 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6291                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6292                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6293                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6294   if (ThisArg) {
6295     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6296     assert(!isa<CXXConstructorDecl>(Method) &&
6297            "Shouldn't have `this` for ctors!");
6298     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6299     ExprResult R = S.PerformObjectArgumentInitialization(
6300         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6301     if (R.isInvalid())
6302       return false;
6303     ConvertedThis = R.get();
6304   } else {
6305     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6306       (void)MD;
6307       assert((MissingImplicitThis || MD->isStatic() ||
6308               isa<CXXConstructorDecl>(MD)) &&
6309              "Expected `this` for non-ctor instance methods");
6310     }
6311     ConvertedThis = nullptr;
6312   }
6313 
6314   // Ignore any variadic arguments. Converting them is pointless, since the
6315   // user can't refer to them in the function condition.
6316   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6317 
6318   // Convert the arguments.
6319   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6320     ExprResult R;
6321     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6322                                         S.Context, Function->getParamDecl(I)),
6323                                     SourceLocation(), Args[I]);
6324 
6325     if (R.isInvalid())
6326       return false;
6327 
6328     ConvertedArgs.push_back(R.get());
6329   }
6330 
6331   if (Trap.hasErrorOccurred())
6332     return false;
6333 
6334   // Push default arguments if needed.
6335   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6336     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6337       ParmVarDecl *P = Function->getParamDecl(i);
6338       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6339                          ? P->getUninstantiatedDefaultArg()
6340                          : P->getDefaultArg();
6341       // This can only happen in code completion, i.e. when PartialOverloading
6342       // is true.
6343       if (!DefArg)
6344         return false;
6345       ExprResult R =
6346           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6347                                           S.Context, Function->getParamDecl(i)),
6348                                       SourceLocation(), DefArg);
6349       if (R.isInvalid())
6350         return false;
6351       ConvertedArgs.push_back(R.get());
6352     }
6353 
6354     if (Trap.hasErrorOccurred())
6355       return false;
6356   }
6357   return true;
6358 }
6359 
6360 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6361                                   bool MissingImplicitThis) {
6362   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6363   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6364     return nullptr;
6365 
6366   SFINAETrap Trap(*this);
6367   SmallVector<Expr *, 16> ConvertedArgs;
6368   // FIXME: We should look into making enable_if late-parsed.
6369   Expr *DiscardedThis;
6370   if (!convertArgsForAvailabilityChecks(
6371           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6372           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6373     return *EnableIfAttrs.begin();
6374 
6375   for (auto *EIA : EnableIfAttrs) {
6376     APValue Result;
6377     // FIXME: This doesn't consider value-dependent cases, because doing so is
6378     // very difficult. Ideally, we should handle them more gracefully.
6379     if (!EIA->getCond()->EvaluateWithSubstitution(
6380             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6381       return EIA;
6382 
6383     if (!Result.isInt() || !Result.getInt().getBoolValue())
6384       return EIA;
6385   }
6386   return nullptr;
6387 }
6388 
6389 template <typename CheckFn>
6390 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6391                                         bool ArgDependent, SourceLocation Loc,
6392                                         CheckFn &&IsSuccessful) {
6393   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6394   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6395     if (ArgDependent == DIA->getArgDependent())
6396       Attrs.push_back(DIA);
6397   }
6398 
6399   // Common case: No diagnose_if attributes, so we can quit early.
6400   if (Attrs.empty())
6401     return false;
6402 
6403   auto WarningBegin = std::stable_partition(
6404       Attrs.begin(), Attrs.end(),
6405       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6406 
6407   // Note that diagnose_if attributes are late-parsed, so they appear in the
6408   // correct order (unlike enable_if attributes).
6409   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6410                                IsSuccessful);
6411   if (ErrAttr != WarningBegin) {
6412     const DiagnoseIfAttr *DIA = *ErrAttr;
6413     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6414     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6415         << DIA->getParent() << DIA->getCond()->getSourceRange();
6416     return true;
6417   }
6418 
6419   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6420     if (IsSuccessful(DIA)) {
6421       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6422       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6423           << DIA->getParent() << DIA->getCond()->getSourceRange();
6424     }
6425 
6426   return false;
6427 }
6428 
6429 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6430                                                const Expr *ThisArg,
6431                                                ArrayRef<const Expr *> Args,
6432                                                SourceLocation Loc) {
6433   return diagnoseDiagnoseIfAttrsWith(
6434       *this, Function, /*ArgDependent=*/true, Loc,
6435       [&](const DiagnoseIfAttr *DIA) {
6436         APValue Result;
6437         // It's sane to use the same Args for any redecl of this function, since
6438         // EvaluateWithSubstitution only cares about the position of each
6439         // argument in the arg list, not the ParmVarDecl* it maps to.
6440         if (!DIA->getCond()->EvaluateWithSubstitution(
6441                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6442           return false;
6443         return Result.isInt() && Result.getInt().getBoolValue();
6444       });
6445 }
6446 
6447 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6448                                                  SourceLocation Loc) {
6449   return diagnoseDiagnoseIfAttrsWith(
6450       *this, ND, /*ArgDependent=*/false, Loc,
6451       [&](const DiagnoseIfAttr *DIA) {
6452         bool Result;
6453         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6454                Result;
6455       });
6456 }
6457 
6458 /// Add all of the function declarations in the given function set to
6459 /// the overload candidate set.
6460 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6461                                  ArrayRef<Expr *> Args,
6462                                  OverloadCandidateSet &CandidateSet,
6463                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6464                                  bool SuppressUserConversions,
6465                                  bool PartialOverloading,
6466                                  bool FirstArgumentIsBase) {
6467   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6468     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6469     ArrayRef<Expr *> FunctionArgs = Args;
6470 
6471     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6472     FunctionDecl *FD =
6473         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6474 
6475     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6476       QualType ObjectType;
6477       Expr::Classification ObjectClassification;
6478       if (Args.size() > 0) {
6479         if (Expr *E = Args[0]) {
6480           // Use the explicit base to restrict the lookup:
6481           ObjectType = E->getType();
6482           // Pointers in the object arguments are implicitly dereferenced, so we
6483           // always classify them as l-values.
6484           if (!ObjectType.isNull() && ObjectType->isPointerType())
6485             ObjectClassification = Expr::Classification::makeSimpleLValue();
6486           else
6487             ObjectClassification = E->Classify(Context);
6488         } // .. else there is an implicit base.
6489         FunctionArgs = Args.slice(1);
6490       }
6491       if (FunTmpl) {
6492         AddMethodTemplateCandidate(
6493             FunTmpl, F.getPair(),
6494             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6495             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6496             FunctionArgs, CandidateSet, SuppressUserConversions,
6497             PartialOverloading);
6498       } else {
6499         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6500                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6501                            ObjectClassification, FunctionArgs, CandidateSet,
6502                            SuppressUserConversions, PartialOverloading);
6503       }
6504     } else {
6505       // This branch handles both standalone functions and static methods.
6506 
6507       // Slice the first argument (which is the base) when we access
6508       // static method as non-static.
6509       if (Args.size() > 0 &&
6510           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6511                         !isa<CXXConstructorDecl>(FD)))) {
6512         assert(cast<CXXMethodDecl>(FD)->isStatic());
6513         FunctionArgs = Args.slice(1);
6514       }
6515       if (FunTmpl) {
6516         AddTemplateOverloadCandidate(
6517             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6518             CandidateSet, SuppressUserConversions, PartialOverloading);
6519       } else {
6520         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6521                              SuppressUserConversions, PartialOverloading);
6522       }
6523     }
6524   }
6525 }
6526 
6527 /// AddMethodCandidate - Adds a named decl (which is some kind of
6528 /// method) as a method candidate to the given overload set.
6529 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6530                               QualType ObjectType,
6531                               Expr::Classification ObjectClassification,
6532                               ArrayRef<Expr *> Args,
6533                               OverloadCandidateSet& CandidateSet,
6534                               bool SuppressUserConversions) {
6535   NamedDecl *Decl = FoundDecl.getDecl();
6536   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6537 
6538   if (isa<UsingShadowDecl>(Decl))
6539     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6540 
6541   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6542     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6543            "Expected a member function template");
6544     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6545                                /*ExplicitArgs*/ nullptr, ObjectType,
6546                                ObjectClassification, Args, CandidateSet,
6547                                SuppressUserConversions);
6548   } else {
6549     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6550                        ObjectType, ObjectClassification, Args, CandidateSet,
6551                        SuppressUserConversions);
6552   }
6553 }
6554 
6555 /// AddMethodCandidate - Adds the given C++ member function to the set
6556 /// of candidate functions, using the given function call arguments
6557 /// and the object argument (@c Object). For example, in a call
6558 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6559 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6560 /// allow user-defined conversions via constructors or conversion
6561 /// operators.
6562 void
6563 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6564                          CXXRecordDecl *ActingContext, QualType ObjectType,
6565                          Expr::Classification ObjectClassification,
6566                          ArrayRef<Expr *> Args,
6567                          OverloadCandidateSet &CandidateSet,
6568                          bool SuppressUserConversions,
6569                          bool PartialOverloading,
6570                          ConversionSequenceList EarlyConversions) {
6571   const FunctionProtoType *Proto
6572     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6573   assert(Proto && "Methods without a prototype cannot be overloaded");
6574   assert(!isa<CXXConstructorDecl>(Method) &&
6575          "Use AddOverloadCandidate for constructors");
6576 
6577   if (!CandidateSet.isNewCandidate(Method))
6578     return;
6579 
6580   // C++11 [class.copy]p23: [DR1402]
6581   //   A defaulted move assignment operator that is defined as deleted is
6582   //   ignored by overload resolution.
6583   if (Method->isDefaulted() && Method->isDeleted() &&
6584       Method->isMoveAssignmentOperator())
6585     return;
6586 
6587   // Overload resolution is always an unevaluated context.
6588   EnterExpressionEvaluationContext Unevaluated(
6589       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6590 
6591   // Add this candidate
6592   OverloadCandidate &Candidate =
6593       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6594   Candidate.FoundDecl = FoundDecl;
6595   Candidate.Function = Method;
6596   Candidate.IsSurrogate = false;
6597   Candidate.IgnoreObjectArgument = false;
6598   Candidate.ExplicitCallArguments = Args.size();
6599 
6600   unsigned NumParams = Proto->getNumParams();
6601 
6602   // (C++ 13.3.2p2): A candidate function having fewer than m
6603   // parameters is viable only if it has an ellipsis in its parameter
6604   // list (8.3.5).
6605   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6606       !Proto->isVariadic()) {
6607     Candidate.Viable = false;
6608     Candidate.FailureKind = ovl_fail_too_many_arguments;
6609     return;
6610   }
6611 
6612   // (C++ 13.3.2p2): A candidate function having more than m parameters
6613   // is viable only if the (m+1)st parameter has a default argument
6614   // (8.3.6). For the purposes of overload resolution, the
6615   // parameter list is truncated on the right, so that there are
6616   // exactly m parameters.
6617   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6618   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6619     // Not enough arguments.
6620     Candidate.Viable = false;
6621     Candidate.FailureKind = ovl_fail_too_few_arguments;
6622     return;
6623   }
6624 
6625   Candidate.Viable = true;
6626 
6627   if (Method->isStatic() || ObjectType.isNull())
6628     // The implicit object argument is ignored.
6629     Candidate.IgnoreObjectArgument = true;
6630   else {
6631     // Determine the implicit conversion sequence for the object
6632     // parameter.
6633     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6634         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6635         Method, ActingContext);
6636     if (Candidate.Conversions[0].isBad()) {
6637       Candidate.Viable = false;
6638       Candidate.FailureKind = ovl_fail_bad_conversion;
6639       return;
6640     }
6641   }
6642 
6643   // (CUDA B.1): Check for invalid calls between targets.
6644   if (getLangOpts().CUDA)
6645     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6646       if (!IsAllowedCUDACall(Caller, Method)) {
6647         Candidate.Viable = false;
6648         Candidate.FailureKind = ovl_fail_bad_target;
6649         return;
6650       }
6651 
6652   // Determine the implicit conversion sequences for each of the
6653   // arguments.
6654   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6655     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6656       // We already formed a conversion sequence for this parameter during
6657       // template argument deduction.
6658     } else if (ArgIdx < NumParams) {
6659       // (C++ 13.3.2p3): for F to be a viable function, there shall
6660       // exist for each argument an implicit conversion sequence
6661       // (13.3.3.1) that converts that argument to the corresponding
6662       // parameter of F.
6663       QualType ParamType = Proto->getParamType(ArgIdx);
6664       Candidate.Conversions[ArgIdx + 1]
6665         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6666                                 SuppressUserConversions,
6667                                 /*InOverloadResolution=*/true,
6668                                 /*AllowObjCWritebackConversion=*/
6669                                   getLangOpts().ObjCAutoRefCount);
6670       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6671         Candidate.Viable = false;
6672         Candidate.FailureKind = ovl_fail_bad_conversion;
6673         return;
6674       }
6675     } else {
6676       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6677       // argument for which there is no corresponding parameter is
6678       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6679       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6680     }
6681   }
6682 
6683   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6684     Candidate.Viable = false;
6685     Candidate.FailureKind = ovl_fail_enable_if;
6686     Candidate.DeductionFailure.Data = FailedAttr;
6687     return;
6688   }
6689 
6690   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6691       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6692     Candidate.Viable = false;
6693     Candidate.FailureKind = ovl_non_default_multiversion_function;
6694   }
6695 }
6696 
6697 /// Add a C++ member function template as a candidate to the candidate
6698 /// set, using template argument deduction to produce an appropriate member
6699 /// function template specialization.
6700 void
6701 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6702                                  DeclAccessPair FoundDecl,
6703                                  CXXRecordDecl *ActingContext,
6704                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6705                                  QualType ObjectType,
6706                                  Expr::Classification ObjectClassification,
6707                                  ArrayRef<Expr *> Args,
6708                                  OverloadCandidateSet& CandidateSet,
6709                                  bool SuppressUserConversions,
6710                                  bool PartialOverloading) {
6711   if (!CandidateSet.isNewCandidate(MethodTmpl))
6712     return;
6713 
6714   // C++ [over.match.funcs]p7:
6715   //   In each case where a candidate is a function template, candidate
6716   //   function template specializations are generated using template argument
6717   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6718   //   candidate functions in the usual way.113) A given name can refer to one
6719   //   or more function templates and also to a set of overloaded non-template
6720   //   functions. In such a case, the candidate functions generated from each
6721   //   function template are combined with the set of non-template candidate
6722   //   functions.
6723   TemplateDeductionInfo Info(CandidateSet.getLocation());
6724   FunctionDecl *Specialization = nullptr;
6725   ConversionSequenceList Conversions;
6726   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6727           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6728           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6729             return CheckNonDependentConversions(
6730                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6731                 SuppressUserConversions, ActingContext, ObjectType,
6732                 ObjectClassification);
6733           })) {
6734     OverloadCandidate &Candidate =
6735         CandidateSet.addCandidate(Conversions.size(), Conversions);
6736     Candidate.FoundDecl = FoundDecl;
6737     Candidate.Function = MethodTmpl->getTemplatedDecl();
6738     Candidate.Viable = false;
6739     Candidate.IsSurrogate = false;
6740     Candidate.IgnoreObjectArgument =
6741         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6742         ObjectType.isNull();
6743     Candidate.ExplicitCallArguments = Args.size();
6744     if (Result == TDK_NonDependentConversionFailure)
6745       Candidate.FailureKind = ovl_fail_bad_conversion;
6746     else {
6747       Candidate.FailureKind = ovl_fail_bad_deduction;
6748       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6749                                                             Info);
6750     }
6751     return;
6752   }
6753 
6754   // Add the function template specialization produced by template argument
6755   // deduction as a candidate.
6756   assert(Specialization && "Missing member function template specialization?");
6757   assert(isa<CXXMethodDecl>(Specialization) &&
6758          "Specialization is not a member function?");
6759   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6760                      ActingContext, ObjectType, ObjectClassification, Args,
6761                      CandidateSet, SuppressUserConversions, PartialOverloading,
6762                      Conversions);
6763 }
6764 
6765 /// Add a C++ function template specialization as a candidate
6766 /// in the candidate set, using template argument deduction to produce
6767 /// an appropriate function template specialization.
6768 void Sema::AddTemplateOverloadCandidate(
6769     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6770     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6771     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6772     bool PartialOverloading, ADLCallKind IsADLCandidate) {
6773   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6774     return;
6775 
6776   // C++ [over.match.funcs]p7:
6777   //   In each case where a candidate is a function template, candidate
6778   //   function template specializations are generated using template argument
6779   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6780   //   candidate functions in the usual way.113) A given name can refer to one
6781   //   or more function templates and also to a set of overloaded non-template
6782   //   functions. In such a case, the candidate functions generated from each
6783   //   function template are combined with the set of non-template candidate
6784   //   functions.
6785   TemplateDeductionInfo Info(CandidateSet.getLocation());
6786   FunctionDecl *Specialization = nullptr;
6787   ConversionSequenceList Conversions;
6788   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6789           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6790           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6791             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6792                                                 Args, CandidateSet, Conversions,
6793                                                 SuppressUserConversions);
6794           })) {
6795     OverloadCandidate &Candidate =
6796         CandidateSet.addCandidate(Conversions.size(), Conversions);
6797     Candidate.FoundDecl = FoundDecl;
6798     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6799     Candidate.Viable = false;
6800     Candidate.IsSurrogate = false;
6801     Candidate.IsADLCandidate = IsADLCandidate;
6802     // Ignore the object argument if there is one, since we don't have an object
6803     // type.
6804     Candidate.IgnoreObjectArgument =
6805         isa<CXXMethodDecl>(Candidate.Function) &&
6806         !isa<CXXConstructorDecl>(Candidate.Function);
6807     Candidate.ExplicitCallArguments = Args.size();
6808     if (Result == TDK_NonDependentConversionFailure)
6809       Candidate.FailureKind = ovl_fail_bad_conversion;
6810     else {
6811       Candidate.FailureKind = ovl_fail_bad_deduction;
6812       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6813                                                             Info);
6814     }
6815     return;
6816   }
6817 
6818   // Add the function template specialization produced by template argument
6819   // deduction as a candidate.
6820   assert(Specialization && "Missing function template specialization?");
6821   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6822                        SuppressUserConversions, PartialOverloading,
6823                        /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6824 }
6825 
6826 /// Check that implicit conversion sequences can be formed for each argument
6827 /// whose corresponding parameter has a non-dependent type, per DR1391's
6828 /// [temp.deduct.call]p10.
6829 bool Sema::CheckNonDependentConversions(
6830     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6831     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6832     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6833     CXXRecordDecl *ActingContext, QualType ObjectType,
6834     Expr::Classification ObjectClassification) {
6835   // FIXME: The cases in which we allow explicit conversions for constructor
6836   // arguments never consider calling a constructor template. It's not clear
6837   // that is correct.
6838   const bool AllowExplicit = false;
6839 
6840   auto *FD = FunctionTemplate->getTemplatedDecl();
6841   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6842   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6843   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6844 
6845   Conversions =
6846       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6847 
6848   // Overload resolution is always an unevaluated context.
6849   EnterExpressionEvaluationContext Unevaluated(
6850       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6851 
6852   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6853   // require that, but this check should never result in a hard error, and
6854   // overload resolution is permitted to sidestep instantiations.
6855   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6856       !ObjectType.isNull()) {
6857     Conversions[0] = TryObjectArgumentInitialization(
6858         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6859         Method, ActingContext);
6860     if (Conversions[0].isBad())
6861       return true;
6862   }
6863 
6864   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6865        ++I) {
6866     QualType ParamType = ParamTypes[I];
6867     if (!ParamType->isDependentType()) {
6868       Conversions[ThisConversions + I]
6869         = TryCopyInitialization(*this, Args[I], ParamType,
6870                                 SuppressUserConversions,
6871                                 /*InOverloadResolution=*/true,
6872                                 /*AllowObjCWritebackConversion=*/
6873                                   getLangOpts().ObjCAutoRefCount,
6874                                 AllowExplicit);
6875       if (Conversions[ThisConversions + I].isBad())
6876         return true;
6877     }
6878   }
6879 
6880   return false;
6881 }
6882 
6883 /// Determine whether this is an allowable conversion from the result
6884 /// of an explicit conversion operator to the expected type, per C++
6885 /// [over.match.conv]p1 and [over.match.ref]p1.
6886 ///
6887 /// \param ConvType The return type of the conversion function.
6888 ///
6889 /// \param ToType The type we are converting to.
6890 ///
6891 /// \param AllowObjCPointerConversion Allow a conversion from one
6892 /// Objective-C pointer to another.
6893 ///
6894 /// \returns true if the conversion is allowable, false otherwise.
6895 static bool isAllowableExplicitConversion(Sema &S,
6896                                           QualType ConvType, QualType ToType,
6897                                           bool AllowObjCPointerConversion) {
6898   QualType ToNonRefType = ToType.getNonReferenceType();
6899 
6900   // Easy case: the types are the same.
6901   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6902     return true;
6903 
6904   // Allow qualification conversions.
6905   bool ObjCLifetimeConversion;
6906   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6907                                   ObjCLifetimeConversion))
6908     return true;
6909 
6910   // If we're not allowed to consider Objective-C pointer conversions,
6911   // we're done.
6912   if (!AllowObjCPointerConversion)
6913     return false;
6914 
6915   // Is this an Objective-C pointer conversion?
6916   bool IncompatibleObjC = false;
6917   QualType ConvertedType;
6918   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6919                                    IncompatibleObjC);
6920 }
6921 
6922 /// AddConversionCandidate - Add a C++ conversion function as a
6923 /// candidate in the candidate set (C++ [over.match.conv],
6924 /// C++ [over.match.copy]). From is the expression we're converting from,
6925 /// and ToType is the type that we're eventually trying to convert to
6926 /// (which may or may not be the same type as the type that the
6927 /// conversion function produces).
6928 void
6929 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6930                              DeclAccessPair FoundDecl,
6931                              CXXRecordDecl *ActingContext,
6932                              Expr *From, QualType ToType,
6933                              OverloadCandidateSet& CandidateSet,
6934                              bool AllowObjCConversionOnExplicit,
6935                              bool AllowResultConversion) {
6936   assert(!Conversion->getDescribedFunctionTemplate() &&
6937          "Conversion function templates use AddTemplateConversionCandidate");
6938   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6939   if (!CandidateSet.isNewCandidate(Conversion))
6940     return;
6941 
6942   // If the conversion function has an undeduced return type, trigger its
6943   // deduction now.
6944   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6945     if (DeduceReturnType(Conversion, From->getExprLoc()))
6946       return;
6947     ConvType = Conversion->getConversionType().getNonReferenceType();
6948   }
6949 
6950   // If we don't allow any conversion of the result type, ignore conversion
6951   // functions that don't convert to exactly (possibly cv-qualified) T.
6952   if (!AllowResultConversion &&
6953       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6954     return;
6955 
6956   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6957   // operator is only a candidate if its return type is the target type or
6958   // can be converted to the target type with a qualification conversion.
6959   if (Conversion->isExplicit() &&
6960       !isAllowableExplicitConversion(*this, ConvType, ToType,
6961                                      AllowObjCConversionOnExplicit))
6962     return;
6963 
6964   // Overload resolution is always an unevaluated context.
6965   EnterExpressionEvaluationContext Unevaluated(
6966       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6967 
6968   // Add this candidate
6969   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6970   Candidate.FoundDecl = FoundDecl;
6971   Candidate.Function = Conversion;
6972   Candidate.IsSurrogate = false;
6973   Candidate.IgnoreObjectArgument = false;
6974   Candidate.FinalConversion.setAsIdentityConversion();
6975   Candidate.FinalConversion.setFromType(ConvType);
6976   Candidate.FinalConversion.setAllToTypes(ToType);
6977   Candidate.Viable = true;
6978   Candidate.ExplicitCallArguments = 1;
6979 
6980   // C++ [over.match.funcs]p4:
6981   //   For conversion functions, the function is considered to be a member of
6982   //   the class of the implicit implied object argument for the purpose of
6983   //   defining the type of the implicit object parameter.
6984   //
6985   // Determine the implicit conversion sequence for the implicit
6986   // object parameter.
6987   QualType ImplicitParamType = From->getType();
6988   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6989     ImplicitParamType = FromPtrType->getPointeeType();
6990   CXXRecordDecl *ConversionContext
6991     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6992 
6993   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6994       *this, CandidateSet.getLocation(), From->getType(),
6995       From->Classify(Context), Conversion, ConversionContext);
6996 
6997   if (Candidate.Conversions[0].isBad()) {
6998     Candidate.Viable = false;
6999     Candidate.FailureKind = ovl_fail_bad_conversion;
7000     return;
7001   }
7002 
7003   // We won't go through a user-defined type conversion function to convert a
7004   // derived to base as such conversions are given Conversion Rank. They only
7005   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7006   QualType FromCanon
7007     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7008   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7009   if (FromCanon == ToCanon ||
7010       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7011     Candidate.Viable = false;
7012     Candidate.FailureKind = ovl_fail_trivial_conversion;
7013     return;
7014   }
7015 
7016   // To determine what the conversion from the result of calling the
7017   // conversion function to the type we're eventually trying to
7018   // convert to (ToType), we need to synthesize a call to the
7019   // conversion function and attempt copy initialization from it. This
7020   // makes sure that we get the right semantics with respect to
7021   // lvalues/rvalues and the type. Fortunately, we can allocate this
7022   // call on the stack and we don't need its arguments to be
7023   // well-formed.
7024   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7025                             VK_LValue, From->getBeginLoc());
7026   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7027                                 Context.getPointerType(Conversion->getType()),
7028                                 CK_FunctionToPointerDecay,
7029                                 &ConversionRef, VK_RValue);
7030 
7031   QualType ConversionType = Conversion->getConversionType();
7032   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7033     Candidate.Viable = false;
7034     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7035     return;
7036   }
7037 
7038   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7039 
7040   // Note that it is safe to allocate CallExpr on the stack here because
7041   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7042   // allocator).
7043   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7044 
7045   llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7046       Buffer;
7047   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7048       Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7049 
7050   ImplicitConversionSequence ICS =
7051       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7052                             /*SuppressUserConversions=*/true,
7053                             /*InOverloadResolution=*/false,
7054                             /*AllowObjCWritebackConversion=*/false);
7055 
7056   switch (ICS.getKind()) {
7057   case ImplicitConversionSequence::StandardConversion:
7058     Candidate.FinalConversion = ICS.Standard;
7059 
7060     // C++ [over.ics.user]p3:
7061     //   If the user-defined conversion is specified by a specialization of a
7062     //   conversion function template, the second standard conversion sequence
7063     //   shall have exact match rank.
7064     if (Conversion->getPrimaryTemplate() &&
7065         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7066       Candidate.Viable = false;
7067       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7068       return;
7069     }
7070 
7071     // C++0x [dcl.init.ref]p5:
7072     //    In the second case, if the reference is an rvalue reference and
7073     //    the second standard conversion sequence of the user-defined
7074     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7075     //    program is ill-formed.
7076     if (ToType->isRValueReferenceType() &&
7077         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7078       Candidate.Viable = false;
7079       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7080       return;
7081     }
7082     break;
7083 
7084   case ImplicitConversionSequence::BadConversion:
7085     Candidate.Viable = false;
7086     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7087     return;
7088 
7089   default:
7090     llvm_unreachable(
7091            "Can only end up with a standard conversion sequence or failure");
7092   }
7093 
7094   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7095     Candidate.Viable = false;
7096     Candidate.FailureKind = ovl_fail_enable_if;
7097     Candidate.DeductionFailure.Data = FailedAttr;
7098     return;
7099   }
7100 
7101   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7102       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7103     Candidate.Viable = false;
7104     Candidate.FailureKind = ovl_non_default_multiversion_function;
7105   }
7106 }
7107 
7108 /// Adds a conversion function template specialization
7109 /// candidate to the overload set, using template argument deduction
7110 /// to deduce the template arguments of the conversion function
7111 /// template from the type that we are converting to (C++
7112 /// [temp.deduct.conv]).
7113 void
7114 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7115                                      DeclAccessPair FoundDecl,
7116                                      CXXRecordDecl *ActingDC,
7117                                      Expr *From, QualType ToType,
7118                                      OverloadCandidateSet &CandidateSet,
7119                                      bool AllowObjCConversionOnExplicit,
7120                                      bool AllowResultConversion) {
7121   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7122          "Only conversion function templates permitted here");
7123 
7124   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7125     return;
7126 
7127   TemplateDeductionInfo Info(CandidateSet.getLocation());
7128   CXXConversionDecl *Specialization = nullptr;
7129   if (TemplateDeductionResult Result
7130         = DeduceTemplateArguments(FunctionTemplate, ToType,
7131                                   Specialization, Info)) {
7132     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7133     Candidate.FoundDecl = FoundDecl;
7134     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7135     Candidate.Viable = false;
7136     Candidate.FailureKind = ovl_fail_bad_deduction;
7137     Candidate.IsSurrogate = false;
7138     Candidate.IgnoreObjectArgument = false;
7139     Candidate.ExplicitCallArguments = 1;
7140     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7141                                                           Info);
7142     return;
7143   }
7144 
7145   // Add the conversion function template specialization produced by
7146   // template argument deduction as a candidate.
7147   assert(Specialization && "Missing function template specialization?");
7148   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7149                          CandidateSet, AllowObjCConversionOnExplicit,
7150                          AllowResultConversion);
7151 }
7152 
7153 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7154 /// converts the given @c Object to a function pointer via the
7155 /// conversion function @c Conversion, and then attempts to call it
7156 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7157 /// the type of function that we'll eventually be calling.
7158 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7159                                  DeclAccessPair FoundDecl,
7160                                  CXXRecordDecl *ActingContext,
7161                                  const FunctionProtoType *Proto,
7162                                  Expr *Object,
7163                                  ArrayRef<Expr *> Args,
7164                                  OverloadCandidateSet& CandidateSet) {
7165   if (!CandidateSet.isNewCandidate(Conversion))
7166     return;
7167 
7168   // Overload resolution is always an unevaluated context.
7169   EnterExpressionEvaluationContext Unevaluated(
7170       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7171 
7172   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7173   Candidate.FoundDecl = FoundDecl;
7174   Candidate.Function = nullptr;
7175   Candidate.Surrogate = Conversion;
7176   Candidate.Viable = true;
7177   Candidate.IsSurrogate = true;
7178   Candidate.IgnoreObjectArgument = false;
7179   Candidate.ExplicitCallArguments = Args.size();
7180 
7181   // Determine the implicit conversion sequence for the implicit
7182   // object parameter.
7183   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7184       *this, CandidateSet.getLocation(), Object->getType(),
7185       Object->Classify(Context), Conversion, ActingContext);
7186   if (ObjectInit.isBad()) {
7187     Candidate.Viable = false;
7188     Candidate.FailureKind = ovl_fail_bad_conversion;
7189     Candidate.Conversions[0] = ObjectInit;
7190     return;
7191   }
7192 
7193   // The first conversion is actually a user-defined conversion whose
7194   // first conversion is ObjectInit's standard conversion (which is
7195   // effectively a reference binding). Record it as such.
7196   Candidate.Conversions[0].setUserDefined();
7197   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7198   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7199   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7200   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7201   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7202   Candidate.Conversions[0].UserDefined.After
7203     = Candidate.Conversions[0].UserDefined.Before;
7204   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7205 
7206   // Find the
7207   unsigned NumParams = Proto->getNumParams();
7208 
7209   // (C++ 13.3.2p2): A candidate function having fewer than m
7210   // parameters is viable only if it has an ellipsis in its parameter
7211   // list (8.3.5).
7212   if (Args.size() > NumParams && !Proto->isVariadic()) {
7213     Candidate.Viable = false;
7214     Candidate.FailureKind = ovl_fail_too_many_arguments;
7215     return;
7216   }
7217 
7218   // Function types don't have any default arguments, so just check if
7219   // we have enough arguments.
7220   if (Args.size() < NumParams) {
7221     // Not enough arguments.
7222     Candidate.Viable = false;
7223     Candidate.FailureKind = ovl_fail_too_few_arguments;
7224     return;
7225   }
7226 
7227   // Determine the implicit conversion sequences for each of the
7228   // arguments.
7229   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7230     if (ArgIdx < NumParams) {
7231       // (C++ 13.3.2p3): for F to be a viable function, there shall
7232       // exist for each argument an implicit conversion sequence
7233       // (13.3.3.1) that converts that argument to the corresponding
7234       // parameter of F.
7235       QualType ParamType = Proto->getParamType(ArgIdx);
7236       Candidate.Conversions[ArgIdx + 1]
7237         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7238                                 /*SuppressUserConversions=*/false,
7239                                 /*InOverloadResolution=*/false,
7240                                 /*AllowObjCWritebackConversion=*/
7241                                   getLangOpts().ObjCAutoRefCount);
7242       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7243         Candidate.Viable = false;
7244         Candidate.FailureKind = ovl_fail_bad_conversion;
7245         return;
7246       }
7247     } else {
7248       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7249       // argument for which there is no corresponding parameter is
7250       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7251       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7252     }
7253   }
7254 
7255   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7256     Candidate.Viable = false;
7257     Candidate.FailureKind = ovl_fail_enable_if;
7258     Candidate.DeductionFailure.Data = FailedAttr;
7259     return;
7260   }
7261 }
7262 
7263 /// Add overload candidates for overloaded operators that are
7264 /// member functions.
7265 ///
7266 /// Add the overloaded operator candidates that are member functions
7267 /// for the operator Op that was used in an operator expression such
7268 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7269 /// CandidateSet will store the added overload candidates. (C++
7270 /// [over.match.oper]).
7271 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7272                                        SourceLocation OpLoc,
7273                                        ArrayRef<Expr *> Args,
7274                                        OverloadCandidateSet& CandidateSet,
7275                                        SourceRange OpRange) {
7276   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7277 
7278   // C++ [over.match.oper]p3:
7279   //   For a unary operator @ with an operand of a type whose
7280   //   cv-unqualified version is T1, and for a binary operator @ with
7281   //   a left operand of a type whose cv-unqualified version is T1 and
7282   //   a right operand of a type whose cv-unqualified version is T2,
7283   //   three sets of candidate functions, designated member
7284   //   candidates, non-member candidates and built-in candidates, are
7285   //   constructed as follows:
7286   QualType T1 = Args[0]->getType();
7287 
7288   //     -- If T1 is a complete class type or a class currently being
7289   //        defined, the set of member candidates is the result of the
7290   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7291   //        the set of member candidates is empty.
7292   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7293     // Complete the type if it can be completed.
7294     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7295       return;
7296     // If the type is neither complete nor being defined, bail out now.
7297     if (!T1Rec->getDecl()->getDefinition())
7298       return;
7299 
7300     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7301     LookupQualifiedName(Operators, T1Rec->getDecl());
7302     Operators.suppressDiagnostics();
7303 
7304     for (LookupResult::iterator Oper = Operators.begin(),
7305                              OperEnd = Operators.end();
7306          Oper != OperEnd;
7307          ++Oper)
7308       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7309                          Args[0]->Classify(Context), Args.slice(1),
7310                          CandidateSet, /*SuppressUserConversions=*/false);
7311   }
7312 }
7313 
7314 /// AddBuiltinCandidate - Add a candidate for a built-in
7315 /// operator. ResultTy and ParamTys are the result and parameter types
7316 /// of the built-in candidate, respectively. Args and NumArgs are the
7317 /// arguments being passed to the candidate. IsAssignmentOperator
7318 /// should be true when this built-in candidate is an assignment
7319 /// operator. NumContextualBoolArguments is the number of arguments
7320 /// (at the beginning of the argument list) that will be contextually
7321 /// converted to bool.
7322 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7323                                OverloadCandidateSet& CandidateSet,
7324                                bool IsAssignmentOperator,
7325                                unsigned NumContextualBoolArguments) {
7326   // Overload resolution is always an unevaluated context.
7327   EnterExpressionEvaluationContext Unevaluated(
7328       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7329 
7330   // Add this candidate
7331   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7332   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7333   Candidate.Function = nullptr;
7334   Candidate.IsSurrogate = false;
7335   Candidate.IgnoreObjectArgument = false;
7336   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7337 
7338   // Determine the implicit conversion sequences for each of the
7339   // arguments.
7340   Candidate.Viable = true;
7341   Candidate.ExplicitCallArguments = Args.size();
7342   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7343     // C++ [over.match.oper]p4:
7344     //   For the built-in assignment operators, conversions of the
7345     //   left operand are restricted as follows:
7346     //     -- no temporaries are introduced to hold the left operand, and
7347     //     -- no user-defined conversions are applied to the left
7348     //        operand to achieve a type match with the left-most
7349     //        parameter of a built-in candidate.
7350     //
7351     // We block these conversions by turning off user-defined
7352     // conversions, since that is the only way that initialization of
7353     // a reference to a non-class type can occur from something that
7354     // is not of the same type.
7355     if (ArgIdx < NumContextualBoolArguments) {
7356       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7357              "Contextual conversion to bool requires bool type");
7358       Candidate.Conversions[ArgIdx]
7359         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7360     } else {
7361       Candidate.Conversions[ArgIdx]
7362         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7363                                 ArgIdx == 0 && IsAssignmentOperator,
7364                                 /*InOverloadResolution=*/false,
7365                                 /*AllowObjCWritebackConversion=*/
7366                                   getLangOpts().ObjCAutoRefCount);
7367     }
7368     if (Candidate.Conversions[ArgIdx].isBad()) {
7369       Candidate.Viable = false;
7370       Candidate.FailureKind = ovl_fail_bad_conversion;
7371       break;
7372     }
7373   }
7374 }
7375 
7376 namespace {
7377 
7378 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7379 /// candidate operator functions for built-in operators (C++
7380 /// [over.built]). The types are separated into pointer types and
7381 /// enumeration types.
7382 class BuiltinCandidateTypeSet  {
7383   /// TypeSet - A set of types.
7384   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7385                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7386 
7387   /// PointerTypes - The set of pointer types that will be used in the
7388   /// built-in candidates.
7389   TypeSet PointerTypes;
7390 
7391   /// MemberPointerTypes - The set of member pointer types that will be
7392   /// used in the built-in candidates.
7393   TypeSet MemberPointerTypes;
7394 
7395   /// EnumerationTypes - The set of enumeration types that will be
7396   /// used in the built-in candidates.
7397   TypeSet EnumerationTypes;
7398 
7399   /// The set of vector types that will be used in the built-in
7400   /// candidates.
7401   TypeSet VectorTypes;
7402 
7403   /// A flag indicating non-record types are viable candidates
7404   bool HasNonRecordTypes;
7405 
7406   /// A flag indicating whether either arithmetic or enumeration types
7407   /// were present in the candidate set.
7408   bool HasArithmeticOrEnumeralTypes;
7409 
7410   /// A flag indicating whether the nullptr type was present in the
7411   /// candidate set.
7412   bool HasNullPtrType;
7413 
7414   /// Sema - The semantic analysis instance where we are building the
7415   /// candidate type set.
7416   Sema &SemaRef;
7417 
7418   /// Context - The AST context in which we will build the type sets.
7419   ASTContext &Context;
7420 
7421   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7422                                                const Qualifiers &VisibleQuals);
7423   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7424 
7425 public:
7426   /// iterator - Iterates through the types that are part of the set.
7427   typedef TypeSet::iterator iterator;
7428 
7429   BuiltinCandidateTypeSet(Sema &SemaRef)
7430     : HasNonRecordTypes(false),
7431       HasArithmeticOrEnumeralTypes(false),
7432       HasNullPtrType(false),
7433       SemaRef(SemaRef),
7434       Context(SemaRef.Context) { }
7435 
7436   void AddTypesConvertedFrom(QualType Ty,
7437                              SourceLocation Loc,
7438                              bool AllowUserConversions,
7439                              bool AllowExplicitConversions,
7440                              const Qualifiers &VisibleTypeConversionsQuals);
7441 
7442   /// pointer_begin - First pointer type found;
7443   iterator pointer_begin() { return PointerTypes.begin(); }
7444 
7445   /// pointer_end - Past the last pointer type found;
7446   iterator pointer_end() { return PointerTypes.end(); }
7447 
7448   /// member_pointer_begin - First member pointer type found;
7449   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7450 
7451   /// member_pointer_end - Past the last member pointer type found;
7452   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7453 
7454   /// enumeration_begin - First enumeration type found;
7455   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7456 
7457   /// enumeration_end - Past the last enumeration type found;
7458   iterator enumeration_end() { return EnumerationTypes.end(); }
7459 
7460   iterator vector_begin() { return VectorTypes.begin(); }
7461   iterator vector_end() { return VectorTypes.end(); }
7462 
7463   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7464   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7465   bool hasNullPtrType() const { return HasNullPtrType; }
7466 };
7467 
7468 } // end anonymous namespace
7469 
7470 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7471 /// the set of pointer types along with any more-qualified variants of
7472 /// that type. For example, if @p Ty is "int const *", this routine
7473 /// will add "int const *", "int const volatile *", "int const
7474 /// restrict *", and "int const volatile restrict *" to the set of
7475 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7476 /// false otherwise.
7477 ///
7478 /// FIXME: what to do about extended qualifiers?
7479 bool
7480 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7481                                              const Qualifiers &VisibleQuals) {
7482 
7483   // Insert this type.
7484   if (!PointerTypes.insert(Ty))
7485     return false;
7486 
7487   QualType PointeeTy;
7488   const PointerType *PointerTy = Ty->getAs<PointerType>();
7489   bool buildObjCPtr = false;
7490   if (!PointerTy) {
7491     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7492     PointeeTy = PTy->getPointeeType();
7493     buildObjCPtr = true;
7494   } else {
7495     PointeeTy = PointerTy->getPointeeType();
7496   }
7497 
7498   // Don't add qualified variants of arrays. For one, they're not allowed
7499   // (the qualifier would sink to the element type), and for another, the
7500   // only overload situation where it matters is subscript or pointer +- int,
7501   // and those shouldn't have qualifier variants anyway.
7502   if (PointeeTy->isArrayType())
7503     return true;
7504 
7505   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7506   bool hasVolatile = VisibleQuals.hasVolatile();
7507   bool hasRestrict = VisibleQuals.hasRestrict();
7508 
7509   // Iterate through all strict supersets of BaseCVR.
7510   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7511     if ((CVR | BaseCVR) != CVR) continue;
7512     // Skip over volatile if no volatile found anywhere in the types.
7513     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7514 
7515     // Skip over restrict if no restrict found anywhere in the types, or if
7516     // the type cannot be restrict-qualified.
7517     if ((CVR & Qualifiers::Restrict) &&
7518         (!hasRestrict ||
7519          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7520       continue;
7521 
7522     // Build qualified pointee type.
7523     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7524 
7525     // Build qualified pointer type.
7526     QualType QPointerTy;
7527     if (!buildObjCPtr)
7528       QPointerTy = Context.getPointerType(QPointeeTy);
7529     else
7530       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7531 
7532     // Insert qualified pointer type.
7533     PointerTypes.insert(QPointerTy);
7534   }
7535 
7536   return true;
7537 }
7538 
7539 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7540 /// to the set of pointer types along with any more-qualified variants of
7541 /// that type. For example, if @p Ty is "int const *", this routine
7542 /// will add "int const *", "int const volatile *", "int const
7543 /// restrict *", and "int const volatile restrict *" to the set of
7544 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7545 /// false otherwise.
7546 ///
7547 /// FIXME: what to do about extended qualifiers?
7548 bool
7549 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7550     QualType Ty) {
7551   // Insert this type.
7552   if (!MemberPointerTypes.insert(Ty))
7553     return false;
7554 
7555   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7556   assert(PointerTy && "type was not a member pointer type!");
7557 
7558   QualType PointeeTy = PointerTy->getPointeeType();
7559   // Don't add qualified variants of arrays. For one, they're not allowed
7560   // (the qualifier would sink to the element type), and for another, the
7561   // only overload situation where it matters is subscript or pointer +- int,
7562   // and those shouldn't have qualifier variants anyway.
7563   if (PointeeTy->isArrayType())
7564     return true;
7565   const Type *ClassTy = PointerTy->getClass();
7566 
7567   // Iterate through all strict supersets of the pointee type's CVR
7568   // qualifiers.
7569   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7570   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7571     if ((CVR | BaseCVR) != CVR) continue;
7572 
7573     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7574     MemberPointerTypes.insert(
7575       Context.getMemberPointerType(QPointeeTy, ClassTy));
7576   }
7577 
7578   return true;
7579 }
7580 
7581 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7582 /// Ty can be implicit converted to the given set of @p Types. We're
7583 /// primarily interested in pointer types and enumeration types. We also
7584 /// take member pointer types, for the conditional operator.
7585 /// AllowUserConversions is true if we should look at the conversion
7586 /// functions of a class type, and AllowExplicitConversions if we
7587 /// should also include the explicit conversion functions of a class
7588 /// type.
7589 void
7590 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7591                                                SourceLocation Loc,
7592                                                bool AllowUserConversions,
7593                                                bool AllowExplicitConversions,
7594                                                const Qualifiers &VisibleQuals) {
7595   // Only deal with canonical types.
7596   Ty = Context.getCanonicalType(Ty);
7597 
7598   // Look through reference types; they aren't part of the type of an
7599   // expression for the purposes of conversions.
7600   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7601     Ty = RefTy->getPointeeType();
7602 
7603   // If we're dealing with an array type, decay to the pointer.
7604   if (Ty->isArrayType())
7605     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7606 
7607   // Otherwise, we don't care about qualifiers on the type.
7608   Ty = Ty.getLocalUnqualifiedType();
7609 
7610   // Flag if we ever add a non-record type.
7611   const RecordType *TyRec = Ty->getAs<RecordType>();
7612   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7613 
7614   // Flag if we encounter an arithmetic type.
7615   HasArithmeticOrEnumeralTypes =
7616     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7617 
7618   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7619     PointerTypes.insert(Ty);
7620   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7621     // Insert our type, and its more-qualified variants, into the set
7622     // of types.
7623     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7624       return;
7625   } else if (Ty->isMemberPointerType()) {
7626     // Member pointers are far easier, since the pointee can't be converted.
7627     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7628       return;
7629   } else if (Ty->isEnumeralType()) {
7630     HasArithmeticOrEnumeralTypes = true;
7631     EnumerationTypes.insert(Ty);
7632   } else if (Ty->isVectorType()) {
7633     // We treat vector types as arithmetic types in many contexts as an
7634     // extension.
7635     HasArithmeticOrEnumeralTypes = true;
7636     VectorTypes.insert(Ty);
7637   } else if (Ty->isNullPtrType()) {
7638     HasNullPtrType = true;
7639   } else if (AllowUserConversions && TyRec) {
7640     // No conversion functions in incomplete types.
7641     if (!SemaRef.isCompleteType(Loc, Ty))
7642       return;
7643 
7644     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7645     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7646       if (isa<UsingShadowDecl>(D))
7647         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7648 
7649       // Skip conversion function templates; they don't tell us anything
7650       // about which builtin types we can convert to.
7651       if (isa<FunctionTemplateDecl>(D))
7652         continue;
7653 
7654       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7655       if (AllowExplicitConversions || !Conv->isExplicit()) {
7656         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7657                               VisibleQuals);
7658       }
7659     }
7660   }
7661 }
7662 
7663 /// Helper function for AddBuiltinOperatorCandidates() that adds
7664 /// the volatile- and non-volatile-qualified assignment operators for the
7665 /// given type to the candidate set.
7666 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7667                                                    QualType T,
7668                                                    ArrayRef<Expr *> Args,
7669                                     OverloadCandidateSet &CandidateSet) {
7670   QualType ParamTypes[2];
7671 
7672   // T& operator=(T&, T)
7673   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7674   ParamTypes[1] = T;
7675   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7676                         /*IsAssignmentOperator=*/true);
7677 
7678   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7679     // volatile T& operator=(volatile T&, T)
7680     ParamTypes[0]
7681       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7682     ParamTypes[1] = T;
7683     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7684                           /*IsAssignmentOperator=*/true);
7685   }
7686 }
7687 
7688 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7689 /// if any, found in visible type conversion functions found in ArgExpr's type.
7690 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7691     Qualifiers VRQuals;
7692     const RecordType *TyRec;
7693     if (const MemberPointerType *RHSMPType =
7694         ArgExpr->getType()->getAs<MemberPointerType>())
7695       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7696     else
7697       TyRec = ArgExpr->getType()->getAs<RecordType>();
7698     if (!TyRec) {
7699       // Just to be safe, assume the worst case.
7700       VRQuals.addVolatile();
7701       VRQuals.addRestrict();
7702       return VRQuals;
7703     }
7704 
7705     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7706     if (!ClassDecl->hasDefinition())
7707       return VRQuals;
7708 
7709     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7710       if (isa<UsingShadowDecl>(D))
7711         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7712       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7713         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7714         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7715           CanTy = ResTypeRef->getPointeeType();
7716         // Need to go down the pointer/mempointer chain and add qualifiers
7717         // as see them.
7718         bool done = false;
7719         while (!done) {
7720           if (CanTy.isRestrictQualified())
7721             VRQuals.addRestrict();
7722           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7723             CanTy = ResTypePtr->getPointeeType();
7724           else if (const MemberPointerType *ResTypeMPtr =
7725                 CanTy->getAs<MemberPointerType>())
7726             CanTy = ResTypeMPtr->getPointeeType();
7727           else
7728             done = true;
7729           if (CanTy.isVolatileQualified())
7730             VRQuals.addVolatile();
7731           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7732             return VRQuals;
7733         }
7734       }
7735     }
7736     return VRQuals;
7737 }
7738 
7739 namespace {
7740 
7741 /// Helper class to manage the addition of builtin operator overload
7742 /// candidates. It provides shared state and utility methods used throughout
7743 /// the process, as well as a helper method to add each group of builtin
7744 /// operator overloads from the standard to a candidate set.
7745 class BuiltinOperatorOverloadBuilder {
7746   // Common instance state available to all overload candidate addition methods.
7747   Sema &S;
7748   ArrayRef<Expr *> Args;
7749   Qualifiers VisibleTypeConversionsQuals;
7750   bool HasArithmeticOrEnumeralCandidateType;
7751   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7752   OverloadCandidateSet &CandidateSet;
7753 
7754   static constexpr int ArithmeticTypesCap = 24;
7755   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7756 
7757   // Define some indices used to iterate over the arithemetic types in
7758   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7759   // types are that preserved by promotion (C++ [over.built]p2).
7760   unsigned FirstIntegralType,
7761            LastIntegralType;
7762   unsigned FirstPromotedIntegralType,
7763            LastPromotedIntegralType;
7764   unsigned FirstPromotedArithmeticType,
7765            LastPromotedArithmeticType;
7766   unsigned NumArithmeticTypes;
7767 
7768   void InitArithmeticTypes() {
7769     // Start of promoted types.
7770     FirstPromotedArithmeticType = 0;
7771     ArithmeticTypes.push_back(S.Context.FloatTy);
7772     ArithmeticTypes.push_back(S.Context.DoubleTy);
7773     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7774     if (S.Context.getTargetInfo().hasFloat128Type())
7775       ArithmeticTypes.push_back(S.Context.Float128Ty);
7776 
7777     // Start of integral types.
7778     FirstIntegralType = ArithmeticTypes.size();
7779     FirstPromotedIntegralType = ArithmeticTypes.size();
7780     ArithmeticTypes.push_back(S.Context.IntTy);
7781     ArithmeticTypes.push_back(S.Context.LongTy);
7782     ArithmeticTypes.push_back(S.Context.LongLongTy);
7783     if (S.Context.getTargetInfo().hasInt128Type())
7784       ArithmeticTypes.push_back(S.Context.Int128Ty);
7785     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7786     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7787     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7788     if (S.Context.getTargetInfo().hasInt128Type())
7789       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7790     LastPromotedIntegralType = ArithmeticTypes.size();
7791     LastPromotedArithmeticType = ArithmeticTypes.size();
7792     // End of promoted types.
7793 
7794     ArithmeticTypes.push_back(S.Context.BoolTy);
7795     ArithmeticTypes.push_back(S.Context.CharTy);
7796     ArithmeticTypes.push_back(S.Context.WCharTy);
7797     if (S.Context.getLangOpts().Char8)
7798       ArithmeticTypes.push_back(S.Context.Char8Ty);
7799     ArithmeticTypes.push_back(S.Context.Char16Ty);
7800     ArithmeticTypes.push_back(S.Context.Char32Ty);
7801     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7802     ArithmeticTypes.push_back(S.Context.ShortTy);
7803     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7804     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7805     LastIntegralType = ArithmeticTypes.size();
7806     NumArithmeticTypes = ArithmeticTypes.size();
7807     // End of integral types.
7808     // FIXME: What about complex? What about half?
7809 
7810     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7811            "Enough inline storage for all arithmetic types.");
7812   }
7813 
7814   /// Helper method to factor out the common pattern of adding overloads
7815   /// for '++' and '--' builtin operators.
7816   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7817                                            bool HasVolatile,
7818                                            bool HasRestrict) {
7819     QualType ParamTypes[2] = {
7820       S.Context.getLValueReferenceType(CandidateTy),
7821       S.Context.IntTy
7822     };
7823 
7824     // Non-volatile version.
7825     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7826 
7827     // Use a heuristic to reduce number of builtin candidates in the set:
7828     // add volatile version only if there are conversions to a volatile type.
7829     if (HasVolatile) {
7830       ParamTypes[0] =
7831         S.Context.getLValueReferenceType(
7832           S.Context.getVolatileType(CandidateTy));
7833       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7834     }
7835 
7836     // Add restrict version only if there are conversions to a restrict type
7837     // and our candidate type is a non-restrict-qualified pointer.
7838     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7839         !CandidateTy.isRestrictQualified()) {
7840       ParamTypes[0]
7841         = S.Context.getLValueReferenceType(
7842             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7843       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7844 
7845       if (HasVolatile) {
7846         ParamTypes[0]
7847           = S.Context.getLValueReferenceType(
7848               S.Context.getCVRQualifiedType(CandidateTy,
7849                                             (Qualifiers::Volatile |
7850                                              Qualifiers::Restrict)));
7851         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7852       }
7853     }
7854 
7855   }
7856 
7857 public:
7858   BuiltinOperatorOverloadBuilder(
7859     Sema &S, ArrayRef<Expr *> Args,
7860     Qualifiers VisibleTypeConversionsQuals,
7861     bool HasArithmeticOrEnumeralCandidateType,
7862     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7863     OverloadCandidateSet &CandidateSet)
7864     : S(S), Args(Args),
7865       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7866       HasArithmeticOrEnumeralCandidateType(
7867         HasArithmeticOrEnumeralCandidateType),
7868       CandidateTypes(CandidateTypes),
7869       CandidateSet(CandidateSet) {
7870 
7871     InitArithmeticTypes();
7872   }
7873 
7874   // Increment is deprecated for bool since C++17.
7875   //
7876   // C++ [over.built]p3:
7877   //
7878   //   For every pair (T, VQ), where T is an arithmetic type other
7879   //   than bool, and VQ is either volatile or empty, there exist
7880   //   candidate operator functions of the form
7881   //
7882   //       VQ T&      operator++(VQ T&);
7883   //       T          operator++(VQ T&, int);
7884   //
7885   // C++ [over.built]p4:
7886   //
7887   //   For every pair (T, VQ), where T is an arithmetic type other
7888   //   than bool, and VQ is either volatile or empty, there exist
7889   //   candidate operator functions of the form
7890   //
7891   //       VQ T&      operator--(VQ T&);
7892   //       T          operator--(VQ T&, int);
7893   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7894     if (!HasArithmeticOrEnumeralCandidateType)
7895       return;
7896 
7897     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7898       const auto TypeOfT = ArithmeticTypes[Arith];
7899       if (TypeOfT == S.Context.BoolTy) {
7900         if (Op == OO_MinusMinus)
7901           continue;
7902         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7903           continue;
7904       }
7905       addPlusPlusMinusMinusStyleOverloads(
7906         TypeOfT,
7907         VisibleTypeConversionsQuals.hasVolatile(),
7908         VisibleTypeConversionsQuals.hasRestrict());
7909     }
7910   }
7911 
7912   // C++ [over.built]p5:
7913   //
7914   //   For every pair (T, VQ), where T is a cv-qualified or
7915   //   cv-unqualified object type, and VQ is either volatile or
7916   //   empty, there exist candidate operator functions of the form
7917   //
7918   //       T*VQ&      operator++(T*VQ&);
7919   //       T*VQ&      operator--(T*VQ&);
7920   //       T*         operator++(T*VQ&, int);
7921   //       T*         operator--(T*VQ&, int);
7922   void addPlusPlusMinusMinusPointerOverloads() {
7923     for (BuiltinCandidateTypeSet::iterator
7924               Ptr = CandidateTypes[0].pointer_begin(),
7925            PtrEnd = CandidateTypes[0].pointer_end();
7926          Ptr != PtrEnd; ++Ptr) {
7927       // Skip pointer types that aren't pointers to object types.
7928       if (!(*Ptr)->getPointeeType()->isObjectType())
7929         continue;
7930 
7931       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7932         (!(*Ptr).isVolatileQualified() &&
7933          VisibleTypeConversionsQuals.hasVolatile()),
7934         (!(*Ptr).isRestrictQualified() &&
7935          VisibleTypeConversionsQuals.hasRestrict()));
7936     }
7937   }
7938 
7939   // C++ [over.built]p6:
7940   //   For every cv-qualified or cv-unqualified object type T, there
7941   //   exist candidate operator functions of the form
7942   //
7943   //       T&         operator*(T*);
7944   //
7945   // C++ [over.built]p7:
7946   //   For every function type T that does not have cv-qualifiers or a
7947   //   ref-qualifier, there exist candidate operator functions of the form
7948   //       T&         operator*(T*);
7949   void addUnaryStarPointerOverloads() {
7950     for (BuiltinCandidateTypeSet::iterator
7951               Ptr = CandidateTypes[0].pointer_begin(),
7952            PtrEnd = CandidateTypes[0].pointer_end();
7953          Ptr != PtrEnd; ++Ptr) {
7954       QualType ParamTy = *Ptr;
7955       QualType PointeeTy = ParamTy->getPointeeType();
7956       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7957         continue;
7958 
7959       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7960         if (Proto->getMethodQuals() || Proto->getRefQualifier())
7961           continue;
7962 
7963       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7964     }
7965   }
7966 
7967   // C++ [over.built]p9:
7968   //  For every promoted arithmetic type T, there exist candidate
7969   //  operator functions of the form
7970   //
7971   //       T         operator+(T);
7972   //       T         operator-(T);
7973   void addUnaryPlusOrMinusArithmeticOverloads() {
7974     if (!HasArithmeticOrEnumeralCandidateType)
7975       return;
7976 
7977     for (unsigned Arith = FirstPromotedArithmeticType;
7978          Arith < LastPromotedArithmeticType; ++Arith) {
7979       QualType ArithTy = ArithmeticTypes[Arith];
7980       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7981     }
7982 
7983     // Extension: We also add these operators for vector types.
7984     for (BuiltinCandidateTypeSet::iterator
7985               Vec = CandidateTypes[0].vector_begin(),
7986            VecEnd = CandidateTypes[0].vector_end();
7987          Vec != VecEnd; ++Vec) {
7988       QualType VecTy = *Vec;
7989       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7990     }
7991   }
7992 
7993   // C++ [over.built]p8:
7994   //   For every type T, there exist candidate operator functions of
7995   //   the form
7996   //
7997   //       T*         operator+(T*);
7998   void addUnaryPlusPointerOverloads() {
7999     for (BuiltinCandidateTypeSet::iterator
8000               Ptr = CandidateTypes[0].pointer_begin(),
8001            PtrEnd = CandidateTypes[0].pointer_end();
8002          Ptr != PtrEnd; ++Ptr) {
8003       QualType ParamTy = *Ptr;
8004       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8005     }
8006   }
8007 
8008   // C++ [over.built]p10:
8009   //   For every promoted integral type T, there exist candidate
8010   //   operator functions of the form
8011   //
8012   //        T         operator~(T);
8013   void addUnaryTildePromotedIntegralOverloads() {
8014     if (!HasArithmeticOrEnumeralCandidateType)
8015       return;
8016 
8017     for (unsigned Int = FirstPromotedIntegralType;
8018          Int < LastPromotedIntegralType; ++Int) {
8019       QualType IntTy = ArithmeticTypes[Int];
8020       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8021     }
8022 
8023     // Extension: We also add this operator for vector types.
8024     for (BuiltinCandidateTypeSet::iterator
8025               Vec = CandidateTypes[0].vector_begin(),
8026            VecEnd = CandidateTypes[0].vector_end();
8027          Vec != VecEnd; ++Vec) {
8028       QualType VecTy = *Vec;
8029       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8030     }
8031   }
8032 
8033   // C++ [over.match.oper]p16:
8034   //   For every pointer to member type T or type std::nullptr_t, there
8035   //   exist candidate operator functions of the form
8036   //
8037   //        bool operator==(T,T);
8038   //        bool operator!=(T,T);
8039   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8040     /// Set of (canonical) types that we've already handled.
8041     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8042 
8043     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8044       for (BuiltinCandidateTypeSet::iterator
8045                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8046              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8047            MemPtr != MemPtrEnd;
8048            ++MemPtr) {
8049         // Don't add the same builtin candidate twice.
8050         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8051           continue;
8052 
8053         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8054         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8055       }
8056 
8057       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8058         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8059         if (AddedTypes.insert(NullPtrTy).second) {
8060           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8061           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8062         }
8063       }
8064     }
8065   }
8066 
8067   // C++ [over.built]p15:
8068   //
8069   //   For every T, where T is an enumeration type or a pointer type,
8070   //   there exist candidate operator functions of the form
8071   //
8072   //        bool       operator<(T, T);
8073   //        bool       operator>(T, T);
8074   //        bool       operator<=(T, T);
8075   //        bool       operator>=(T, T);
8076   //        bool       operator==(T, T);
8077   //        bool       operator!=(T, T);
8078   //           R       operator<=>(T, T)
8079   void addGenericBinaryPointerOrEnumeralOverloads() {
8080     // C++ [over.match.oper]p3:
8081     //   [...]the built-in candidates include all of the candidate operator
8082     //   functions defined in 13.6 that, compared to the given operator, [...]
8083     //   do not have the same parameter-type-list as any non-template non-member
8084     //   candidate.
8085     //
8086     // Note that in practice, this only affects enumeration types because there
8087     // aren't any built-in candidates of record type, and a user-defined operator
8088     // must have an operand of record or enumeration type. Also, the only other
8089     // overloaded operator with enumeration arguments, operator=,
8090     // cannot be overloaded for enumeration types, so this is the only place
8091     // where we must suppress candidates like this.
8092     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8093       UserDefinedBinaryOperators;
8094 
8095     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8096       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8097           CandidateTypes[ArgIdx].enumeration_end()) {
8098         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8099                                          CEnd = CandidateSet.end();
8100              C != CEnd; ++C) {
8101           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8102             continue;
8103 
8104           if (C->Function->isFunctionTemplateSpecialization())
8105             continue;
8106 
8107           QualType FirstParamType =
8108             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8109           QualType SecondParamType =
8110             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8111 
8112           // Skip if either parameter isn't of enumeral type.
8113           if (!FirstParamType->isEnumeralType() ||
8114               !SecondParamType->isEnumeralType())
8115             continue;
8116 
8117           // Add this operator to the set of known user-defined operators.
8118           UserDefinedBinaryOperators.insert(
8119             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8120                            S.Context.getCanonicalType(SecondParamType)));
8121         }
8122       }
8123     }
8124 
8125     /// Set of (canonical) types that we've already handled.
8126     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8127 
8128     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8129       for (BuiltinCandidateTypeSet::iterator
8130                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8131              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8132            Ptr != PtrEnd; ++Ptr) {
8133         // Don't add the same builtin candidate twice.
8134         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8135           continue;
8136 
8137         QualType ParamTypes[2] = { *Ptr, *Ptr };
8138         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8139       }
8140       for (BuiltinCandidateTypeSet::iterator
8141                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8142              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8143            Enum != EnumEnd; ++Enum) {
8144         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8145 
8146         // Don't add the same builtin candidate twice, or if a user defined
8147         // candidate exists.
8148         if (!AddedTypes.insert(CanonType).second ||
8149             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8150                                                             CanonType)))
8151           continue;
8152         QualType ParamTypes[2] = { *Enum, *Enum };
8153         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8154       }
8155     }
8156   }
8157 
8158   // C++ [over.built]p13:
8159   //
8160   //   For every cv-qualified or cv-unqualified object type T
8161   //   there exist candidate operator functions of the form
8162   //
8163   //      T*         operator+(T*, ptrdiff_t);
8164   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8165   //      T*         operator-(T*, ptrdiff_t);
8166   //      T*         operator+(ptrdiff_t, T*);
8167   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8168   //
8169   // C++ [over.built]p14:
8170   //
8171   //   For every T, where T is a pointer to object type, there
8172   //   exist candidate operator functions of the form
8173   //
8174   //      ptrdiff_t  operator-(T, T);
8175   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8176     /// Set of (canonical) types that we've already handled.
8177     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8178 
8179     for (int Arg = 0; Arg < 2; ++Arg) {
8180       QualType AsymmetricParamTypes[2] = {
8181         S.Context.getPointerDiffType(),
8182         S.Context.getPointerDiffType(),
8183       };
8184       for (BuiltinCandidateTypeSet::iterator
8185                 Ptr = CandidateTypes[Arg].pointer_begin(),
8186              PtrEnd = CandidateTypes[Arg].pointer_end();
8187            Ptr != PtrEnd; ++Ptr) {
8188         QualType PointeeTy = (*Ptr)->getPointeeType();
8189         if (!PointeeTy->isObjectType())
8190           continue;
8191 
8192         AsymmetricParamTypes[Arg] = *Ptr;
8193         if (Arg == 0 || Op == OO_Plus) {
8194           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8195           // T* operator+(ptrdiff_t, T*);
8196           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8197         }
8198         if (Op == OO_Minus) {
8199           // ptrdiff_t operator-(T, T);
8200           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8201             continue;
8202 
8203           QualType ParamTypes[2] = { *Ptr, *Ptr };
8204           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8205         }
8206       }
8207     }
8208   }
8209 
8210   // C++ [over.built]p12:
8211   //
8212   //   For every pair of promoted arithmetic types L and R, there
8213   //   exist candidate operator functions of the form
8214   //
8215   //        LR         operator*(L, R);
8216   //        LR         operator/(L, R);
8217   //        LR         operator+(L, R);
8218   //        LR         operator-(L, R);
8219   //        bool       operator<(L, R);
8220   //        bool       operator>(L, R);
8221   //        bool       operator<=(L, R);
8222   //        bool       operator>=(L, R);
8223   //        bool       operator==(L, R);
8224   //        bool       operator!=(L, R);
8225   //
8226   //   where LR is the result of the usual arithmetic conversions
8227   //   between types L and R.
8228   //
8229   // C++ [over.built]p24:
8230   //
8231   //   For every pair of promoted arithmetic types L and R, there exist
8232   //   candidate operator functions of the form
8233   //
8234   //        LR       operator?(bool, L, R);
8235   //
8236   //   where LR is the result of the usual arithmetic conversions
8237   //   between types L and R.
8238   // Our candidates ignore the first parameter.
8239   void addGenericBinaryArithmeticOverloads() {
8240     if (!HasArithmeticOrEnumeralCandidateType)
8241       return;
8242 
8243     for (unsigned Left = FirstPromotedArithmeticType;
8244          Left < LastPromotedArithmeticType; ++Left) {
8245       for (unsigned Right = FirstPromotedArithmeticType;
8246            Right < LastPromotedArithmeticType; ++Right) {
8247         QualType LandR[2] = { ArithmeticTypes[Left],
8248                               ArithmeticTypes[Right] };
8249         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8250       }
8251     }
8252 
8253     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8254     // conditional operator for vector types.
8255     for (BuiltinCandidateTypeSet::iterator
8256               Vec1 = CandidateTypes[0].vector_begin(),
8257            Vec1End = CandidateTypes[0].vector_end();
8258          Vec1 != Vec1End; ++Vec1) {
8259       for (BuiltinCandidateTypeSet::iterator
8260                 Vec2 = CandidateTypes[1].vector_begin(),
8261              Vec2End = CandidateTypes[1].vector_end();
8262            Vec2 != Vec2End; ++Vec2) {
8263         QualType LandR[2] = { *Vec1, *Vec2 };
8264         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8265       }
8266     }
8267   }
8268 
8269   // C++2a [over.built]p14:
8270   //
8271   //   For every integral type T there exists a candidate operator function
8272   //   of the form
8273   //
8274   //        std::strong_ordering operator<=>(T, T)
8275   //
8276   // C++2a [over.built]p15:
8277   //
8278   //   For every pair of floating-point types L and R, there exists a candidate
8279   //   operator function of the form
8280   //
8281   //       std::partial_ordering operator<=>(L, R);
8282   //
8283   // FIXME: The current specification for integral types doesn't play nice with
8284   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8285   // comparisons. Under the current spec this can lead to ambiguity during
8286   // overload resolution. For example:
8287   //
8288   //   enum A : int {a};
8289   //   auto x = (a <=> (long)42);
8290   //
8291   //   error: call is ambiguous for arguments 'A' and 'long'.
8292   //   note: candidate operator<=>(int, int)
8293   //   note: candidate operator<=>(long, long)
8294   //
8295   // To avoid this error, this function deviates from the specification and adds
8296   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8297   // arithmetic types (the same as the generic relational overloads).
8298   //
8299   // For now this function acts as a placeholder.
8300   void addThreeWayArithmeticOverloads() {
8301     addGenericBinaryArithmeticOverloads();
8302   }
8303 
8304   // C++ [over.built]p17:
8305   //
8306   //   For every pair of promoted integral types L and R, there
8307   //   exist candidate operator functions of the form
8308   //
8309   //      LR         operator%(L, R);
8310   //      LR         operator&(L, R);
8311   //      LR         operator^(L, R);
8312   //      LR         operator|(L, R);
8313   //      L          operator<<(L, R);
8314   //      L          operator>>(L, R);
8315   //
8316   //   where LR is the result of the usual arithmetic conversions
8317   //   between types L and R.
8318   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8319     if (!HasArithmeticOrEnumeralCandidateType)
8320       return;
8321 
8322     for (unsigned Left = FirstPromotedIntegralType;
8323          Left < LastPromotedIntegralType; ++Left) {
8324       for (unsigned Right = FirstPromotedIntegralType;
8325            Right < LastPromotedIntegralType; ++Right) {
8326         QualType LandR[2] = { ArithmeticTypes[Left],
8327                               ArithmeticTypes[Right] };
8328         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8329       }
8330     }
8331   }
8332 
8333   // C++ [over.built]p20:
8334   //
8335   //   For every pair (T, VQ), where T is an enumeration or
8336   //   pointer to member type and VQ is either volatile or
8337   //   empty, there exist candidate operator functions of the form
8338   //
8339   //        VQ T&      operator=(VQ T&, T);
8340   void addAssignmentMemberPointerOrEnumeralOverloads() {
8341     /// Set of (canonical) types that we've already handled.
8342     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8343 
8344     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8345       for (BuiltinCandidateTypeSet::iterator
8346                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8347              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8348            Enum != EnumEnd; ++Enum) {
8349         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8350           continue;
8351 
8352         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8353       }
8354 
8355       for (BuiltinCandidateTypeSet::iterator
8356                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8357              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8358            MemPtr != MemPtrEnd; ++MemPtr) {
8359         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8360           continue;
8361 
8362         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8363       }
8364     }
8365   }
8366 
8367   // C++ [over.built]p19:
8368   //
8369   //   For every pair (T, VQ), where T is any type and VQ is either
8370   //   volatile or empty, there exist candidate operator functions
8371   //   of the form
8372   //
8373   //        T*VQ&      operator=(T*VQ&, T*);
8374   //
8375   // C++ [over.built]p21:
8376   //
8377   //   For every pair (T, VQ), where T is a cv-qualified or
8378   //   cv-unqualified object type and VQ is either volatile or
8379   //   empty, there exist candidate operator functions of the form
8380   //
8381   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8382   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8383   void addAssignmentPointerOverloads(bool isEqualOp) {
8384     /// Set of (canonical) types that we've already handled.
8385     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8386 
8387     for (BuiltinCandidateTypeSet::iterator
8388               Ptr = CandidateTypes[0].pointer_begin(),
8389            PtrEnd = CandidateTypes[0].pointer_end();
8390          Ptr != PtrEnd; ++Ptr) {
8391       // If this is operator=, keep track of the builtin candidates we added.
8392       if (isEqualOp)
8393         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8394       else if (!(*Ptr)->getPointeeType()->isObjectType())
8395         continue;
8396 
8397       // non-volatile version
8398       QualType ParamTypes[2] = {
8399         S.Context.getLValueReferenceType(*Ptr),
8400         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8401       };
8402       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8403                             /*IsAssigmentOperator=*/ isEqualOp);
8404 
8405       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8406                           VisibleTypeConversionsQuals.hasVolatile();
8407       if (NeedVolatile) {
8408         // volatile version
8409         ParamTypes[0] =
8410           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8411         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8412                               /*IsAssigmentOperator=*/isEqualOp);
8413       }
8414 
8415       if (!(*Ptr).isRestrictQualified() &&
8416           VisibleTypeConversionsQuals.hasRestrict()) {
8417         // restrict version
8418         ParamTypes[0]
8419           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8420         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8421                               /*IsAssigmentOperator=*/isEqualOp);
8422 
8423         if (NeedVolatile) {
8424           // volatile restrict version
8425           ParamTypes[0]
8426             = S.Context.getLValueReferenceType(
8427                 S.Context.getCVRQualifiedType(*Ptr,
8428                                               (Qualifiers::Volatile |
8429                                                Qualifiers::Restrict)));
8430           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8431                                 /*IsAssigmentOperator=*/isEqualOp);
8432         }
8433       }
8434     }
8435 
8436     if (isEqualOp) {
8437       for (BuiltinCandidateTypeSet::iterator
8438                 Ptr = CandidateTypes[1].pointer_begin(),
8439              PtrEnd = CandidateTypes[1].pointer_end();
8440            Ptr != PtrEnd; ++Ptr) {
8441         // Make sure we don't add the same candidate twice.
8442         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8443           continue;
8444 
8445         QualType ParamTypes[2] = {
8446           S.Context.getLValueReferenceType(*Ptr),
8447           *Ptr,
8448         };
8449 
8450         // non-volatile version
8451         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8452                               /*IsAssigmentOperator=*/true);
8453 
8454         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8455                            VisibleTypeConversionsQuals.hasVolatile();
8456         if (NeedVolatile) {
8457           // volatile version
8458           ParamTypes[0] =
8459             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8460           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8461                                 /*IsAssigmentOperator=*/true);
8462         }
8463 
8464         if (!(*Ptr).isRestrictQualified() &&
8465             VisibleTypeConversionsQuals.hasRestrict()) {
8466           // restrict version
8467           ParamTypes[0]
8468             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8469           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8470                                 /*IsAssigmentOperator=*/true);
8471 
8472           if (NeedVolatile) {
8473             // volatile restrict version
8474             ParamTypes[0]
8475               = S.Context.getLValueReferenceType(
8476                   S.Context.getCVRQualifiedType(*Ptr,
8477                                                 (Qualifiers::Volatile |
8478                                                  Qualifiers::Restrict)));
8479             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8480                                   /*IsAssigmentOperator=*/true);
8481           }
8482         }
8483       }
8484     }
8485   }
8486 
8487   // C++ [over.built]p18:
8488   //
8489   //   For every triple (L, VQ, R), where L is an arithmetic type,
8490   //   VQ is either volatile or empty, and R is a promoted
8491   //   arithmetic type, there exist candidate operator functions of
8492   //   the form
8493   //
8494   //        VQ L&      operator=(VQ L&, R);
8495   //        VQ L&      operator*=(VQ L&, R);
8496   //        VQ L&      operator/=(VQ L&, R);
8497   //        VQ L&      operator+=(VQ L&, R);
8498   //        VQ L&      operator-=(VQ L&, R);
8499   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8500     if (!HasArithmeticOrEnumeralCandidateType)
8501       return;
8502 
8503     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8504       for (unsigned Right = FirstPromotedArithmeticType;
8505            Right < LastPromotedArithmeticType; ++Right) {
8506         QualType ParamTypes[2];
8507         ParamTypes[1] = ArithmeticTypes[Right];
8508 
8509         // Add this built-in operator as a candidate (VQ is empty).
8510         ParamTypes[0] =
8511           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8512         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8513                               /*IsAssigmentOperator=*/isEqualOp);
8514 
8515         // Add this built-in operator as a candidate (VQ is 'volatile').
8516         if (VisibleTypeConversionsQuals.hasVolatile()) {
8517           ParamTypes[0] =
8518             S.Context.getVolatileType(ArithmeticTypes[Left]);
8519           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8520           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8521                                 /*IsAssigmentOperator=*/isEqualOp);
8522         }
8523       }
8524     }
8525 
8526     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8527     for (BuiltinCandidateTypeSet::iterator
8528               Vec1 = CandidateTypes[0].vector_begin(),
8529            Vec1End = CandidateTypes[0].vector_end();
8530          Vec1 != Vec1End; ++Vec1) {
8531       for (BuiltinCandidateTypeSet::iterator
8532                 Vec2 = CandidateTypes[1].vector_begin(),
8533              Vec2End = CandidateTypes[1].vector_end();
8534            Vec2 != Vec2End; ++Vec2) {
8535         QualType ParamTypes[2];
8536         ParamTypes[1] = *Vec2;
8537         // Add this built-in operator as a candidate (VQ is empty).
8538         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8539         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8540                               /*IsAssigmentOperator=*/isEqualOp);
8541 
8542         // Add this built-in operator as a candidate (VQ is 'volatile').
8543         if (VisibleTypeConversionsQuals.hasVolatile()) {
8544           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8545           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8546           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8547                                 /*IsAssigmentOperator=*/isEqualOp);
8548         }
8549       }
8550     }
8551   }
8552 
8553   // C++ [over.built]p22:
8554   //
8555   //   For every triple (L, VQ, R), where L is an integral type, VQ
8556   //   is either volatile or empty, and R is a promoted integral
8557   //   type, there exist candidate operator functions of the form
8558   //
8559   //        VQ L&       operator%=(VQ L&, R);
8560   //        VQ L&       operator<<=(VQ L&, R);
8561   //        VQ L&       operator>>=(VQ L&, R);
8562   //        VQ L&       operator&=(VQ L&, R);
8563   //        VQ L&       operator^=(VQ L&, R);
8564   //        VQ L&       operator|=(VQ L&, R);
8565   void addAssignmentIntegralOverloads() {
8566     if (!HasArithmeticOrEnumeralCandidateType)
8567       return;
8568 
8569     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8570       for (unsigned Right = FirstPromotedIntegralType;
8571            Right < LastPromotedIntegralType; ++Right) {
8572         QualType ParamTypes[2];
8573         ParamTypes[1] = ArithmeticTypes[Right];
8574 
8575         // Add this built-in operator as a candidate (VQ is empty).
8576         ParamTypes[0] =
8577           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8578         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8579         if (VisibleTypeConversionsQuals.hasVolatile()) {
8580           // Add this built-in operator as a candidate (VQ is 'volatile').
8581           ParamTypes[0] = ArithmeticTypes[Left];
8582           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8583           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8584           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8585         }
8586       }
8587     }
8588   }
8589 
8590   // C++ [over.operator]p23:
8591   //
8592   //   There also exist candidate operator functions of the form
8593   //
8594   //        bool        operator!(bool);
8595   //        bool        operator&&(bool, bool);
8596   //        bool        operator||(bool, bool);
8597   void addExclaimOverload() {
8598     QualType ParamTy = S.Context.BoolTy;
8599     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8600                           /*IsAssignmentOperator=*/false,
8601                           /*NumContextualBoolArguments=*/1);
8602   }
8603   void addAmpAmpOrPipePipeOverload() {
8604     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8605     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8606                           /*IsAssignmentOperator=*/false,
8607                           /*NumContextualBoolArguments=*/2);
8608   }
8609 
8610   // C++ [over.built]p13:
8611   //
8612   //   For every cv-qualified or cv-unqualified object type T there
8613   //   exist candidate operator functions of the form
8614   //
8615   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8616   //        T&         operator[](T*, ptrdiff_t);
8617   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8618   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8619   //        T&         operator[](ptrdiff_t, T*);
8620   void addSubscriptOverloads() {
8621     for (BuiltinCandidateTypeSet::iterator
8622               Ptr = CandidateTypes[0].pointer_begin(),
8623            PtrEnd = CandidateTypes[0].pointer_end();
8624          Ptr != PtrEnd; ++Ptr) {
8625       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8626       QualType PointeeType = (*Ptr)->getPointeeType();
8627       if (!PointeeType->isObjectType())
8628         continue;
8629 
8630       // T& operator[](T*, ptrdiff_t)
8631       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8632     }
8633 
8634     for (BuiltinCandidateTypeSet::iterator
8635               Ptr = CandidateTypes[1].pointer_begin(),
8636            PtrEnd = CandidateTypes[1].pointer_end();
8637          Ptr != PtrEnd; ++Ptr) {
8638       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8639       QualType PointeeType = (*Ptr)->getPointeeType();
8640       if (!PointeeType->isObjectType())
8641         continue;
8642 
8643       // T& operator[](ptrdiff_t, T*)
8644       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8645     }
8646   }
8647 
8648   // C++ [over.built]p11:
8649   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8650   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8651   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8652   //    there exist candidate operator functions of the form
8653   //
8654   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8655   //
8656   //    where CV12 is the union of CV1 and CV2.
8657   void addArrowStarOverloads() {
8658     for (BuiltinCandidateTypeSet::iterator
8659              Ptr = CandidateTypes[0].pointer_begin(),
8660            PtrEnd = CandidateTypes[0].pointer_end();
8661          Ptr != PtrEnd; ++Ptr) {
8662       QualType C1Ty = (*Ptr);
8663       QualType C1;
8664       QualifierCollector Q1;
8665       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8666       if (!isa<RecordType>(C1))
8667         continue;
8668       // heuristic to reduce number of builtin candidates in the set.
8669       // Add volatile/restrict version only if there are conversions to a
8670       // volatile/restrict type.
8671       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8672         continue;
8673       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8674         continue;
8675       for (BuiltinCandidateTypeSet::iterator
8676                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8677              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8678            MemPtr != MemPtrEnd; ++MemPtr) {
8679         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8680         QualType C2 = QualType(mptr->getClass(), 0);
8681         C2 = C2.getUnqualifiedType();
8682         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8683           break;
8684         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8685         // build CV12 T&
8686         QualType T = mptr->getPointeeType();
8687         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8688             T.isVolatileQualified())
8689           continue;
8690         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8691             T.isRestrictQualified())
8692           continue;
8693         T = Q1.apply(S.Context, T);
8694         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8695       }
8696     }
8697   }
8698 
8699   // Note that we don't consider the first argument, since it has been
8700   // contextually converted to bool long ago. The candidates below are
8701   // therefore added as binary.
8702   //
8703   // C++ [over.built]p25:
8704   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8705   //   enumeration type, there exist candidate operator functions of the form
8706   //
8707   //        T        operator?(bool, T, T);
8708   //
8709   void addConditionalOperatorOverloads() {
8710     /// Set of (canonical) types that we've already handled.
8711     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8712 
8713     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8714       for (BuiltinCandidateTypeSet::iterator
8715                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8716              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8717            Ptr != PtrEnd; ++Ptr) {
8718         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8719           continue;
8720 
8721         QualType ParamTypes[2] = { *Ptr, *Ptr };
8722         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8723       }
8724 
8725       for (BuiltinCandidateTypeSet::iterator
8726                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8727              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8728            MemPtr != MemPtrEnd; ++MemPtr) {
8729         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8730           continue;
8731 
8732         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8733         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8734       }
8735 
8736       if (S.getLangOpts().CPlusPlus11) {
8737         for (BuiltinCandidateTypeSet::iterator
8738                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8739                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8740              Enum != EnumEnd; ++Enum) {
8741           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8742             continue;
8743 
8744           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8745             continue;
8746 
8747           QualType ParamTypes[2] = { *Enum, *Enum };
8748           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8749         }
8750       }
8751     }
8752   }
8753 };
8754 
8755 } // end anonymous namespace
8756 
8757 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8758 /// operator overloads to the candidate set (C++ [over.built]), based
8759 /// on the operator @p Op and the arguments given. For example, if the
8760 /// operator is a binary '+', this routine might add "int
8761 /// operator+(int, int)" to cover integer addition.
8762 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8763                                         SourceLocation OpLoc,
8764                                         ArrayRef<Expr *> Args,
8765                                         OverloadCandidateSet &CandidateSet) {
8766   // Find all of the types that the arguments can convert to, but only
8767   // if the operator we're looking at has built-in operator candidates
8768   // that make use of these types. Also record whether we encounter non-record
8769   // candidate types or either arithmetic or enumeral candidate types.
8770   Qualifiers VisibleTypeConversionsQuals;
8771   VisibleTypeConversionsQuals.addConst();
8772   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8773     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8774 
8775   bool HasNonRecordCandidateType = false;
8776   bool HasArithmeticOrEnumeralCandidateType = false;
8777   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8778   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8779     CandidateTypes.emplace_back(*this);
8780     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8781                                                  OpLoc,
8782                                                  true,
8783                                                  (Op == OO_Exclaim ||
8784                                                   Op == OO_AmpAmp ||
8785                                                   Op == OO_PipePipe),
8786                                                  VisibleTypeConversionsQuals);
8787     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8788         CandidateTypes[ArgIdx].hasNonRecordTypes();
8789     HasArithmeticOrEnumeralCandidateType =
8790         HasArithmeticOrEnumeralCandidateType ||
8791         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8792   }
8793 
8794   // Exit early when no non-record types have been added to the candidate set
8795   // for any of the arguments to the operator.
8796   //
8797   // We can't exit early for !, ||, or &&, since there we have always have
8798   // 'bool' overloads.
8799   if (!HasNonRecordCandidateType &&
8800       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8801     return;
8802 
8803   // Setup an object to manage the common state for building overloads.
8804   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8805                                            VisibleTypeConversionsQuals,
8806                                            HasArithmeticOrEnumeralCandidateType,
8807                                            CandidateTypes, CandidateSet);
8808 
8809   // Dispatch over the operation to add in only those overloads which apply.
8810   switch (Op) {
8811   case OO_None:
8812   case NUM_OVERLOADED_OPERATORS:
8813     llvm_unreachable("Expected an overloaded operator");
8814 
8815   case OO_New:
8816   case OO_Delete:
8817   case OO_Array_New:
8818   case OO_Array_Delete:
8819   case OO_Call:
8820     llvm_unreachable(
8821                     "Special operators don't use AddBuiltinOperatorCandidates");
8822 
8823   case OO_Comma:
8824   case OO_Arrow:
8825   case OO_Coawait:
8826     // C++ [over.match.oper]p3:
8827     //   -- For the operator ',', the unary operator '&', the
8828     //      operator '->', or the operator 'co_await', the
8829     //      built-in candidates set is empty.
8830     break;
8831 
8832   case OO_Plus: // '+' is either unary or binary
8833     if (Args.size() == 1)
8834       OpBuilder.addUnaryPlusPointerOverloads();
8835     LLVM_FALLTHROUGH;
8836 
8837   case OO_Minus: // '-' is either unary or binary
8838     if (Args.size() == 1) {
8839       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8840     } else {
8841       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8842       OpBuilder.addGenericBinaryArithmeticOverloads();
8843     }
8844     break;
8845 
8846   case OO_Star: // '*' is either unary or binary
8847     if (Args.size() == 1)
8848       OpBuilder.addUnaryStarPointerOverloads();
8849     else
8850       OpBuilder.addGenericBinaryArithmeticOverloads();
8851     break;
8852 
8853   case OO_Slash:
8854     OpBuilder.addGenericBinaryArithmeticOverloads();
8855     break;
8856 
8857   case OO_PlusPlus:
8858   case OO_MinusMinus:
8859     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8860     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8861     break;
8862 
8863   case OO_EqualEqual:
8864   case OO_ExclaimEqual:
8865     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8866     LLVM_FALLTHROUGH;
8867 
8868   case OO_Less:
8869   case OO_Greater:
8870   case OO_LessEqual:
8871   case OO_GreaterEqual:
8872     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8873     OpBuilder.addGenericBinaryArithmeticOverloads();
8874     break;
8875 
8876   case OO_Spaceship:
8877     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8878     OpBuilder.addThreeWayArithmeticOverloads();
8879     break;
8880 
8881   case OO_Percent:
8882   case OO_Caret:
8883   case OO_Pipe:
8884   case OO_LessLess:
8885   case OO_GreaterGreater:
8886     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8887     break;
8888 
8889   case OO_Amp: // '&' is either unary or binary
8890     if (Args.size() == 1)
8891       // C++ [over.match.oper]p3:
8892       //   -- For the operator ',', the unary operator '&', or the
8893       //      operator '->', the built-in candidates set is empty.
8894       break;
8895 
8896     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8897     break;
8898 
8899   case OO_Tilde:
8900     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8901     break;
8902 
8903   case OO_Equal:
8904     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8905     LLVM_FALLTHROUGH;
8906 
8907   case OO_PlusEqual:
8908   case OO_MinusEqual:
8909     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8910     LLVM_FALLTHROUGH;
8911 
8912   case OO_StarEqual:
8913   case OO_SlashEqual:
8914     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8915     break;
8916 
8917   case OO_PercentEqual:
8918   case OO_LessLessEqual:
8919   case OO_GreaterGreaterEqual:
8920   case OO_AmpEqual:
8921   case OO_CaretEqual:
8922   case OO_PipeEqual:
8923     OpBuilder.addAssignmentIntegralOverloads();
8924     break;
8925 
8926   case OO_Exclaim:
8927     OpBuilder.addExclaimOverload();
8928     break;
8929 
8930   case OO_AmpAmp:
8931   case OO_PipePipe:
8932     OpBuilder.addAmpAmpOrPipePipeOverload();
8933     break;
8934 
8935   case OO_Subscript:
8936     OpBuilder.addSubscriptOverloads();
8937     break;
8938 
8939   case OO_ArrowStar:
8940     OpBuilder.addArrowStarOverloads();
8941     break;
8942 
8943   case OO_Conditional:
8944     OpBuilder.addConditionalOperatorOverloads();
8945     OpBuilder.addGenericBinaryArithmeticOverloads();
8946     break;
8947   }
8948 }
8949 
8950 /// Add function candidates found via argument-dependent lookup
8951 /// to the set of overloading candidates.
8952 ///
8953 /// This routine performs argument-dependent name lookup based on the
8954 /// given function name (which may also be an operator name) and adds
8955 /// all of the overload candidates found by ADL to the overload
8956 /// candidate set (C++ [basic.lookup.argdep]).
8957 void
8958 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8959                                            SourceLocation Loc,
8960                                            ArrayRef<Expr *> Args,
8961                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8962                                            OverloadCandidateSet& CandidateSet,
8963                                            bool PartialOverloading) {
8964   ADLResult Fns;
8965 
8966   // FIXME: This approach for uniquing ADL results (and removing
8967   // redundant candidates from the set) relies on pointer-equality,
8968   // which means we need to key off the canonical decl.  However,
8969   // always going back to the canonical decl might not get us the
8970   // right set of default arguments.  What default arguments are
8971   // we supposed to consider on ADL candidates, anyway?
8972 
8973   // FIXME: Pass in the explicit template arguments?
8974   ArgumentDependentLookup(Name, Loc, Args, Fns);
8975 
8976   // Erase all of the candidates we already knew about.
8977   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8978                                    CandEnd = CandidateSet.end();
8979        Cand != CandEnd; ++Cand)
8980     if (Cand->Function) {
8981       Fns.erase(Cand->Function);
8982       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8983         Fns.erase(FunTmpl);
8984     }
8985 
8986   // For each of the ADL candidates we found, add it to the overload
8987   // set.
8988   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8989     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8990 
8991     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8992       if (ExplicitTemplateArgs)
8993         continue;
8994 
8995       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8996                            /*SupressUserConversions=*/false, PartialOverloading,
8997                            /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8998     } else {
8999       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
9000                                    ExplicitTemplateArgs, Args, CandidateSet,
9001                                    /*SupressUserConversions=*/false,
9002                                    PartialOverloading, ADLCallKind::UsesADL);
9003     }
9004   }
9005 }
9006 
9007 namespace {
9008 enum class Comparison { Equal, Better, Worse };
9009 }
9010 
9011 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9012 /// overload resolution.
9013 ///
9014 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9015 /// Cand1's first N enable_if attributes have precisely the same conditions as
9016 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9017 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9018 ///
9019 /// Note that you can have a pair of candidates such that Cand1's enable_if
9020 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9021 /// worse than Cand1's.
9022 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9023                                        const FunctionDecl *Cand2) {
9024   // Common case: One (or both) decls don't have enable_if attrs.
9025   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9026   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9027   if (!Cand1Attr || !Cand2Attr) {
9028     if (Cand1Attr == Cand2Attr)
9029       return Comparison::Equal;
9030     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9031   }
9032 
9033   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9034   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9035 
9036   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9037   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9038     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9039     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9040 
9041     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9042     // has fewer enable_if attributes than Cand2, and vice versa.
9043     if (!Cand1A)
9044       return Comparison::Worse;
9045     if (!Cand2A)
9046       return Comparison::Better;
9047 
9048     Cand1ID.clear();
9049     Cand2ID.clear();
9050 
9051     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9052     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9053     if (Cand1ID != Cand2ID)
9054       return Comparison::Worse;
9055   }
9056 
9057   return Comparison::Equal;
9058 }
9059 
9060 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9061                                           const OverloadCandidate &Cand2) {
9062   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9063       !Cand2.Function->isMultiVersion())
9064     return false;
9065 
9066   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9067   // is obviously better.
9068   if (Cand1.Function->isInvalidDecl()) return false;
9069   if (Cand2.Function->isInvalidDecl()) return true;
9070 
9071   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9072   // cpu_dispatch, else arbitrarily based on the identifiers.
9073   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9074   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9075   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9076   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9077 
9078   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9079     return false;
9080 
9081   if (Cand1CPUDisp && !Cand2CPUDisp)
9082     return true;
9083   if (Cand2CPUDisp && !Cand1CPUDisp)
9084     return false;
9085 
9086   if (Cand1CPUSpec && Cand2CPUSpec) {
9087     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9088       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9089 
9090     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9091         FirstDiff = std::mismatch(
9092             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9093             Cand2CPUSpec->cpus_begin(),
9094             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9095               return LHS->getName() == RHS->getName();
9096             });
9097 
9098     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9099            "Two different cpu-specific versions should not have the same "
9100            "identifier list, otherwise they'd be the same decl!");
9101     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9102   }
9103   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9104 }
9105 
9106 /// isBetterOverloadCandidate - Determines whether the first overload
9107 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9108 bool clang::isBetterOverloadCandidate(
9109     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9110     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9111   // Define viable functions to be better candidates than non-viable
9112   // functions.
9113   if (!Cand2.Viable)
9114     return Cand1.Viable;
9115   else if (!Cand1.Viable)
9116     return false;
9117 
9118   // C++ [over.match.best]p1:
9119   //
9120   //   -- if F is a static member function, ICS1(F) is defined such
9121   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9122   //      any function G, and, symmetrically, ICS1(G) is neither
9123   //      better nor worse than ICS1(F).
9124   unsigned StartArg = 0;
9125   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9126     StartArg = 1;
9127 
9128   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9129     // We don't allow incompatible pointer conversions in C++.
9130     if (!S.getLangOpts().CPlusPlus)
9131       return ICS.isStandard() &&
9132              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9133 
9134     // The only ill-formed conversion we allow in C++ is the string literal to
9135     // char* conversion, which is only considered ill-formed after C++11.
9136     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9137            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9138   };
9139 
9140   // Define functions that don't require ill-formed conversions for a given
9141   // argument to be better candidates than functions that do.
9142   unsigned NumArgs = Cand1.Conversions.size();
9143   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9144   bool HasBetterConversion = false;
9145   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9146     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9147     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9148     if (Cand1Bad != Cand2Bad) {
9149       if (Cand1Bad)
9150         return false;
9151       HasBetterConversion = true;
9152     }
9153   }
9154 
9155   if (HasBetterConversion)
9156     return true;
9157 
9158   // C++ [over.match.best]p1:
9159   //   A viable function F1 is defined to be a better function than another
9160   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9161   //   conversion sequence than ICSi(F2), and then...
9162   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9163     switch (CompareImplicitConversionSequences(S, Loc,
9164                                                Cand1.Conversions[ArgIdx],
9165                                                Cand2.Conversions[ArgIdx])) {
9166     case ImplicitConversionSequence::Better:
9167       // Cand1 has a better conversion sequence.
9168       HasBetterConversion = true;
9169       break;
9170 
9171     case ImplicitConversionSequence::Worse:
9172       // Cand1 can't be better than Cand2.
9173       return false;
9174 
9175     case ImplicitConversionSequence::Indistinguishable:
9176       // Do nothing.
9177       break;
9178     }
9179   }
9180 
9181   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9182   //       ICSj(F2), or, if not that,
9183   if (HasBetterConversion)
9184     return true;
9185 
9186   //   -- the context is an initialization by user-defined conversion
9187   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9188   //      from the return type of F1 to the destination type (i.e.,
9189   //      the type of the entity being initialized) is a better
9190   //      conversion sequence than the standard conversion sequence
9191   //      from the return type of F2 to the destination type.
9192   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9193       Cand1.Function && Cand2.Function &&
9194       isa<CXXConversionDecl>(Cand1.Function) &&
9195       isa<CXXConversionDecl>(Cand2.Function)) {
9196     // First check whether we prefer one of the conversion functions over the
9197     // other. This only distinguishes the results in non-standard, extension
9198     // cases such as the conversion from a lambda closure type to a function
9199     // pointer or block.
9200     ImplicitConversionSequence::CompareKind Result =
9201         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9202     if (Result == ImplicitConversionSequence::Indistinguishable)
9203       Result = CompareStandardConversionSequences(S, Loc,
9204                                                   Cand1.FinalConversion,
9205                                                   Cand2.FinalConversion);
9206 
9207     if (Result != ImplicitConversionSequence::Indistinguishable)
9208       return Result == ImplicitConversionSequence::Better;
9209 
9210     // FIXME: Compare kind of reference binding if conversion functions
9211     // convert to a reference type used in direct reference binding, per
9212     // C++14 [over.match.best]p1 section 2 bullet 3.
9213   }
9214 
9215   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9216   // as combined with the resolution to CWG issue 243.
9217   //
9218   // When the context is initialization by constructor ([over.match.ctor] or
9219   // either phase of [over.match.list]), a constructor is preferred over
9220   // a conversion function.
9221   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9222       Cand1.Function && Cand2.Function &&
9223       isa<CXXConstructorDecl>(Cand1.Function) !=
9224           isa<CXXConstructorDecl>(Cand2.Function))
9225     return isa<CXXConstructorDecl>(Cand1.Function);
9226 
9227   //    -- F1 is a non-template function and F2 is a function template
9228   //       specialization, or, if not that,
9229   bool Cand1IsSpecialization = Cand1.Function &&
9230                                Cand1.Function->getPrimaryTemplate();
9231   bool Cand2IsSpecialization = Cand2.Function &&
9232                                Cand2.Function->getPrimaryTemplate();
9233   if (Cand1IsSpecialization != Cand2IsSpecialization)
9234     return Cand2IsSpecialization;
9235 
9236   //   -- F1 and F2 are function template specializations, and the function
9237   //      template for F1 is more specialized than the template for F2
9238   //      according to the partial ordering rules described in 14.5.5.2, or,
9239   //      if not that,
9240   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9241     if (FunctionTemplateDecl *BetterTemplate
9242           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9243                                          Cand2.Function->getPrimaryTemplate(),
9244                                          Loc,
9245                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9246                                                              : TPOC_Call,
9247                                          Cand1.ExplicitCallArguments,
9248                                          Cand2.ExplicitCallArguments))
9249       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9250   }
9251 
9252   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9253   // A derived-class constructor beats an (inherited) base class constructor.
9254   bool Cand1IsInherited =
9255       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9256   bool Cand2IsInherited =
9257       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9258   if (Cand1IsInherited != Cand2IsInherited)
9259     return Cand2IsInherited;
9260   else if (Cand1IsInherited) {
9261     assert(Cand2IsInherited);
9262     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9263     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9264     if (Cand1Class->isDerivedFrom(Cand2Class))
9265       return true;
9266     if (Cand2Class->isDerivedFrom(Cand1Class))
9267       return false;
9268     // Inherited from sibling base classes: still ambiguous.
9269   }
9270 
9271   // Check C++17 tie-breakers for deduction guides.
9272   {
9273     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9274     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9275     if (Guide1 && Guide2) {
9276       //  -- F1 is generated from a deduction-guide and F2 is not
9277       if (Guide1->isImplicit() != Guide2->isImplicit())
9278         return Guide2->isImplicit();
9279 
9280       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9281       if (Guide1->isCopyDeductionCandidate())
9282         return true;
9283     }
9284   }
9285 
9286   // Check for enable_if value-based overload resolution.
9287   if (Cand1.Function && Cand2.Function) {
9288     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9289     if (Cmp != Comparison::Equal)
9290       return Cmp == Comparison::Better;
9291   }
9292 
9293   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9294     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9295     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9296            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9297   }
9298 
9299   bool HasPS1 = Cand1.Function != nullptr &&
9300                 functionHasPassObjectSizeParams(Cand1.Function);
9301   bool HasPS2 = Cand2.Function != nullptr &&
9302                 functionHasPassObjectSizeParams(Cand2.Function);
9303   if (HasPS1 != HasPS2 && HasPS1)
9304     return true;
9305 
9306   return isBetterMultiversionCandidate(Cand1, Cand2);
9307 }
9308 
9309 /// Determine whether two declarations are "equivalent" for the purposes of
9310 /// name lookup and overload resolution. This applies when the same internal/no
9311 /// linkage entity is defined by two modules (probably by textually including
9312 /// the same header). In such a case, we don't consider the declarations to
9313 /// declare the same entity, but we also don't want lookups with both
9314 /// declarations visible to be ambiguous in some cases (this happens when using
9315 /// a modularized libstdc++).
9316 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9317                                                   const NamedDecl *B) {
9318   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9319   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9320   if (!VA || !VB)
9321     return false;
9322 
9323   // The declarations must be declaring the same name as an internal linkage
9324   // entity in different modules.
9325   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9326           VB->getDeclContext()->getRedeclContext()) ||
9327       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9328           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9329       VA->isExternallyVisible() || VB->isExternallyVisible())
9330     return false;
9331 
9332   // Check that the declarations appear to be equivalent.
9333   //
9334   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9335   // For constants and functions, we should check the initializer or body is
9336   // the same. For non-constant variables, we shouldn't allow it at all.
9337   if (Context.hasSameType(VA->getType(), VB->getType()))
9338     return true;
9339 
9340   // Enum constants within unnamed enumerations will have different types, but
9341   // may still be similar enough to be interchangeable for our purposes.
9342   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9343     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9344       // Only handle anonymous enums. If the enumerations were named and
9345       // equivalent, they would have been merged to the same type.
9346       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9347       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9348       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9349           !Context.hasSameType(EnumA->getIntegerType(),
9350                                EnumB->getIntegerType()))
9351         return false;
9352       // Allow this only if the value is the same for both enumerators.
9353       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9354     }
9355   }
9356 
9357   // Nothing else is sufficiently similar.
9358   return false;
9359 }
9360 
9361 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9362     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9363   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9364 
9365   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9366   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9367       << !M << (M ? M->getFullModuleName() : "");
9368 
9369   for (auto *E : Equiv) {
9370     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9371     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9372         << !M << (M ? M->getFullModuleName() : "");
9373   }
9374 }
9375 
9376 /// Computes the best viable function (C++ 13.3.3)
9377 /// within an overload candidate set.
9378 ///
9379 /// \param Loc The location of the function name (or operator symbol) for
9380 /// which overload resolution occurs.
9381 ///
9382 /// \param Best If overload resolution was successful or found a deleted
9383 /// function, \p Best points to the candidate function found.
9384 ///
9385 /// \returns The result of overload resolution.
9386 OverloadingResult
9387 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9388                                          iterator &Best) {
9389   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9390   std::transform(begin(), end(), std::back_inserter(Candidates),
9391                  [](OverloadCandidate &Cand) { return &Cand; });
9392 
9393   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9394   // are accepted by both clang and NVCC. However, during a particular
9395   // compilation mode only one call variant is viable. We need to
9396   // exclude non-viable overload candidates from consideration based
9397   // only on their host/device attributes. Specifically, if one
9398   // candidate call is WrongSide and the other is SameSide, we ignore
9399   // the WrongSide candidate.
9400   if (S.getLangOpts().CUDA) {
9401     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9402     bool ContainsSameSideCandidate =
9403         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9404           return Cand->Function &&
9405                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9406                      Sema::CFP_SameSide;
9407         });
9408     if (ContainsSameSideCandidate) {
9409       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9410         return Cand->Function &&
9411                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9412                    Sema::CFP_WrongSide;
9413       };
9414       llvm::erase_if(Candidates, IsWrongSideCandidate);
9415     }
9416   }
9417 
9418   // Find the best viable function.
9419   Best = end();
9420   for (auto *Cand : Candidates)
9421     if (Cand->Viable)
9422       if (Best == end() ||
9423           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9424         Best = Cand;
9425 
9426   // If we didn't find any viable functions, abort.
9427   if (Best == end())
9428     return OR_No_Viable_Function;
9429 
9430   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9431 
9432   // Make sure that this function is better than every other viable
9433   // function. If not, we have an ambiguity.
9434   for (auto *Cand : Candidates) {
9435     if (Cand->Viable && Cand != Best &&
9436         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9437       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9438                                                    Cand->Function)) {
9439         EquivalentCands.push_back(Cand->Function);
9440         continue;
9441       }
9442 
9443       Best = end();
9444       return OR_Ambiguous;
9445     }
9446   }
9447 
9448   // Best is the best viable function.
9449   if (Best->Function &&
9450       (Best->Function->isDeleted() ||
9451        S.isFunctionConsideredUnavailable(Best->Function)))
9452     return OR_Deleted;
9453 
9454   if (!EquivalentCands.empty())
9455     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9456                                                     EquivalentCands);
9457 
9458   return OR_Success;
9459 }
9460 
9461 namespace {
9462 
9463 enum OverloadCandidateKind {
9464   oc_function,
9465   oc_method,
9466   oc_constructor,
9467   oc_implicit_default_constructor,
9468   oc_implicit_copy_constructor,
9469   oc_implicit_move_constructor,
9470   oc_implicit_copy_assignment,
9471   oc_implicit_move_assignment,
9472   oc_inherited_constructor
9473 };
9474 
9475 enum OverloadCandidateSelect {
9476   ocs_non_template,
9477   ocs_template,
9478   ocs_described_template,
9479 };
9480 
9481 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9482 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9483                           std::string &Description) {
9484 
9485   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9486   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9487     isTemplate = true;
9488     Description = S.getTemplateArgumentBindingsText(
9489         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9490   }
9491 
9492   OverloadCandidateSelect Select = [&]() {
9493     if (!Description.empty())
9494       return ocs_described_template;
9495     return isTemplate ? ocs_template : ocs_non_template;
9496   }();
9497 
9498   OverloadCandidateKind Kind = [&]() {
9499     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9500       if (!Ctor->isImplicit()) {
9501         if (isa<ConstructorUsingShadowDecl>(Found))
9502           return oc_inherited_constructor;
9503         else
9504           return oc_constructor;
9505       }
9506 
9507       if (Ctor->isDefaultConstructor())
9508         return oc_implicit_default_constructor;
9509 
9510       if (Ctor->isMoveConstructor())
9511         return oc_implicit_move_constructor;
9512 
9513       assert(Ctor->isCopyConstructor() &&
9514              "unexpected sort of implicit constructor");
9515       return oc_implicit_copy_constructor;
9516     }
9517 
9518     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9519       // This actually gets spelled 'candidate function' for now, but
9520       // it doesn't hurt to split it out.
9521       if (!Meth->isImplicit())
9522         return oc_method;
9523 
9524       if (Meth->isMoveAssignmentOperator())
9525         return oc_implicit_move_assignment;
9526 
9527       if (Meth->isCopyAssignmentOperator())
9528         return oc_implicit_copy_assignment;
9529 
9530       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9531       return oc_method;
9532     }
9533 
9534     return oc_function;
9535   }();
9536 
9537   return std::make_pair(Kind, Select);
9538 }
9539 
9540 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9541   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9542   // set.
9543   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9544     S.Diag(FoundDecl->getLocation(),
9545            diag::note_ovl_candidate_inherited_constructor)
9546       << Shadow->getNominatedBaseClass();
9547 }
9548 
9549 } // end anonymous namespace
9550 
9551 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9552                                     const FunctionDecl *FD) {
9553   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9554     bool AlwaysTrue;
9555     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9556       return false;
9557     if (!AlwaysTrue)
9558       return false;
9559   }
9560   return true;
9561 }
9562 
9563 /// Returns true if we can take the address of the function.
9564 ///
9565 /// \param Complain - If true, we'll emit a diagnostic
9566 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9567 ///   we in overload resolution?
9568 /// \param Loc - The location of the statement we're complaining about. Ignored
9569 ///   if we're not complaining, or if we're in overload resolution.
9570 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9571                                               bool Complain,
9572                                               bool InOverloadResolution,
9573                                               SourceLocation Loc) {
9574   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9575     if (Complain) {
9576       if (InOverloadResolution)
9577         S.Diag(FD->getBeginLoc(),
9578                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9579       else
9580         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9581     }
9582     return false;
9583   }
9584 
9585   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9586     return P->hasAttr<PassObjectSizeAttr>();
9587   });
9588   if (I == FD->param_end())
9589     return true;
9590 
9591   if (Complain) {
9592     // Add one to ParamNo because it's user-facing
9593     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9594     if (InOverloadResolution)
9595       S.Diag(FD->getLocation(),
9596              diag::note_ovl_candidate_has_pass_object_size_params)
9597           << ParamNo;
9598     else
9599       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9600           << FD << ParamNo;
9601   }
9602   return false;
9603 }
9604 
9605 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9606                                                const FunctionDecl *FD) {
9607   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9608                                            /*InOverloadResolution=*/true,
9609                                            /*Loc=*/SourceLocation());
9610 }
9611 
9612 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9613                                              bool Complain,
9614                                              SourceLocation Loc) {
9615   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9616                                              /*InOverloadResolution=*/false,
9617                                              Loc);
9618 }
9619 
9620 // Notes the location of an overload candidate.
9621 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9622                                  QualType DestType, bool TakingAddress) {
9623   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9624     return;
9625   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9626       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9627     return;
9628 
9629   std::string FnDesc;
9630   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9631       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9632   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9633                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9634                          << Fn << FnDesc;
9635 
9636   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9637   Diag(Fn->getLocation(), PD);
9638   MaybeEmitInheritedConstructorNote(*this, Found);
9639 }
9640 
9641 // Notes the location of all overload candidates designated through
9642 // OverloadedExpr
9643 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9644                                      bool TakingAddress) {
9645   assert(OverloadedExpr->getType() == Context.OverloadTy);
9646 
9647   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9648   OverloadExpr *OvlExpr = Ovl.Expression;
9649 
9650   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9651                             IEnd = OvlExpr->decls_end();
9652        I != IEnd; ++I) {
9653     if (FunctionTemplateDecl *FunTmpl =
9654                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9655       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9656                             TakingAddress);
9657     } else if (FunctionDecl *Fun
9658                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9659       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9660     }
9661   }
9662 }
9663 
9664 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9665 /// "lead" diagnostic; it will be given two arguments, the source and
9666 /// target types of the conversion.
9667 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9668                                  Sema &S,
9669                                  SourceLocation CaretLoc,
9670                                  const PartialDiagnostic &PDiag) const {
9671   S.Diag(CaretLoc, PDiag)
9672     << Ambiguous.getFromType() << Ambiguous.getToType();
9673   // FIXME: The note limiting machinery is borrowed from
9674   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9675   // refactoring here.
9676   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9677   unsigned CandsShown = 0;
9678   AmbiguousConversionSequence::const_iterator I, E;
9679   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9680     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9681       break;
9682     ++CandsShown;
9683     S.NoteOverloadCandidate(I->first, I->second);
9684   }
9685   if (I != E)
9686     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9687 }
9688 
9689 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9690                                   unsigned I, bool TakingCandidateAddress) {
9691   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9692   assert(Conv.isBad());
9693   assert(Cand->Function && "for now, candidate must be a function");
9694   FunctionDecl *Fn = Cand->Function;
9695 
9696   // There's a conversion slot for the object argument if this is a
9697   // non-constructor method.  Note that 'I' corresponds the
9698   // conversion-slot index.
9699   bool isObjectArgument = false;
9700   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9701     if (I == 0)
9702       isObjectArgument = true;
9703     else
9704       I--;
9705   }
9706 
9707   std::string FnDesc;
9708   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9709       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9710 
9711   Expr *FromExpr = Conv.Bad.FromExpr;
9712   QualType FromTy = Conv.Bad.getFromType();
9713   QualType ToTy = Conv.Bad.getToType();
9714 
9715   if (FromTy == S.Context.OverloadTy) {
9716     assert(FromExpr && "overload set argument came from implicit argument?");
9717     Expr *E = FromExpr->IgnoreParens();
9718     if (isa<UnaryOperator>(E))
9719       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9720     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9721 
9722     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9723         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9724         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9725         << Name << I + 1;
9726     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9727     return;
9728   }
9729 
9730   // Do some hand-waving analysis to see if the non-viability is due
9731   // to a qualifier mismatch.
9732   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9733   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9734   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9735     CToTy = RT->getPointeeType();
9736   else {
9737     // TODO: detect and diagnose the full richness of const mismatches.
9738     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9739       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9740         CFromTy = FromPT->getPointeeType();
9741         CToTy = ToPT->getPointeeType();
9742       }
9743   }
9744 
9745   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9746       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9747     Qualifiers FromQs = CFromTy.getQualifiers();
9748     Qualifiers ToQs = CToTy.getQualifiers();
9749 
9750     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9751       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9752           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9753           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9754           << ToTy << (unsigned)isObjectArgument << I + 1;
9755       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9756       return;
9757     }
9758 
9759     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9760       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9761           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9762           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9763           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9764           << (unsigned)isObjectArgument << I + 1;
9765       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9766       return;
9767     }
9768 
9769     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9770       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9771           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9772           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9773           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9774           << (unsigned)isObjectArgument << I + 1;
9775       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9776       return;
9777     }
9778 
9779     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9780       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9781           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9782           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9783           << FromQs.hasUnaligned() << I + 1;
9784       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9785       return;
9786     }
9787 
9788     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9789     assert(CVR && "unexpected qualifiers mismatch");
9790 
9791     if (isObjectArgument) {
9792       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9793           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9794           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9795           << (CVR - 1);
9796     } else {
9797       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9798           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9799           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9800           << (CVR - 1) << I + 1;
9801     }
9802     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9803     return;
9804   }
9805 
9806   // Special diagnostic for failure to convert an initializer list, since
9807   // telling the user that it has type void is not useful.
9808   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9809     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9810         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9811         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9812         << ToTy << (unsigned)isObjectArgument << I + 1;
9813     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9814     return;
9815   }
9816 
9817   // Diagnose references or pointers to incomplete types differently,
9818   // since it's far from impossible that the incompleteness triggered
9819   // the failure.
9820   QualType TempFromTy = FromTy.getNonReferenceType();
9821   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9822     TempFromTy = PTy->getPointeeType();
9823   if (TempFromTy->isIncompleteType()) {
9824     // Emit the generic diagnostic and, optionally, add the hints to it.
9825     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9826         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9827         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9828         << ToTy << (unsigned)isObjectArgument << I + 1
9829         << (unsigned)(Cand->Fix.Kind);
9830 
9831     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9832     return;
9833   }
9834 
9835   // Diagnose base -> derived pointer conversions.
9836   unsigned BaseToDerivedConversion = 0;
9837   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9838     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9839       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9840                                                FromPtrTy->getPointeeType()) &&
9841           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9842           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9843           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9844                           FromPtrTy->getPointeeType()))
9845         BaseToDerivedConversion = 1;
9846     }
9847   } else if (const ObjCObjectPointerType *FromPtrTy
9848                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9849     if (const ObjCObjectPointerType *ToPtrTy
9850                                         = ToTy->getAs<ObjCObjectPointerType>())
9851       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9852         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9853           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9854                                                 FromPtrTy->getPointeeType()) &&
9855               FromIface->isSuperClassOf(ToIface))
9856             BaseToDerivedConversion = 2;
9857   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9858     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9859         !FromTy->isIncompleteType() &&
9860         !ToRefTy->getPointeeType()->isIncompleteType() &&
9861         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9862       BaseToDerivedConversion = 3;
9863     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9864                ToTy.getNonReferenceType().getCanonicalType() ==
9865                FromTy.getNonReferenceType().getCanonicalType()) {
9866       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9867           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9868           << (unsigned)isObjectArgument << I + 1
9869           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9870       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9871       return;
9872     }
9873   }
9874 
9875   if (BaseToDerivedConversion) {
9876     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9877         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9878         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9879         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9880     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9881     return;
9882   }
9883 
9884   if (isa<ObjCObjectPointerType>(CFromTy) &&
9885       isa<PointerType>(CToTy)) {
9886       Qualifiers FromQs = CFromTy.getQualifiers();
9887       Qualifiers ToQs = CToTy.getQualifiers();
9888       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9889         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9890             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9891             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9892             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9893         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9894         return;
9895       }
9896   }
9897 
9898   if (TakingCandidateAddress &&
9899       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9900     return;
9901 
9902   // Emit the generic diagnostic and, optionally, add the hints to it.
9903   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9904   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9905         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9906         << ToTy << (unsigned)isObjectArgument << I + 1
9907         << (unsigned)(Cand->Fix.Kind);
9908 
9909   // If we can fix the conversion, suggest the FixIts.
9910   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9911        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9912     FDiag << *HI;
9913   S.Diag(Fn->getLocation(), FDiag);
9914 
9915   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9916 }
9917 
9918 /// Additional arity mismatch diagnosis specific to a function overload
9919 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9920 /// over a candidate in any candidate set.
9921 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9922                                unsigned NumArgs) {
9923   FunctionDecl *Fn = Cand->Function;
9924   unsigned MinParams = Fn->getMinRequiredArguments();
9925 
9926   // With invalid overloaded operators, it's possible that we think we
9927   // have an arity mismatch when in fact it looks like we have the
9928   // right number of arguments, because only overloaded operators have
9929   // the weird behavior of overloading member and non-member functions.
9930   // Just don't report anything.
9931   if (Fn->isInvalidDecl() &&
9932       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9933     return true;
9934 
9935   if (NumArgs < MinParams) {
9936     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9937            (Cand->FailureKind == ovl_fail_bad_deduction &&
9938             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9939   } else {
9940     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9941            (Cand->FailureKind == ovl_fail_bad_deduction &&
9942             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9943   }
9944 
9945   return false;
9946 }
9947 
9948 /// General arity mismatch diagnosis over a candidate in a candidate set.
9949 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9950                                   unsigned NumFormalArgs) {
9951   assert(isa<FunctionDecl>(D) &&
9952       "The templated declaration should at least be a function"
9953       " when diagnosing bad template argument deduction due to too many"
9954       " or too few arguments");
9955 
9956   FunctionDecl *Fn = cast<FunctionDecl>(D);
9957 
9958   // TODO: treat calls to a missing default constructor as a special case
9959   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9960   unsigned MinParams = Fn->getMinRequiredArguments();
9961 
9962   // at least / at most / exactly
9963   unsigned mode, modeCount;
9964   if (NumFormalArgs < MinParams) {
9965     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9966         FnTy->isTemplateVariadic())
9967       mode = 0; // "at least"
9968     else
9969       mode = 2; // "exactly"
9970     modeCount = MinParams;
9971   } else {
9972     if (MinParams != FnTy->getNumParams())
9973       mode = 1; // "at most"
9974     else
9975       mode = 2; // "exactly"
9976     modeCount = FnTy->getNumParams();
9977   }
9978 
9979   std::string Description;
9980   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9981       ClassifyOverloadCandidate(S, Found, Fn, Description);
9982 
9983   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9984     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9985         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9986         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9987   else
9988     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9989         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9990         << Description << mode << modeCount << NumFormalArgs;
9991 
9992   MaybeEmitInheritedConstructorNote(S, Found);
9993 }
9994 
9995 /// Arity mismatch diagnosis specific to a function overload candidate.
9996 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9997                                   unsigned NumFormalArgs) {
9998   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9999     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10000 }
10001 
10002 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10003   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10004     return TD;
10005   llvm_unreachable("Unsupported: Getting the described template declaration"
10006                    " for bad deduction diagnosis");
10007 }
10008 
10009 /// Diagnose a failed template-argument deduction.
10010 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10011                                  DeductionFailureInfo &DeductionFailure,
10012                                  unsigned NumArgs,
10013                                  bool TakingCandidateAddress) {
10014   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10015   NamedDecl *ParamD;
10016   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10017   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10018   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10019   switch (DeductionFailure.Result) {
10020   case Sema::TDK_Success:
10021     llvm_unreachable("TDK_success while diagnosing bad deduction");
10022 
10023   case Sema::TDK_Incomplete: {
10024     assert(ParamD && "no parameter found for incomplete deduction result");
10025     S.Diag(Templated->getLocation(),
10026            diag::note_ovl_candidate_incomplete_deduction)
10027         << ParamD->getDeclName();
10028     MaybeEmitInheritedConstructorNote(S, Found);
10029     return;
10030   }
10031 
10032   case Sema::TDK_IncompletePack: {
10033     assert(ParamD && "no parameter found for incomplete deduction result");
10034     S.Diag(Templated->getLocation(),
10035            diag::note_ovl_candidate_incomplete_deduction_pack)
10036         << ParamD->getDeclName()
10037         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10038         << *DeductionFailure.getFirstArg();
10039     MaybeEmitInheritedConstructorNote(S, Found);
10040     return;
10041   }
10042 
10043   case Sema::TDK_Underqualified: {
10044     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10045     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10046 
10047     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10048 
10049     // Param will have been canonicalized, but it should just be a
10050     // qualified version of ParamD, so move the qualifiers to that.
10051     QualifierCollector Qs;
10052     Qs.strip(Param);
10053     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10054     assert(S.Context.hasSameType(Param, NonCanonParam));
10055 
10056     // Arg has also been canonicalized, but there's nothing we can do
10057     // about that.  It also doesn't matter as much, because it won't
10058     // have any template parameters in it (because deduction isn't
10059     // done on dependent types).
10060     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10061 
10062     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10063         << ParamD->getDeclName() << Arg << NonCanonParam;
10064     MaybeEmitInheritedConstructorNote(S, Found);
10065     return;
10066   }
10067 
10068   case Sema::TDK_Inconsistent: {
10069     assert(ParamD && "no parameter found for inconsistent deduction result");
10070     int which = 0;
10071     if (isa<TemplateTypeParmDecl>(ParamD))
10072       which = 0;
10073     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10074       // Deduction might have failed because we deduced arguments of two
10075       // different types for a non-type template parameter.
10076       // FIXME: Use a different TDK value for this.
10077       QualType T1 =
10078           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10079       QualType T2 =
10080           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10081       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10082         S.Diag(Templated->getLocation(),
10083                diag::note_ovl_candidate_inconsistent_deduction_types)
10084           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10085           << *DeductionFailure.getSecondArg() << T2;
10086         MaybeEmitInheritedConstructorNote(S, Found);
10087         return;
10088       }
10089 
10090       which = 1;
10091     } else {
10092       which = 2;
10093     }
10094 
10095     S.Diag(Templated->getLocation(),
10096            diag::note_ovl_candidate_inconsistent_deduction)
10097         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10098         << *DeductionFailure.getSecondArg();
10099     MaybeEmitInheritedConstructorNote(S, Found);
10100     return;
10101   }
10102 
10103   case Sema::TDK_InvalidExplicitArguments:
10104     assert(ParamD && "no parameter found for invalid explicit arguments");
10105     if (ParamD->getDeclName())
10106       S.Diag(Templated->getLocation(),
10107              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10108           << ParamD->getDeclName();
10109     else {
10110       int index = 0;
10111       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10112         index = TTP->getIndex();
10113       else if (NonTypeTemplateParmDecl *NTTP
10114                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10115         index = NTTP->getIndex();
10116       else
10117         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10118       S.Diag(Templated->getLocation(),
10119              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10120           << (index + 1);
10121     }
10122     MaybeEmitInheritedConstructorNote(S, Found);
10123     return;
10124 
10125   case Sema::TDK_TooManyArguments:
10126   case Sema::TDK_TooFewArguments:
10127     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10128     return;
10129 
10130   case Sema::TDK_InstantiationDepth:
10131     S.Diag(Templated->getLocation(),
10132            diag::note_ovl_candidate_instantiation_depth);
10133     MaybeEmitInheritedConstructorNote(S, Found);
10134     return;
10135 
10136   case Sema::TDK_SubstitutionFailure: {
10137     // Format the template argument list into the argument string.
10138     SmallString<128> TemplateArgString;
10139     if (TemplateArgumentList *Args =
10140             DeductionFailure.getTemplateArgumentList()) {
10141       TemplateArgString = " ";
10142       TemplateArgString += S.getTemplateArgumentBindingsText(
10143           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10144     }
10145 
10146     // If this candidate was disabled by enable_if, say so.
10147     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10148     if (PDiag && PDiag->second.getDiagID() ==
10149           diag::err_typename_nested_not_found_enable_if) {
10150       // FIXME: Use the source range of the condition, and the fully-qualified
10151       //        name of the enable_if template. These are both present in PDiag.
10152       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10153         << "'enable_if'" << TemplateArgString;
10154       return;
10155     }
10156 
10157     // We found a specific requirement that disabled the enable_if.
10158     if (PDiag && PDiag->second.getDiagID() ==
10159         diag::err_typename_nested_not_found_requirement) {
10160       S.Diag(Templated->getLocation(),
10161              diag::note_ovl_candidate_disabled_by_requirement)
10162         << PDiag->second.getStringArg(0) << TemplateArgString;
10163       return;
10164     }
10165 
10166     // Format the SFINAE diagnostic into the argument string.
10167     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10168     //        formatted message in another diagnostic.
10169     SmallString<128> SFINAEArgString;
10170     SourceRange R;
10171     if (PDiag) {
10172       SFINAEArgString = ": ";
10173       R = SourceRange(PDiag->first, PDiag->first);
10174       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10175     }
10176 
10177     S.Diag(Templated->getLocation(),
10178            diag::note_ovl_candidate_substitution_failure)
10179         << TemplateArgString << SFINAEArgString << R;
10180     MaybeEmitInheritedConstructorNote(S, Found);
10181     return;
10182   }
10183 
10184   case Sema::TDK_DeducedMismatch:
10185   case Sema::TDK_DeducedMismatchNested: {
10186     // Format the template argument list into the argument string.
10187     SmallString<128> TemplateArgString;
10188     if (TemplateArgumentList *Args =
10189             DeductionFailure.getTemplateArgumentList()) {
10190       TemplateArgString = " ";
10191       TemplateArgString += S.getTemplateArgumentBindingsText(
10192           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10193     }
10194 
10195     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10196         << (*DeductionFailure.getCallArgIndex() + 1)
10197         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10198         << TemplateArgString
10199         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10200     break;
10201   }
10202 
10203   case Sema::TDK_NonDeducedMismatch: {
10204     // FIXME: Provide a source location to indicate what we couldn't match.
10205     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10206     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10207     if (FirstTA.getKind() == TemplateArgument::Template &&
10208         SecondTA.getKind() == TemplateArgument::Template) {
10209       TemplateName FirstTN = FirstTA.getAsTemplate();
10210       TemplateName SecondTN = SecondTA.getAsTemplate();
10211       if (FirstTN.getKind() == TemplateName::Template &&
10212           SecondTN.getKind() == TemplateName::Template) {
10213         if (FirstTN.getAsTemplateDecl()->getName() ==
10214             SecondTN.getAsTemplateDecl()->getName()) {
10215           // FIXME: This fixes a bad diagnostic where both templates are named
10216           // the same.  This particular case is a bit difficult since:
10217           // 1) It is passed as a string to the diagnostic printer.
10218           // 2) The diagnostic printer only attempts to find a better
10219           //    name for types, not decls.
10220           // Ideally, this should folded into the diagnostic printer.
10221           S.Diag(Templated->getLocation(),
10222                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10223               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10224           return;
10225         }
10226       }
10227     }
10228 
10229     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10230         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10231       return;
10232 
10233     // FIXME: For generic lambda parameters, check if the function is a lambda
10234     // call operator, and if so, emit a prettier and more informative
10235     // diagnostic that mentions 'auto' and lambda in addition to
10236     // (or instead of?) the canonical template type parameters.
10237     S.Diag(Templated->getLocation(),
10238            diag::note_ovl_candidate_non_deduced_mismatch)
10239         << FirstTA << SecondTA;
10240     return;
10241   }
10242   // TODO: diagnose these individually, then kill off
10243   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10244   case Sema::TDK_MiscellaneousDeductionFailure:
10245     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10246     MaybeEmitInheritedConstructorNote(S, Found);
10247     return;
10248   case Sema::TDK_CUDATargetMismatch:
10249     S.Diag(Templated->getLocation(),
10250            diag::note_cuda_ovl_candidate_target_mismatch);
10251     return;
10252   }
10253 }
10254 
10255 /// Diagnose a failed template-argument deduction, for function calls.
10256 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10257                                  unsigned NumArgs,
10258                                  bool TakingCandidateAddress) {
10259   unsigned TDK = Cand->DeductionFailure.Result;
10260   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10261     if (CheckArityMismatch(S, Cand, NumArgs))
10262       return;
10263   }
10264   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10265                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10266 }
10267 
10268 /// CUDA: diagnose an invalid call across targets.
10269 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10270   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10271   FunctionDecl *Callee = Cand->Function;
10272 
10273   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10274                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10275 
10276   std::string FnDesc;
10277   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10278       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10279 
10280   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10281       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10282       << FnDesc /* Ignored */
10283       << CalleeTarget << CallerTarget;
10284 
10285   // This could be an implicit constructor for which we could not infer the
10286   // target due to a collsion. Diagnose that case.
10287   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10288   if (Meth != nullptr && Meth->isImplicit()) {
10289     CXXRecordDecl *ParentClass = Meth->getParent();
10290     Sema::CXXSpecialMember CSM;
10291 
10292     switch (FnKindPair.first) {
10293     default:
10294       return;
10295     case oc_implicit_default_constructor:
10296       CSM = Sema::CXXDefaultConstructor;
10297       break;
10298     case oc_implicit_copy_constructor:
10299       CSM = Sema::CXXCopyConstructor;
10300       break;
10301     case oc_implicit_move_constructor:
10302       CSM = Sema::CXXMoveConstructor;
10303       break;
10304     case oc_implicit_copy_assignment:
10305       CSM = Sema::CXXCopyAssignment;
10306       break;
10307     case oc_implicit_move_assignment:
10308       CSM = Sema::CXXMoveAssignment;
10309       break;
10310     };
10311 
10312     bool ConstRHS = false;
10313     if (Meth->getNumParams()) {
10314       if (const ReferenceType *RT =
10315               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10316         ConstRHS = RT->getPointeeType().isConstQualified();
10317       }
10318     }
10319 
10320     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10321                                               /* ConstRHS */ ConstRHS,
10322                                               /* Diagnose */ true);
10323   }
10324 }
10325 
10326 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10327   FunctionDecl *Callee = Cand->Function;
10328   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10329 
10330   S.Diag(Callee->getLocation(),
10331          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10332       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10333 }
10334 
10335 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10336   FunctionDecl *Callee = Cand->Function;
10337 
10338   S.Diag(Callee->getLocation(),
10339          diag::note_ovl_candidate_disabled_by_extension)
10340     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10341 }
10342 
10343 /// Generates a 'note' diagnostic for an overload candidate.  We've
10344 /// already generated a primary error at the call site.
10345 ///
10346 /// It really does need to be a single diagnostic with its caret
10347 /// pointed at the candidate declaration.  Yes, this creates some
10348 /// major challenges of technical writing.  Yes, this makes pointing
10349 /// out problems with specific arguments quite awkward.  It's still
10350 /// better than generating twenty screens of text for every failed
10351 /// overload.
10352 ///
10353 /// It would be great to be able to express per-candidate problems
10354 /// more richly for those diagnostic clients that cared, but we'd
10355 /// still have to be just as careful with the default diagnostics.
10356 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10357                                   unsigned NumArgs,
10358                                   bool TakingCandidateAddress) {
10359   FunctionDecl *Fn = Cand->Function;
10360 
10361   // Note deleted candidates, but only if they're viable.
10362   if (Cand->Viable) {
10363     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10364       std::string FnDesc;
10365       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10366           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10367 
10368       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10369           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10370           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10371       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10372       return;
10373     }
10374 
10375     // We don't really have anything else to say about viable candidates.
10376     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10377     return;
10378   }
10379 
10380   switch (Cand->FailureKind) {
10381   case ovl_fail_too_many_arguments:
10382   case ovl_fail_too_few_arguments:
10383     return DiagnoseArityMismatch(S, Cand, NumArgs);
10384 
10385   case ovl_fail_bad_deduction:
10386     return DiagnoseBadDeduction(S, Cand, NumArgs,
10387                                 TakingCandidateAddress);
10388 
10389   case ovl_fail_illegal_constructor: {
10390     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10391       << (Fn->getPrimaryTemplate() ? 1 : 0);
10392     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10393     return;
10394   }
10395 
10396   case ovl_fail_trivial_conversion:
10397   case ovl_fail_bad_final_conversion:
10398   case ovl_fail_final_conversion_not_exact:
10399     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10400 
10401   case ovl_fail_bad_conversion: {
10402     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10403     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10404       if (Cand->Conversions[I].isBad())
10405         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10406 
10407     // FIXME: this currently happens when we're called from SemaInit
10408     // when user-conversion overload fails.  Figure out how to handle
10409     // those conditions and diagnose them well.
10410     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10411   }
10412 
10413   case ovl_fail_bad_target:
10414     return DiagnoseBadTarget(S, Cand);
10415 
10416   case ovl_fail_enable_if:
10417     return DiagnoseFailedEnableIfAttr(S, Cand);
10418 
10419   case ovl_fail_ext_disabled:
10420     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10421 
10422   case ovl_fail_inhctor_slice:
10423     // It's generally not interesting to note copy/move constructors here.
10424     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10425       return;
10426     S.Diag(Fn->getLocation(),
10427            diag::note_ovl_candidate_inherited_constructor_slice)
10428       << (Fn->getPrimaryTemplate() ? 1 : 0)
10429       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10430     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10431     return;
10432 
10433   case ovl_fail_addr_not_available: {
10434     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10435     (void)Available;
10436     assert(!Available);
10437     break;
10438   }
10439   case ovl_non_default_multiversion_function:
10440     // Do nothing, these should simply be ignored.
10441     break;
10442   }
10443 }
10444 
10445 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10446   // Desugar the type of the surrogate down to a function type,
10447   // retaining as many typedefs as possible while still showing
10448   // the function type (and, therefore, its parameter types).
10449   QualType FnType = Cand->Surrogate->getConversionType();
10450   bool isLValueReference = false;
10451   bool isRValueReference = false;
10452   bool isPointer = false;
10453   if (const LValueReferenceType *FnTypeRef =
10454         FnType->getAs<LValueReferenceType>()) {
10455     FnType = FnTypeRef->getPointeeType();
10456     isLValueReference = true;
10457   } else if (const RValueReferenceType *FnTypeRef =
10458                FnType->getAs<RValueReferenceType>()) {
10459     FnType = FnTypeRef->getPointeeType();
10460     isRValueReference = true;
10461   }
10462   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10463     FnType = FnTypePtr->getPointeeType();
10464     isPointer = true;
10465   }
10466   // Desugar down to a function type.
10467   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10468   // Reconstruct the pointer/reference as appropriate.
10469   if (isPointer) FnType = S.Context.getPointerType(FnType);
10470   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10471   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10472 
10473   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10474     << FnType;
10475 }
10476 
10477 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10478                                          SourceLocation OpLoc,
10479                                          OverloadCandidate *Cand) {
10480   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10481   std::string TypeStr("operator");
10482   TypeStr += Opc;
10483   TypeStr += "(";
10484   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10485   if (Cand->Conversions.size() == 1) {
10486     TypeStr += ")";
10487     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10488   } else {
10489     TypeStr += ", ";
10490     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10491     TypeStr += ")";
10492     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10493   }
10494 }
10495 
10496 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10497                                          OverloadCandidate *Cand) {
10498   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10499     if (ICS.isBad()) break; // all meaningless after first invalid
10500     if (!ICS.isAmbiguous()) continue;
10501 
10502     ICS.DiagnoseAmbiguousConversion(
10503         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10504   }
10505 }
10506 
10507 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10508   if (Cand->Function)
10509     return Cand->Function->getLocation();
10510   if (Cand->IsSurrogate)
10511     return Cand->Surrogate->getLocation();
10512   return SourceLocation();
10513 }
10514 
10515 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10516   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10517   case Sema::TDK_Success:
10518   case Sema::TDK_NonDependentConversionFailure:
10519     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10520 
10521   case Sema::TDK_Invalid:
10522   case Sema::TDK_Incomplete:
10523   case Sema::TDK_IncompletePack:
10524     return 1;
10525 
10526   case Sema::TDK_Underqualified:
10527   case Sema::TDK_Inconsistent:
10528     return 2;
10529 
10530   case Sema::TDK_SubstitutionFailure:
10531   case Sema::TDK_DeducedMismatch:
10532   case Sema::TDK_DeducedMismatchNested:
10533   case Sema::TDK_NonDeducedMismatch:
10534   case Sema::TDK_MiscellaneousDeductionFailure:
10535   case Sema::TDK_CUDATargetMismatch:
10536     return 3;
10537 
10538   case Sema::TDK_InstantiationDepth:
10539     return 4;
10540 
10541   case Sema::TDK_InvalidExplicitArguments:
10542     return 5;
10543 
10544   case Sema::TDK_TooManyArguments:
10545   case Sema::TDK_TooFewArguments:
10546     return 6;
10547   }
10548   llvm_unreachable("Unhandled deduction result");
10549 }
10550 
10551 namespace {
10552 struct CompareOverloadCandidatesForDisplay {
10553   Sema &S;
10554   SourceLocation Loc;
10555   size_t NumArgs;
10556   OverloadCandidateSet::CandidateSetKind CSK;
10557 
10558   CompareOverloadCandidatesForDisplay(
10559       Sema &S, SourceLocation Loc, size_t NArgs,
10560       OverloadCandidateSet::CandidateSetKind CSK)
10561       : S(S), NumArgs(NArgs), CSK(CSK) {}
10562 
10563   bool operator()(const OverloadCandidate *L,
10564                   const OverloadCandidate *R) {
10565     // Fast-path this check.
10566     if (L == R) return false;
10567 
10568     // Order first by viability.
10569     if (L->Viable) {
10570       if (!R->Viable) return true;
10571 
10572       // TODO: introduce a tri-valued comparison for overload
10573       // candidates.  Would be more worthwhile if we had a sort
10574       // that could exploit it.
10575       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10576         return true;
10577       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10578         return false;
10579     } else if (R->Viable)
10580       return false;
10581 
10582     assert(L->Viable == R->Viable);
10583 
10584     // Criteria by which we can sort non-viable candidates:
10585     if (!L->Viable) {
10586       // 1. Arity mismatches come after other candidates.
10587       if (L->FailureKind == ovl_fail_too_many_arguments ||
10588           L->FailureKind == ovl_fail_too_few_arguments) {
10589         if (R->FailureKind == ovl_fail_too_many_arguments ||
10590             R->FailureKind == ovl_fail_too_few_arguments) {
10591           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10592           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10593           if (LDist == RDist) {
10594             if (L->FailureKind == R->FailureKind)
10595               // Sort non-surrogates before surrogates.
10596               return !L->IsSurrogate && R->IsSurrogate;
10597             // Sort candidates requiring fewer parameters than there were
10598             // arguments given after candidates requiring more parameters
10599             // than there were arguments given.
10600             return L->FailureKind == ovl_fail_too_many_arguments;
10601           }
10602           return LDist < RDist;
10603         }
10604         return false;
10605       }
10606       if (R->FailureKind == ovl_fail_too_many_arguments ||
10607           R->FailureKind == ovl_fail_too_few_arguments)
10608         return true;
10609 
10610       // 2. Bad conversions come first and are ordered by the number
10611       // of bad conversions and quality of good conversions.
10612       if (L->FailureKind == ovl_fail_bad_conversion) {
10613         if (R->FailureKind != ovl_fail_bad_conversion)
10614           return true;
10615 
10616         // The conversion that can be fixed with a smaller number of changes,
10617         // comes first.
10618         unsigned numLFixes = L->Fix.NumConversionsFixed;
10619         unsigned numRFixes = R->Fix.NumConversionsFixed;
10620         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10621         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10622         if (numLFixes != numRFixes) {
10623           return numLFixes < numRFixes;
10624         }
10625 
10626         // If there's any ordering between the defined conversions...
10627         // FIXME: this might not be transitive.
10628         assert(L->Conversions.size() == R->Conversions.size());
10629 
10630         int leftBetter = 0;
10631         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10632         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10633           switch (CompareImplicitConversionSequences(S, Loc,
10634                                                      L->Conversions[I],
10635                                                      R->Conversions[I])) {
10636           case ImplicitConversionSequence::Better:
10637             leftBetter++;
10638             break;
10639 
10640           case ImplicitConversionSequence::Worse:
10641             leftBetter--;
10642             break;
10643 
10644           case ImplicitConversionSequence::Indistinguishable:
10645             break;
10646           }
10647         }
10648         if (leftBetter > 0) return true;
10649         if (leftBetter < 0) return false;
10650 
10651       } else if (R->FailureKind == ovl_fail_bad_conversion)
10652         return false;
10653 
10654       if (L->FailureKind == ovl_fail_bad_deduction) {
10655         if (R->FailureKind != ovl_fail_bad_deduction)
10656           return true;
10657 
10658         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10659           return RankDeductionFailure(L->DeductionFailure)
10660                < RankDeductionFailure(R->DeductionFailure);
10661       } else if (R->FailureKind == ovl_fail_bad_deduction)
10662         return false;
10663 
10664       // TODO: others?
10665     }
10666 
10667     // Sort everything else by location.
10668     SourceLocation LLoc = GetLocationForCandidate(L);
10669     SourceLocation RLoc = GetLocationForCandidate(R);
10670 
10671     // Put candidates without locations (e.g. builtins) at the end.
10672     if (LLoc.isInvalid()) return false;
10673     if (RLoc.isInvalid()) return true;
10674 
10675     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10676   }
10677 };
10678 }
10679 
10680 /// CompleteNonViableCandidate - Normally, overload resolution only
10681 /// computes up to the first bad conversion. Produces the FixIt set if
10682 /// possible.
10683 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10684                                        ArrayRef<Expr *> Args) {
10685   assert(!Cand->Viable);
10686 
10687   // Don't do anything on failures other than bad conversion.
10688   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10689 
10690   // We only want the FixIts if all the arguments can be corrected.
10691   bool Unfixable = false;
10692   // Use a implicit copy initialization to check conversion fixes.
10693   Cand->Fix.setConversionChecker(TryCopyInitialization);
10694 
10695   // Attempt to fix the bad conversion.
10696   unsigned ConvCount = Cand->Conversions.size();
10697   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10698        ++ConvIdx) {
10699     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10700     if (Cand->Conversions[ConvIdx].isInitialized() &&
10701         Cand->Conversions[ConvIdx].isBad()) {
10702       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10703       break;
10704     }
10705   }
10706 
10707   // FIXME: this should probably be preserved from the overload
10708   // operation somehow.
10709   bool SuppressUserConversions = false;
10710 
10711   unsigned ConvIdx = 0;
10712   ArrayRef<QualType> ParamTypes;
10713 
10714   if (Cand->IsSurrogate) {
10715     QualType ConvType
10716       = Cand->Surrogate->getConversionType().getNonReferenceType();
10717     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10718       ConvType = ConvPtrType->getPointeeType();
10719     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10720     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10721     ConvIdx = 1;
10722   } else if (Cand->Function) {
10723     ParamTypes =
10724         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10725     if (isa<CXXMethodDecl>(Cand->Function) &&
10726         !isa<CXXConstructorDecl>(Cand->Function)) {
10727       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10728       ConvIdx = 1;
10729     }
10730   } else {
10731     // Builtin operator.
10732     assert(ConvCount <= 3);
10733     ParamTypes = Cand->BuiltinParamTypes;
10734   }
10735 
10736   // Fill in the rest of the conversions.
10737   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10738     if (Cand->Conversions[ConvIdx].isInitialized()) {
10739       // We've already checked this conversion.
10740     } else if (ArgIdx < ParamTypes.size()) {
10741       if (ParamTypes[ArgIdx]->isDependentType())
10742         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10743             Args[ArgIdx]->getType());
10744       else {
10745         Cand->Conversions[ConvIdx] =
10746             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10747                                   SuppressUserConversions,
10748                                   /*InOverloadResolution=*/true,
10749                                   /*AllowObjCWritebackConversion=*/
10750                                   S.getLangOpts().ObjCAutoRefCount);
10751         // Store the FixIt in the candidate if it exists.
10752         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10753           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10754       }
10755     } else
10756       Cand->Conversions[ConvIdx].setEllipsis();
10757   }
10758 }
10759 
10760 /// When overload resolution fails, prints diagnostic messages containing the
10761 /// candidates in the candidate set.
10762 void OverloadCandidateSet::NoteCandidates(
10763     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10764     StringRef Opc, SourceLocation OpLoc,
10765     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10766   // Sort the candidates by viability and position.  Sorting directly would
10767   // be prohibitive, so we make a set of pointers and sort those.
10768   SmallVector<OverloadCandidate*, 32> Cands;
10769   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10770   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10771     if (!Filter(*Cand))
10772       continue;
10773     if (Cand->Viable)
10774       Cands.push_back(Cand);
10775     else if (OCD == OCD_AllCandidates) {
10776       CompleteNonViableCandidate(S, Cand, Args);
10777       if (Cand->Function || Cand->IsSurrogate)
10778         Cands.push_back(Cand);
10779       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10780       // want to list every possible builtin candidate.
10781     }
10782   }
10783 
10784   std::stable_sort(Cands.begin(), Cands.end(),
10785             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10786 
10787   bool ReportedAmbiguousConversions = false;
10788 
10789   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10790   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10791   unsigned CandsShown = 0;
10792   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10793     OverloadCandidate *Cand = *I;
10794 
10795     // Set an arbitrary limit on the number of candidate functions we'll spam
10796     // the user with.  FIXME: This limit should depend on details of the
10797     // candidate list.
10798     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10799       break;
10800     }
10801     ++CandsShown;
10802 
10803     if (Cand->Function)
10804       NoteFunctionCandidate(S, Cand, Args.size(),
10805                             /*TakingCandidateAddress=*/false);
10806     else if (Cand->IsSurrogate)
10807       NoteSurrogateCandidate(S, Cand);
10808     else {
10809       assert(Cand->Viable &&
10810              "Non-viable built-in candidates are not added to Cands.");
10811       // Generally we only see ambiguities including viable builtin
10812       // operators if overload resolution got screwed up by an
10813       // ambiguous user-defined conversion.
10814       //
10815       // FIXME: It's quite possible for different conversions to see
10816       // different ambiguities, though.
10817       if (!ReportedAmbiguousConversions) {
10818         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10819         ReportedAmbiguousConversions = true;
10820       }
10821 
10822       // If this is a viable builtin, print it.
10823       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10824     }
10825   }
10826 
10827   if (I != E)
10828     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10829 }
10830 
10831 static SourceLocation
10832 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10833   return Cand->Specialization ? Cand->Specialization->getLocation()
10834                               : SourceLocation();
10835 }
10836 
10837 namespace {
10838 struct CompareTemplateSpecCandidatesForDisplay {
10839   Sema &S;
10840   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10841 
10842   bool operator()(const TemplateSpecCandidate *L,
10843                   const TemplateSpecCandidate *R) {
10844     // Fast-path this check.
10845     if (L == R)
10846       return false;
10847 
10848     // Assuming that both candidates are not matches...
10849 
10850     // Sort by the ranking of deduction failures.
10851     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10852       return RankDeductionFailure(L->DeductionFailure) <
10853              RankDeductionFailure(R->DeductionFailure);
10854 
10855     // Sort everything else by location.
10856     SourceLocation LLoc = GetLocationForCandidate(L);
10857     SourceLocation RLoc = GetLocationForCandidate(R);
10858 
10859     // Put candidates without locations (e.g. builtins) at the end.
10860     if (LLoc.isInvalid())
10861       return false;
10862     if (RLoc.isInvalid())
10863       return true;
10864 
10865     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10866   }
10867 };
10868 }
10869 
10870 /// Diagnose a template argument deduction failure.
10871 /// We are treating these failures as overload failures due to bad
10872 /// deductions.
10873 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10874                                                  bool ForTakingAddress) {
10875   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10876                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10877 }
10878 
10879 void TemplateSpecCandidateSet::destroyCandidates() {
10880   for (iterator i = begin(), e = end(); i != e; ++i) {
10881     i->DeductionFailure.Destroy();
10882   }
10883 }
10884 
10885 void TemplateSpecCandidateSet::clear() {
10886   destroyCandidates();
10887   Candidates.clear();
10888 }
10889 
10890 /// NoteCandidates - When no template specialization match is found, prints
10891 /// diagnostic messages containing the non-matching specializations that form
10892 /// the candidate set.
10893 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10894 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10895 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10896   // Sort the candidates by position (assuming no candidate is a match).
10897   // Sorting directly would be prohibitive, so we make a set of pointers
10898   // and sort those.
10899   SmallVector<TemplateSpecCandidate *, 32> Cands;
10900   Cands.reserve(size());
10901   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10902     if (Cand->Specialization)
10903       Cands.push_back(Cand);
10904     // Otherwise, this is a non-matching builtin candidate.  We do not,
10905     // in general, want to list every possible builtin candidate.
10906   }
10907 
10908   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10909 
10910   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10911   // for generalization purposes (?).
10912   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10913 
10914   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10915   unsigned CandsShown = 0;
10916   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10917     TemplateSpecCandidate *Cand = *I;
10918 
10919     // Set an arbitrary limit on the number of candidates we'll spam
10920     // the user with.  FIXME: This limit should depend on details of the
10921     // candidate list.
10922     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10923       break;
10924     ++CandsShown;
10925 
10926     assert(Cand->Specialization &&
10927            "Non-matching built-in candidates are not added to Cands.");
10928     Cand->NoteDeductionFailure(S, ForTakingAddress);
10929   }
10930 
10931   if (I != E)
10932     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10933 }
10934 
10935 // [PossiblyAFunctionType]  -->   [Return]
10936 // NonFunctionType --> NonFunctionType
10937 // R (A) --> R(A)
10938 // R (*)(A) --> R (A)
10939 // R (&)(A) --> R (A)
10940 // R (S::*)(A) --> R (A)
10941 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10942   QualType Ret = PossiblyAFunctionType;
10943   if (const PointerType *ToTypePtr =
10944     PossiblyAFunctionType->getAs<PointerType>())
10945     Ret = ToTypePtr->getPointeeType();
10946   else if (const ReferenceType *ToTypeRef =
10947     PossiblyAFunctionType->getAs<ReferenceType>())
10948     Ret = ToTypeRef->getPointeeType();
10949   else if (const MemberPointerType *MemTypePtr =
10950     PossiblyAFunctionType->getAs<MemberPointerType>())
10951     Ret = MemTypePtr->getPointeeType();
10952   Ret =
10953     Context.getCanonicalType(Ret).getUnqualifiedType();
10954   return Ret;
10955 }
10956 
10957 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10958                                  bool Complain = true) {
10959   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10960       S.DeduceReturnType(FD, Loc, Complain))
10961     return true;
10962 
10963   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10964   if (S.getLangOpts().CPlusPlus17 &&
10965       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10966       !S.ResolveExceptionSpec(Loc, FPT))
10967     return true;
10968 
10969   return false;
10970 }
10971 
10972 namespace {
10973 // A helper class to help with address of function resolution
10974 // - allows us to avoid passing around all those ugly parameters
10975 class AddressOfFunctionResolver {
10976   Sema& S;
10977   Expr* SourceExpr;
10978   const QualType& TargetType;
10979   QualType TargetFunctionType; // Extracted function type from target type
10980 
10981   bool Complain;
10982   //DeclAccessPair& ResultFunctionAccessPair;
10983   ASTContext& Context;
10984 
10985   bool TargetTypeIsNonStaticMemberFunction;
10986   bool FoundNonTemplateFunction;
10987   bool StaticMemberFunctionFromBoundPointer;
10988   bool HasComplained;
10989 
10990   OverloadExpr::FindResult OvlExprInfo;
10991   OverloadExpr *OvlExpr;
10992   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10993   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10994   TemplateSpecCandidateSet FailedCandidates;
10995 
10996 public:
10997   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10998                             const QualType &TargetType, bool Complain)
10999       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11000         Complain(Complain), Context(S.getASTContext()),
11001         TargetTypeIsNonStaticMemberFunction(
11002             !!TargetType->getAs<MemberPointerType>()),
11003         FoundNonTemplateFunction(false),
11004         StaticMemberFunctionFromBoundPointer(false),
11005         HasComplained(false),
11006         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11007         OvlExpr(OvlExprInfo.Expression),
11008         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11009     ExtractUnqualifiedFunctionTypeFromTargetType();
11010 
11011     if (TargetFunctionType->isFunctionType()) {
11012       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11013         if (!UME->isImplicitAccess() &&
11014             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11015           StaticMemberFunctionFromBoundPointer = true;
11016     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11017       DeclAccessPair dap;
11018       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11019               OvlExpr, false, &dap)) {
11020         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11021           if (!Method->isStatic()) {
11022             // If the target type is a non-function type and the function found
11023             // is a non-static member function, pretend as if that was the
11024             // target, it's the only possible type to end up with.
11025             TargetTypeIsNonStaticMemberFunction = true;
11026 
11027             // And skip adding the function if its not in the proper form.
11028             // We'll diagnose this due to an empty set of functions.
11029             if (!OvlExprInfo.HasFormOfMemberPointer)
11030               return;
11031           }
11032 
11033         Matches.push_back(std::make_pair(dap, Fn));
11034       }
11035       return;
11036     }
11037 
11038     if (OvlExpr->hasExplicitTemplateArgs())
11039       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11040 
11041     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11042       // C++ [over.over]p4:
11043       //   If more than one function is selected, [...]
11044       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11045         if (FoundNonTemplateFunction)
11046           EliminateAllTemplateMatches();
11047         else
11048           EliminateAllExceptMostSpecializedTemplate();
11049       }
11050     }
11051 
11052     if (S.getLangOpts().CUDA && Matches.size() > 1)
11053       EliminateSuboptimalCudaMatches();
11054   }
11055 
11056   bool hasComplained() const { return HasComplained; }
11057 
11058 private:
11059   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11060     QualType Discard;
11061     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11062            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11063   }
11064 
11065   /// \return true if A is considered a better overload candidate for the
11066   /// desired type than B.
11067   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11068     // If A doesn't have exactly the correct type, we don't want to classify it
11069     // as "better" than anything else. This way, the user is required to
11070     // disambiguate for us if there are multiple candidates and no exact match.
11071     return candidateHasExactlyCorrectType(A) &&
11072            (!candidateHasExactlyCorrectType(B) ||
11073             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11074   }
11075 
11076   /// \return true if we were able to eliminate all but one overload candidate,
11077   /// false otherwise.
11078   bool eliminiateSuboptimalOverloadCandidates() {
11079     // Same algorithm as overload resolution -- one pass to pick the "best",
11080     // another pass to be sure that nothing is better than the best.
11081     auto Best = Matches.begin();
11082     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11083       if (isBetterCandidate(I->second, Best->second))
11084         Best = I;
11085 
11086     const FunctionDecl *BestFn = Best->second;
11087     auto IsBestOrInferiorToBest = [this, BestFn](
11088         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11089       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11090     };
11091 
11092     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11093     // option, so we can potentially give the user a better error
11094     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11095       return false;
11096     Matches[0] = *Best;
11097     Matches.resize(1);
11098     return true;
11099   }
11100 
11101   bool isTargetTypeAFunction() const {
11102     return TargetFunctionType->isFunctionType();
11103   }
11104 
11105   // [ToType]     [Return]
11106 
11107   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11108   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11109   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11110   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11111     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11112   }
11113 
11114   // return true if any matching specializations were found
11115   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11116                                    const DeclAccessPair& CurAccessFunPair) {
11117     if (CXXMethodDecl *Method
11118               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11119       // Skip non-static function templates when converting to pointer, and
11120       // static when converting to member pointer.
11121       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11122         return false;
11123     }
11124     else if (TargetTypeIsNonStaticMemberFunction)
11125       return false;
11126 
11127     // C++ [over.over]p2:
11128     //   If the name is a function template, template argument deduction is
11129     //   done (14.8.2.2), and if the argument deduction succeeds, the
11130     //   resulting template argument list is used to generate a single
11131     //   function template specialization, which is added to the set of
11132     //   overloaded functions considered.
11133     FunctionDecl *Specialization = nullptr;
11134     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11135     if (Sema::TemplateDeductionResult Result
11136           = S.DeduceTemplateArguments(FunctionTemplate,
11137                                       &OvlExplicitTemplateArgs,
11138                                       TargetFunctionType, Specialization,
11139                                       Info, /*IsAddressOfFunction*/true)) {
11140       // Make a note of the failed deduction for diagnostics.
11141       FailedCandidates.addCandidate()
11142           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11143                MakeDeductionFailureInfo(Context, Result, Info));
11144       return false;
11145     }
11146 
11147     // Template argument deduction ensures that we have an exact match or
11148     // compatible pointer-to-function arguments that would be adjusted by ICS.
11149     // This function template specicalization works.
11150     assert(S.isSameOrCompatibleFunctionType(
11151               Context.getCanonicalType(Specialization->getType()),
11152               Context.getCanonicalType(TargetFunctionType)));
11153 
11154     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11155       return false;
11156 
11157     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11158     return true;
11159   }
11160 
11161   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11162                                       const DeclAccessPair& CurAccessFunPair) {
11163     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11164       // Skip non-static functions when converting to pointer, and static
11165       // when converting to member pointer.
11166       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11167         return false;
11168     }
11169     else if (TargetTypeIsNonStaticMemberFunction)
11170       return false;
11171 
11172     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11173       if (S.getLangOpts().CUDA)
11174         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11175           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11176             return false;
11177       if (FunDecl->isMultiVersion()) {
11178         const auto *TA = FunDecl->getAttr<TargetAttr>();
11179         if (TA && !TA->isDefaultVersion())
11180           return false;
11181       }
11182 
11183       // If any candidate has a placeholder return type, trigger its deduction
11184       // now.
11185       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11186                                Complain)) {
11187         HasComplained |= Complain;
11188         return false;
11189       }
11190 
11191       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11192         return false;
11193 
11194       // If we're in C, we need to support types that aren't exactly identical.
11195       if (!S.getLangOpts().CPlusPlus ||
11196           candidateHasExactlyCorrectType(FunDecl)) {
11197         Matches.push_back(std::make_pair(
11198             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11199         FoundNonTemplateFunction = true;
11200         return true;
11201       }
11202     }
11203 
11204     return false;
11205   }
11206 
11207   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11208     bool Ret = false;
11209 
11210     // If the overload expression doesn't have the form of a pointer to
11211     // member, don't try to convert it to a pointer-to-member type.
11212     if (IsInvalidFormOfPointerToMemberFunction())
11213       return false;
11214 
11215     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11216                                E = OvlExpr->decls_end();
11217          I != E; ++I) {
11218       // Look through any using declarations to find the underlying function.
11219       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11220 
11221       // C++ [over.over]p3:
11222       //   Non-member functions and static member functions match
11223       //   targets of type "pointer-to-function" or "reference-to-function."
11224       //   Nonstatic member functions match targets of
11225       //   type "pointer-to-member-function."
11226       // Note that according to DR 247, the containing class does not matter.
11227       if (FunctionTemplateDecl *FunctionTemplate
11228                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11229         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11230           Ret = true;
11231       }
11232       // If we have explicit template arguments supplied, skip non-templates.
11233       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11234                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11235         Ret = true;
11236     }
11237     assert(Ret || Matches.empty());
11238     return Ret;
11239   }
11240 
11241   void EliminateAllExceptMostSpecializedTemplate() {
11242     //   [...] and any given function template specialization F1 is
11243     //   eliminated if the set contains a second function template
11244     //   specialization whose function template is more specialized
11245     //   than the function template of F1 according to the partial
11246     //   ordering rules of 14.5.5.2.
11247 
11248     // The algorithm specified above is quadratic. We instead use a
11249     // two-pass algorithm (similar to the one used to identify the
11250     // best viable function in an overload set) that identifies the
11251     // best function template (if it exists).
11252 
11253     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11254     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11255       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11256 
11257     // TODO: It looks like FailedCandidates does not serve much purpose
11258     // here, since the no_viable diagnostic has index 0.
11259     UnresolvedSetIterator Result = S.getMostSpecialized(
11260         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11261         SourceExpr->getBeginLoc(), S.PDiag(),
11262         S.PDiag(diag::err_addr_ovl_ambiguous)
11263             << Matches[0].second->getDeclName(),
11264         S.PDiag(diag::note_ovl_candidate)
11265             << (unsigned)oc_function << (unsigned)ocs_described_template,
11266         Complain, TargetFunctionType);
11267 
11268     if (Result != MatchesCopy.end()) {
11269       // Make it the first and only element
11270       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11271       Matches[0].second = cast<FunctionDecl>(*Result);
11272       Matches.resize(1);
11273     } else
11274       HasComplained |= Complain;
11275   }
11276 
11277   void EliminateAllTemplateMatches() {
11278     //   [...] any function template specializations in the set are
11279     //   eliminated if the set also contains a non-template function, [...]
11280     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11281       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11282         ++I;
11283       else {
11284         Matches[I] = Matches[--N];
11285         Matches.resize(N);
11286       }
11287     }
11288   }
11289 
11290   void EliminateSuboptimalCudaMatches() {
11291     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11292   }
11293 
11294 public:
11295   void ComplainNoMatchesFound() const {
11296     assert(Matches.empty());
11297     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11298         << OvlExpr->getName() << TargetFunctionType
11299         << OvlExpr->getSourceRange();
11300     if (FailedCandidates.empty())
11301       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11302                                   /*TakingAddress=*/true);
11303     else {
11304       // We have some deduction failure messages. Use them to diagnose
11305       // the function templates, and diagnose the non-template candidates
11306       // normally.
11307       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11308                                  IEnd = OvlExpr->decls_end();
11309            I != IEnd; ++I)
11310         if (FunctionDecl *Fun =
11311                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11312           if (!functionHasPassObjectSizeParams(Fun))
11313             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11314                                     /*TakingAddress=*/true);
11315       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11316     }
11317   }
11318 
11319   bool IsInvalidFormOfPointerToMemberFunction() const {
11320     return TargetTypeIsNonStaticMemberFunction &&
11321       !OvlExprInfo.HasFormOfMemberPointer;
11322   }
11323 
11324   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11325       // TODO: Should we condition this on whether any functions might
11326       // have matched, or is it more appropriate to do that in callers?
11327       // TODO: a fixit wouldn't hurt.
11328       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11329         << TargetType << OvlExpr->getSourceRange();
11330   }
11331 
11332   bool IsStaticMemberFunctionFromBoundPointer() const {
11333     return StaticMemberFunctionFromBoundPointer;
11334   }
11335 
11336   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11337     S.Diag(OvlExpr->getBeginLoc(),
11338            diag::err_invalid_form_pointer_member_function)
11339         << OvlExpr->getSourceRange();
11340   }
11341 
11342   void ComplainOfInvalidConversion() const {
11343     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11344         << OvlExpr->getName() << TargetType;
11345   }
11346 
11347   void ComplainMultipleMatchesFound() const {
11348     assert(Matches.size() > 1);
11349     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11350         << OvlExpr->getName() << OvlExpr->getSourceRange();
11351     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11352                                 /*TakingAddress=*/true);
11353   }
11354 
11355   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11356 
11357   int getNumMatches() const { return Matches.size(); }
11358 
11359   FunctionDecl* getMatchingFunctionDecl() const {
11360     if (Matches.size() != 1) return nullptr;
11361     return Matches[0].second;
11362   }
11363 
11364   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11365     if (Matches.size() != 1) return nullptr;
11366     return &Matches[0].first;
11367   }
11368 };
11369 }
11370 
11371 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11372 /// an overloaded function (C++ [over.over]), where @p From is an
11373 /// expression with overloaded function type and @p ToType is the type
11374 /// we're trying to resolve to. For example:
11375 ///
11376 /// @code
11377 /// int f(double);
11378 /// int f(int);
11379 ///
11380 /// int (*pfd)(double) = f; // selects f(double)
11381 /// @endcode
11382 ///
11383 /// This routine returns the resulting FunctionDecl if it could be
11384 /// resolved, and NULL otherwise. When @p Complain is true, this
11385 /// routine will emit diagnostics if there is an error.
11386 FunctionDecl *
11387 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11388                                          QualType TargetType,
11389                                          bool Complain,
11390                                          DeclAccessPair &FoundResult,
11391                                          bool *pHadMultipleCandidates) {
11392   assert(AddressOfExpr->getType() == Context.OverloadTy);
11393 
11394   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11395                                      Complain);
11396   int NumMatches = Resolver.getNumMatches();
11397   FunctionDecl *Fn = nullptr;
11398   bool ShouldComplain = Complain && !Resolver.hasComplained();
11399   if (NumMatches == 0 && ShouldComplain) {
11400     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11401       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11402     else
11403       Resolver.ComplainNoMatchesFound();
11404   }
11405   else if (NumMatches > 1 && ShouldComplain)
11406     Resolver.ComplainMultipleMatchesFound();
11407   else if (NumMatches == 1) {
11408     Fn = Resolver.getMatchingFunctionDecl();
11409     assert(Fn);
11410     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11411       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11412     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11413     if (Complain) {
11414       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11415         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11416       else
11417         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11418     }
11419   }
11420 
11421   if (pHadMultipleCandidates)
11422     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11423   return Fn;
11424 }
11425 
11426 /// Given an expression that refers to an overloaded function, try to
11427 /// resolve that function to a single function that can have its address taken.
11428 /// This will modify `Pair` iff it returns non-null.
11429 ///
11430 /// This routine can only realistically succeed if all but one candidates in the
11431 /// overload set for SrcExpr cannot have their addresses taken.
11432 FunctionDecl *
11433 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11434                                                   DeclAccessPair &Pair) {
11435   OverloadExpr::FindResult R = OverloadExpr::find(E);
11436   OverloadExpr *Ovl = R.Expression;
11437   FunctionDecl *Result = nullptr;
11438   DeclAccessPair DAP;
11439   // Don't use the AddressOfResolver because we're specifically looking for
11440   // cases where we have one overload candidate that lacks
11441   // enable_if/pass_object_size/...
11442   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11443     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11444     if (!FD)
11445       return nullptr;
11446 
11447     if (!checkAddressOfFunctionIsAvailable(FD))
11448       continue;
11449 
11450     // We have more than one result; quit.
11451     if (Result)
11452       return nullptr;
11453     DAP = I.getPair();
11454     Result = FD;
11455   }
11456 
11457   if (Result)
11458     Pair = DAP;
11459   return Result;
11460 }
11461 
11462 /// Given an overloaded function, tries to turn it into a non-overloaded
11463 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11464 /// will perform access checks, diagnose the use of the resultant decl, and, if
11465 /// requested, potentially perform a function-to-pointer decay.
11466 ///
11467 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11468 /// Otherwise, returns true. This may emit diagnostics and return true.
11469 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11470     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11471   Expr *E = SrcExpr.get();
11472   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11473 
11474   DeclAccessPair DAP;
11475   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11476   if (!Found || Found->isCPUDispatchMultiVersion() ||
11477       Found->isCPUSpecificMultiVersion())
11478     return false;
11479 
11480   // Emitting multiple diagnostics for a function that is both inaccessible and
11481   // unavailable is consistent with our behavior elsewhere. So, always check
11482   // for both.
11483   DiagnoseUseOfDecl(Found, E->getExprLoc());
11484   CheckAddressOfMemberAccess(E, DAP);
11485   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11486   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11487     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11488   else
11489     SrcExpr = Fixed;
11490   return true;
11491 }
11492 
11493 /// Given an expression that refers to an overloaded function, try to
11494 /// resolve that overloaded function expression down to a single function.
11495 ///
11496 /// This routine can only resolve template-ids that refer to a single function
11497 /// template, where that template-id refers to a single template whose template
11498 /// arguments are either provided by the template-id or have defaults,
11499 /// as described in C++0x [temp.arg.explicit]p3.
11500 ///
11501 /// If no template-ids are found, no diagnostics are emitted and NULL is
11502 /// returned.
11503 FunctionDecl *
11504 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11505                                                   bool Complain,
11506                                                   DeclAccessPair *FoundResult) {
11507   // C++ [over.over]p1:
11508   //   [...] [Note: any redundant set of parentheses surrounding the
11509   //   overloaded function name is ignored (5.1). ]
11510   // C++ [over.over]p1:
11511   //   [...] The overloaded function name can be preceded by the &
11512   //   operator.
11513 
11514   // If we didn't actually find any template-ids, we're done.
11515   if (!ovl->hasExplicitTemplateArgs())
11516     return nullptr;
11517 
11518   TemplateArgumentListInfo ExplicitTemplateArgs;
11519   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11520   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11521 
11522   // Look through all of the overloaded functions, searching for one
11523   // whose type matches exactly.
11524   FunctionDecl *Matched = nullptr;
11525   for (UnresolvedSetIterator I = ovl->decls_begin(),
11526          E = ovl->decls_end(); I != E; ++I) {
11527     // C++0x [temp.arg.explicit]p3:
11528     //   [...] In contexts where deduction is done and fails, or in contexts
11529     //   where deduction is not done, if a template argument list is
11530     //   specified and it, along with any default template arguments,
11531     //   identifies a single function template specialization, then the
11532     //   template-id is an lvalue for the function template specialization.
11533     FunctionTemplateDecl *FunctionTemplate
11534       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11535 
11536     // C++ [over.over]p2:
11537     //   If the name is a function template, template argument deduction is
11538     //   done (14.8.2.2), and if the argument deduction succeeds, the
11539     //   resulting template argument list is used to generate a single
11540     //   function template specialization, which is added to the set of
11541     //   overloaded functions considered.
11542     FunctionDecl *Specialization = nullptr;
11543     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11544     if (TemplateDeductionResult Result
11545           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11546                                     Specialization, Info,
11547                                     /*IsAddressOfFunction*/true)) {
11548       // Make a note of the failed deduction for diagnostics.
11549       // TODO: Actually use the failed-deduction info?
11550       FailedCandidates.addCandidate()
11551           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11552                MakeDeductionFailureInfo(Context, Result, Info));
11553       continue;
11554     }
11555 
11556     assert(Specialization && "no specialization and no error?");
11557 
11558     // Multiple matches; we can't resolve to a single declaration.
11559     if (Matched) {
11560       if (Complain) {
11561         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11562           << ovl->getName();
11563         NoteAllOverloadCandidates(ovl);
11564       }
11565       return nullptr;
11566     }
11567 
11568     Matched = Specialization;
11569     if (FoundResult) *FoundResult = I.getPair();
11570   }
11571 
11572   if (Matched &&
11573       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11574     return nullptr;
11575 
11576   return Matched;
11577 }
11578 
11579 // Resolve and fix an overloaded expression that can be resolved
11580 // because it identifies a single function template specialization.
11581 //
11582 // Last three arguments should only be supplied if Complain = true
11583 //
11584 // Return true if it was logically possible to so resolve the
11585 // expression, regardless of whether or not it succeeded.  Always
11586 // returns true if 'complain' is set.
11587 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11588                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11589                       bool complain, SourceRange OpRangeForComplaining,
11590                                            QualType DestTypeForComplaining,
11591                                             unsigned DiagIDForComplaining) {
11592   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11593 
11594   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11595 
11596   DeclAccessPair found;
11597   ExprResult SingleFunctionExpression;
11598   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11599                            ovl.Expression, /*complain*/ false, &found)) {
11600     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11601       SrcExpr = ExprError();
11602       return true;
11603     }
11604 
11605     // It is only correct to resolve to an instance method if we're
11606     // resolving a form that's permitted to be a pointer to member.
11607     // Otherwise we'll end up making a bound member expression, which
11608     // is illegal in all the contexts we resolve like this.
11609     if (!ovl.HasFormOfMemberPointer &&
11610         isa<CXXMethodDecl>(fn) &&
11611         cast<CXXMethodDecl>(fn)->isInstance()) {
11612       if (!complain) return false;
11613 
11614       Diag(ovl.Expression->getExprLoc(),
11615            diag::err_bound_member_function)
11616         << 0 << ovl.Expression->getSourceRange();
11617 
11618       // TODO: I believe we only end up here if there's a mix of
11619       // static and non-static candidates (otherwise the expression
11620       // would have 'bound member' type, not 'overload' type).
11621       // Ideally we would note which candidate was chosen and why
11622       // the static candidates were rejected.
11623       SrcExpr = ExprError();
11624       return true;
11625     }
11626 
11627     // Fix the expression to refer to 'fn'.
11628     SingleFunctionExpression =
11629         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11630 
11631     // If desired, do function-to-pointer decay.
11632     if (doFunctionPointerConverion) {
11633       SingleFunctionExpression =
11634         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11635       if (SingleFunctionExpression.isInvalid()) {
11636         SrcExpr = ExprError();
11637         return true;
11638       }
11639     }
11640   }
11641 
11642   if (!SingleFunctionExpression.isUsable()) {
11643     if (complain) {
11644       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11645         << ovl.Expression->getName()
11646         << DestTypeForComplaining
11647         << OpRangeForComplaining
11648         << ovl.Expression->getQualifierLoc().getSourceRange();
11649       NoteAllOverloadCandidates(SrcExpr.get());
11650 
11651       SrcExpr = ExprError();
11652       return true;
11653     }
11654 
11655     return false;
11656   }
11657 
11658   SrcExpr = SingleFunctionExpression;
11659   return true;
11660 }
11661 
11662 /// Add a single candidate to the overload set.
11663 static void AddOverloadedCallCandidate(Sema &S,
11664                                        DeclAccessPair FoundDecl,
11665                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11666                                        ArrayRef<Expr *> Args,
11667                                        OverloadCandidateSet &CandidateSet,
11668                                        bool PartialOverloading,
11669                                        bool KnownValid) {
11670   NamedDecl *Callee = FoundDecl.getDecl();
11671   if (isa<UsingShadowDecl>(Callee))
11672     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11673 
11674   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11675     if (ExplicitTemplateArgs) {
11676       assert(!KnownValid && "Explicit template arguments?");
11677       return;
11678     }
11679     // Prevent ill-formed function decls to be added as overload candidates.
11680     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11681       return;
11682 
11683     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11684                            /*SuppressUsedConversions=*/false,
11685                            PartialOverloading);
11686     return;
11687   }
11688 
11689   if (FunctionTemplateDecl *FuncTemplate
11690       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11691     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11692                                    ExplicitTemplateArgs, Args, CandidateSet,
11693                                    /*SuppressUsedConversions=*/false,
11694                                    PartialOverloading);
11695     return;
11696   }
11697 
11698   assert(!KnownValid && "unhandled case in overloaded call candidate");
11699 }
11700 
11701 /// Add the overload candidates named by callee and/or found by argument
11702 /// dependent lookup to the given overload set.
11703 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11704                                        ArrayRef<Expr *> Args,
11705                                        OverloadCandidateSet &CandidateSet,
11706                                        bool PartialOverloading) {
11707 
11708 #ifndef NDEBUG
11709   // Verify that ArgumentDependentLookup is consistent with the rules
11710   // in C++0x [basic.lookup.argdep]p3:
11711   //
11712   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11713   //   and let Y be the lookup set produced by argument dependent
11714   //   lookup (defined as follows). If X contains
11715   //
11716   //     -- a declaration of a class member, or
11717   //
11718   //     -- a block-scope function declaration that is not a
11719   //        using-declaration, or
11720   //
11721   //     -- a declaration that is neither a function or a function
11722   //        template
11723   //
11724   //   then Y is empty.
11725 
11726   if (ULE->requiresADL()) {
11727     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11728            E = ULE->decls_end(); I != E; ++I) {
11729       assert(!(*I)->getDeclContext()->isRecord());
11730       assert(isa<UsingShadowDecl>(*I) ||
11731              !(*I)->getDeclContext()->isFunctionOrMethod());
11732       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11733     }
11734   }
11735 #endif
11736 
11737   // It would be nice to avoid this copy.
11738   TemplateArgumentListInfo TABuffer;
11739   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11740   if (ULE->hasExplicitTemplateArgs()) {
11741     ULE->copyTemplateArgumentsInto(TABuffer);
11742     ExplicitTemplateArgs = &TABuffer;
11743   }
11744 
11745   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11746          E = ULE->decls_end(); I != E; ++I)
11747     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11748                                CandidateSet, PartialOverloading,
11749                                /*KnownValid*/ true);
11750 
11751   if (ULE->requiresADL())
11752     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11753                                          Args, ExplicitTemplateArgs,
11754                                          CandidateSet, PartialOverloading);
11755 }
11756 
11757 /// Determine whether a declaration with the specified name could be moved into
11758 /// a different namespace.
11759 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11760   switch (Name.getCXXOverloadedOperator()) {
11761   case OO_New: case OO_Array_New:
11762   case OO_Delete: case OO_Array_Delete:
11763     return false;
11764 
11765   default:
11766     return true;
11767   }
11768 }
11769 
11770 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11771 /// template, where the non-dependent name was declared after the template
11772 /// was defined. This is common in code written for a compilers which do not
11773 /// correctly implement two-stage name lookup.
11774 ///
11775 /// Returns true if a viable candidate was found and a diagnostic was issued.
11776 static bool
11777 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11778                        const CXXScopeSpec &SS, LookupResult &R,
11779                        OverloadCandidateSet::CandidateSetKind CSK,
11780                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11781                        ArrayRef<Expr *> Args,
11782                        bool *DoDiagnoseEmptyLookup = nullptr) {
11783   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11784     return false;
11785 
11786   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11787     if (DC->isTransparentContext())
11788       continue;
11789 
11790     SemaRef.LookupQualifiedName(R, DC);
11791 
11792     if (!R.empty()) {
11793       R.suppressDiagnostics();
11794 
11795       if (isa<CXXRecordDecl>(DC)) {
11796         // Don't diagnose names we find in classes; we get much better
11797         // diagnostics for these from DiagnoseEmptyLookup.
11798         R.clear();
11799         if (DoDiagnoseEmptyLookup)
11800           *DoDiagnoseEmptyLookup = true;
11801         return false;
11802       }
11803 
11804       OverloadCandidateSet Candidates(FnLoc, CSK);
11805       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11806         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11807                                    ExplicitTemplateArgs, Args,
11808                                    Candidates, false, /*KnownValid*/ false);
11809 
11810       OverloadCandidateSet::iterator Best;
11811       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11812         // No viable functions. Don't bother the user with notes for functions
11813         // which don't work and shouldn't be found anyway.
11814         R.clear();
11815         return false;
11816       }
11817 
11818       // Find the namespaces where ADL would have looked, and suggest
11819       // declaring the function there instead.
11820       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11821       Sema::AssociatedClassSet AssociatedClasses;
11822       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11823                                                  AssociatedNamespaces,
11824                                                  AssociatedClasses);
11825       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11826       if (canBeDeclaredInNamespace(R.getLookupName())) {
11827         DeclContext *Std = SemaRef.getStdNamespace();
11828         for (Sema::AssociatedNamespaceSet::iterator
11829                it = AssociatedNamespaces.begin(),
11830                end = AssociatedNamespaces.end(); it != end; ++it) {
11831           // Never suggest declaring a function within namespace 'std'.
11832           if (Std && Std->Encloses(*it))
11833             continue;
11834 
11835           // Never suggest declaring a function within a namespace with a
11836           // reserved name, like __gnu_cxx.
11837           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11838           if (NS &&
11839               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11840             continue;
11841 
11842           SuggestedNamespaces.insert(*it);
11843         }
11844       }
11845 
11846       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11847         << R.getLookupName();
11848       if (SuggestedNamespaces.empty()) {
11849         SemaRef.Diag(Best->Function->getLocation(),
11850                      diag::note_not_found_by_two_phase_lookup)
11851           << R.getLookupName() << 0;
11852       } else if (SuggestedNamespaces.size() == 1) {
11853         SemaRef.Diag(Best->Function->getLocation(),
11854                      diag::note_not_found_by_two_phase_lookup)
11855           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11856       } else {
11857         // FIXME: It would be useful to list the associated namespaces here,
11858         // but the diagnostics infrastructure doesn't provide a way to produce
11859         // a localized representation of a list of items.
11860         SemaRef.Diag(Best->Function->getLocation(),
11861                      diag::note_not_found_by_two_phase_lookup)
11862           << R.getLookupName() << 2;
11863       }
11864 
11865       // Try to recover by calling this function.
11866       return true;
11867     }
11868 
11869     R.clear();
11870   }
11871 
11872   return false;
11873 }
11874 
11875 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11876 /// template, where the non-dependent operator was declared after the template
11877 /// was defined.
11878 ///
11879 /// Returns true if a viable candidate was found and a diagnostic was issued.
11880 static bool
11881 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11882                                SourceLocation OpLoc,
11883                                ArrayRef<Expr *> Args) {
11884   DeclarationName OpName =
11885     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11886   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11887   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11888                                 OverloadCandidateSet::CSK_Operator,
11889                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11890 }
11891 
11892 namespace {
11893 class BuildRecoveryCallExprRAII {
11894   Sema &SemaRef;
11895 public:
11896   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11897     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11898     SemaRef.IsBuildingRecoveryCallExpr = true;
11899   }
11900 
11901   ~BuildRecoveryCallExprRAII() {
11902     SemaRef.IsBuildingRecoveryCallExpr = false;
11903   }
11904 };
11905 
11906 }
11907 
11908 static std::unique_ptr<CorrectionCandidateCallback>
11909 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11910               bool HasTemplateArgs, bool AllowTypoCorrection) {
11911   if (!AllowTypoCorrection)
11912     return llvm::make_unique<NoTypoCorrectionCCC>();
11913   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11914                                                   HasTemplateArgs, ME);
11915 }
11916 
11917 /// Attempts to recover from a call where no functions were found.
11918 ///
11919 /// Returns true if new candidates were found.
11920 static ExprResult
11921 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11922                       UnresolvedLookupExpr *ULE,
11923                       SourceLocation LParenLoc,
11924                       MutableArrayRef<Expr *> Args,
11925                       SourceLocation RParenLoc,
11926                       bool EmptyLookup, bool AllowTypoCorrection) {
11927   // Do not try to recover if it is already building a recovery call.
11928   // This stops infinite loops for template instantiations like
11929   //
11930   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11931   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11932   //
11933   if (SemaRef.IsBuildingRecoveryCallExpr)
11934     return ExprError();
11935   BuildRecoveryCallExprRAII RCE(SemaRef);
11936 
11937   CXXScopeSpec SS;
11938   SS.Adopt(ULE->getQualifierLoc());
11939   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11940 
11941   TemplateArgumentListInfo TABuffer;
11942   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11943   if (ULE->hasExplicitTemplateArgs()) {
11944     ULE->copyTemplateArgumentsInto(TABuffer);
11945     ExplicitTemplateArgs = &TABuffer;
11946   }
11947 
11948   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11949                  Sema::LookupOrdinaryName);
11950   bool DoDiagnoseEmptyLookup = EmptyLookup;
11951   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11952                               OverloadCandidateSet::CSK_Normal,
11953                               ExplicitTemplateArgs, Args,
11954                               &DoDiagnoseEmptyLookup) &&
11955     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11956         S, SS, R,
11957         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11958                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11959         ExplicitTemplateArgs, Args)))
11960     return ExprError();
11961 
11962   assert(!R.empty() && "lookup results empty despite recovery");
11963 
11964   // If recovery created an ambiguity, just bail out.
11965   if (R.isAmbiguous()) {
11966     R.suppressDiagnostics();
11967     return ExprError();
11968   }
11969 
11970   // Build an implicit member call if appropriate.  Just drop the
11971   // casts and such from the call, we don't really care.
11972   ExprResult NewFn = ExprError();
11973   if ((*R.begin())->isCXXClassMember())
11974     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11975                                                     ExplicitTemplateArgs, S);
11976   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11977     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11978                                         ExplicitTemplateArgs);
11979   else
11980     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11981 
11982   if (NewFn.isInvalid())
11983     return ExprError();
11984 
11985   // This shouldn't cause an infinite loop because we're giving it
11986   // an expression with viable lookup results, which should never
11987   // end up here.
11988   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11989                                MultiExprArg(Args.data(), Args.size()),
11990                                RParenLoc);
11991 }
11992 
11993 /// Constructs and populates an OverloadedCandidateSet from
11994 /// the given function.
11995 /// \returns true when an the ExprResult output parameter has been set.
11996 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11997                                   UnresolvedLookupExpr *ULE,
11998                                   MultiExprArg Args,
11999                                   SourceLocation RParenLoc,
12000                                   OverloadCandidateSet *CandidateSet,
12001                                   ExprResult *Result) {
12002 #ifndef NDEBUG
12003   if (ULE->requiresADL()) {
12004     // To do ADL, we must have found an unqualified name.
12005     assert(!ULE->getQualifier() && "qualified name with ADL");
12006 
12007     // We don't perform ADL for implicit declarations of builtins.
12008     // Verify that this was correctly set up.
12009     FunctionDecl *F;
12010     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
12011         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12012         F->getBuiltinID() && F->isImplicit())
12013       llvm_unreachable("performing ADL for builtin");
12014 
12015     // We don't perform ADL in C.
12016     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12017   }
12018 #endif
12019 
12020   UnbridgedCastsSet UnbridgedCasts;
12021   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12022     *Result = ExprError();
12023     return true;
12024   }
12025 
12026   // Add the functions denoted by the callee to the set of candidate
12027   // functions, including those from argument-dependent lookup.
12028   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12029 
12030   if (getLangOpts().MSVCCompat &&
12031       CurContext->isDependentContext() && !isSFINAEContext() &&
12032       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12033 
12034     OverloadCandidateSet::iterator Best;
12035     if (CandidateSet->empty() ||
12036         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12037             OR_No_Viable_Function) {
12038       // In Microsoft mode, if we are inside a template class member function
12039       // then create a type dependent CallExpr. The goal is to postpone name
12040       // lookup to instantiation time to be able to search into type dependent
12041       // base classes.
12042       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12043                                       VK_RValue, RParenLoc);
12044       CE->setTypeDependent(true);
12045       CE->setValueDependent(true);
12046       CE->setInstantiationDependent(true);
12047       *Result = CE;
12048       return true;
12049     }
12050   }
12051 
12052   if (CandidateSet->empty())
12053     return false;
12054 
12055   UnbridgedCasts.restore();
12056   return false;
12057 }
12058 
12059 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12060 /// the completed call expression. If overload resolution fails, emits
12061 /// diagnostics and returns ExprError()
12062 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12063                                            UnresolvedLookupExpr *ULE,
12064                                            SourceLocation LParenLoc,
12065                                            MultiExprArg Args,
12066                                            SourceLocation RParenLoc,
12067                                            Expr *ExecConfig,
12068                                            OverloadCandidateSet *CandidateSet,
12069                                            OverloadCandidateSet::iterator *Best,
12070                                            OverloadingResult OverloadResult,
12071                                            bool AllowTypoCorrection) {
12072   if (CandidateSet->empty())
12073     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12074                                  RParenLoc, /*EmptyLookup=*/true,
12075                                  AllowTypoCorrection);
12076 
12077   switch (OverloadResult) {
12078   case OR_Success: {
12079     FunctionDecl *FDecl = (*Best)->Function;
12080     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12081     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12082       return ExprError();
12083     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12084     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12085                                          ExecConfig, /*IsExecConfig=*/false,
12086                                          (*Best)->IsADLCandidate);
12087   }
12088 
12089   case OR_No_Viable_Function: {
12090     // Try to recover by looking for viable functions which the user might
12091     // have meant to call.
12092     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12093                                                 Args, RParenLoc,
12094                                                 /*EmptyLookup=*/false,
12095                                                 AllowTypoCorrection);
12096     if (!Recovery.isInvalid())
12097       return Recovery;
12098 
12099     // If the user passes in a function that we can't take the address of, we
12100     // generally end up emitting really bad error messages. Here, we attempt to
12101     // emit better ones.
12102     for (const Expr *Arg : Args) {
12103       if (!Arg->getType()->isFunctionType())
12104         continue;
12105       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12106         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12107         if (FD &&
12108             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12109                                                        Arg->getExprLoc()))
12110           return ExprError();
12111       }
12112     }
12113 
12114     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12115         << ULE->getName() << Fn->getSourceRange();
12116     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12117     break;
12118   }
12119 
12120   case OR_Ambiguous:
12121     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12122         << ULE->getName() << Fn->getSourceRange();
12123     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12124     break;
12125 
12126   case OR_Deleted: {
12127     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12128         << (*Best)->Function->isDeleted() << ULE->getName()
12129         << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12130         << Fn->getSourceRange();
12131     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12132 
12133     // We emitted an error for the unavailable/deleted function call but keep
12134     // the call in the AST.
12135     FunctionDecl *FDecl = (*Best)->Function;
12136     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12137     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12138                                          ExecConfig, /*IsExecConfig=*/false,
12139                                          (*Best)->IsADLCandidate);
12140   }
12141   }
12142 
12143   // Overload resolution failed.
12144   return ExprError();
12145 }
12146 
12147 static void markUnaddressableCandidatesUnviable(Sema &S,
12148                                                 OverloadCandidateSet &CS) {
12149   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12150     if (I->Viable &&
12151         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12152       I->Viable = false;
12153       I->FailureKind = ovl_fail_addr_not_available;
12154     }
12155   }
12156 }
12157 
12158 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12159 /// (which eventually refers to the declaration Func) and the call
12160 /// arguments Args/NumArgs, attempt to resolve the function call down
12161 /// to a specific function. If overload resolution succeeds, returns
12162 /// the call expression produced by overload resolution.
12163 /// Otherwise, emits diagnostics and returns ExprError.
12164 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12165                                          UnresolvedLookupExpr *ULE,
12166                                          SourceLocation LParenLoc,
12167                                          MultiExprArg Args,
12168                                          SourceLocation RParenLoc,
12169                                          Expr *ExecConfig,
12170                                          bool AllowTypoCorrection,
12171                                          bool CalleesAddressIsTaken) {
12172   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12173                                     OverloadCandidateSet::CSK_Normal);
12174   ExprResult result;
12175 
12176   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12177                              &result))
12178     return result;
12179 
12180   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12181   // functions that aren't addressible are considered unviable.
12182   if (CalleesAddressIsTaken)
12183     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12184 
12185   OverloadCandidateSet::iterator Best;
12186   OverloadingResult OverloadResult =
12187       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12188 
12189   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12190                                   RParenLoc, ExecConfig, &CandidateSet,
12191                                   &Best, OverloadResult,
12192                                   AllowTypoCorrection);
12193 }
12194 
12195 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12196   return Functions.size() > 1 ||
12197     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12198 }
12199 
12200 /// Create a unary operation that may resolve to an overloaded
12201 /// operator.
12202 ///
12203 /// \param OpLoc The location of the operator itself (e.g., '*').
12204 ///
12205 /// \param Opc The UnaryOperatorKind that describes this operator.
12206 ///
12207 /// \param Fns The set of non-member functions that will be
12208 /// considered by overload resolution. The caller needs to build this
12209 /// set based on the context using, e.g.,
12210 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12211 /// set should not contain any member functions; those will be added
12212 /// by CreateOverloadedUnaryOp().
12213 ///
12214 /// \param Input The input argument.
12215 ExprResult
12216 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12217                               const UnresolvedSetImpl &Fns,
12218                               Expr *Input, bool PerformADL) {
12219   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12220   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12221   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12222   // TODO: provide better source location info.
12223   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12224 
12225   if (checkPlaceholderForOverload(*this, Input))
12226     return ExprError();
12227 
12228   Expr *Args[2] = { Input, nullptr };
12229   unsigned NumArgs = 1;
12230 
12231   // For post-increment and post-decrement, add the implicit '0' as
12232   // the second argument, so that we know this is a post-increment or
12233   // post-decrement.
12234   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12235     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12236     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12237                                      SourceLocation());
12238     NumArgs = 2;
12239   }
12240 
12241   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12242 
12243   if (Input->isTypeDependent()) {
12244     if (Fns.empty())
12245       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12246                                          VK_RValue, OK_Ordinary, OpLoc, false);
12247 
12248     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12249     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12250         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12251         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12252     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12253                                        Context.DependentTy, VK_RValue, OpLoc,
12254                                        FPOptions());
12255   }
12256 
12257   // Build an empty overload set.
12258   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12259 
12260   // Add the candidates from the given function set.
12261   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12262 
12263   // Add operator candidates that are member functions.
12264   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12265 
12266   // Add candidates from ADL.
12267   if (PerformADL) {
12268     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12269                                          /*ExplicitTemplateArgs*/nullptr,
12270                                          CandidateSet);
12271   }
12272 
12273   // Add builtin operator candidates.
12274   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12275 
12276   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12277 
12278   // Perform overload resolution.
12279   OverloadCandidateSet::iterator Best;
12280   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12281   case OR_Success: {
12282     // We found a built-in operator or an overloaded operator.
12283     FunctionDecl *FnDecl = Best->Function;
12284 
12285     if (FnDecl) {
12286       Expr *Base = nullptr;
12287       // We matched an overloaded operator. Build a call to that
12288       // operator.
12289 
12290       // Convert the arguments.
12291       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12292         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12293 
12294         ExprResult InputRes =
12295           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12296                                               Best->FoundDecl, Method);
12297         if (InputRes.isInvalid())
12298           return ExprError();
12299         Base = Input = InputRes.get();
12300       } else {
12301         // Convert the arguments.
12302         ExprResult InputInit
12303           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12304                                                       Context,
12305                                                       FnDecl->getParamDecl(0)),
12306                                       SourceLocation(),
12307                                       Input);
12308         if (InputInit.isInvalid())
12309           return ExprError();
12310         Input = InputInit.get();
12311       }
12312 
12313       // Build the actual expression node.
12314       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12315                                                 Base, HadMultipleCandidates,
12316                                                 OpLoc);
12317       if (FnExpr.isInvalid())
12318         return ExprError();
12319 
12320       // Determine the result type.
12321       QualType ResultTy = FnDecl->getReturnType();
12322       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12323       ResultTy = ResultTy.getNonLValueExprType(Context);
12324 
12325       Args[0] = Input;
12326       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12327           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12328           FPOptions(), Best->IsADLCandidate);
12329 
12330       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12331         return ExprError();
12332 
12333       if (CheckFunctionCall(FnDecl, TheCall,
12334                             FnDecl->getType()->castAs<FunctionProtoType>()))
12335         return ExprError();
12336 
12337       return MaybeBindToTemporary(TheCall);
12338     } else {
12339       // We matched a built-in operator. Convert the arguments, then
12340       // break out so that we will build the appropriate built-in
12341       // operator node.
12342       ExprResult InputRes = PerformImplicitConversion(
12343           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12344           CCK_ForBuiltinOverloadedOp);
12345       if (InputRes.isInvalid())
12346         return ExprError();
12347       Input = InputRes.get();
12348       break;
12349     }
12350   }
12351 
12352   case OR_No_Viable_Function:
12353     // This is an erroneous use of an operator which can be overloaded by
12354     // a non-member function. Check for non-member operators which were
12355     // defined too late to be candidates.
12356     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12357       // FIXME: Recover by calling the found function.
12358       return ExprError();
12359 
12360     // No viable function; fall through to handling this as a
12361     // built-in operator, which will produce an error message for us.
12362     break;
12363 
12364   case OR_Ambiguous:
12365     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12366         << UnaryOperator::getOpcodeStr(Opc)
12367         << Input->getType()
12368         << Input->getSourceRange();
12369     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12370                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12371     return ExprError();
12372 
12373   case OR_Deleted:
12374     Diag(OpLoc, diag::err_ovl_deleted_oper)
12375       << Best->Function->isDeleted()
12376       << UnaryOperator::getOpcodeStr(Opc)
12377       << getDeletedOrUnavailableSuffix(Best->Function)
12378       << Input->getSourceRange();
12379     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12380                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12381     return ExprError();
12382   }
12383 
12384   // Either we found no viable overloaded operator or we matched a
12385   // built-in operator. In either case, fall through to trying to
12386   // build a built-in operation.
12387   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12388 }
12389 
12390 /// Create a binary operation that may resolve to an overloaded
12391 /// operator.
12392 ///
12393 /// \param OpLoc The location of the operator itself (e.g., '+').
12394 ///
12395 /// \param Opc The BinaryOperatorKind that describes this operator.
12396 ///
12397 /// \param Fns The set of non-member functions that will be
12398 /// considered by overload resolution. The caller needs to build this
12399 /// set based on the context using, e.g.,
12400 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12401 /// set should not contain any member functions; those will be added
12402 /// by CreateOverloadedBinOp().
12403 ///
12404 /// \param LHS Left-hand argument.
12405 /// \param RHS Right-hand argument.
12406 ExprResult
12407 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12408                             BinaryOperatorKind Opc,
12409                             const UnresolvedSetImpl &Fns,
12410                             Expr *LHS, Expr *RHS, bool PerformADL) {
12411   Expr *Args[2] = { LHS, RHS };
12412   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12413 
12414   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12415   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12416 
12417   // If either side is type-dependent, create an appropriate dependent
12418   // expression.
12419   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12420     if (Fns.empty()) {
12421       // If there are no functions to store, just build a dependent
12422       // BinaryOperator or CompoundAssignment.
12423       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12424         return new (Context) BinaryOperator(
12425             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12426             OpLoc, FPFeatures);
12427 
12428       return new (Context) CompoundAssignOperator(
12429           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12430           Context.DependentTy, Context.DependentTy, OpLoc,
12431           FPFeatures);
12432     }
12433 
12434     // FIXME: save results of ADL from here?
12435     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12436     // TODO: provide better source location info in DNLoc component.
12437     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12438     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12439         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12440         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12441     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12442                                        Context.DependentTy, VK_RValue, OpLoc,
12443                                        FPFeatures);
12444   }
12445 
12446   // Always do placeholder-like conversions on the RHS.
12447   if (checkPlaceholderForOverload(*this, Args[1]))
12448     return ExprError();
12449 
12450   // Do placeholder-like conversion on the LHS; note that we should
12451   // not get here with a PseudoObject LHS.
12452   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12453   if (checkPlaceholderForOverload(*this, Args[0]))
12454     return ExprError();
12455 
12456   // If this is the assignment operator, we only perform overload resolution
12457   // if the left-hand side is a class or enumeration type. This is actually
12458   // a hack. The standard requires that we do overload resolution between the
12459   // various built-in candidates, but as DR507 points out, this can lead to
12460   // problems. So we do it this way, which pretty much follows what GCC does.
12461   // Note that we go the traditional code path for compound assignment forms.
12462   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12463     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12464 
12465   // If this is the .* operator, which is not overloadable, just
12466   // create a built-in binary operator.
12467   if (Opc == BO_PtrMemD)
12468     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12469 
12470   // Build an empty overload set.
12471   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12472 
12473   // Add the candidates from the given function set.
12474   AddFunctionCandidates(Fns, Args, CandidateSet);
12475 
12476   // Add operator candidates that are member functions.
12477   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12478 
12479   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12480   // performed for an assignment operator (nor for operator[] nor operator->,
12481   // which don't get here).
12482   if (Opc != BO_Assign && PerformADL)
12483     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12484                                          /*ExplicitTemplateArgs*/ nullptr,
12485                                          CandidateSet);
12486 
12487   // Add builtin operator candidates.
12488   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12489 
12490   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12491 
12492   // Perform overload resolution.
12493   OverloadCandidateSet::iterator Best;
12494   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12495     case OR_Success: {
12496       // We found a built-in operator or an overloaded operator.
12497       FunctionDecl *FnDecl = Best->Function;
12498 
12499       if (FnDecl) {
12500         Expr *Base = nullptr;
12501         // We matched an overloaded operator. Build a call to that
12502         // operator.
12503 
12504         // Convert the arguments.
12505         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12506           // Best->Access is only meaningful for class members.
12507           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12508 
12509           ExprResult Arg1 =
12510             PerformCopyInitialization(
12511               InitializedEntity::InitializeParameter(Context,
12512                                                      FnDecl->getParamDecl(0)),
12513               SourceLocation(), Args[1]);
12514           if (Arg1.isInvalid())
12515             return ExprError();
12516 
12517           ExprResult Arg0 =
12518             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12519                                                 Best->FoundDecl, Method);
12520           if (Arg0.isInvalid())
12521             return ExprError();
12522           Base = Args[0] = Arg0.getAs<Expr>();
12523           Args[1] = RHS = Arg1.getAs<Expr>();
12524         } else {
12525           // Convert the arguments.
12526           ExprResult Arg0 = PerformCopyInitialization(
12527             InitializedEntity::InitializeParameter(Context,
12528                                                    FnDecl->getParamDecl(0)),
12529             SourceLocation(), Args[0]);
12530           if (Arg0.isInvalid())
12531             return ExprError();
12532 
12533           ExprResult Arg1 =
12534             PerformCopyInitialization(
12535               InitializedEntity::InitializeParameter(Context,
12536                                                      FnDecl->getParamDecl(1)),
12537               SourceLocation(), Args[1]);
12538           if (Arg1.isInvalid())
12539             return ExprError();
12540           Args[0] = LHS = Arg0.getAs<Expr>();
12541           Args[1] = RHS = Arg1.getAs<Expr>();
12542         }
12543 
12544         // Build the actual expression node.
12545         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12546                                                   Best->FoundDecl, Base,
12547                                                   HadMultipleCandidates, OpLoc);
12548         if (FnExpr.isInvalid())
12549           return ExprError();
12550 
12551         // Determine the result type.
12552         QualType ResultTy = FnDecl->getReturnType();
12553         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12554         ResultTy = ResultTy.getNonLValueExprType(Context);
12555 
12556         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12557             Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12558             Best->IsADLCandidate);
12559 
12560         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12561                                 FnDecl))
12562           return ExprError();
12563 
12564         ArrayRef<const Expr *> ArgsArray(Args, 2);
12565         const Expr *ImplicitThis = nullptr;
12566         // Cut off the implicit 'this'.
12567         if (isa<CXXMethodDecl>(FnDecl)) {
12568           ImplicitThis = ArgsArray[0];
12569           ArgsArray = ArgsArray.slice(1);
12570         }
12571 
12572         // Check for a self move.
12573         if (Op == OO_Equal)
12574           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12575 
12576         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12577                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12578                   VariadicDoesNotApply);
12579 
12580         return MaybeBindToTemporary(TheCall);
12581       } else {
12582         // We matched a built-in operator. Convert the arguments, then
12583         // break out so that we will build the appropriate built-in
12584         // operator node.
12585         ExprResult ArgsRes0 = PerformImplicitConversion(
12586             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12587             AA_Passing, CCK_ForBuiltinOverloadedOp);
12588         if (ArgsRes0.isInvalid())
12589           return ExprError();
12590         Args[0] = ArgsRes0.get();
12591 
12592         ExprResult ArgsRes1 = PerformImplicitConversion(
12593             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12594             AA_Passing, CCK_ForBuiltinOverloadedOp);
12595         if (ArgsRes1.isInvalid())
12596           return ExprError();
12597         Args[1] = ArgsRes1.get();
12598         break;
12599       }
12600     }
12601 
12602     case OR_No_Viable_Function: {
12603       // C++ [over.match.oper]p9:
12604       //   If the operator is the operator , [...] and there are no
12605       //   viable functions, then the operator is assumed to be the
12606       //   built-in operator and interpreted according to clause 5.
12607       if (Opc == BO_Comma)
12608         break;
12609 
12610       // For class as left operand for assignment or compound assignment
12611       // operator do not fall through to handling in built-in, but report that
12612       // no overloaded assignment operator found
12613       ExprResult Result = ExprError();
12614       if (Args[0]->getType()->isRecordType() &&
12615           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12616         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12617              << BinaryOperator::getOpcodeStr(Opc)
12618              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12619         if (Args[0]->getType()->isIncompleteType()) {
12620           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12621             << Args[0]->getType()
12622             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12623         }
12624       } else {
12625         // This is an erroneous use of an operator which can be overloaded by
12626         // a non-member function. Check for non-member operators which were
12627         // defined too late to be candidates.
12628         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12629           // FIXME: Recover by calling the found function.
12630           return ExprError();
12631 
12632         // No viable function; try to create a built-in operation, which will
12633         // produce an error. Then, show the non-viable candidates.
12634         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12635       }
12636       assert(Result.isInvalid() &&
12637              "C++ binary operator overloading is missing candidates!");
12638       if (Result.isInvalid())
12639         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12640                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12641       return Result;
12642     }
12643 
12644     case OR_Ambiguous:
12645       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12646           << BinaryOperator::getOpcodeStr(Opc)
12647           << Args[0]->getType() << Args[1]->getType()
12648           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12649       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12650                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12651       return ExprError();
12652 
12653     case OR_Deleted:
12654       if (isImplicitlyDeleted(Best->Function)) {
12655         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12656         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12657           << Context.getRecordType(Method->getParent())
12658           << getSpecialMember(Method);
12659 
12660         // The user probably meant to call this special member. Just
12661         // explain why it's deleted.
12662         NoteDeletedFunction(Method);
12663         return ExprError();
12664       } else {
12665         Diag(OpLoc, diag::err_ovl_deleted_oper)
12666           << Best->Function->isDeleted()
12667           << BinaryOperator::getOpcodeStr(Opc)
12668           << getDeletedOrUnavailableSuffix(Best->Function)
12669           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12670       }
12671       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12672                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12673       return ExprError();
12674   }
12675 
12676   // We matched a built-in operator; build it.
12677   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12678 }
12679 
12680 ExprResult
12681 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12682                                          SourceLocation RLoc,
12683                                          Expr *Base, Expr *Idx) {
12684   Expr *Args[2] = { Base, Idx };
12685   DeclarationName OpName =
12686       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12687 
12688   // If either side is type-dependent, create an appropriate dependent
12689   // expression.
12690   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12691 
12692     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12693     // CHECKME: no 'operator' keyword?
12694     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12695     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12696     UnresolvedLookupExpr *Fn
12697       = UnresolvedLookupExpr::Create(Context, NamingClass,
12698                                      NestedNameSpecifierLoc(), OpNameInfo,
12699                                      /*ADL*/ true, /*Overloaded*/ false,
12700                                      UnresolvedSetIterator(),
12701                                      UnresolvedSetIterator());
12702     // Can't add any actual overloads yet
12703 
12704     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12705                                        Context.DependentTy, VK_RValue, RLoc,
12706                                        FPOptions());
12707   }
12708 
12709   // Handle placeholders on both operands.
12710   if (checkPlaceholderForOverload(*this, Args[0]))
12711     return ExprError();
12712   if (checkPlaceholderForOverload(*this, Args[1]))
12713     return ExprError();
12714 
12715   // Build an empty overload set.
12716   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12717 
12718   // Subscript can only be overloaded as a member function.
12719 
12720   // Add operator candidates that are member functions.
12721   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12722 
12723   // Add builtin operator candidates.
12724   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12725 
12726   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12727 
12728   // Perform overload resolution.
12729   OverloadCandidateSet::iterator Best;
12730   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12731     case OR_Success: {
12732       // We found a built-in operator or an overloaded operator.
12733       FunctionDecl *FnDecl = Best->Function;
12734 
12735       if (FnDecl) {
12736         // We matched an overloaded operator. Build a call to that
12737         // operator.
12738 
12739         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12740 
12741         // Convert the arguments.
12742         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12743         ExprResult Arg0 =
12744           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12745                                               Best->FoundDecl, Method);
12746         if (Arg0.isInvalid())
12747           return ExprError();
12748         Args[0] = Arg0.get();
12749 
12750         // Convert the arguments.
12751         ExprResult InputInit
12752           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12753                                                       Context,
12754                                                       FnDecl->getParamDecl(0)),
12755                                       SourceLocation(),
12756                                       Args[1]);
12757         if (InputInit.isInvalid())
12758           return ExprError();
12759 
12760         Args[1] = InputInit.getAs<Expr>();
12761 
12762         // Build the actual expression node.
12763         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12764         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12765         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12766                                                   Best->FoundDecl,
12767                                                   Base,
12768                                                   HadMultipleCandidates,
12769                                                   OpLocInfo.getLoc(),
12770                                                   OpLocInfo.getInfo());
12771         if (FnExpr.isInvalid())
12772           return ExprError();
12773 
12774         // Determine the result type
12775         QualType ResultTy = FnDecl->getReturnType();
12776         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12777         ResultTy = ResultTy.getNonLValueExprType(Context);
12778 
12779         CXXOperatorCallExpr *TheCall =
12780             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12781                                         Args, ResultTy, VK, RLoc, FPOptions());
12782 
12783         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12784           return ExprError();
12785 
12786         if (CheckFunctionCall(Method, TheCall,
12787                               Method->getType()->castAs<FunctionProtoType>()))
12788           return ExprError();
12789 
12790         return MaybeBindToTemporary(TheCall);
12791       } else {
12792         // We matched a built-in operator. Convert the arguments, then
12793         // break out so that we will build the appropriate built-in
12794         // operator node.
12795         ExprResult ArgsRes0 = PerformImplicitConversion(
12796             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12797             AA_Passing, CCK_ForBuiltinOverloadedOp);
12798         if (ArgsRes0.isInvalid())
12799           return ExprError();
12800         Args[0] = ArgsRes0.get();
12801 
12802         ExprResult ArgsRes1 = PerformImplicitConversion(
12803             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12804             AA_Passing, CCK_ForBuiltinOverloadedOp);
12805         if (ArgsRes1.isInvalid())
12806           return ExprError();
12807         Args[1] = ArgsRes1.get();
12808 
12809         break;
12810       }
12811     }
12812 
12813     case OR_No_Viable_Function: {
12814       if (CandidateSet.empty())
12815         Diag(LLoc, diag::err_ovl_no_oper)
12816           << Args[0]->getType() << /*subscript*/ 0
12817           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12818       else
12819         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12820           << Args[0]->getType()
12821           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12822       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12823                                   "[]", LLoc);
12824       return ExprError();
12825     }
12826 
12827     case OR_Ambiguous:
12828       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12829           << "[]"
12830           << Args[0]->getType() << Args[1]->getType()
12831           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12832       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12833                                   "[]", LLoc);
12834       return ExprError();
12835 
12836     case OR_Deleted:
12837       Diag(LLoc, diag::err_ovl_deleted_oper)
12838         << Best->Function->isDeleted() << "[]"
12839         << getDeletedOrUnavailableSuffix(Best->Function)
12840         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12841       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12842                                   "[]", LLoc);
12843       return ExprError();
12844     }
12845 
12846   // We matched a built-in operator; build it.
12847   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12848 }
12849 
12850 /// BuildCallToMemberFunction - Build a call to a member
12851 /// function. MemExpr is the expression that refers to the member
12852 /// function (and includes the object parameter), Args/NumArgs are the
12853 /// arguments to the function call (not including the object
12854 /// parameter). The caller needs to validate that the member
12855 /// expression refers to a non-static member function or an overloaded
12856 /// member function.
12857 ExprResult
12858 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12859                                 SourceLocation LParenLoc,
12860                                 MultiExprArg Args,
12861                                 SourceLocation RParenLoc) {
12862   assert(MemExprE->getType() == Context.BoundMemberTy ||
12863          MemExprE->getType() == Context.OverloadTy);
12864 
12865   // Dig out the member expression. This holds both the object
12866   // argument and the member function we're referring to.
12867   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12868 
12869   // Determine whether this is a call to a pointer-to-member function.
12870   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12871     assert(op->getType() == Context.BoundMemberTy);
12872     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12873 
12874     QualType fnType =
12875       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12876 
12877     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12878     QualType resultType = proto->getCallResultType(Context);
12879     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12880 
12881     // Check that the object type isn't more qualified than the
12882     // member function we're calling.
12883     Qualifiers funcQuals = proto->getMethodQuals();
12884 
12885     QualType objectType = op->getLHS()->getType();
12886     if (op->getOpcode() == BO_PtrMemI)
12887       objectType = objectType->castAs<PointerType>()->getPointeeType();
12888     Qualifiers objectQuals = objectType.getQualifiers();
12889 
12890     Qualifiers difference = objectQuals - funcQuals;
12891     difference.removeObjCGCAttr();
12892     difference.removeAddressSpace();
12893     if (difference) {
12894       std::string qualsString = difference.getAsString();
12895       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12896         << fnType.getUnqualifiedType()
12897         << qualsString
12898         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12899     }
12900 
12901     CXXMemberCallExpr *call =
12902         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12903                                   valueKind, RParenLoc, proto->getNumParams());
12904 
12905     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12906                             call, nullptr))
12907       return ExprError();
12908 
12909     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12910       return ExprError();
12911 
12912     if (CheckOtherCall(call, proto))
12913       return ExprError();
12914 
12915     return MaybeBindToTemporary(call);
12916   }
12917 
12918   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12919     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
12920                             RParenLoc);
12921 
12922   UnbridgedCastsSet UnbridgedCasts;
12923   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12924     return ExprError();
12925 
12926   MemberExpr *MemExpr;
12927   CXXMethodDecl *Method = nullptr;
12928   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12929   NestedNameSpecifier *Qualifier = nullptr;
12930   if (isa<MemberExpr>(NakedMemExpr)) {
12931     MemExpr = cast<MemberExpr>(NakedMemExpr);
12932     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12933     FoundDecl = MemExpr->getFoundDecl();
12934     Qualifier = MemExpr->getQualifier();
12935     UnbridgedCasts.restore();
12936   } else {
12937     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12938     Qualifier = UnresExpr->getQualifier();
12939 
12940     QualType ObjectType = UnresExpr->getBaseType();
12941     Expr::Classification ObjectClassification
12942       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12943                             : UnresExpr->getBase()->Classify(Context);
12944 
12945     // Add overload candidates
12946     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12947                                       OverloadCandidateSet::CSK_Normal);
12948 
12949     // FIXME: avoid copy.
12950     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12951     if (UnresExpr->hasExplicitTemplateArgs()) {
12952       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12953       TemplateArgs = &TemplateArgsBuffer;
12954     }
12955 
12956     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12957            E = UnresExpr->decls_end(); I != E; ++I) {
12958 
12959       NamedDecl *Func = *I;
12960       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12961       if (isa<UsingShadowDecl>(Func))
12962         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12963 
12964 
12965       // Microsoft supports direct constructor calls.
12966       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12967         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12968                              Args, CandidateSet);
12969       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12970         // If explicit template arguments were provided, we can't call a
12971         // non-template member function.
12972         if (TemplateArgs)
12973           continue;
12974 
12975         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12976                            ObjectClassification, Args, CandidateSet,
12977                            /*SuppressUserConversions=*/false);
12978       } else {
12979         AddMethodTemplateCandidate(
12980             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12981             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12982             /*SuppressUsedConversions=*/false);
12983       }
12984     }
12985 
12986     DeclarationName DeclName = UnresExpr->getMemberName();
12987 
12988     UnbridgedCasts.restore();
12989 
12990     OverloadCandidateSet::iterator Best;
12991     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12992                                             Best)) {
12993     case OR_Success:
12994       Method = cast<CXXMethodDecl>(Best->Function);
12995       FoundDecl = Best->FoundDecl;
12996       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12997       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12998         return ExprError();
12999       // If FoundDecl is different from Method (such as if one is a template
13000       // and the other a specialization), make sure DiagnoseUseOfDecl is
13001       // called on both.
13002       // FIXME: This would be more comprehensively addressed by modifying
13003       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13004       // being used.
13005       if (Method != FoundDecl.getDecl() &&
13006                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13007         return ExprError();
13008       break;
13009 
13010     case OR_No_Viable_Function:
13011       Diag(UnresExpr->getMemberLoc(),
13012            diag::err_ovl_no_viable_member_function_in_call)
13013         << DeclName << MemExprE->getSourceRange();
13014       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13015       // FIXME: Leaking incoming expressions!
13016       return ExprError();
13017 
13018     case OR_Ambiguous:
13019       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
13020         << DeclName << MemExprE->getSourceRange();
13021       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13022       // FIXME: Leaking incoming expressions!
13023       return ExprError();
13024 
13025     case OR_Deleted:
13026       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
13027         << Best->Function->isDeleted()
13028         << DeclName
13029         << getDeletedOrUnavailableSuffix(Best->Function)
13030         << MemExprE->getSourceRange();
13031       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13032       // FIXME: Leaking incoming expressions!
13033       return ExprError();
13034     }
13035 
13036     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13037 
13038     // If overload resolution picked a static member, build a
13039     // non-member call based on that function.
13040     if (Method->isStatic()) {
13041       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13042                                    RParenLoc);
13043     }
13044 
13045     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13046   }
13047 
13048   QualType ResultType = Method->getReturnType();
13049   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13050   ResultType = ResultType.getNonLValueExprType(Context);
13051 
13052   assert(Method && "Member call to something that isn't a method?");
13053   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13054   CXXMemberCallExpr *TheCall =
13055       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13056                                 RParenLoc, Proto->getNumParams());
13057 
13058   // Check for a valid return type.
13059   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13060                           TheCall, Method))
13061     return ExprError();
13062 
13063   // Convert the object argument (for a non-static member function call).
13064   // We only need to do this if there was actually an overload; otherwise
13065   // it was done at lookup.
13066   if (!Method->isStatic()) {
13067     ExprResult ObjectArg =
13068       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13069                                           FoundDecl, Method);
13070     if (ObjectArg.isInvalid())
13071       return ExprError();
13072     MemExpr->setBase(ObjectArg.get());
13073   }
13074 
13075   // Convert the rest of the arguments
13076   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13077                               RParenLoc))
13078     return ExprError();
13079 
13080   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13081 
13082   if (CheckFunctionCall(Method, TheCall, Proto))
13083     return ExprError();
13084 
13085   // In the case the method to call was not selected by the overloading
13086   // resolution process, we still need to handle the enable_if attribute. Do
13087   // that here, so it will not hide previous -- and more relevant -- errors.
13088   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13089     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13090       Diag(MemE->getMemberLoc(),
13091            diag::err_ovl_no_viable_member_function_in_call)
13092           << Method << Method->getSourceRange();
13093       Diag(Method->getLocation(),
13094            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13095           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13096       return ExprError();
13097     }
13098   }
13099 
13100   if ((isa<CXXConstructorDecl>(CurContext) ||
13101        isa<CXXDestructorDecl>(CurContext)) &&
13102       TheCall->getMethodDecl()->isPure()) {
13103     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13104 
13105     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13106         MemExpr->performsVirtualDispatch(getLangOpts())) {
13107       Diag(MemExpr->getBeginLoc(),
13108            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13109           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13110           << MD->getParent()->getDeclName();
13111 
13112       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13113       if (getLangOpts().AppleKext)
13114         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13115             << MD->getParent()->getDeclName() << MD->getDeclName();
13116     }
13117   }
13118 
13119   if (CXXDestructorDecl *DD =
13120           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13121     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13122     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13123     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13124                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13125                          MemExpr->getMemberLoc());
13126   }
13127 
13128   return MaybeBindToTemporary(TheCall);
13129 }
13130 
13131 /// BuildCallToObjectOfClassType - Build a call to an object of class
13132 /// type (C++ [over.call.object]), which can end up invoking an
13133 /// overloaded function call operator (@c operator()) or performing a
13134 /// user-defined conversion on the object argument.
13135 ExprResult
13136 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13137                                    SourceLocation LParenLoc,
13138                                    MultiExprArg Args,
13139                                    SourceLocation RParenLoc) {
13140   if (checkPlaceholderForOverload(*this, Obj))
13141     return ExprError();
13142   ExprResult Object = Obj;
13143 
13144   UnbridgedCastsSet UnbridgedCasts;
13145   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13146     return ExprError();
13147 
13148   assert(Object.get()->getType()->isRecordType() &&
13149          "Requires object type argument");
13150   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13151 
13152   // C++ [over.call.object]p1:
13153   //  If the primary-expression E in the function call syntax
13154   //  evaluates to a class object of type "cv T", then the set of
13155   //  candidate functions includes at least the function call
13156   //  operators of T. The function call operators of T are obtained by
13157   //  ordinary lookup of the name operator() in the context of
13158   //  (E).operator().
13159   OverloadCandidateSet CandidateSet(LParenLoc,
13160                                     OverloadCandidateSet::CSK_Operator);
13161   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13162 
13163   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13164                           diag::err_incomplete_object_call, Object.get()))
13165     return true;
13166 
13167   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13168   LookupQualifiedName(R, Record->getDecl());
13169   R.suppressDiagnostics();
13170 
13171   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13172        Oper != OperEnd; ++Oper) {
13173     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13174                        Object.get()->Classify(Context), Args, CandidateSet,
13175                        /*SuppressUserConversions=*/false);
13176   }
13177 
13178   // C++ [over.call.object]p2:
13179   //   In addition, for each (non-explicit in C++0x) conversion function
13180   //   declared in T of the form
13181   //
13182   //        operator conversion-type-id () cv-qualifier;
13183   //
13184   //   where cv-qualifier is the same cv-qualification as, or a
13185   //   greater cv-qualification than, cv, and where conversion-type-id
13186   //   denotes the type "pointer to function of (P1,...,Pn) returning
13187   //   R", or the type "reference to pointer to function of
13188   //   (P1,...,Pn) returning R", or the type "reference to function
13189   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13190   //   is also considered as a candidate function. Similarly,
13191   //   surrogate call functions are added to the set of candidate
13192   //   functions for each conversion function declared in an
13193   //   accessible base class provided the function is not hidden
13194   //   within T by another intervening declaration.
13195   const auto &Conversions =
13196       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13197   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13198     NamedDecl *D = *I;
13199     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13200     if (isa<UsingShadowDecl>(D))
13201       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13202 
13203     // Skip over templated conversion functions; they aren't
13204     // surrogates.
13205     if (isa<FunctionTemplateDecl>(D))
13206       continue;
13207 
13208     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13209     if (!Conv->isExplicit()) {
13210       // Strip the reference type (if any) and then the pointer type (if
13211       // any) to get down to what might be a function type.
13212       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13213       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13214         ConvType = ConvPtrType->getPointeeType();
13215 
13216       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13217       {
13218         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13219                               Object.get(), Args, CandidateSet);
13220       }
13221     }
13222   }
13223 
13224   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13225 
13226   // Perform overload resolution.
13227   OverloadCandidateSet::iterator Best;
13228   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13229                                           Best)) {
13230   case OR_Success:
13231     // Overload resolution succeeded; we'll build the appropriate call
13232     // below.
13233     break;
13234 
13235   case OR_No_Viable_Function:
13236     if (CandidateSet.empty())
13237       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13238           << Object.get()->getType() << /*call*/ 1
13239           << Object.get()->getSourceRange();
13240     else
13241       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13242           << Object.get()->getType() << Object.get()->getSourceRange();
13243     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13244     break;
13245 
13246   case OR_Ambiguous:
13247     Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13248         << Object.get()->getType() << Object.get()->getSourceRange();
13249     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13250     break;
13251 
13252   case OR_Deleted:
13253     Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13254         << Best->Function->isDeleted() << Object.get()->getType()
13255         << getDeletedOrUnavailableSuffix(Best->Function)
13256         << Object.get()->getSourceRange();
13257     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13258     break;
13259   }
13260 
13261   if (Best == CandidateSet.end())
13262     return true;
13263 
13264   UnbridgedCasts.restore();
13265 
13266   if (Best->Function == nullptr) {
13267     // Since there is no function declaration, this is one of the
13268     // surrogate candidates. Dig out the conversion function.
13269     CXXConversionDecl *Conv
13270       = cast<CXXConversionDecl>(
13271                          Best->Conversions[0].UserDefined.ConversionFunction);
13272 
13273     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13274                               Best->FoundDecl);
13275     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13276       return ExprError();
13277     assert(Conv == Best->FoundDecl.getDecl() &&
13278              "Found Decl & conversion-to-functionptr should be same, right?!");
13279     // We selected one of the surrogate functions that converts the
13280     // object parameter to a function pointer. Perform the conversion
13281     // on the object argument, then let ActOnCallExpr finish the job.
13282 
13283     // Create an implicit member expr to refer to the conversion operator.
13284     // and then call it.
13285     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13286                                              Conv, HadMultipleCandidates);
13287     if (Call.isInvalid())
13288       return ExprError();
13289     // Record usage of conversion in an implicit cast.
13290     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13291                                     CK_UserDefinedConversion, Call.get(),
13292                                     nullptr, VK_RValue);
13293 
13294     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13295   }
13296 
13297   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13298 
13299   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13300   // that calls this method, using Object for the implicit object
13301   // parameter and passing along the remaining arguments.
13302   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13303 
13304   // An error diagnostic has already been printed when parsing the declaration.
13305   if (Method->isInvalidDecl())
13306     return ExprError();
13307 
13308   const FunctionProtoType *Proto =
13309     Method->getType()->getAs<FunctionProtoType>();
13310 
13311   unsigned NumParams = Proto->getNumParams();
13312 
13313   DeclarationNameInfo OpLocInfo(
13314                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13315   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13316   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13317                                            Obj, HadMultipleCandidates,
13318                                            OpLocInfo.getLoc(),
13319                                            OpLocInfo.getInfo());
13320   if (NewFn.isInvalid())
13321     return true;
13322 
13323   // The number of argument slots to allocate in the call. If we have default
13324   // arguments we need to allocate space for them as well. We additionally
13325   // need one more slot for the object parameter.
13326   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13327 
13328   // Build the full argument list for the method call (the implicit object
13329   // parameter is placed at the beginning of the list).
13330   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13331 
13332   bool IsError = false;
13333 
13334   // Initialize the implicit object parameter.
13335   ExprResult ObjRes =
13336     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13337                                         Best->FoundDecl, Method);
13338   if (ObjRes.isInvalid())
13339     IsError = true;
13340   else
13341     Object = ObjRes;
13342   MethodArgs[0] = Object.get();
13343 
13344   // Check the argument types.
13345   for (unsigned i = 0; i != NumParams; i++) {
13346     Expr *Arg;
13347     if (i < Args.size()) {
13348       Arg = Args[i];
13349 
13350       // Pass the argument.
13351 
13352       ExprResult InputInit
13353         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13354                                                     Context,
13355                                                     Method->getParamDecl(i)),
13356                                     SourceLocation(), Arg);
13357 
13358       IsError |= InputInit.isInvalid();
13359       Arg = InputInit.getAs<Expr>();
13360     } else {
13361       ExprResult DefArg
13362         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13363       if (DefArg.isInvalid()) {
13364         IsError = true;
13365         break;
13366       }
13367 
13368       Arg = DefArg.getAs<Expr>();
13369     }
13370 
13371     MethodArgs[i + 1] = Arg;
13372   }
13373 
13374   // If this is a variadic call, handle args passed through "...".
13375   if (Proto->isVariadic()) {
13376     // Promote the arguments (C99 6.5.2.2p7).
13377     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13378       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13379                                                         nullptr);
13380       IsError |= Arg.isInvalid();
13381       MethodArgs[i + 1] = Arg.get();
13382     }
13383   }
13384 
13385   if (IsError)
13386     return true;
13387 
13388   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13389 
13390   // Once we've built TheCall, all of the expressions are properly owned.
13391   QualType ResultTy = Method->getReturnType();
13392   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13393   ResultTy = ResultTy.getNonLValueExprType(Context);
13394 
13395   CXXOperatorCallExpr *TheCall =
13396       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13397                                   ResultTy, VK, RParenLoc, FPOptions());
13398 
13399   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13400     return true;
13401 
13402   if (CheckFunctionCall(Method, TheCall, Proto))
13403     return true;
13404 
13405   return MaybeBindToTemporary(TheCall);
13406 }
13407 
13408 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13409 ///  (if one exists), where @c Base is an expression of class type and
13410 /// @c Member is the name of the member we're trying to find.
13411 ExprResult
13412 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13413                                bool *NoArrowOperatorFound) {
13414   assert(Base->getType()->isRecordType() &&
13415          "left-hand side must have class type");
13416 
13417   if (checkPlaceholderForOverload(*this, Base))
13418     return ExprError();
13419 
13420   SourceLocation Loc = Base->getExprLoc();
13421 
13422   // C++ [over.ref]p1:
13423   //
13424   //   [...] An expression x->m is interpreted as (x.operator->())->m
13425   //   for a class object x of type T if T::operator->() exists and if
13426   //   the operator is selected as the best match function by the
13427   //   overload resolution mechanism (13.3).
13428   DeclarationName OpName =
13429     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13430   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13431   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13432 
13433   if (RequireCompleteType(Loc, Base->getType(),
13434                           diag::err_typecheck_incomplete_tag, Base))
13435     return ExprError();
13436 
13437   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13438   LookupQualifiedName(R, BaseRecord->getDecl());
13439   R.suppressDiagnostics();
13440 
13441   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13442        Oper != OperEnd; ++Oper) {
13443     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13444                        None, CandidateSet, /*SuppressUserConversions=*/false);
13445   }
13446 
13447   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13448 
13449   // Perform overload resolution.
13450   OverloadCandidateSet::iterator Best;
13451   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13452   case OR_Success:
13453     // Overload resolution succeeded; we'll build the call below.
13454     break;
13455 
13456   case OR_No_Viable_Function:
13457     if (CandidateSet.empty()) {
13458       QualType BaseType = Base->getType();
13459       if (NoArrowOperatorFound) {
13460         // Report this specific error to the caller instead of emitting a
13461         // diagnostic, as requested.
13462         *NoArrowOperatorFound = true;
13463         return ExprError();
13464       }
13465       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13466         << BaseType << Base->getSourceRange();
13467       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13468         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13469           << FixItHint::CreateReplacement(OpLoc, ".");
13470       }
13471     } else
13472       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13473         << "operator->" << Base->getSourceRange();
13474     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13475     return ExprError();
13476 
13477   case OR_Ambiguous:
13478     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13479       << "->" << Base->getType() << Base->getSourceRange();
13480     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13481     return ExprError();
13482 
13483   case OR_Deleted:
13484     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13485       << Best->Function->isDeleted()
13486       << "->"
13487       << getDeletedOrUnavailableSuffix(Best->Function)
13488       << Base->getSourceRange();
13489     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13490     return ExprError();
13491   }
13492 
13493   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13494 
13495   // Convert the object parameter.
13496   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13497   ExprResult BaseResult =
13498     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13499                                         Best->FoundDecl, Method);
13500   if (BaseResult.isInvalid())
13501     return ExprError();
13502   Base = BaseResult.get();
13503 
13504   // Build the operator call.
13505   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13506                                             Base, HadMultipleCandidates, OpLoc);
13507   if (FnExpr.isInvalid())
13508     return ExprError();
13509 
13510   QualType ResultTy = Method->getReturnType();
13511   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13512   ResultTy = ResultTy.getNonLValueExprType(Context);
13513   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13514       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13515 
13516   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13517     return ExprError();
13518 
13519   if (CheckFunctionCall(Method, TheCall,
13520                         Method->getType()->castAs<FunctionProtoType>()))
13521     return ExprError();
13522 
13523   return MaybeBindToTemporary(TheCall);
13524 }
13525 
13526 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13527 /// a literal operator described by the provided lookup results.
13528 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13529                                           DeclarationNameInfo &SuffixInfo,
13530                                           ArrayRef<Expr*> Args,
13531                                           SourceLocation LitEndLoc,
13532                                        TemplateArgumentListInfo *TemplateArgs) {
13533   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13534 
13535   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13536                                     OverloadCandidateSet::CSK_Normal);
13537   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13538                         /*SuppressUserConversions=*/true);
13539 
13540   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13541 
13542   // Perform overload resolution. This will usually be trivial, but might need
13543   // to perform substitutions for a literal operator template.
13544   OverloadCandidateSet::iterator Best;
13545   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13546   case OR_Success:
13547   case OR_Deleted:
13548     break;
13549 
13550   case OR_No_Viable_Function:
13551     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13552       << R.getLookupName();
13553     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13554     return ExprError();
13555 
13556   case OR_Ambiguous:
13557     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13558     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13559     return ExprError();
13560   }
13561 
13562   FunctionDecl *FD = Best->Function;
13563   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13564                                         nullptr, HadMultipleCandidates,
13565                                         SuffixInfo.getLoc(),
13566                                         SuffixInfo.getInfo());
13567   if (Fn.isInvalid())
13568     return true;
13569 
13570   // Check the argument types. This should almost always be a no-op, except
13571   // that array-to-pointer decay is applied to string literals.
13572   Expr *ConvArgs[2];
13573   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13574     ExprResult InputInit = PerformCopyInitialization(
13575       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13576       SourceLocation(), Args[ArgIdx]);
13577     if (InputInit.isInvalid())
13578       return true;
13579     ConvArgs[ArgIdx] = InputInit.get();
13580   }
13581 
13582   QualType ResultTy = FD->getReturnType();
13583   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13584   ResultTy = ResultTy.getNonLValueExprType(Context);
13585 
13586   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13587       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13588       VK, LitEndLoc, UDSuffixLoc);
13589 
13590   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13591     return ExprError();
13592 
13593   if (CheckFunctionCall(FD, UDL, nullptr))
13594     return ExprError();
13595 
13596   return MaybeBindToTemporary(UDL);
13597 }
13598 
13599 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13600 /// given LookupResult is non-empty, it is assumed to describe a member which
13601 /// will be invoked. Otherwise, the function will be found via argument
13602 /// dependent lookup.
13603 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13604 /// otherwise CallExpr is set to ExprError() and some non-success value
13605 /// is returned.
13606 Sema::ForRangeStatus
13607 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13608                                 SourceLocation RangeLoc,
13609                                 const DeclarationNameInfo &NameInfo,
13610                                 LookupResult &MemberLookup,
13611                                 OverloadCandidateSet *CandidateSet,
13612                                 Expr *Range, ExprResult *CallExpr) {
13613   Scope *S = nullptr;
13614 
13615   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13616   if (!MemberLookup.empty()) {
13617     ExprResult MemberRef =
13618         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13619                                  /*IsPtr=*/false, CXXScopeSpec(),
13620                                  /*TemplateKWLoc=*/SourceLocation(),
13621                                  /*FirstQualifierInScope=*/nullptr,
13622                                  MemberLookup,
13623                                  /*TemplateArgs=*/nullptr, S);
13624     if (MemberRef.isInvalid()) {
13625       *CallExpr = ExprError();
13626       return FRS_DiagnosticIssued;
13627     }
13628     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13629     if (CallExpr->isInvalid()) {
13630       *CallExpr = ExprError();
13631       return FRS_DiagnosticIssued;
13632     }
13633   } else {
13634     UnresolvedSet<0> FoundNames;
13635     UnresolvedLookupExpr *Fn =
13636       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13637                                    NestedNameSpecifierLoc(), NameInfo,
13638                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13639                                    FoundNames.begin(), FoundNames.end());
13640 
13641     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13642                                                     CandidateSet, CallExpr);
13643     if (CandidateSet->empty() || CandidateSetError) {
13644       *CallExpr = ExprError();
13645       return FRS_NoViableFunction;
13646     }
13647     OverloadCandidateSet::iterator Best;
13648     OverloadingResult OverloadResult =
13649         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13650 
13651     if (OverloadResult == OR_No_Viable_Function) {
13652       *CallExpr = ExprError();
13653       return FRS_NoViableFunction;
13654     }
13655     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13656                                          Loc, nullptr, CandidateSet, &Best,
13657                                          OverloadResult,
13658                                          /*AllowTypoCorrection=*/false);
13659     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13660       *CallExpr = ExprError();
13661       return FRS_DiagnosticIssued;
13662     }
13663   }
13664   return FRS_Success;
13665 }
13666 
13667 
13668 /// FixOverloadedFunctionReference - E is an expression that refers to
13669 /// a C++ overloaded function (possibly with some parentheses and
13670 /// perhaps a '&' around it). We have resolved the overloaded function
13671 /// to the function declaration Fn, so patch up the expression E to
13672 /// refer (possibly indirectly) to Fn. Returns the new expr.
13673 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13674                                            FunctionDecl *Fn) {
13675   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13676     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13677                                                    Found, Fn);
13678     if (SubExpr == PE->getSubExpr())
13679       return PE;
13680 
13681     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13682   }
13683 
13684   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13685     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13686                                                    Found, Fn);
13687     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13688                                SubExpr->getType()) &&
13689            "Implicit cast type cannot be determined from overload");
13690     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13691     if (SubExpr == ICE->getSubExpr())
13692       return ICE;
13693 
13694     return ImplicitCastExpr::Create(Context, ICE->getType(),
13695                                     ICE->getCastKind(),
13696                                     SubExpr, nullptr,
13697                                     ICE->getValueKind());
13698   }
13699 
13700   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13701     if (!GSE->isResultDependent()) {
13702       Expr *SubExpr =
13703           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13704       if (SubExpr == GSE->getResultExpr())
13705         return GSE;
13706 
13707       // Replace the resulting type information before rebuilding the generic
13708       // selection expression.
13709       ArrayRef<Expr *> A = GSE->getAssocExprs();
13710       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13711       unsigned ResultIdx = GSE->getResultIndex();
13712       AssocExprs[ResultIdx] = SubExpr;
13713 
13714       return GenericSelectionExpr::Create(
13715           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13716           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13717           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13718           ResultIdx);
13719     }
13720     // Rather than fall through to the unreachable, return the original generic
13721     // selection expression.
13722     return GSE;
13723   }
13724 
13725   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13726     assert(UnOp->getOpcode() == UO_AddrOf &&
13727            "Can only take the address of an overloaded function");
13728     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13729       if (Method->isStatic()) {
13730         // Do nothing: static member functions aren't any different
13731         // from non-member functions.
13732       } else {
13733         // Fix the subexpression, which really has to be an
13734         // UnresolvedLookupExpr holding an overloaded member function
13735         // or template.
13736         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13737                                                        Found, Fn);
13738         if (SubExpr == UnOp->getSubExpr())
13739           return UnOp;
13740 
13741         assert(isa<DeclRefExpr>(SubExpr)
13742                && "fixed to something other than a decl ref");
13743         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13744                && "fixed to a member ref with no nested name qualifier");
13745 
13746         // We have taken the address of a pointer to member
13747         // function. Perform the computation here so that we get the
13748         // appropriate pointer to member type.
13749         QualType ClassType
13750           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13751         QualType MemPtrType
13752           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13753         // Under the MS ABI, lock down the inheritance model now.
13754         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13755           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13756 
13757         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13758                                            VK_RValue, OK_Ordinary,
13759                                            UnOp->getOperatorLoc(), false);
13760       }
13761     }
13762     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13763                                                    Found, Fn);
13764     if (SubExpr == UnOp->getSubExpr())
13765       return UnOp;
13766 
13767     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13768                                      Context.getPointerType(SubExpr->getType()),
13769                                        VK_RValue, OK_Ordinary,
13770                                        UnOp->getOperatorLoc(), false);
13771   }
13772 
13773   // C++ [except.spec]p17:
13774   //   An exception-specification is considered to be needed when:
13775   //   - in an expression the function is the unique lookup result or the
13776   //     selected member of a set of overloaded functions
13777   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13778     ResolveExceptionSpec(E->getExprLoc(), FPT);
13779 
13780   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13781     // FIXME: avoid copy.
13782     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13783     if (ULE->hasExplicitTemplateArgs()) {
13784       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13785       TemplateArgs = &TemplateArgsBuffer;
13786     }
13787 
13788     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13789                                            ULE->getQualifierLoc(),
13790                                            ULE->getTemplateKeywordLoc(),
13791                                            Fn,
13792                                            /*enclosing*/ false, // FIXME?
13793                                            ULE->getNameLoc(),
13794                                            Fn->getType(),
13795                                            VK_LValue,
13796                                            Found.getDecl(),
13797                                            TemplateArgs);
13798     MarkDeclRefReferenced(DRE);
13799     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13800     return DRE;
13801   }
13802 
13803   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13804     // FIXME: avoid copy.
13805     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13806     if (MemExpr->hasExplicitTemplateArgs()) {
13807       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13808       TemplateArgs = &TemplateArgsBuffer;
13809     }
13810 
13811     Expr *Base;
13812 
13813     // If we're filling in a static method where we used to have an
13814     // implicit member access, rewrite to a simple decl ref.
13815     if (MemExpr->isImplicitAccess()) {
13816       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13817         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13818                                                MemExpr->getQualifierLoc(),
13819                                                MemExpr->getTemplateKeywordLoc(),
13820                                                Fn,
13821                                                /*enclosing*/ false,
13822                                                MemExpr->getMemberLoc(),
13823                                                Fn->getType(),
13824                                                VK_LValue,
13825                                                Found.getDecl(),
13826                                                TemplateArgs);
13827         MarkDeclRefReferenced(DRE);
13828         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13829         return DRE;
13830       } else {
13831         SourceLocation Loc = MemExpr->getMemberLoc();
13832         if (MemExpr->getQualifier())
13833           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13834         CheckCXXThisCapture(Loc);
13835         Base = new (Context) CXXThisExpr(Loc,
13836                                          MemExpr->getBaseType(),
13837                                          /*isImplicit=*/true);
13838       }
13839     } else
13840       Base = MemExpr->getBase();
13841 
13842     ExprValueKind valueKind;
13843     QualType type;
13844     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13845       valueKind = VK_LValue;
13846       type = Fn->getType();
13847     } else {
13848       valueKind = VK_RValue;
13849       type = Context.BoundMemberTy;
13850     }
13851 
13852     MemberExpr *ME = MemberExpr::Create(
13853         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13854         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13855         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13856         OK_Ordinary);
13857     ME->setHadMultipleCandidates(true);
13858     MarkMemberReferenced(ME);
13859     return ME;
13860   }
13861 
13862   llvm_unreachable("Invalid reference to overloaded function");
13863 }
13864 
13865 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13866                                                 DeclAccessPair Found,
13867                                                 FunctionDecl *Fn) {
13868   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13869 }
13870