]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp
MFC r363013:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaOverload.cpp
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   DeclRefExpr *DRE = new (S.Context)
64       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65   if (HadMultipleCandidates)
66     DRE->setHadMultipleCandidates(true);
67
68   S.MarkDeclRefReferenced(DRE, Base);
69   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71       S.ResolveExceptionSpec(Loc, FPT);
72       DRE->setType(Fn->getType());
73     }
74   }
75   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76                              CK_FunctionToPointerDecay);
77 }
78
79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80                                  bool InOverloadResolution,
81                                  StandardConversionSequence &SCS,
82                                  bool CStyle,
83                                  bool AllowObjCWritebackConversion);
84
85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
86                                                  QualType &ToType,
87                                                  bool InOverloadResolution,
88                                                  StandardConversionSequence &SCS,
89                                                  bool CStyle);
90 static OverloadingResult
91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92                         UserDefinedConversionSequence& User,
93                         OverloadCandidateSet& Conversions,
94                         bool AllowExplicit,
95                         bool AllowObjCConversionOnExplicit);
96
97
98 static ImplicitConversionSequence::CompareKind
99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100                                    const StandardConversionSequence& SCS1,
101                                    const StandardConversionSequence& SCS2);
102
103 static ImplicitConversionSequence::CompareKind
104 CompareQualificationConversions(Sema &S,
105                                 const StandardConversionSequence& SCS1,
106                                 const StandardConversionSequence& SCS2);
107
108 static ImplicitConversionSequence::CompareKind
109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110                                 const StandardConversionSequence& SCS1,
111                                 const StandardConversionSequence& SCS2);
112
113 /// GetConversionRank - Retrieve the implicit conversion rank
114 /// corresponding to the given implicit conversion kind.
115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116   static const ImplicitConversionRank
117     Rank[(int)ICK_Num_Conversion_Kinds] = {
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Promotion,
125     ICR_Promotion,
126     ICR_Promotion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_OCL_Scalar_Widening,
138     ICR_Complex_Real_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Writeback_Conversion,
142     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143                      // it was omitted by the patch that added
144                      // ICK_Zero_Event_Conversion
145     ICR_C_Conversion,
146     ICR_C_Conversion_Extension
147   };
148   return Rank[(int)Kind];
149 }
150
151 /// GetImplicitConversionName - Return the name of this kind of
152 /// implicit conversion.
153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155     "No conversion",
156     "Lvalue-to-rvalue",
157     "Array-to-pointer",
158     "Function-to-pointer",
159     "Function pointer conversion",
160     "Qualification",
161     "Integral promotion",
162     "Floating point promotion",
163     "Complex promotion",
164     "Integral conversion",
165     "Floating conversion",
166     "Complex conversion",
167     "Floating-integral conversion",
168     "Pointer conversion",
169     "Pointer-to-member conversion",
170     "Boolean conversion",
171     "Compatible-types conversion",
172     "Derived-to-base conversion",
173     "Vector conversion",
174     "Vector splat",
175     "Complex-real conversion",
176     "Block Pointer conversion",
177     "Transparent Union Conversion",
178     "Writeback conversion",
179     "OpenCL Zero Event Conversion",
180     "C specific type conversion",
181     "Incompatible pointer conversion"
182   };
183   return Name[Kind];
184 }
185
186 /// StandardConversionSequence - Set the standard conversion
187 /// sequence to the identity conversion.
188 void StandardConversionSequence::setAsIdentityConversion() {
189   First = ICK_Identity;
190   Second = ICK_Identity;
191   Third = ICK_Identity;
192   DeprecatedStringLiteralToCharPtr = false;
193   QualificationIncludesObjCLifetime = false;
194   ReferenceBinding = false;
195   DirectBinding = false;
196   IsLvalueReference = true;
197   BindsToFunctionLvalue = false;
198   BindsToRvalue = false;
199   BindsImplicitObjectArgumentWithoutRefQualifier = false;
200   ObjCLifetimeConversionBinding = false;
201   CopyConstructor = nullptr;
202 }
203
204 /// getRank - Retrieve the rank of this standard conversion sequence
205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206 /// implicit conversions.
207 ImplicitConversionRank StandardConversionSequence::getRank() const {
208   ImplicitConversionRank Rank = ICR_Exact_Match;
209   if  (GetConversionRank(First) > Rank)
210     Rank = GetConversionRank(First);
211   if  (GetConversionRank(Second) > Rank)
212     Rank = GetConversionRank(Second);
213   if  (GetConversionRank(Third) > Rank)
214     Rank = GetConversionRank(Third);
215   return Rank;
216 }
217
218 /// isPointerConversionToBool - Determines whether this conversion is
219 /// a conversion of a pointer or pointer-to-member to bool. This is
220 /// used as part of the ranking of standard conversion sequences
221 /// (C++ 13.3.3.2p4).
222 bool StandardConversionSequence::isPointerConversionToBool() const {
223   // Note that FromType has not necessarily been transformed by the
224   // array-to-pointer or function-to-pointer implicit conversions, so
225   // check for their presence as well as checking whether FromType is
226   // a pointer.
227   if (getToType(1)->isBooleanType() &&
228       (getFromType()->isPointerType() ||
229        getFromType()->isMemberPointerType() ||
230        getFromType()->isObjCObjectPointerType() ||
231        getFromType()->isBlockPointerType() ||
232        getFromType()->isNullPtrType() ||
233        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234     return true;
235
236   return false;
237 }
238
239 /// isPointerConversionToVoidPointer - Determines whether this
240 /// conversion is a conversion of a pointer to a void pointer. This is
241 /// used as part of the ranking of standard conversion sequences (C++
242 /// 13.3.3.2p4).
243 bool
244 StandardConversionSequence::
245 isPointerConversionToVoidPointer(ASTContext& Context) const {
246   QualType FromType = getFromType();
247   QualType ToType = getToType(1);
248
249   // Note that FromType has not necessarily been transformed by the
250   // array-to-pointer implicit conversion, so check for its presence
251   // and redo the conversion to get a pointer.
252   if (First == ICK_Array_To_Pointer)
253     FromType = Context.getArrayDecayedType(FromType);
254
255   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257       return ToPtrType->getPointeeType()->isVoidType();
258
259   return false;
260 }
261
262 /// Skip any implicit casts which could be either part of a narrowing conversion
263 /// or after one in an implicit conversion.
264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265                                              const Expr *Converted) {
266   // We can have cleanups wrapping the converted expression; these need to be
267   // preserved so that destructors run if necessary.
268   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
269     Expr *Inner =
270         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
272                                     EWC->getObjects());
273   }
274
275   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276     switch (ICE->getCastKind()) {
277     case CK_NoOp:
278     case CK_IntegralCast:
279     case CK_IntegralToBoolean:
280     case CK_IntegralToFloating:
281     case CK_BooleanToSignedIntegral:
282     case CK_FloatingToIntegral:
283     case CK_FloatingToBoolean:
284     case CK_FloatingCast:
285       Converted = ICE->getSubExpr();
286       continue;
287
288     default:
289       return Converted;
290     }
291   }
292
293   return Converted;
294 }
295
296 /// Check if this standard conversion sequence represents a narrowing
297 /// conversion, according to C++11 [dcl.init.list]p7.
298 ///
299 /// \param Ctx  The AST context.
300 /// \param Converted  The result of applying this standard conversion sequence.
301 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
302 ///        value of the expression prior to the narrowing conversion.
303 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
304 ///        type of the expression prior to the narrowing conversion.
305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306 ///        from floating point types to integral types should be ignored.
307 NarrowingKind StandardConversionSequence::getNarrowingKind(
308     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
311
312   // C++11 [dcl.init.list]p7:
313   //   A narrowing conversion is an implicit conversion ...
314   QualType FromType = getToType(0);
315   QualType ToType = getToType(1);
316
317   // A conversion to an enumeration type is narrowing if the conversion to
318   // the underlying type is narrowing. This only arises for expressions of
319   // the form 'Enum{init}'.
320   if (auto *ET = ToType->getAs<EnumType>())
321     ToType = ET->getDecl()->getIntegerType();
322
323   switch (Second) {
324   // 'bool' is an integral type; dispatch to the right place to handle it.
325   case ICK_Boolean_Conversion:
326     if (FromType->isRealFloatingType())
327       goto FloatingIntegralConversion;
328     if (FromType->isIntegralOrUnscopedEnumerationType())
329       goto IntegralConversion;
330     // Boolean conversions can be from pointers and pointers to members
331     // [conv.bool], and those aren't considered narrowing conversions.
332     return NK_Not_Narrowing;
333
334   // -- from a floating-point type to an integer type, or
335   //
336   // -- from an integer type or unscoped enumeration type to a floating-point
337   //    type, except where the source is a constant expression and the actual
338   //    value after conversion will fit into the target type and will produce
339   //    the original value when converted back to the original type, or
340   case ICK_Floating_Integral:
341   FloatingIntegralConversion:
342     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343       return NK_Type_Narrowing;
344     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345                ToType->isRealFloatingType()) {
346       if (IgnoreFloatToIntegralConversion)
347         return NK_Not_Narrowing;
348       llvm::APSInt IntConstantValue;
349       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350       assert(Initializer && "Unknown conversion expression");
351
352       // If it's value-dependent, we can't tell whether it's narrowing.
353       if (Initializer->isValueDependent())
354         return NK_Dependent_Narrowing;
355
356       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357         // Convert the integer to the floating type.
358         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360                                 llvm::APFloat::rmNearestTiesToEven);
361         // And back.
362         llvm::APSInt ConvertedValue = IntConstantValue;
363         bool ignored;
364         Result.convertToInteger(ConvertedValue,
365                                 llvm::APFloat::rmTowardZero, &ignored);
366         // If the resulting value is different, this was a narrowing conversion.
367         if (IntConstantValue != ConvertedValue) {
368           ConstantValue = APValue(IntConstantValue);
369           ConstantType = Initializer->getType();
370           return NK_Constant_Narrowing;
371         }
372       } else {
373         // Variables are always narrowings.
374         return NK_Variable_Narrowing;
375       }
376     }
377     return NK_Not_Narrowing;
378
379   // -- from long double to double or float, or from double to float, except
380   //    where the source is a constant expression and the actual value after
381   //    conversion is within the range of values that can be represented (even
382   //    if it cannot be represented exactly), or
383   case ICK_Floating_Conversion:
384     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386       // FromType is larger than ToType.
387       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
388
389       // If it's value-dependent, we can't tell whether it's narrowing.
390       if (Initializer->isValueDependent())
391         return NK_Dependent_Narrowing;
392
393       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
394         // Constant!
395         assert(ConstantValue.isFloat());
396         llvm::APFloat FloatVal = ConstantValue.getFloat();
397         // Convert the source value into the target type.
398         bool ignored;
399         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400           Ctx.getFloatTypeSemantics(ToType),
401           llvm::APFloat::rmNearestTiesToEven, &ignored);
402         // If there was no overflow, the source value is within the range of
403         // values that can be represented.
404         if (ConvertStatus & llvm::APFloat::opOverflow) {
405           ConstantType = Initializer->getType();
406           return NK_Constant_Narrowing;
407         }
408       } else {
409         return NK_Variable_Narrowing;
410       }
411     }
412     return NK_Not_Narrowing;
413
414   // -- from an integer type or unscoped enumeration type to an integer type
415   //    that cannot represent all the values of the original type, except where
416   //    the source is a constant expression and the actual value after
417   //    conversion will fit into the target type and will produce the original
418   //    value when converted back to the original type.
419   case ICK_Integral_Conversion:
420   IntegralConversion: {
421     assert(FromType->isIntegralOrUnscopedEnumerationType());
422     assert(ToType->isIntegralOrUnscopedEnumerationType());
423     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424     const unsigned FromWidth = Ctx.getIntWidth(FromType);
425     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426     const unsigned ToWidth = Ctx.getIntWidth(ToType);
427
428     if (FromWidth > ToWidth ||
429         (FromWidth == ToWidth && FromSigned != ToSigned) ||
430         (FromSigned && !ToSigned)) {
431       // Not all values of FromType can be represented in ToType.
432       llvm::APSInt InitializerValue;
433       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434
435       // If it's value-dependent, we can't tell whether it's narrowing.
436       if (Initializer->isValueDependent())
437         return NK_Dependent_Narrowing;
438
439       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440         // Such conversions on variables are always narrowing.
441         return NK_Variable_Narrowing;
442       }
443       bool Narrowing = false;
444       if (FromWidth < ToWidth) {
445         // Negative -> unsigned is narrowing. Otherwise, more bits is never
446         // narrowing.
447         if (InitializerValue.isSigned() && InitializerValue.isNegative())
448           Narrowing = true;
449       } else {
450         // Add a bit to the InitializerValue so we don't have to worry about
451         // signed vs. unsigned comparisons.
452         InitializerValue = InitializerValue.extend(
453           InitializerValue.getBitWidth() + 1);
454         // Convert the initializer to and from the target width and signed-ness.
455         llvm::APSInt ConvertedValue = InitializerValue;
456         ConvertedValue = ConvertedValue.trunc(ToWidth);
457         ConvertedValue.setIsSigned(ToSigned);
458         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459         ConvertedValue.setIsSigned(InitializerValue.isSigned());
460         // If the result is different, this was a narrowing conversion.
461         if (ConvertedValue != InitializerValue)
462           Narrowing = true;
463       }
464       if (Narrowing) {
465         ConstantType = Initializer->getType();
466         ConstantValue = APValue(InitializerValue);
467         return NK_Constant_Narrowing;
468       }
469     }
470     return NK_Not_Narrowing;
471   }
472
473   default:
474     // Other kinds of conversions are not narrowings.
475     return NK_Not_Narrowing;
476   }
477 }
478
479 /// dump - Print this standard conversion sequence to standard
480 /// error. Useful for debugging overloading issues.
481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
482   raw_ostream &OS = llvm::errs();
483   bool PrintedSomething = false;
484   if (First != ICK_Identity) {
485     OS << GetImplicitConversionName(First);
486     PrintedSomething = true;
487   }
488
489   if (Second != ICK_Identity) {
490     if (PrintedSomething) {
491       OS << " -> ";
492     }
493     OS << GetImplicitConversionName(Second);
494
495     if (CopyConstructor) {
496       OS << " (by copy constructor)";
497     } else if (DirectBinding) {
498       OS << " (direct reference binding)";
499     } else if (ReferenceBinding) {
500       OS << " (reference binding)";
501     }
502     PrintedSomething = true;
503   }
504
505   if (Third != ICK_Identity) {
506     if (PrintedSomething) {
507       OS << " -> ";
508     }
509     OS << GetImplicitConversionName(Third);
510     PrintedSomething = true;
511   }
512
513   if (!PrintedSomething) {
514     OS << "No conversions required";
515   }
516 }
517
518 /// dump - Print this user-defined conversion sequence to standard
519 /// error. Useful for debugging overloading issues.
520 void UserDefinedConversionSequence::dump() const {
521   raw_ostream &OS = llvm::errs();
522   if (Before.First || Before.Second || Before.Third) {
523     Before.dump();
524     OS << " -> ";
525   }
526   if (ConversionFunction)
527     OS << '\'' << *ConversionFunction << '\'';
528   else
529     OS << "aggregate initialization";
530   if (After.First || After.Second || After.Third) {
531     OS << " -> ";
532     After.dump();
533   }
534 }
535
536 /// dump - Print this implicit conversion sequence to standard
537 /// error. Useful for debugging overloading issues.
538 void ImplicitConversionSequence::dump() const {
539   raw_ostream &OS = llvm::errs();
540   if (isStdInitializerListElement())
541     OS << "Worst std::initializer_list element conversion: ";
542   switch (ConversionKind) {
543   case StandardConversion:
544     OS << "Standard conversion: ";
545     Standard.dump();
546     break;
547   case UserDefinedConversion:
548     OS << "User-defined conversion: ";
549     UserDefined.dump();
550     break;
551   case EllipsisConversion:
552     OS << "Ellipsis conversion";
553     break;
554   case AmbiguousConversion:
555     OS << "Ambiguous conversion";
556     break;
557   case BadConversion:
558     OS << "Bad conversion";
559     break;
560   }
561
562   OS << "\n";
563 }
564
565 void AmbiguousConversionSequence::construct() {
566   new (&conversions()) ConversionSet();
567 }
568
569 void AmbiguousConversionSequence::destruct() {
570   conversions().~ConversionSet();
571 }
572
573 void
574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575   FromTypePtr = O.FromTypePtr;
576   ToTypePtr = O.ToTypePtr;
577   new (&conversions()) ConversionSet(O.conversions());
578 }
579
580 namespace {
581   // Structure used by DeductionFailureInfo to store
582   // template argument information.
583   struct DFIArguments {
584     TemplateArgument FirstArg;
585     TemplateArgument SecondArg;
586   };
587   // Structure used by DeductionFailureInfo to store
588   // template parameter and template argument information.
589   struct DFIParamWithArguments : DFIArguments {
590     TemplateParameter Param;
591   };
592   // Structure used by DeductionFailureInfo to store template argument
593   // information and the index of the problematic call argument.
594   struct DFIDeducedMismatchArgs : DFIArguments {
595     TemplateArgumentList *TemplateArgs;
596     unsigned CallArgIndex;
597   };
598   // Structure used by DeductionFailureInfo to store information about
599   // unsatisfied constraints.
600   struct CNSInfo {
601     TemplateArgumentList *TemplateArgs;
602     ConstraintSatisfaction Satisfaction;
603   };
604 }
605
606 /// Convert from Sema's representation of template deduction information
607 /// to the form used in overload-candidate information.
608 DeductionFailureInfo
609 clang::MakeDeductionFailureInfo(ASTContext &Context,
610                                 Sema::TemplateDeductionResult TDK,
611                                 TemplateDeductionInfo &Info) {
612   DeductionFailureInfo Result;
613   Result.Result = static_cast<unsigned>(TDK);
614   Result.HasDiagnostic = false;
615   switch (TDK) {
616   case Sema::TDK_Invalid:
617   case Sema::TDK_InstantiationDepth:
618   case Sema::TDK_TooManyArguments:
619   case Sema::TDK_TooFewArguments:
620   case Sema::TDK_MiscellaneousDeductionFailure:
621   case Sema::TDK_CUDATargetMismatch:
622     Result.Data = nullptr;
623     break;
624
625   case Sema::TDK_Incomplete:
626   case Sema::TDK_InvalidExplicitArguments:
627     Result.Data = Info.Param.getOpaqueValue();
628     break;
629
630   case Sema::TDK_DeducedMismatch:
631   case Sema::TDK_DeducedMismatchNested: {
632     // FIXME: Should allocate from normal heap so that we can free this later.
633     auto *Saved = new (Context) DFIDeducedMismatchArgs;
634     Saved->FirstArg = Info.FirstArg;
635     Saved->SecondArg = Info.SecondArg;
636     Saved->TemplateArgs = Info.take();
637     Saved->CallArgIndex = Info.CallArgIndex;
638     Result.Data = Saved;
639     break;
640   }
641
642   case Sema::TDK_NonDeducedMismatch: {
643     // FIXME: Should allocate from normal heap so that we can free this later.
644     DFIArguments *Saved = new (Context) DFIArguments;
645     Saved->FirstArg = Info.FirstArg;
646     Saved->SecondArg = Info.SecondArg;
647     Result.Data = Saved;
648     break;
649   }
650
651   case Sema::TDK_IncompletePack:
652     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653   case Sema::TDK_Inconsistent:
654   case Sema::TDK_Underqualified: {
655     // FIXME: Should allocate from normal heap so that we can free this later.
656     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657     Saved->Param = Info.Param;
658     Saved->FirstArg = Info.FirstArg;
659     Saved->SecondArg = Info.SecondArg;
660     Result.Data = Saved;
661     break;
662   }
663
664   case Sema::TDK_SubstitutionFailure:
665     Result.Data = Info.take();
666     if (Info.hasSFINAEDiagnostic()) {
667       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668           SourceLocation(), PartialDiagnostic::NullDiagnostic());
669       Info.takeSFINAEDiagnostic(*Diag);
670       Result.HasDiagnostic = true;
671     }
672     break;
673
674   case Sema::TDK_ConstraintsNotSatisfied: {
675     CNSInfo *Saved = new (Context) CNSInfo;
676     Saved->TemplateArgs = Info.take();
677     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
678     Result.Data = Saved;
679     break;
680   }
681
682   case Sema::TDK_Success:
683   case Sema::TDK_NonDependentConversionFailure:
684     llvm_unreachable("not a deduction failure");
685   }
686
687   return Result;
688 }
689
690 void DeductionFailureInfo::Destroy() {
691   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692   case Sema::TDK_Success:
693   case Sema::TDK_Invalid:
694   case Sema::TDK_InstantiationDepth:
695   case Sema::TDK_Incomplete:
696   case Sema::TDK_TooManyArguments:
697   case Sema::TDK_TooFewArguments:
698   case Sema::TDK_InvalidExplicitArguments:
699   case Sema::TDK_CUDATargetMismatch:
700   case Sema::TDK_NonDependentConversionFailure:
701     break;
702
703   case Sema::TDK_IncompletePack:
704   case Sema::TDK_Inconsistent:
705   case Sema::TDK_Underqualified:
706   case Sema::TDK_DeducedMismatch:
707   case Sema::TDK_DeducedMismatchNested:
708   case Sema::TDK_NonDeducedMismatch:
709     // FIXME: Destroy the data?
710     Data = nullptr;
711     break;
712
713   case Sema::TDK_SubstitutionFailure:
714     // FIXME: Destroy the template argument list?
715     Data = nullptr;
716     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717       Diag->~PartialDiagnosticAt();
718       HasDiagnostic = false;
719     }
720     break;
721
722   case Sema::TDK_ConstraintsNotSatisfied:
723     // FIXME: Destroy the template argument list?
724     Data = nullptr;
725     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726       Diag->~PartialDiagnosticAt();
727       HasDiagnostic = false;
728     }
729     break;
730
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 }
736
737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
738   if (HasDiagnostic)
739     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
740   return nullptr;
741 }
742
743 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745   case Sema::TDK_Success:
746   case Sema::TDK_Invalid:
747   case Sema::TDK_InstantiationDepth:
748   case Sema::TDK_TooManyArguments:
749   case Sema::TDK_TooFewArguments:
750   case Sema::TDK_SubstitutionFailure:
751   case Sema::TDK_DeducedMismatch:
752   case Sema::TDK_DeducedMismatchNested:
753   case Sema::TDK_NonDeducedMismatch:
754   case Sema::TDK_CUDATargetMismatch:
755   case Sema::TDK_NonDependentConversionFailure:
756   case Sema::TDK_ConstraintsNotSatisfied:
757     return TemplateParameter();
758
759   case Sema::TDK_Incomplete:
760   case Sema::TDK_InvalidExplicitArguments:
761     return TemplateParameter::getFromOpaqueValue(Data);
762
763   case Sema::TDK_IncompletePack:
764   case Sema::TDK_Inconsistent:
765   case Sema::TDK_Underqualified:
766     return static_cast<DFIParamWithArguments*>(Data)->Param;
767
768   // Unhandled
769   case Sema::TDK_MiscellaneousDeductionFailure:
770     break;
771   }
772
773   return TemplateParameter();
774 }
775
776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778   case Sema::TDK_Success:
779   case Sema::TDK_Invalid:
780   case Sema::TDK_InstantiationDepth:
781   case Sema::TDK_TooManyArguments:
782   case Sema::TDK_TooFewArguments:
783   case Sema::TDK_Incomplete:
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_InvalidExplicitArguments:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_NonDeducedMismatch:
789   case Sema::TDK_CUDATargetMismatch:
790   case Sema::TDK_NonDependentConversionFailure:
791     return nullptr;
792
793   case Sema::TDK_DeducedMismatch:
794   case Sema::TDK_DeducedMismatchNested:
795     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
796
797   case Sema::TDK_SubstitutionFailure:
798     return static_cast<TemplateArgumentList*>(Data);
799
800   case Sema::TDK_ConstraintsNotSatisfied:
801     return static_cast<CNSInfo*>(Data)->TemplateArgs;
802
803   // Unhandled
804   case Sema::TDK_MiscellaneousDeductionFailure:
805     break;
806   }
807
808   return nullptr;
809 }
810
811 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813   case Sema::TDK_Success:
814   case Sema::TDK_Invalid:
815   case Sema::TDK_InstantiationDepth:
816   case Sema::TDK_Incomplete:
817   case Sema::TDK_TooManyArguments:
818   case Sema::TDK_TooFewArguments:
819   case Sema::TDK_InvalidExplicitArguments:
820   case Sema::TDK_SubstitutionFailure:
821   case Sema::TDK_CUDATargetMismatch:
822   case Sema::TDK_NonDependentConversionFailure:
823   case Sema::TDK_ConstraintsNotSatisfied:
824     return nullptr;
825
826   case Sema::TDK_IncompletePack:
827   case Sema::TDK_Inconsistent:
828   case Sema::TDK_Underqualified:
829   case Sema::TDK_DeducedMismatch:
830   case Sema::TDK_DeducedMismatchNested:
831   case Sema::TDK_NonDeducedMismatch:
832     return &static_cast<DFIArguments*>(Data)->FirstArg;
833
834   // Unhandled
835   case Sema::TDK_MiscellaneousDeductionFailure:
836     break;
837   }
838
839   return nullptr;
840 }
841
842 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844   case Sema::TDK_Success:
845   case Sema::TDK_Invalid:
846   case Sema::TDK_InstantiationDepth:
847   case Sema::TDK_Incomplete:
848   case Sema::TDK_IncompletePack:
849   case Sema::TDK_TooManyArguments:
850   case Sema::TDK_TooFewArguments:
851   case Sema::TDK_InvalidExplicitArguments:
852   case Sema::TDK_SubstitutionFailure:
853   case Sema::TDK_CUDATargetMismatch:
854   case Sema::TDK_NonDependentConversionFailure:
855   case Sema::TDK_ConstraintsNotSatisfied:
856     return nullptr;
857
858   case Sema::TDK_Inconsistent:
859   case Sema::TDK_Underqualified:
860   case Sema::TDK_DeducedMismatch:
861   case Sema::TDK_DeducedMismatchNested:
862   case Sema::TDK_NonDeducedMismatch:
863     return &static_cast<DFIArguments*>(Data)->SecondArg;
864
865   // Unhandled
866   case Sema::TDK_MiscellaneousDeductionFailure:
867     break;
868   }
869
870   return nullptr;
871 }
872
873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875   case Sema::TDK_DeducedMismatch:
876   case Sema::TDK_DeducedMismatchNested:
877     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
878
879   default:
880     return llvm::None;
881   }
882 }
883
884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885     OverloadedOperatorKind Op) {
886   if (!AllowRewrittenCandidates)
887     return false;
888   return Op == OO_EqualEqual || Op == OO_Spaceship;
889 }
890
891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892     ASTContext &Ctx, const FunctionDecl *FD) {
893   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
894     return false;
895   // Don't bother adding a reversed candidate that can never be a better
896   // match than the non-reversed version.
897   return FD->getNumParams() != 2 ||
898          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899                                      FD->getParamDecl(1)->getType()) ||
900          FD->hasAttr<EnableIfAttr>();
901 }
902
903 void OverloadCandidateSet::destroyCandidates() {
904   for (iterator i = begin(), e = end(); i != e; ++i) {
905     for (auto &C : i->Conversions)
906       C.~ImplicitConversionSequence();
907     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908       i->DeductionFailure.Destroy();
909   }
910 }
911
912 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
913   destroyCandidates();
914   SlabAllocator.Reset();
915   NumInlineBytesUsed = 0;
916   Candidates.clear();
917   Functions.clear();
918   Kind = CSK;
919 }
920
921 namespace {
922   class UnbridgedCastsSet {
923     struct Entry {
924       Expr **Addr;
925       Expr *Saved;
926     };
927     SmallVector<Entry, 2> Entries;
928
929   public:
930     void save(Sema &S, Expr *&E) {
931       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
932       Entry entry = { &E, E };
933       Entries.push_back(entry);
934       E = S.stripARCUnbridgedCast(E);
935     }
936
937     void restore() {
938       for (SmallVectorImpl<Entry>::iterator
939              i = Entries.begin(), e = Entries.end(); i != e; ++i)
940         *i->Addr = i->Saved;
941     }
942   };
943 }
944
945 /// checkPlaceholderForOverload - Do any interesting placeholder-like
946 /// preprocessing on the given expression.
947 ///
948 /// \param unbridgedCasts a collection to which to add unbridged casts;
949 ///   without this, they will be immediately diagnosed as errors
950 ///
951 /// Return true on unrecoverable error.
952 static bool
953 checkPlaceholderForOverload(Sema &S, Expr *&E,
954                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
955   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
956     // We can't handle overloaded expressions here because overload
957     // resolution might reasonably tweak them.
958     if (placeholder->getKind() == BuiltinType::Overload) return false;
959
960     // If the context potentially accepts unbridged ARC casts, strip
961     // the unbridged cast and add it to the collection for later restoration.
962     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
963         unbridgedCasts) {
964       unbridgedCasts->save(S, E);
965       return false;
966     }
967
968     // Go ahead and check everything else.
969     ExprResult result = S.CheckPlaceholderExpr(E);
970     if (result.isInvalid())
971       return true;
972
973     E = result.get();
974     return false;
975   }
976
977   // Nothing to do.
978   return false;
979 }
980
981 /// checkArgPlaceholdersForOverload - Check a set of call operands for
982 /// placeholders.
983 static bool checkArgPlaceholdersForOverload(Sema &S,
984                                             MultiExprArg Args,
985                                             UnbridgedCastsSet &unbridged) {
986   for (unsigned i = 0, e = Args.size(); i != e; ++i)
987     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
988       return true;
989
990   return false;
991 }
992
993 /// Determine whether the given New declaration is an overload of the
994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995 /// New and Old cannot be overloaded, e.g., if New has the same signature as
996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997 /// functions (or function templates) at all. When it does return Ovl_Match or
998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1000 /// declaration.
1001 ///
1002 /// Example: Given the following input:
1003 ///
1004 ///   void f(int, float); // #1
1005 ///   void f(int, int); // #2
1006 ///   int f(int, int); // #3
1007 ///
1008 /// When we process #1, there is no previous declaration of "f", so IsOverload
1009 /// will not be used.
1010 ///
1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1014 /// unchanged.
1015 ///
1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1020 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1021 ///
1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023 /// by a using declaration. The rules for whether to hide shadow declarations
1024 /// ignore some properties which otherwise figure into a function template's
1025 /// signature.
1026 Sema::OverloadKind
1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028                     NamedDecl *&Match, bool NewIsUsingDecl) {
1029   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1030          I != E; ++I) {
1031     NamedDecl *OldD = *I;
1032
1033     bool OldIsUsingDecl = false;
1034     if (isa<UsingShadowDecl>(OldD)) {
1035       OldIsUsingDecl = true;
1036
1037       // We can always introduce two using declarations into the same
1038       // context, even if they have identical signatures.
1039       if (NewIsUsingDecl) continue;
1040
1041       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1042     }
1043
1044     // A using-declaration does not conflict with another declaration
1045     // if one of them is hidden.
1046     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1047       continue;
1048
1049     // If either declaration was introduced by a using declaration,
1050     // we'll need to use slightly different rules for matching.
1051     // Essentially, these rules are the normal rules, except that
1052     // function templates hide function templates with different
1053     // return types or template parameter lists.
1054     bool UseMemberUsingDeclRules =
1055       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056       !New->getFriendObjectKind();
1057
1058     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1062           continue;
1063         }
1064
1065         if (!isa<FunctionTemplateDecl>(OldD) &&
1066             !shouldLinkPossiblyHiddenDecl(*I, New))
1067           continue;
1068
1069         Match = *I;
1070         return Ovl_Match;
1071       }
1072
1073       // Builtins that have custom typechecking or have a reference should
1074       // not be overloadable or redeclarable.
1075       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1076         Match = *I;
1077         return Ovl_NonFunction;
1078       }
1079     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080       // We can overload with these, which can show up when doing
1081       // redeclaration checks for UsingDecls.
1082       assert(Old.getLookupKind() == LookupUsingDeclName);
1083     } else if (isa<TagDecl>(OldD)) {
1084       // We can always overload with tags by hiding them.
1085     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086       // Optimistically assume that an unresolved using decl will
1087       // overload; if it doesn't, we'll have to diagnose during
1088       // template instantiation.
1089       //
1090       // Exception: if the scope is dependent and this is not a class
1091       // member, the using declaration can only introduce an enumerator.
1092       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1093         Match = *I;
1094         return Ovl_NonFunction;
1095       }
1096     } else {
1097       // (C++ 13p1):
1098       //   Only function declarations can be overloaded; object and type
1099       //   declarations cannot be overloaded.
1100       Match = *I;
1101       return Ovl_NonFunction;
1102     }
1103   }
1104
1105   // C++ [temp.friend]p1:
1106   //   For a friend function declaration that is not a template declaration:
1107   //    -- if the name of the friend is a qualified or unqualified template-id,
1108   //       [...], otherwise
1109   //    -- if the name of the friend is a qualified-id and a matching
1110   //       non-template function is found in the specified class or namespace,
1111   //       the friend declaration refers to that function, otherwise,
1112   //    -- if the name of the friend is a qualified-id and a matching function
1113   //       template is found in the specified class or namespace, the friend
1114   //       declaration refers to the deduced specialization of that function
1115   //       template, otherwise
1116   //    -- the name shall be an unqualified-id [...]
1117   // If we get here for a qualified friend declaration, we've just reached the
1118   // third bullet. If the type of the friend is dependent, skip this lookup
1119   // until instantiation.
1120   if (New->getFriendObjectKind() && New->getQualifier() &&
1121       !New->getDescribedFunctionTemplate() &&
1122       !New->getDependentSpecializationInfo() &&
1123       !New->getType()->isDependentType()) {
1124     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125     TemplateSpecResult.addAllDecls(Old);
1126     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127                                             /*QualifiedFriend*/true)) {
1128       New->setInvalidDecl();
1129       return Ovl_Overload;
1130     }
1131
1132     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1133     return Ovl_Match;
1134   }
1135
1136   return Ovl_Overload;
1137 }
1138
1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1141                       bool ConsiderRequiresClauses) {
1142   // C++ [basic.start.main]p2: This function shall not be overloaded.
1143   if (New->isMain())
1144     return false;
1145
1146   // MSVCRT user defined entry points cannot be overloaded.
1147   if (New->isMSVCRTEntryPoint())
1148     return false;
1149
1150   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1151   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1152
1153   // C++ [temp.fct]p2:
1154   //   A function template can be overloaded with other function templates
1155   //   and with normal (non-template) functions.
1156   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1157     return true;
1158
1159   // Is the function New an overload of the function Old?
1160   QualType OldQType = Context.getCanonicalType(Old->getType());
1161   QualType NewQType = Context.getCanonicalType(New->getType());
1162
1163   // Compare the signatures (C++ 1.3.10) of the two functions to
1164   // determine whether they are overloads. If we find any mismatch
1165   // in the signature, they are overloads.
1166
1167   // If either of these functions is a K&R-style function (no
1168   // prototype), then we consider them to have matching signatures.
1169   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1170       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1171     return false;
1172
1173   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1174   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1175
1176   // The signature of a function includes the types of its
1177   // parameters (C++ 1.3.10), which includes the presence or absence
1178   // of the ellipsis; see C++ DR 357).
1179   if (OldQType != NewQType &&
1180       (OldType->getNumParams() != NewType->getNumParams() ||
1181        OldType->isVariadic() != NewType->isVariadic() ||
1182        !FunctionParamTypesAreEqual(OldType, NewType)))
1183     return true;
1184
1185   // C++ [temp.over.link]p4:
1186   //   The signature of a function template consists of its function
1187   //   signature, its return type and its template parameter list. The names
1188   //   of the template parameters are significant only for establishing the
1189   //   relationship between the template parameters and the rest of the
1190   //   signature.
1191   //
1192   // We check the return type and template parameter lists for function
1193   // templates first; the remaining checks follow.
1194   //
1195   // However, we don't consider either of these when deciding whether
1196   // a member introduced by a shadow declaration is hidden.
1197   if (!UseMemberUsingDeclRules && NewTemplate &&
1198       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1199                                        OldTemplate->getTemplateParameters(),
1200                                        false, TPL_TemplateMatch) ||
1201        !Context.hasSameType(Old->getDeclaredReturnType(),
1202                             New->getDeclaredReturnType())))
1203     return true;
1204
1205   // If the function is a class member, its signature includes the
1206   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1207   //
1208   // As part of this, also check whether one of the member functions
1209   // is static, in which case they are not overloads (C++
1210   // 13.1p2). While not part of the definition of the signature,
1211   // this check is important to determine whether these functions
1212   // can be overloaded.
1213   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1214   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1215   if (OldMethod && NewMethod &&
1216       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1217     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1218       if (!UseMemberUsingDeclRules &&
1219           (OldMethod->getRefQualifier() == RQ_None ||
1220            NewMethod->getRefQualifier() == RQ_None)) {
1221         // C++0x [over.load]p2:
1222         //   - Member function declarations with the same name and the same
1223         //     parameter-type-list as well as member function template
1224         //     declarations with the same name, the same parameter-type-list, and
1225         //     the same template parameter lists cannot be overloaded if any of
1226         //     them, but not all, have a ref-qualifier (8.3.5).
1227         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1228           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1229         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1230       }
1231       return true;
1232     }
1233
1234     // We may not have applied the implicit const for a constexpr member
1235     // function yet (because we haven't yet resolved whether this is a static
1236     // or non-static member function). Add it now, on the assumption that this
1237     // is a redeclaration of OldMethod.
1238     auto OldQuals = OldMethod->getMethodQualifiers();
1239     auto NewQuals = NewMethod->getMethodQualifiers();
1240     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1241         !isa<CXXConstructorDecl>(NewMethod))
1242       NewQuals.addConst();
1243     // We do not allow overloading based off of '__restrict'.
1244     OldQuals.removeRestrict();
1245     NewQuals.removeRestrict();
1246     if (OldQuals != NewQuals)
1247       return true;
1248   }
1249
1250   // Though pass_object_size is placed on parameters and takes an argument, we
1251   // consider it to be a function-level modifier for the sake of function
1252   // identity. Either the function has one or more parameters with
1253   // pass_object_size or it doesn't.
1254   if (functionHasPassObjectSizeParams(New) !=
1255       functionHasPassObjectSizeParams(Old))
1256     return true;
1257
1258   // enable_if attributes are an order-sensitive part of the signature.
1259   for (specific_attr_iterator<EnableIfAttr>
1260          NewI = New->specific_attr_begin<EnableIfAttr>(),
1261          NewE = New->specific_attr_end<EnableIfAttr>(),
1262          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1263          OldE = Old->specific_attr_end<EnableIfAttr>();
1264        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1265     if (NewI == NewE || OldI == OldE)
1266       return true;
1267     llvm::FoldingSetNodeID NewID, OldID;
1268     NewI->getCond()->Profile(NewID, Context, true);
1269     OldI->getCond()->Profile(OldID, Context, true);
1270     if (NewID != OldID)
1271       return true;
1272   }
1273
1274   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1275     // Don't allow overloading of destructors.  (In theory we could, but it
1276     // would be a giant change to clang.)
1277     if (!isa<CXXDestructorDecl>(New)) {
1278       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1279                          OldTarget = IdentifyCUDATarget(Old);
1280       if (NewTarget != CFT_InvalidTarget) {
1281         assert((OldTarget != CFT_InvalidTarget) &&
1282                "Unexpected invalid target.");
1283
1284         // Allow overloading of functions with same signature and different CUDA
1285         // target attributes.
1286         if (NewTarget != OldTarget)
1287           return true;
1288       }
1289     }
1290   }
1291
1292   if (ConsiderRequiresClauses) {
1293     Expr *NewRC = New->getTrailingRequiresClause(),
1294          *OldRC = Old->getTrailingRequiresClause();
1295     if ((NewRC != nullptr) != (OldRC != nullptr))
1296       // RC are most certainly different - these are overloads.
1297       return true;
1298
1299     if (NewRC) {
1300       llvm::FoldingSetNodeID NewID, OldID;
1301       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1302       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1303       if (NewID != OldID)
1304         // RCs are not equivalent - these are overloads.
1305         return true;
1306     }
1307   }
1308
1309   // The signatures match; this is not an overload.
1310   return false;
1311 }
1312
1313 /// Tries a user-defined conversion from From to ToType.
1314 ///
1315 /// Produces an implicit conversion sequence for when a standard conversion
1316 /// is not an option. See TryImplicitConversion for more information.
1317 static ImplicitConversionSequence
1318 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1319                          bool SuppressUserConversions,
1320                          bool AllowExplicit,
1321                          bool InOverloadResolution,
1322                          bool CStyle,
1323                          bool AllowObjCWritebackConversion,
1324                          bool AllowObjCConversionOnExplicit) {
1325   ImplicitConversionSequence ICS;
1326
1327   if (SuppressUserConversions) {
1328     // We're not in the case above, so there is no conversion that
1329     // we can perform.
1330     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1331     return ICS;
1332   }
1333
1334   // Attempt user-defined conversion.
1335   OverloadCandidateSet Conversions(From->getExprLoc(),
1336                                    OverloadCandidateSet::CSK_Normal);
1337   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1338                                   Conversions, AllowExplicit,
1339                                   AllowObjCConversionOnExplicit)) {
1340   case OR_Success:
1341   case OR_Deleted:
1342     ICS.setUserDefined();
1343     // C++ [over.ics.user]p4:
1344     //   A conversion of an expression of class type to the same class
1345     //   type is given Exact Match rank, and a conversion of an
1346     //   expression of class type to a base class of that type is
1347     //   given Conversion rank, in spite of the fact that a copy
1348     //   constructor (i.e., a user-defined conversion function) is
1349     //   called for those cases.
1350     if (CXXConstructorDecl *Constructor
1351           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1352       QualType FromCanon
1353         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1354       QualType ToCanon
1355         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1356       if (Constructor->isCopyConstructor() &&
1357           (FromCanon == ToCanon ||
1358            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1359         // Turn this into a "standard" conversion sequence, so that it
1360         // gets ranked with standard conversion sequences.
1361         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1362         ICS.setStandard();
1363         ICS.Standard.setAsIdentityConversion();
1364         ICS.Standard.setFromType(From->getType());
1365         ICS.Standard.setAllToTypes(ToType);
1366         ICS.Standard.CopyConstructor = Constructor;
1367         ICS.Standard.FoundCopyConstructor = Found;
1368         if (ToCanon != FromCanon)
1369           ICS.Standard.Second = ICK_Derived_To_Base;
1370       }
1371     }
1372     break;
1373
1374   case OR_Ambiguous:
1375     ICS.setAmbiguous();
1376     ICS.Ambiguous.setFromType(From->getType());
1377     ICS.Ambiguous.setToType(ToType);
1378     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1379          Cand != Conversions.end(); ++Cand)
1380       if (Cand->Best)
1381         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1382     break;
1383
1384     // Fall through.
1385   case OR_No_Viable_Function:
1386     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1387     break;
1388   }
1389
1390   return ICS;
1391 }
1392
1393 /// TryImplicitConversion - Attempt to perform an implicit conversion
1394 /// from the given expression (Expr) to the given type (ToType). This
1395 /// function returns an implicit conversion sequence that can be used
1396 /// to perform the initialization. Given
1397 ///
1398 ///   void f(float f);
1399 ///   void g(int i) { f(i); }
1400 ///
1401 /// this routine would produce an implicit conversion sequence to
1402 /// describe the initialization of f from i, which will be a standard
1403 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1404 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1405 //
1406 /// Note that this routine only determines how the conversion can be
1407 /// performed; it does not actually perform the conversion. As such,
1408 /// it will not produce any diagnostics if no conversion is available,
1409 /// but will instead return an implicit conversion sequence of kind
1410 /// "BadConversion".
1411 ///
1412 /// If @p SuppressUserConversions, then user-defined conversions are
1413 /// not permitted.
1414 /// If @p AllowExplicit, then explicit user-defined conversions are
1415 /// permitted.
1416 ///
1417 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1418 /// writeback conversion, which allows __autoreleasing id* parameters to
1419 /// be initialized with __strong id* or __weak id* arguments.
1420 static ImplicitConversionSequence
1421 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1422                       bool SuppressUserConversions,
1423                       bool AllowExplicit,
1424                       bool InOverloadResolution,
1425                       bool CStyle,
1426                       bool AllowObjCWritebackConversion,
1427                       bool AllowObjCConversionOnExplicit) {
1428   ImplicitConversionSequence ICS;
1429   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1430                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1431     ICS.setStandard();
1432     return ICS;
1433   }
1434
1435   if (!S.getLangOpts().CPlusPlus) {
1436     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1437     return ICS;
1438   }
1439
1440   // C++ [over.ics.user]p4:
1441   //   A conversion of an expression of class type to the same class
1442   //   type is given Exact Match rank, and a conversion of an
1443   //   expression of class type to a base class of that type is
1444   //   given Conversion rank, in spite of the fact that a copy/move
1445   //   constructor (i.e., a user-defined conversion function) is
1446   //   called for those cases.
1447   QualType FromType = From->getType();
1448   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1449       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1450        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1451     ICS.setStandard();
1452     ICS.Standard.setAsIdentityConversion();
1453     ICS.Standard.setFromType(FromType);
1454     ICS.Standard.setAllToTypes(ToType);
1455
1456     // We don't actually check at this point whether there is a valid
1457     // copy/move constructor, since overloading just assumes that it
1458     // exists. When we actually perform initialization, we'll find the
1459     // appropriate constructor to copy the returned object, if needed.
1460     ICS.Standard.CopyConstructor = nullptr;
1461
1462     // Determine whether this is considered a derived-to-base conversion.
1463     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1464       ICS.Standard.Second = ICK_Derived_To_Base;
1465
1466     return ICS;
1467   }
1468
1469   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1470                                   AllowExplicit, InOverloadResolution, CStyle,
1471                                   AllowObjCWritebackConversion,
1472                                   AllowObjCConversionOnExplicit);
1473 }
1474
1475 ImplicitConversionSequence
1476 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1477                             bool SuppressUserConversions,
1478                             bool AllowExplicit,
1479                             bool InOverloadResolution,
1480                             bool CStyle,
1481                             bool AllowObjCWritebackConversion) {
1482   return ::TryImplicitConversion(*this, From, ToType,
1483                                  SuppressUserConversions, AllowExplicit,
1484                                  InOverloadResolution, CStyle,
1485                                  AllowObjCWritebackConversion,
1486                                  /*AllowObjCConversionOnExplicit=*/false);
1487 }
1488
1489 /// PerformImplicitConversion - Perform an implicit conversion of the
1490 /// expression From to the type ToType. Returns the
1491 /// converted expression. Flavor is the kind of conversion we're
1492 /// performing, used in the error message. If @p AllowExplicit,
1493 /// explicit user-defined conversions are permitted.
1494 ExprResult
1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                 AssignmentAction Action, bool AllowExplicit) {
1497   ImplicitConversionSequence ICS;
1498   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499 }
1500
1501 ExprResult
1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503                                 AssignmentAction Action, bool AllowExplicit,
1504                                 ImplicitConversionSequence& ICS) {
1505   if (checkPlaceholderForOverload(*this, From))
1506     return ExprError();
1507
1508   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509   bool AllowObjCWritebackConversion
1510     = getLangOpts().ObjCAutoRefCount &&
1511       (Action == AA_Passing || Action == AA_Sending);
1512   if (getLangOpts().ObjC)
1513     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514                                       From->getType(), From);
1515   ICS = ::TryImplicitConversion(*this, From, ToType,
1516                                 /*SuppressUserConversions=*/false,
1517                                 AllowExplicit,
1518                                 /*InOverloadResolution=*/false,
1519                                 /*CStyle=*/false,
1520                                 AllowObjCWritebackConversion,
1521                                 /*AllowObjCConversionOnExplicit=*/false);
1522   return PerformImplicitConversion(From, ToType, ICS, Action);
1523 }
1524
1525 /// Determine whether the conversion from FromType to ToType is a valid
1526 /// conversion that strips "noexcept" or "noreturn" off the nested function
1527 /// type.
1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529                                 QualType &ResultTy) {
1530   if (Context.hasSameUnqualifiedType(FromType, ToType))
1531     return false;
1532
1533   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534   //                    or F(t noexcept) -> F(t)
1535   // where F adds one of the following at most once:
1536   //   - a pointer
1537   //   - a member pointer
1538   //   - a block pointer
1539   // Changes here need matching changes in FindCompositePointerType.
1540   CanQualType CanTo = Context.getCanonicalType(ToType);
1541   CanQualType CanFrom = Context.getCanonicalType(FromType);
1542   Type::TypeClass TyClass = CanTo->getTypeClass();
1543   if (TyClass != CanFrom->getTypeClass()) return false;
1544   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545     if (TyClass == Type::Pointer) {
1546       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548     } else if (TyClass == Type::BlockPointer) {
1549       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551     } else if (TyClass == Type::MemberPointer) {
1552       auto ToMPT = CanTo.castAs<MemberPointerType>();
1553       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554       // A function pointer conversion cannot change the class of the function.
1555       if (ToMPT->getClass() != FromMPT->getClass())
1556         return false;
1557       CanTo = ToMPT->getPointeeType();
1558       CanFrom = FromMPT->getPointeeType();
1559     } else {
1560       return false;
1561     }
1562
1563     TyClass = CanTo->getTypeClass();
1564     if (TyClass != CanFrom->getTypeClass()) return false;
1565     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566       return false;
1567   }
1568
1569   const auto *FromFn = cast<FunctionType>(CanFrom);
1570   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571
1572   const auto *ToFn = cast<FunctionType>(CanTo);
1573   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574
1575   bool Changed = false;
1576
1577   // Drop 'noreturn' if not present in target type.
1578   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580     Changed = true;
1581   }
1582
1583   // Drop 'noexcept' if not present in target type.
1584   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587       FromFn = cast<FunctionType>(
1588           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589                                                    EST_None)
1590                  .getTypePtr());
1591       Changed = true;
1592     }
1593
1594     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595     // only if the ExtParameterInfo lists of the two function prototypes can be
1596     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598     bool CanUseToFPT, CanUseFromFPT;
1599     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600                                       CanUseFromFPT, NewParamInfos) &&
1601         CanUseToFPT && !CanUseFromFPT) {
1602       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603       ExtInfo.ExtParameterInfos =
1604           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606                                             FromFPT->getParamTypes(), ExtInfo);
1607       FromFn = QT->getAs<FunctionType>();
1608       Changed = true;
1609     }
1610   }
1611
1612   if (!Changed)
1613     return false;
1614
1615   assert(QualType(FromFn, 0).isCanonical());
1616   if (QualType(FromFn, 0) != CanTo) return false;
1617
1618   ResultTy = ToType;
1619   return true;
1620 }
1621
1622 /// Determine whether the conversion from FromType to ToType is a valid
1623 /// vector conversion.
1624 ///
1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1626 /// conversion.
1627 static bool IsVectorConversion(Sema &S, QualType FromType,
1628                                QualType ToType, ImplicitConversionKind &ICK) {
1629   // We need at least one of these types to be a vector type to have a vector
1630   // conversion.
1631   if (!ToType->isVectorType() && !FromType->isVectorType())
1632     return false;
1633
1634   // Identical types require no conversions.
1635   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636     return false;
1637
1638   // There are no conversions between extended vector types, only identity.
1639   if (ToType->isExtVectorType()) {
1640     // There are no conversions between extended vector types other than the
1641     // identity conversion.
1642     if (FromType->isExtVectorType())
1643       return false;
1644
1645     // Vector splat from any arithmetic type to a vector.
1646     if (FromType->isArithmeticType()) {
1647       ICK = ICK_Vector_Splat;
1648       return true;
1649     }
1650   }
1651
1652   // We can perform the conversion between vector types in the following cases:
1653   // 1)vector types are equivalent AltiVec and GCC vector types
1654   // 2)lax vector conversions are permitted and the vector types are of the
1655   //   same size
1656   if (ToType->isVectorType() && FromType->isVectorType()) {
1657     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1658         S.isLaxVectorConversion(FromType, ToType)) {
1659       ICK = ICK_Vector_Conversion;
1660       return true;
1661     }
1662   }
1663
1664   return false;
1665 }
1666
1667 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1668                                 bool InOverloadResolution,
1669                                 StandardConversionSequence &SCS,
1670                                 bool CStyle);
1671
1672 /// IsStandardConversion - Determines whether there is a standard
1673 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1674 /// expression From to the type ToType. Standard conversion sequences
1675 /// only consider non-class types; for conversions that involve class
1676 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1677 /// contain the standard conversion sequence required to perform this
1678 /// conversion and this routine will return true. Otherwise, this
1679 /// routine will return false and the value of SCS is unspecified.
1680 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1681                                  bool InOverloadResolution,
1682                                  StandardConversionSequence &SCS,
1683                                  bool CStyle,
1684                                  bool AllowObjCWritebackConversion) {
1685   QualType FromType = From->getType();
1686
1687   // Standard conversions (C++ [conv])
1688   SCS.setAsIdentityConversion();
1689   SCS.IncompatibleObjC = false;
1690   SCS.setFromType(FromType);
1691   SCS.CopyConstructor = nullptr;
1692
1693   // There are no standard conversions for class types in C++, so
1694   // abort early. When overloading in C, however, we do permit them.
1695   if (S.getLangOpts().CPlusPlus &&
1696       (FromType->isRecordType() || ToType->isRecordType()))
1697     return false;
1698
1699   // The first conversion can be an lvalue-to-rvalue conversion,
1700   // array-to-pointer conversion, or function-to-pointer conversion
1701   // (C++ 4p1).
1702
1703   if (FromType == S.Context.OverloadTy) {
1704     DeclAccessPair AccessPair;
1705     if (FunctionDecl *Fn
1706           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1707                                                  AccessPair)) {
1708       // We were able to resolve the address of the overloaded function,
1709       // so we can convert to the type of that function.
1710       FromType = Fn->getType();
1711       SCS.setFromType(FromType);
1712
1713       // we can sometimes resolve &foo<int> regardless of ToType, so check
1714       // if the type matches (identity) or we are converting to bool
1715       if (!S.Context.hasSameUnqualifiedType(
1716                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1717         QualType resultTy;
1718         // if the function type matches except for [[noreturn]], it's ok
1719         if (!S.IsFunctionConversion(FromType,
1720               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1721           // otherwise, only a boolean conversion is standard
1722           if (!ToType->isBooleanType())
1723             return false;
1724       }
1725
1726       // Check if the "from" expression is taking the address of an overloaded
1727       // function and recompute the FromType accordingly. Take advantage of the
1728       // fact that non-static member functions *must* have such an address-of
1729       // expression.
1730       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1731       if (Method && !Method->isStatic()) {
1732         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1733                "Non-unary operator on non-static member address");
1734         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1735                == UO_AddrOf &&
1736                "Non-address-of operator on non-static member address");
1737         const Type *ClassType
1738           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1739         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1740       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1741         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1742                UO_AddrOf &&
1743                "Non-address-of operator for overloaded function expression");
1744         FromType = S.Context.getPointerType(FromType);
1745       }
1746
1747       // Check that we've computed the proper type after overload resolution.
1748       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1749       // be calling it from within an NDEBUG block.
1750       assert(S.Context.hasSameType(
1751         FromType,
1752         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1753     } else {
1754       return false;
1755     }
1756   }
1757   // Lvalue-to-rvalue conversion (C++11 4.1):
1758   //   A glvalue (3.10) of a non-function, non-array type T can
1759   //   be converted to a prvalue.
1760   bool argIsLValue = From->isGLValue();
1761   if (argIsLValue &&
1762       !FromType->isFunctionType() && !FromType->isArrayType() &&
1763       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1764     SCS.First = ICK_Lvalue_To_Rvalue;
1765
1766     // C11 6.3.2.1p2:
1767     //   ... if the lvalue has atomic type, the value has the non-atomic version
1768     //   of the type of the lvalue ...
1769     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1770       FromType = Atomic->getValueType();
1771
1772     // If T is a non-class type, the type of the rvalue is the
1773     // cv-unqualified version of T. Otherwise, the type of the rvalue
1774     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1775     // just strip the qualifiers because they don't matter.
1776     FromType = FromType.getUnqualifiedType();
1777   } else if (FromType->isArrayType()) {
1778     // Array-to-pointer conversion (C++ 4.2)
1779     SCS.First = ICK_Array_To_Pointer;
1780
1781     // An lvalue or rvalue of type "array of N T" or "array of unknown
1782     // bound of T" can be converted to an rvalue of type "pointer to
1783     // T" (C++ 4.2p1).
1784     FromType = S.Context.getArrayDecayedType(FromType);
1785
1786     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1787       // This conversion is deprecated in C++03 (D.4)
1788       SCS.DeprecatedStringLiteralToCharPtr = true;
1789
1790       // For the purpose of ranking in overload resolution
1791       // (13.3.3.1.1), this conversion is considered an
1792       // array-to-pointer conversion followed by a qualification
1793       // conversion (4.4). (C++ 4.2p2)
1794       SCS.Second = ICK_Identity;
1795       SCS.Third = ICK_Qualification;
1796       SCS.QualificationIncludesObjCLifetime = false;
1797       SCS.setAllToTypes(FromType);
1798       return true;
1799     }
1800   } else if (FromType->isFunctionType() && argIsLValue) {
1801     // Function-to-pointer conversion (C++ 4.3).
1802     SCS.First = ICK_Function_To_Pointer;
1803
1804     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1805       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1806         if (!S.checkAddressOfFunctionIsAvailable(FD))
1807           return false;
1808
1809     // An lvalue of function type T can be converted to an rvalue of
1810     // type "pointer to T." The result is a pointer to the
1811     // function. (C++ 4.3p1).
1812     FromType = S.Context.getPointerType(FromType);
1813   } else {
1814     // We don't require any conversions for the first step.
1815     SCS.First = ICK_Identity;
1816   }
1817   SCS.setToType(0, FromType);
1818
1819   // The second conversion can be an integral promotion, floating
1820   // point promotion, integral conversion, floating point conversion,
1821   // floating-integral conversion, pointer conversion,
1822   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1823   // For overloading in C, this can also be a "compatible-type"
1824   // conversion.
1825   bool IncompatibleObjC = false;
1826   ImplicitConversionKind SecondICK = ICK_Identity;
1827   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1828     // The unqualified versions of the types are the same: there's no
1829     // conversion to do.
1830     SCS.Second = ICK_Identity;
1831   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1832     // Integral promotion (C++ 4.5).
1833     SCS.Second = ICK_Integral_Promotion;
1834     FromType = ToType.getUnqualifiedType();
1835   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1836     // Floating point promotion (C++ 4.6).
1837     SCS.Second = ICK_Floating_Promotion;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (S.IsComplexPromotion(FromType, ToType)) {
1840     // Complex promotion (Clang extension)
1841     SCS.Second = ICK_Complex_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (ToType->isBooleanType() &&
1844              (FromType->isArithmeticType() ||
1845               FromType->isAnyPointerType() ||
1846               FromType->isBlockPointerType() ||
1847               FromType->isMemberPointerType() ||
1848               FromType->isNullPtrType())) {
1849     // Boolean conversions (C++ 4.12).
1850     SCS.Second = ICK_Boolean_Conversion;
1851     FromType = S.Context.BoolTy;
1852   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1853              ToType->isIntegralType(S.Context)) {
1854     // Integral conversions (C++ 4.7).
1855     SCS.Second = ICK_Integral_Conversion;
1856     FromType = ToType.getUnqualifiedType();
1857   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1858     // Complex conversions (C99 6.3.1.6)
1859     SCS.Second = ICK_Complex_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1862              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1863     // Complex-real conversions (C99 6.3.1.7)
1864     SCS.Second = ICK_Complex_Real;
1865     FromType = ToType.getUnqualifiedType();
1866   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1867     // FIXME: disable conversions between long double and __float128 if
1868     // their representation is different until there is back end support
1869     // We of course allow this conversion if long double is really double.
1870     if (&S.Context.getFloatTypeSemantics(FromType) !=
1871         &S.Context.getFloatTypeSemantics(ToType)) {
1872       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1873                                     ToType == S.Context.LongDoubleTy) ||
1874                                    (FromType == S.Context.LongDoubleTy &&
1875                                     ToType == S.Context.Float128Ty));
1876       if (Float128AndLongDouble &&
1877           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1878            &llvm::APFloat::PPCDoubleDouble()))
1879         return false;
1880     }
1881     // Floating point conversions (C++ 4.8).
1882     SCS.Second = ICK_Floating_Conversion;
1883     FromType = ToType.getUnqualifiedType();
1884   } else if ((FromType->isRealFloatingType() &&
1885               ToType->isIntegralType(S.Context)) ||
1886              (FromType->isIntegralOrUnscopedEnumerationType() &&
1887               ToType->isRealFloatingType())) {
1888     // Floating-integral conversions (C++ 4.9).
1889     SCS.Second = ICK_Floating_Integral;
1890     FromType = ToType.getUnqualifiedType();
1891   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1892     SCS.Second = ICK_Block_Pointer_Conversion;
1893   } else if (AllowObjCWritebackConversion &&
1894              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1895     SCS.Second = ICK_Writeback_Conversion;
1896   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1897                                    FromType, IncompatibleObjC)) {
1898     // Pointer conversions (C++ 4.10).
1899     SCS.Second = ICK_Pointer_Conversion;
1900     SCS.IncompatibleObjC = IncompatibleObjC;
1901     FromType = FromType.getUnqualifiedType();
1902   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1903                                          InOverloadResolution, FromType)) {
1904     // Pointer to member conversions (4.11).
1905     SCS.Second = ICK_Pointer_Member;
1906   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1907     SCS.Second = SecondICK;
1908     FromType = ToType.getUnqualifiedType();
1909   } else if (!S.getLangOpts().CPlusPlus &&
1910              S.Context.typesAreCompatible(ToType, FromType)) {
1911     // Compatible conversions (Clang extension for C function overloading)
1912     SCS.Second = ICK_Compatible_Conversion;
1913     FromType = ToType.getUnqualifiedType();
1914   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1915                                              InOverloadResolution,
1916                                              SCS, CStyle)) {
1917     SCS.Second = ICK_TransparentUnionConversion;
1918     FromType = ToType;
1919   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1920                                  CStyle)) {
1921     // tryAtomicConversion has updated the standard conversion sequence
1922     // appropriately.
1923     return true;
1924   } else if (ToType->isEventT() &&
1925              From->isIntegerConstantExpr(S.getASTContext()) &&
1926              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1927     SCS.Second = ICK_Zero_Event_Conversion;
1928     FromType = ToType;
1929   } else if (ToType->isQueueT() &&
1930              From->isIntegerConstantExpr(S.getASTContext()) &&
1931              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1932     SCS.Second = ICK_Zero_Queue_Conversion;
1933     FromType = ToType;
1934   } else if (ToType->isSamplerT() &&
1935              From->isIntegerConstantExpr(S.getASTContext())) {
1936     SCS.Second = ICK_Compatible_Conversion;
1937     FromType = ToType;
1938   } else {
1939     // No second conversion required.
1940     SCS.Second = ICK_Identity;
1941   }
1942   SCS.setToType(1, FromType);
1943
1944   // The third conversion can be a function pointer conversion or a
1945   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1946   bool ObjCLifetimeConversion;
1947   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1948     // Function pointer conversions (removing 'noexcept') including removal of
1949     // 'noreturn' (Clang extension).
1950     SCS.Third = ICK_Function_Conversion;
1951   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1952                                          ObjCLifetimeConversion)) {
1953     SCS.Third = ICK_Qualification;
1954     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1955     FromType = ToType;
1956   } else {
1957     // No conversion required
1958     SCS.Third = ICK_Identity;
1959   }
1960
1961   // C++ [over.best.ics]p6:
1962   //   [...] Any difference in top-level cv-qualification is
1963   //   subsumed by the initialization itself and does not constitute
1964   //   a conversion. [...]
1965   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1966   QualType CanonTo = S.Context.getCanonicalType(ToType);
1967   if (CanonFrom.getLocalUnqualifiedType()
1968                                      == CanonTo.getLocalUnqualifiedType() &&
1969       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1970     FromType = ToType;
1971     CanonFrom = CanonTo;
1972   }
1973
1974   SCS.setToType(2, FromType);
1975
1976   if (CanonFrom == CanonTo)
1977     return true;
1978
1979   // If we have not converted the argument type to the parameter type,
1980   // this is a bad conversion sequence, unless we're resolving an overload in C.
1981   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1982     return false;
1983
1984   ExprResult ER = ExprResult{From};
1985   Sema::AssignConvertType Conv =
1986       S.CheckSingleAssignmentConstraints(ToType, ER,
1987                                          /*Diagnose=*/false,
1988                                          /*DiagnoseCFAudited=*/false,
1989                                          /*ConvertRHS=*/false);
1990   ImplicitConversionKind SecondConv;
1991   switch (Conv) {
1992   case Sema::Compatible:
1993     SecondConv = ICK_C_Only_Conversion;
1994     break;
1995   // For our purposes, discarding qualifiers is just as bad as using an
1996   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1997   // qualifiers, as well.
1998   case Sema::CompatiblePointerDiscardsQualifiers:
1999   case Sema::IncompatiblePointer:
2000   case Sema::IncompatiblePointerSign:
2001     SecondConv = ICK_Incompatible_Pointer_Conversion;
2002     break;
2003   default:
2004     return false;
2005   }
2006
2007   // First can only be an lvalue conversion, so we pretend that this was the
2008   // second conversion. First should already be valid from earlier in the
2009   // function.
2010   SCS.Second = SecondConv;
2011   SCS.setToType(1, ToType);
2012
2013   // Third is Identity, because Second should rank us worse than any other
2014   // conversion. This could also be ICK_Qualification, but it's simpler to just
2015   // lump everything in with the second conversion, and we don't gain anything
2016   // from making this ICK_Qualification.
2017   SCS.Third = ICK_Identity;
2018   SCS.setToType(2, ToType);
2019   return true;
2020 }
2021
2022 static bool
2023 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2024                                      QualType &ToType,
2025                                      bool InOverloadResolution,
2026                                      StandardConversionSequence &SCS,
2027                                      bool CStyle) {
2028
2029   const RecordType *UT = ToType->getAsUnionType();
2030   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2031     return false;
2032   // The field to initialize within the transparent union.
2033   RecordDecl *UD = UT->getDecl();
2034   // It's compatible if the expression matches any of the fields.
2035   for (const auto *it : UD->fields()) {
2036     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2037                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2038       ToType = it->getType();
2039       return true;
2040     }
2041   }
2042   return false;
2043 }
2044
2045 /// IsIntegralPromotion - Determines whether the conversion from the
2046 /// expression From (whose potentially-adjusted type is FromType) to
2047 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2048 /// sets PromotedType to the promoted type.
2049 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2050   const BuiltinType *To = ToType->getAs<BuiltinType>();
2051   // All integers are built-in.
2052   if (!To) {
2053     return false;
2054   }
2055
2056   // An rvalue of type char, signed char, unsigned char, short int, or
2057   // unsigned short int can be converted to an rvalue of type int if
2058   // int can represent all the values of the source type; otherwise,
2059   // the source rvalue can be converted to an rvalue of type unsigned
2060   // int (C++ 4.5p1).
2061   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2062       !FromType->isEnumeralType()) {
2063     if (// We can promote any signed, promotable integer type to an int
2064         (FromType->isSignedIntegerType() ||
2065          // We can promote any unsigned integer type whose size is
2066          // less than int to an int.
2067          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2068       return To->getKind() == BuiltinType::Int;
2069     }
2070
2071     return To->getKind() == BuiltinType::UInt;
2072   }
2073
2074   // C++11 [conv.prom]p3:
2075   //   A prvalue of an unscoped enumeration type whose underlying type is not
2076   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2077   //   following types that can represent all the values of the enumeration
2078   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2079   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2080   //   long long int. If none of the types in that list can represent all the
2081   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2082   //   type can be converted to an rvalue a prvalue of the extended integer type
2083   //   with lowest integer conversion rank (4.13) greater than the rank of long
2084   //   long in which all the values of the enumeration can be represented. If
2085   //   there are two such extended types, the signed one is chosen.
2086   // C++11 [conv.prom]p4:
2087   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2088   //   can be converted to a prvalue of its underlying type. Moreover, if
2089   //   integral promotion can be applied to its underlying type, a prvalue of an
2090   //   unscoped enumeration type whose underlying type is fixed can also be
2091   //   converted to a prvalue of the promoted underlying type.
2092   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2093     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2094     // provided for a scoped enumeration.
2095     if (FromEnumType->getDecl()->isScoped())
2096       return false;
2097
2098     // We can perform an integral promotion to the underlying type of the enum,
2099     // even if that's not the promoted type. Note that the check for promoting
2100     // the underlying type is based on the type alone, and does not consider
2101     // the bitfield-ness of the actual source expression.
2102     if (FromEnumType->getDecl()->isFixed()) {
2103       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2104       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2105              IsIntegralPromotion(nullptr, Underlying, ToType);
2106     }
2107
2108     // We have already pre-calculated the promotion type, so this is trivial.
2109     if (ToType->isIntegerType() &&
2110         isCompleteType(From->getBeginLoc(), FromType))
2111       return Context.hasSameUnqualifiedType(
2112           ToType, FromEnumType->getDecl()->getPromotionType());
2113
2114     // C++ [conv.prom]p5:
2115     //   If the bit-field has an enumerated type, it is treated as any other
2116     //   value of that type for promotion purposes.
2117     //
2118     // ... so do not fall through into the bit-field checks below in C++.
2119     if (getLangOpts().CPlusPlus)
2120       return false;
2121   }
2122
2123   // C++0x [conv.prom]p2:
2124   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2125   //   to an rvalue a prvalue of the first of the following types that can
2126   //   represent all the values of its underlying type: int, unsigned int,
2127   //   long int, unsigned long int, long long int, or unsigned long long int.
2128   //   If none of the types in that list can represent all the values of its
2129   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2130   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2131   //   type.
2132   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2133       ToType->isIntegerType()) {
2134     // Determine whether the type we're converting from is signed or
2135     // unsigned.
2136     bool FromIsSigned = FromType->isSignedIntegerType();
2137     uint64_t FromSize = Context.getTypeSize(FromType);
2138
2139     // The types we'll try to promote to, in the appropriate
2140     // order. Try each of these types.
2141     QualType PromoteTypes[6] = {
2142       Context.IntTy, Context.UnsignedIntTy,
2143       Context.LongTy, Context.UnsignedLongTy ,
2144       Context.LongLongTy, Context.UnsignedLongLongTy
2145     };
2146     for (int Idx = 0; Idx < 6; ++Idx) {
2147       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2148       if (FromSize < ToSize ||
2149           (FromSize == ToSize &&
2150            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2151         // We found the type that we can promote to. If this is the
2152         // type we wanted, we have a promotion. Otherwise, no
2153         // promotion.
2154         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2155       }
2156     }
2157   }
2158
2159   // An rvalue for an integral bit-field (9.6) can be converted to an
2160   // rvalue of type int if int can represent all the values of the
2161   // bit-field; otherwise, it can be converted to unsigned int if
2162   // unsigned int can represent all the values of the bit-field. If
2163   // the bit-field is larger yet, no integral promotion applies to
2164   // it. If the bit-field has an enumerated type, it is treated as any
2165   // other value of that type for promotion purposes (C++ 4.5p3).
2166   // FIXME: We should delay checking of bit-fields until we actually perform the
2167   // conversion.
2168   //
2169   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2170   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2171   // bit-fields and those whose underlying type is larger than int) for GCC
2172   // compatibility.
2173   if (From) {
2174     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2175       llvm::APSInt BitWidth;
2176       if (FromType->isIntegralType(Context) &&
2177           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2178         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2179         ToSize = Context.getTypeSize(ToType);
2180
2181         // Are we promoting to an int from a bitfield that fits in an int?
2182         if (BitWidth < ToSize ||
2183             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2184           return To->getKind() == BuiltinType::Int;
2185         }
2186
2187         // Are we promoting to an unsigned int from an unsigned bitfield
2188         // that fits into an unsigned int?
2189         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2190           return To->getKind() == BuiltinType::UInt;
2191         }
2192
2193         return false;
2194       }
2195     }
2196   }
2197
2198   // An rvalue of type bool can be converted to an rvalue of type int,
2199   // with false becoming zero and true becoming one (C++ 4.5p4).
2200   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2201     return true;
2202   }
2203
2204   return false;
2205 }
2206
2207 /// IsFloatingPointPromotion - Determines whether the conversion from
2208 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2209 /// returns true and sets PromotedType to the promoted type.
2210 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2211   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2212     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2213       /// An rvalue of type float can be converted to an rvalue of type
2214       /// double. (C++ 4.6p1).
2215       if (FromBuiltin->getKind() == BuiltinType::Float &&
2216           ToBuiltin->getKind() == BuiltinType::Double)
2217         return true;
2218
2219       // C99 6.3.1.5p1:
2220       //   When a float is promoted to double or long double, or a
2221       //   double is promoted to long double [...].
2222       if (!getLangOpts().CPlusPlus &&
2223           (FromBuiltin->getKind() == BuiltinType::Float ||
2224            FromBuiltin->getKind() == BuiltinType::Double) &&
2225           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2226            ToBuiltin->getKind() == BuiltinType::Float128))
2227         return true;
2228
2229       // Half can be promoted to float.
2230       if (!getLangOpts().NativeHalfType &&
2231            FromBuiltin->getKind() == BuiltinType::Half &&
2232           ToBuiltin->getKind() == BuiltinType::Float)
2233         return true;
2234     }
2235
2236   return false;
2237 }
2238
2239 /// Determine if a conversion is a complex promotion.
2240 ///
2241 /// A complex promotion is defined as a complex -> complex conversion
2242 /// where the conversion between the underlying real types is a
2243 /// floating-point or integral promotion.
2244 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2245   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2246   if (!FromComplex)
2247     return false;
2248
2249   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2250   if (!ToComplex)
2251     return false;
2252
2253   return IsFloatingPointPromotion(FromComplex->getElementType(),
2254                                   ToComplex->getElementType()) ||
2255     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2256                         ToComplex->getElementType());
2257 }
2258
2259 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2260 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2261 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2262 /// if non-empty, will be a pointer to ToType that may or may not have
2263 /// the right set of qualifiers on its pointee.
2264 ///
2265 static QualType
2266 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2267                                    QualType ToPointee, QualType ToType,
2268                                    ASTContext &Context,
2269                                    bool StripObjCLifetime = false) {
2270   assert((FromPtr->getTypeClass() == Type::Pointer ||
2271           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2272          "Invalid similarly-qualified pointer type");
2273
2274   /// Conversions to 'id' subsume cv-qualifier conversions.
2275   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2276     return ToType.getUnqualifiedType();
2277
2278   QualType CanonFromPointee
2279     = Context.getCanonicalType(FromPtr->getPointeeType());
2280   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2281   Qualifiers Quals = CanonFromPointee.getQualifiers();
2282
2283   if (StripObjCLifetime)
2284     Quals.removeObjCLifetime();
2285
2286   // Exact qualifier match -> return the pointer type we're converting to.
2287   if (CanonToPointee.getLocalQualifiers() == Quals) {
2288     // ToType is exactly what we need. Return it.
2289     if (!ToType.isNull())
2290       return ToType.getUnqualifiedType();
2291
2292     // Build a pointer to ToPointee. It has the right qualifiers
2293     // already.
2294     if (isa<ObjCObjectPointerType>(ToType))
2295       return Context.getObjCObjectPointerType(ToPointee);
2296     return Context.getPointerType(ToPointee);
2297   }
2298
2299   // Just build a canonical type that has the right qualifiers.
2300   QualType QualifiedCanonToPointee
2301     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2302
2303   if (isa<ObjCObjectPointerType>(ToType))
2304     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2305   return Context.getPointerType(QualifiedCanonToPointee);
2306 }
2307
2308 static bool isNullPointerConstantForConversion(Expr *Expr,
2309                                                bool InOverloadResolution,
2310                                                ASTContext &Context) {
2311   // Handle value-dependent integral null pointer constants correctly.
2312   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2313   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2314       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2315     return !InOverloadResolution;
2316
2317   return Expr->isNullPointerConstant(Context,
2318                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2319                                         : Expr::NPC_ValueDependentIsNull);
2320 }
2321
2322 /// IsPointerConversion - Determines whether the conversion of the
2323 /// expression From, which has the (possibly adjusted) type FromType,
2324 /// can be converted to the type ToType via a pointer conversion (C++
2325 /// 4.10). If so, returns true and places the converted type (that
2326 /// might differ from ToType in its cv-qualifiers at some level) into
2327 /// ConvertedType.
2328 ///
2329 /// This routine also supports conversions to and from block pointers
2330 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2331 /// pointers to interfaces. FIXME: Once we've determined the
2332 /// appropriate overloading rules for Objective-C, we may want to
2333 /// split the Objective-C checks into a different routine; however,
2334 /// GCC seems to consider all of these conversions to be pointer
2335 /// conversions, so for now they live here. IncompatibleObjC will be
2336 /// set if the conversion is an allowed Objective-C conversion that
2337 /// should result in a warning.
2338 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2339                                bool InOverloadResolution,
2340                                QualType& ConvertedType,
2341                                bool &IncompatibleObjC) {
2342   IncompatibleObjC = false;
2343   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2344                               IncompatibleObjC))
2345     return true;
2346
2347   // Conversion from a null pointer constant to any Objective-C pointer type.
2348   if (ToType->isObjCObjectPointerType() &&
2349       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2350     ConvertedType = ToType;
2351     return true;
2352   }
2353
2354   // Blocks: Block pointers can be converted to void*.
2355   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2356       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2357     ConvertedType = ToType;
2358     return true;
2359   }
2360   // Blocks: A null pointer constant can be converted to a block
2361   // pointer type.
2362   if (ToType->isBlockPointerType() &&
2363       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364     ConvertedType = ToType;
2365     return true;
2366   }
2367
2368   // If the left-hand-side is nullptr_t, the right side can be a null
2369   // pointer constant.
2370   if (ToType->isNullPtrType() &&
2371       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372     ConvertedType = ToType;
2373     return true;
2374   }
2375
2376   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2377   if (!ToTypePtr)
2378     return false;
2379
2380   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2381   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2382     ConvertedType = ToType;
2383     return true;
2384   }
2385
2386   // Beyond this point, both types need to be pointers
2387   // , including objective-c pointers.
2388   QualType ToPointeeType = ToTypePtr->getPointeeType();
2389   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2390       !getLangOpts().ObjCAutoRefCount) {
2391     ConvertedType = BuildSimilarlyQualifiedPointerType(
2392                                       FromType->getAs<ObjCObjectPointerType>(),
2393                                                        ToPointeeType,
2394                                                        ToType, Context);
2395     return true;
2396   }
2397   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2398   if (!FromTypePtr)
2399     return false;
2400
2401   QualType FromPointeeType = FromTypePtr->getPointeeType();
2402
2403   // If the unqualified pointee types are the same, this can't be a
2404   // pointer conversion, so don't do all of the work below.
2405   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2406     return false;
2407
2408   // An rvalue of type "pointer to cv T," where T is an object type,
2409   // can be converted to an rvalue of type "pointer to cv void" (C++
2410   // 4.10p2).
2411   if (FromPointeeType->isIncompleteOrObjectType() &&
2412       ToPointeeType->isVoidType()) {
2413     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2414                                                        ToPointeeType,
2415                                                        ToType, Context,
2416                                                    /*StripObjCLifetime=*/true);
2417     return true;
2418   }
2419
2420   // MSVC allows implicit function to void* type conversion.
2421   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2422       ToPointeeType->isVoidType()) {
2423     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2424                                                        ToPointeeType,
2425                                                        ToType, Context);
2426     return true;
2427   }
2428
2429   // When we're overloading in C, we allow a special kind of pointer
2430   // conversion for compatible-but-not-identical pointee types.
2431   if (!getLangOpts().CPlusPlus &&
2432       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2433     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2434                                                        ToPointeeType,
2435                                                        ToType, Context);
2436     return true;
2437   }
2438
2439   // C++ [conv.ptr]p3:
2440   //
2441   //   An rvalue of type "pointer to cv D," where D is a class type,
2442   //   can be converted to an rvalue of type "pointer to cv B," where
2443   //   B is a base class (clause 10) of D. If B is an inaccessible
2444   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2445   //   necessitates this conversion is ill-formed. The result of the
2446   //   conversion is a pointer to the base class sub-object of the
2447   //   derived class object. The null pointer value is converted to
2448   //   the null pointer value of the destination type.
2449   //
2450   // Note that we do not check for ambiguity or inaccessibility
2451   // here. That is handled by CheckPointerConversion.
2452   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2453       ToPointeeType->isRecordType() &&
2454       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2455       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2456     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2457                                                        ToPointeeType,
2458                                                        ToType, Context);
2459     return true;
2460   }
2461
2462   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2463       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2464     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2465                                                        ToPointeeType,
2466                                                        ToType, Context);
2467     return true;
2468   }
2469
2470   return false;
2471 }
2472
2473 /// Adopt the given qualifiers for the given type.
2474 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2475   Qualifiers TQs = T.getQualifiers();
2476
2477   // Check whether qualifiers already match.
2478   if (TQs == Qs)
2479     return T;
2480
2481   if (Qs.compatiblyIncludes(TQs))
2482     return Context.getQualifiedType(T, Qs);
2483
2484   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2485 }
2486
2487 /// isObjCPointerConversion - Determines whether this is an
2488 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2489 /// with the same arguments and return values.
2490 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2491                                    QualType& ConvertedType,
2492                                    bool &IncompatibleObjC) {
2493   if (!getLangOpts().ObjC)
2494     return false;
2495
2496   // The set of qualifiers on the type we're converting from.
2497   Qualifiers FromQualifiers = FromType.getQualifiers();
2498
2499   // First, we handle all conversions on ObjC object pointer types.
2500   const ObjCObjectPointerType* ToObjCPtr =
2501     ToType->getAs<ObjCObjectPointerType>();
2502   const ObjCObjectPointerType *FromObjCPtr =
2503     FromType->getAs<ObjCObjectPointerType>();
2504
2505   if (ToObjCPtr && FromObjCPtr) {
2506     // If the pointee types are the same (ignoring qualifications),
2507     // then this is not a pointer conversion.
2508     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2509                                        FromObjCPtr->getPointeeType()))
2510       return false;
2511
2512     // Conversion between Objective-C pointers.
2513     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2514       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2515       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2516       if (getLangOpts().CPlusPlus && LHS && RHS &&
2517           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2518                                                 FromObjCPtr->getPointeeType()))
2519         return false;
2520       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2521                                                    ToObjCPtr->getPointeeType(),
2522                                                          ToType, Context);
2523       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2524       return true;
2525     }
2526
2527     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2528       // Okay: this is some kind of implicit downcast of Objective-C
2529       // interfaces, which is permitted. However, we're going to
2530       // complain about it.
2531       IncompatibleObjC = true;
2532       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2533                                                    ToObjCPtr->getPointeeType(),
2534                                                          ToType, Context);
2535       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2536       return true;
2537     }
2538   }
2539   // Beyond this point, both types need to be C pointers or block pointers.
2540   QualType ToPointeeType;
2541   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2542     ToPointeeType = ToCPtr->getPointeeType();
2543   else if (const BlockPointerType *ToBlockPtr =
2544             ToType->getAs<BlockPointerType>()) {
2545     // Objective C++: We're able to convert from a pointer to any object
2546     // to a block pointer type.
2547     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2548       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2549       return true;
2550     }
2551     ToPointeeType = ToBlockPtr->getPointeeType();
2552   }
2553   else if (FromType->getAs<BlockPointerType>() &&
2554            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2555     // Objective C++: We're able to convert from a block pointer type to a
2556     // pointer to any object.
2557     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2558     return true;
2559   }
2560   else
2561     return false;
2562
2563   QualType FromPointeeType;
2564   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2565     FromPointeeType = FromCPtr->getPointeeType();
2566   else if (const BlockPointerType *FromBlockPtr =
2567            FromType->getAs<BlockPointerType>())
2568     FromPointeeType = FromBlockPtr->getPointeeType();
2569   else
2570     return false;
2571
2572   // If we have pointers to pointers, recursively check whether this
2573   // is an Objective-C conversion.
2574   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2575       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2576                               IncompatibleObjC)) {
2577     // We always complain about this conversion.
2578     IncompatibleObjC = true;
2579     ConvertedType = Context.getPointerType(ConvertedType);
2580     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2581     return true;
2582   }
2583   // Allow conversion of pointee being objective-c pointer to another one;
2584   // as in I* to id.
2585   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2586       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2587       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2588                               IncompatibleObjC)) {
2589
2590     ConvertedType = Context.getPointerType(ConvertedType);
2591     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2592     return true;
2593   }
2594
2595   // If we have pointers to functions or blocks, check whether the only
2596   // differences in the argument and result types are in Objective-C
2597   // pointer conversions. If so, we permit the conversion (but
2598   // complain about it).
2599   const FunctionProtoType *FromFunctionType
2600     = FromPointeeType->getAs<FunctionProtoType>();
2601   const FunctionProtoType *ToFunctionType
2602     = ToPointeeType->getAs<FunctionProtoType>();
2603   if (FromFunctionType && ToFunctionType) {
2604     // If the function types are exactly the same, this isn't an
2605     // Objective-C pointer conversion.
2606     if (Context.getCanonicalType(FromPointeeType)
2607           == Context.getCanonicalType(ToPointeeType))
2608       return false;
2609
2610     // Perform the quick checks that will tell us whether these
2611     // function types are obviously different.
2612     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2613         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2614         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2615       return false;
2616
2617     bool HasObjCConversion = false;
2618     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2619         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2620       // Okay, the types match exactly. Nothing to do.
2621     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2622                                        ToFunctionType->getReturnType(),
2623                                        ConvertedType, IncompatibleObjC)) {
2624       // Okay, we have an Objective-C pointer conversion.
2625       HasObjCConversion = true;
2626     } else {
2627       // Function types are too different. Abort.
2628       return false;
2629     }
2630
2631     // Check argument types.
2632     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2633          ArgIdx != NumArgs; ++ArgIdx) {
2634       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2635       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2636       if (Context.getCanonicalType(FromArgType)
2637             == Context.getCanonicalType(ToArgType)) {
2638         // Okay, the types match exactly. Nothing to do.
2639       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2640                                          ConvertedType, IncompatibleObjC)) {
2641         // Okay, we have an Objective-C pointer conversion.
2642         HasObjCConversion = true;
2643       } else {
2644         // Argument types are too different. Abort.
2645         return false;
2646       }
2647     }
2648
2649     if (HasObjCConversion) {
2650       // We had an Objective-C conversion. Allow this pointer
2651       // conversion, but complain about it.
2652       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2653       IncompatibleObjC = true;
2654       return true;
2655     }
2656   }
2657
2658   return false;
2659 }
2660
2661 /// Determine whether this is an Objective-C writeback conversion,
2662 /// used for parameter passing when performing automatic reference counting.
2663 ///
2664 /// \param FromType The type we're converting form.
2665 ///
2666 /// \param ToType The type we're converting to.
2667 ///
2668 /// \param ConvertedType The type that will be produced after applying
2669 /// this conversion.
2670 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2671                                      QualType &ConvertedType) {
2672   if (!getLangOpts().ObjCAutoRefCount ||
2673       Context.hasSameUnqualifiedType(FromType, ToType))
2674     return false;
2675
2676   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2677   QualType ToPointee;
2678   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2679     ToPointee = ToPointer->getPointeeType();
2680   else
2681     return false;
2682
2683   Qualifiers ToQuals = ToPointee.getQualifiers();
2684   if (!ToPointee->isObjCLifetimeType() ||
2685       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2686       !ToQuals.withoutObjCLifetime().empty())
2687     return false;
2688
2689   // Argument must be a pointer to __strong to __weak.
2690   QualType FromPointee;
2691   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2692     FromPointee = FromPointer->getPointeeType();
2693   else
2694     return false;
2695
2696   Qualifiers FromQuals = FromPointee.getQualifiers();
2697   if (!FromPointee->isObjCLifetimeType() ||
2698       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2699        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2700     return false;
2701
2702   // Make sure that we have compatible qualifiers.
2703   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2704   if (!ToQuals.compatiblyIncludes(FromQuals))
2705     return false;
2706
2707   // Remove qualifiers from the pointee type we're converting from; they
2708   // aren't used in the compatibility check belong, and we'll be adding back
2709   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2710   FromPointee = FromPointee.getUnqualifiedType();
2711
2712   // The unqualified form of the pointee types must be compatible.
2713   ToPointee = ToPointee.getUnqualifiedType();
2714   bool IncompatibleObjC;
2715   if (Context.typesAreCompatible(FromPointee, ToPointee))
2716     FromPointee = ToPointee;
2717   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2718                                     IncompatibleObjC))
2719     return false;
2720
2721   /// Construct the type we're converting to, which is a pointer to
2722   /// __autoreleasing pointee.
2723   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2724   ConvertedType = Context.getPointerType(FromPointee);
2725   return true;
2726 }
2727
2728 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2729                                     QualType& ConvertedType) {
2730   QualType ToPointeeType;
2731   if (const BlockPointerType *ToBlockPtr =
2732         ToType->getAs<BlockPointerType>())
2733     ToPointeeType = ToBlockPtr->getPointeeType();
2734   else
2735     return false;
2736
2737   QualType FromPointeeType;
2738   if (const BlockPointerType *FromBlockPtr =
2739       FromType->getAs<BlockPointerType>())
2740     FromPointeeType = FromBlockPtr->getPointeeType();
2741   else
2742     return false;
2743   // We have pointer to blocks, check whether the only
2744   // differences in the argument and result types are in Objective-C
2745   // pointer conversions. If so, we permit the conversion.
2746
2747   const FunctionProtoType *FromFunctionType
2748     = FromPointeeType->getAs<FunctionProtoType>();
2749   const FunctionProtoType *ToFunctionType
2750     = ToPointeeType->getAs<FunctionProtoType>();
2751
2752   if (!FromFunctionType || !ToFunctionType)
2753     return false;
2754
2755   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2756     return true;
2757
2758   // Perform the quick checks that will tell us whether these
2759   // function types are obviously different.
2760   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2761       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2762     return false;
2763
2764   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2765   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2766   if (FromEInfo != ToEInfo)
2767     return false;
2768
2769   bool IncompatibleObjC = false;
2770   if (Context.hasSameType(FromFunctionType->getReturnType(),
2771                           ToFunctionType->getReturnType())) {
2772     // Okay, the types match exactly. Nothing to do.
2773   } else {
2774     QualType RHS = FromFunctionType->getReturnType();
2775     QualType LHS = ToFunctionType->getReturnType();
2776     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2777         !RHS.hasQualifiers() && LHS.hasQualifiers())
2778        LHS = LHS.getUnqualifiedType();
2779
2780      if (Context.hasSameType(RHS,LHS)) {
2781        // OK exact match.
2782      } else if (isObjCPointerConversion(RHS, LHS,
2783                                         ConvertedType, IncompatibleObjC)) {
2784      if (IncompatibleObjC)
2785        return false;
2786      // Okay, we have an Objective-C pointer conversion.
2787      }
2788      else
2789        return false;
2790    }
2791
2792    // Check argument types.
2793    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2794         ArgIdx != NumArgs; ++ArgIdx) {
2795      IncompatibleObjC = false;
2796      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2797      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2798      if (Context.hasSameType(FromArgType, ToArgType)) {
2799        // Okay, the types match exactly. Nothing to do.
2800      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2801                                         ConvertedType, IncompatibleObjC)) {
2802        if (IncompatibleObjC)
2803          return false;
2804        // Okay, we have an Objective-C pointer conversion.
2805      } else
2806        // Argument types are too different. Abort.
2807        return false;
2808    }
2809
2810    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2811    bool CanUseToFPT, CanUseFromFPT;
2812    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2813                                       CanUseToFPT, CanUseFromFPT,
2814                                       NewParamInfos))
2815      return false;
2816
2817    ConvertedType = ToType;
2818    return true;
2819 }
2820
2821 enum {
2822   ft_default,
2823   ft_different_class,
2824   ft_parameter_arity,
2825   ft_parameter_mismatch,
2826   ft_return_type,
2827   ft_qualifer_mismatch,
2828   ft_noexcept
2829 };
2830
2831 /// Attempts to get the FunctionProtoType from a Type. Handles
2832 /// MemberFunctionPointers properly.
2833 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2834   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2835     return FPT;
2836
2837   if (auto *MPT = FromType->getAs<MemberPointerType>())
2838     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2839
2840   return nullptr;
2841 }
2842
2843 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2844 /// function types.  Catches different number of parameter, mismatch in
2845 /// parameter types, and different return types.
2846 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2847                                       QualType FromType, QualType ToType) {
2848   // If either type is not valid, include no extra info.
2849   if (FromType.isNull() || ToType.isNull()) {
2850     PDiag << ft_default;
2851     return;
2852   }
2853
2854   // Get the function type from the pointers.
2855   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2856     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2857                *ToMember = ToType->castAs<MemberPointerType>();
2858     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2859       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2860             << QualType(FromMember->getClass(), 0);
2861       return;
2862     }
2863     FromType = FromMember->getPointeeType();
2864     ToType = ToMember->getPointeeType();
2865   }
2866
2867   if (FromType->isPointerType())
2868     FromType = FromType->getPointeeType();
2869   if (ToType->isPointerType())
2870     ToType = ToType->getPointeeType();
2871
2872   // Remove references.
2873   FromType = FromType.getNonReferenceType();
2874   ToType = ToType.getNonReferenceType();
2875
2876   // Don't print extra info for non-specialized template functions.
2877   if (FromType->isInstantiationDependentType() &&
2878       !FromType->getAs<TemplateSpecializationType>()) {
2879     PDiag << ft_default;
2880     return;
2881   }
2882
2883   // No extra info for same types.
2884   if (Context.hasSameType(FromType, ToType)) {
2885     PDiag << ft_default;
2886     return;
2887   }
2888
2889   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2890                           *ToFunction = tryGetFunctionProtoType(ToType);
2891
2892   // Both types need to be function types.
2893   if (!FromFunction || !ToFunction) {
2894     PDiag << ft_default;
2895     return;
2896   }
2897
2898   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2899     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2900           << FromFunction->getNumParams();
2901     return;
2902   }
2903
2904   // Handle different parameter types.
2905   unsigned ArgPos;
2906   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2907     PDiag << ft_parameter_mismatch << ArgPos + 1
2908           << ToFunction->getParamType(ArgPos)
2909           << FromFunction->getParamType(ArgPos);
2910     return;
2911   }
2912
2913   // Handle different return type.
2914   if (!Context.hasSameType(FromFunction->getReturnType(),
2915                            ToFunction->getReturnType())) {
2916     PDiag << ft_return_type << ToFunction->getReturnType()
2917           << FromFunction->getReturnType();
2918     return;
2919   }
2920
2921   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2922     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2923           << FromFunction->getMethodQuals();
2924     return;
2925   }
2926
2927   // Handle exception specification differences on canonical type (in C++17
2928   // onwards).
2929   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2930           ->isNothrow() !=
2931       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2932           ->isNothrow()) {
2933     PDiag << ft_noexcept;
2934     return;
2935   }
2936
2937   // Unable to find a difference, so add no extra info.
2938   PDiag << ft_default;
2939 }
2940
2941 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2942 /// for equality of their argument types. Caller has already checked that
2943 /// they have same number of arguments.  If the parameters are different,
2944 /// ArgPos will have the parameter index of the first different parameter.
2945 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2946                                       const FunctionProtoType *NewType,
2947                                       unsigned *ArgPos) {
2948   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2949                                               N = NewType->param_type_begin(),
2950                                               E = OldType->param_type_end();
2951        O && (O != E); ++O, ++N) {
2952     // Ignore address spaces in pointee type. This is to disallow overloading
2953     // on __ptr32/__ptr64 address spaces.
2954     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2955     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2956
2957     if (!Context.hasSameType(Old, New)) {
2958       if (ArgPos)
2959         *ArgPos = O - OldType->param_type_begin();
2960       return false;
2961     }
2962   }
2963   return true;
2964 }
2965
2966 /// CheckPointerConversion - Check the pointer conversion from the
2967 /// expression From to the type ToType. This routine checks for
2968 /// ambiguous or inaccessible derived-to-base pointer
2969 /// conversions for which IsPointerConversion has already returned
2970 /// true. It returns true and produces a diagnostic if there was an
2971 /// error, or returns false otherwise.
2972 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2973                                   CastKind &Kind,
2974                                   CXXCastPath& BasePath,
2975                                   bool IgnoreBaseAccess,
2976                                   bool Diagnose) {
2977   QualType FromType = From->getType();
2978   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2979
2980   Kind = CK_BitCast;
2981
2982   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2983       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2984           Expr::NPCK_ZeroExpression) {
2985     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2986       DiagRuntimeBehavior(From->getExprLoc(), From,
2987                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2988                             << ToType << From->getSourceRange());
2989     else if (!isUnevaluatedContext())
2990       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2991         << ToType << From->getSourceRange();
2992   }
2993   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2994     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2995       QualType FromPointeeType = FromPtrType->getPointeeType(),
2996                ToPointeeType   = ToPtrType->getPointeeType();
2997
2998       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2999           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3000         // We must have a derived-to-base conversion. Check an
3001         // ambiguous or inaccessible conversion.
3002         unsigned InaccessibleID = 0;
3003         unsigned AmbigiousID = 0;
3004         if (Diagnose) {
3005           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3006           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3007         }
3008         if (CheckDerivedToBaseConversion(
3009                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3010                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3011                 &BasePath, IgnoreBaseAccess))
3012           return true;
3013
3014         // The conversion was successful.
3015         Kind = CK_DerivedToBase;
3016       }
3017
3018       if (Diagnose && !IsCStyleOrFunctionalCast &&
3019           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3020         assert(getLangOpts().MSVCCompat &&
3021                "this should only be possible with MSVCCompat!");
3022         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3023             << From->getSourceRange();
3024       }
3025     }
3026   } else if (const ObjCObjectPointerType *ToPtrType =
3027                ToType->getAs<ObjCObjectPointerType>()) {
3028     if (const ObjCObjectPointerType *FromPtrType =
3029           FromType->getAs<ObjCObjectPointerType>()) {
3030       // Objective-C++ conversions are always okay.
3031       // FIXME: We should have a different class of conversions for the
3032       // Objective-C++ implicit conversions.
3033       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3034         return false;
3035     } else if (FromType->isBlockPointerType()) {
3036       Kind = CK_BlockPointerToObjCPointerCast;
3037     } else {
3038       Kind = CK_CPointerToObjCPointerCast;
3039     }
3040   } else if (ToType->isBlockPointerType()) {
3041     if (!FromType->isBlockPointerType())
3042       Kind = CK_AnyPointerToBlockPointerCast;
3043   }
3044
3045   // We shouldn't fall into this case unless it's valid for other
3046   // reasons.
3047   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3048     Kind = CK_NullToPointer;
3049
3050   return false;
3051 }
3052
3053 /// IsMemberPointerConversion - Determines whether the conversion of the
3054 /// expression From, which has the (possibly adjusted) type FromType, can be
3055 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3056 /// If so, returns true and places the converted type (that might differ from
3057 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3058 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3059                                      QualType ToType,
3060                                      bool InOverloadResolution,
3061                                      QualType &ConvertedType) {
3062   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3063   if (!ToTypePtr)
3064     return false;
3065
3066   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3067   if (From->isNullPointerConstant(Context,
3068                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3069                                         : Expr::NPC_ValueDependentIsNull)) {
3070     ConvertedType = ToType;
3071     return true;
3072   }
3073
3074   // Otherwise, both types have to be member pointers.
3075   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3076   if (!FromTypePtr)
3077     return false;
3078
3079   // A pointer to member of B can be converted to a pointer to member of D,
3080   // where D is derived from B (C++ 4.11p2).
3081   QualType FromClass(FromTypePtr->getClass(), 0);
3082   QualType ToClass(ToTypePtr->getClass(), 0);
3083
3084   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3085       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3086     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3087                                                  ToClass.getTypePtr());
3088     return true;
3089   }
3090
3091   return false;
3092 }
3093
3094 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3095 /// expression From to the type ToType. This routine checks for ambiguous or
3096 /// virtual or inaccessible base-to-derived member pointer conversions
3097 /// for which IsMemberPointerConversion has already returned true. It returns
3098 /// true and produces a diagnostic if there was an error, or returns false
3099 /// otherwise.
3100 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3101                                         CastKind &Kind,
3102                                         CXXCastPath &BasePath,
3103                                         bool IgnoreBaseAccess) {
3104   QualType FromType = From->getType();
3105   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3106   if (!FromPtrType) {
3107     // This must be a null pointer to member pointer conversion
3108     assert(From->isNullPointerConstant(Context,
3109                                        Expr::NPC_ValueDependentIsNull) &&
3110            "Expr must be null pointer constant!");
3111     Kind = CK_NullToMemberPointer;
3112     return false;
3113   }
3114
3115   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3116   assert(ToPtrType && "No member pointer cast has a target type "
3117                       "that is not a member pointer.");
3118
3119   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3120   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3121
3122   // FIXME: What about dependent types?
3123   assert(FromClass->isRecordType() && "Pointer into non-class.");
3124   assert(ToClass->isRecordType() && "Pointer into non-class.");
3125
3126   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3127                      /*DetectVirtual=*/true);
3128   bool DerivationOkay =
3129       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3130   assert(DerivationOkay &&
3131          "Should not have been called if derivation isn't OK.");
3132   (void)DerivationOkay;
3133
3134   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3135                                   getUnqualifiedType())) {
3136     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3137     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3138       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3139     return true;
3140   }
3141
3142   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3143     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3144       << FromClass << ToClass << QualType(VBase, 0)
3145       << From->getSourceRange();
3146     return true;
3147   }
3148
3149   if (!IgnoreBaseAccess)
3150     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3151                          Paths.front(),
3152                          diag::err_downcast_from_inaccessible_base);
3153
3154   // Must be a base to derived member conversion.
3155   BuildBasePathArray(Paths, BasePath);
3156   Kind = CK_BaseToDerivedMemberPointer;
3157   return false;
3158 }
3159
3160 /// Determine whether the lifetime conversion between the two given
3161 /// qualifiers sets is nontrivial.
3162 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3163                                                Qualifiers ToQuals) {
3164   // Converting anything to const __unsafe_unretained is trivial.
3165   if (ToQuals.hasConst() &&
3166       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3167     return false;
3168
3169   return true;
3170 }
3171
3172 /// Perform a single iteration of the loop for checking if a qualification
3173 /// conversion is valid.
3174 ///
3175 /// Specifically, check whether any change between the qualifiers of \p
3176 /// FromType and \p ToType is permissible, given knowledge about whether every
3177 /// outer layer is const-qualified.
3178 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3179                                           bool CStyle, bool IsTopLevel,
3180                                           bool &PreviousToQualsIncludeConst,
3181                                           bool &ObjCLifetimeConversion) {
3182   Qualifiers FromQuals = FromType.getQualifiers();
3183   Qualifiers ToQuals = ToType.getQualifiers();
3184
3185   // Ignore __unaligned qualifier if this type is void.
3186   if (ToType.getUnqualifiedType()->isVoidType())
3187     FromQuals.removeUnaligned();
3188
3189   // Objective-C ARC:
3190   //   Check Objective-C lifetime conversions.
3191   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3192     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3193       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3194         ObjCLifetimeConversion = true;
3195       FromQuals.removeObjCLifetime();
3196       ToQuals.removeObjCLifetime();
3197     } else {
3198       // Qualification conversions cannot cast between different
3199       // Objective-C lifetime qualifiers.
3200       return false;
3201     }
3202   }
3203
3204   // Allow addition/removal of GC attributes but not changing GC attributes.
3205   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3206       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3207     FromQuals.removeObjCGCAttr();
3208     ToQuals.removeObjCGCAttr();
3209   }
3210
3211   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3212   //      2,j, and similarly for volatile.
3213   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3214     return false;
3215
3216   // If address spaces mismatch:
3217   //  - in top level it is only valid to convert to addr space that is a
3218   //    superset in all cases apart from C-style casts where we allow
3219   //    conversions between overlapping address spaces.
3220   //  - in non-top levels it is not a valid conversion.
3221   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3222       (!IsTopLevel ||
3223        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3224          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3225     return false;
3226
3227   //   -- if the cv 1,j and cv 2,j are different, then const is in
3228   //      every cv for 0 < k < j.
3229   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3230       !PreviousToQualsIncludeConst)
3231     return false;
3232
3233   // Keep track of whether all prior cv-qualifiers in the "to" type
3234   // include const.
3235   PreviousToQualsIncludeConst =
3236       PreviousToQualsIncludeConst && ToQuals.hasConst();
3237   return true;
3238 }
3239
3240 /// IsQualificationConversion - Determines whether the conversion from
3241 /// an rvalue of type FromType to ToType is a qualification conversion
3242 /// (C++ 4.4).
3243 ///
3244 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3245 /// when the qualification conversion involves a change in the Objective-C
3246 /// object lifetime.
3247 bool
3248 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3249                                 bool CStyle, bool &ObjCLifetimeConversion) {
3250   FromType = Context.getCanonicalType(FromType);
3251   ToType = Context.getCanonicalType(ToType);
3252   ObjCLifetimeConversion = false;
3253
3254   // If FromType and ToType are the same type, this is not a
3255   // qualification conversion.
3256   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3257     return false;
3258
3259   // (C++ 4.4p4):
3260   //   A conversion can add cv-qualifiers at levels other than the first
3261   //   in multi-level pointers, subject to the following rules: [...]
3262   bool PreviousToQualsIncludeConst = true;
3263   bool UnwrappedAnyPointer = false;
3264   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3265     if (!isQualificationConversionStep(
3266             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3267             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3268       return false;
3269     UnwrappedAnyPointer = true;
3270   }
3271
3272   // We are left with FromType and ToType being the pointee types
3273   // after unwrapping the original FromType and ToType the same number
3274   // of times. If we unwrapped any pointers, and if FromType and
3275   // ToType have the same unqualified type (since we checked
3276   // qualifiers above), then this is a qualification conversion.
3277   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3278 }
3279
3280 /// - Determine whether this is a conversion from a scalar type to an
3281 /// atomic type.
3282 ///
3283 /// If successful, updates \c SCS's second and third steps in the conversion
3284 /// sequence to finish the conversion.
3285 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3286                                 bool InOverloadResolution,
3287                                 StandardConversionSequence &SCS,
3288                                 bool CStyle) {
3289   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3290   if (!ToAtomic)
3291     return false;
3292
3293   StandardConversionSequence InnerSCS;
3294   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3295                             InOverloadResolution, InnerSCS,
3296                             CStyle, /*AllowObjCWritebackConversion=*/false))
3297     return false;
3298
3299   SCS.Second = InnerSCS.Second;
3300   SCS.setToType(1, InnerSCS.getToType(1));
3301   SCS.Third = InnerSCS.Third;
3302   SCS.QualificationIncludesObjCLifetime
3303     = InnerSCS.QualificationIncludesObjCLifetime;
3304   SCS.setToType(2, InnerSCS.getToType(2));
3305   return true;
3306 }
3307
3308 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3309                                               CXXConstructorDecl *Constructor,
3310                                               QualType Type) {
3311   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3312   if (CtorType->getNumParams() > 0) {
3313     QualType FirstArg = CtorType->getParamType(0);
3314     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3315       return true;
3316   }
3317   return false;
3318 }
3319
3320 static OverloadingResult
3321 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3322                                        CXXRecordDecl *To,
3323                                        UserDefinedConversionSequence &User,
3324                                        OverloadCandidateSet &CandidateSet,
3325                                        bool AllowExplicit) {
3326   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3327   for (auto *D : S.LookupConstructors(To)) {
3328     auto Info = getConstructorInfo(D);
3329     if (!Info)
3330       continue;
3331
3332     bool Usable = !Info.Constructor->isInvalidDecl() &&
3333                   S.isInitListConstructor(Info.Constructor);
3334     if (Usable) {
3335       // If the first argument is (a reference to) the target type,
3336       // suppress conversions.
3337       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3338           S.Context, Info.Constructor, ToType);
3339       if (Info.ConstructorTmpl)
3340         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3341                                        /*ExplicitArgs*/ nullptr, From,
3342                                        CandidateSet, SuppressUserConversions,
3343                                        /*PartialOverloading*/ false,
3344                                        AllowExplicit);
3345       else
3346         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3347                                CandidateSet, SuppressUserConversions,
3348                                /*PartialOverloading*/ false, AllowExplicit);
3349     }
3350   }
3351
3352   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3353
3354   OverloadCandidateSet::iterator Best;
3355   switch (auto Result =
3356               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3357   case OR_Deleted:
3358   case OR_Success: {
3359     // Record the standard conversion we used and the conversion function.
3360     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3361     QualType ThisType = Constructor->getThisType();
3362     // Initializer lists don't have conversions as such.
3363     User.Before.setAsIdentityConversion();
3364     User.HadMultipleCandidates = HadMultipleCandidates;
3365     User.ConversionFunction = Constructor;
3366     User.FoundConversionFunction = Best->FoundDecl;
3367     User.After.setAsIdentityConversion();
3368     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3369     User.After.setAllToTypes(ToType);
3370     return Result;
3371   }
3372
3373   case OR_No_Viable_Function:
3374     return OR_No_Viable_Function;
3375   case OR_Ambiguous:
3376     return OR_Ambiguous;
3377   }
3378
3379   llvm_unreachable("Invalid OverloadResult!");
3380 }
3381
3382 /// Determines whether there is a user-defined conversion sequence
3383 /// (C++ [over.ics.user]) that converts expression From to the type
3384 /// ToType. If such a conversion exists, User will contain the
3385 /// user-defined conversion sequence that performs such a conversion
3386 /// and this routine will return true. Otherwise, this routine returns
3387 /// false and User is unspecified.
3388 ///
3389 /// \param AllowExplicit  true if the conversion should consider C++0x
3390 /// "explicit" conversion functions as well as non-explicit conversion
3391 /// functions (C++0x [class.conv.fct]p2).
3392 ///
3393 /// \param AllowObjCConversionOnExplicit true if the conversion should
3394 /// allow an extra Objective-C pointer conversion on uses of explicit
3395 /// constructors. Requires \c AllowExplicit to also be set.
3396 static OverloadingResult
3397 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3398                         UserDefinedConversionSequence &User,
3399                         OverloadCandidateSet &CandidateSet,
3400                         bool AllowExplicit,
3401                         bool AllowObjCConversionOnExplicit) {
3402   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3403   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3404
3405   // Whether we will only visit constructors.
3406   bool ConstructorsOnly = false;
3407
3408   // If the type we are conversion to is a class type, enumerate its
3409   // constructors.
3410   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3411     // C++ [over.match.ctor]p1:
3412     //   When objects of class type are direct-initialized (8.5), or
3413     //   copy-initialized from an expression of the same or a
3414     //   derived class type (8.5), overload resolution selects the
3415     //   constructor. [...] For copy-initialization, the candidate
3416     //   functions are all the converting constructors (12.3.1) of
3417     //   that class. The argument list is the expression-list within
3418     //   the parentheses of the initializer.
3419     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3420         (From->getType()->getAs<RecordType>() &&
3421          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3422       ConstructorsOnly = true;
3423
3424     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3425       // We're not going to find any constructors.
3426     } else if (CXXRecordDecl *ToRecordDecl
3427                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3428
3429       Expr **Args = &From;
3430       unsigned NumArgs = 1;
3431       bool ListInitializing = false;
3432       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3433         // But first, see if there is an init-list-constructor that will work.
3434         OverloadingResult Result = IsInitializerListConstructorConversion(
3435             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3436         if (Result != OR_No_Viable_Function)
3437           return Result;
3438         // Never mind.
3439         CandidateSet.clear(
3440             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3441
3442         // If we're list-initializing, we pass the individual elements as
3443         // arguments, not the entire list.
3444         Args = InitList->getInits();
3445         NumArgs = InitList->getNumInits();
3446         ListInitializing = true;
3447       }
3448
3449       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3450         auto Info = getConstructorInfo(D);
3451         if (!Info)
3452           continue;
3453
3454         bool Usable = !Info.Constructor->isInvalidDecl();
3455         if (!ListInitializing)
3456           Usable = Usable && Info.Constructor->isConvertingConstructor(
3457                                  /*AllowExplicit*/ true);
3458         if (Usable) {
3459           bool SuppressUserConversions = !ConstructorsOnly;
3460           if (SuppressUserConversions && ListInitializing) {
3461             SuppressUserConversions = false;
3462             if (NumArgs == 1) {
3463               // If the first argument is (a reference to) the target type,
3464               // suppress conversions.
3465               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3466                   S.Context, Info.Constructor, ToType);
3467             }
3468           }
3469           if (Info.ConstructorTmpl)
3470             S.AddTemplateOverloadCandidate(
3471                 Info.ConstructorTmpl, Info.FoundDecl,
3472                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3473                 CandidateSet, SuppressUserConversions,
3474                 /*PartialOverloading*/ false, AllowExplicit);
3475           else
3476             // Allow one user-defined conversion when user specifies a
3477             // From->ToType conversion via an static cast (c-style, etc).
3478             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3479                                    llvm::makeArrayRef(Args, NumArgs),
3480                                    CandidateSet, SuppressUserConversions,
3481                                    /*PartialOverloading*/ false, AllowExplicit);
3482         }
3483       }
3484     }
3485   }
3486
3487   // Enumerate conversion functions, if we're allowed to.
3488   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3489   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3490     // No conversion functions from incomplete types.
3491   } else if (const RecordType *FromRecordType =
3492                  From->getType()->getAs<RecordType>()) {
3493     if (CXXRecordDecl *FromRecordDecl
3494          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3495       // Add all of the conversion functions as candidates.
3496       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3497       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3498         DeclAccessPair FoundDecl = I.getPair();
3499         NamedDecl *D = FoundDecl.getDecl();
3500         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3501         if (isa<UsingShadowDecl>(D))
3502           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3503
3504         CXXConversionDecl *Conv;
3505         FunctionTemplateDecl *ConvTemplate;
3506         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3507           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3508         else
3509           Conv = cast<CXXConversionDecl>(D);
3510
3511         if (ConvTemplate)
3512           S.AddTemplateConversionCandidate(
3513               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3514               CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3515         else
3516           S.AddConversionCandidate(
3517               Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3518               AllowObjCConversionOnExplicit, AllowExplicit);
3519       }
3520     }
3521   }
3522
3523   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3524
3525   OverloadCandidateSet::iterator Best;
3526   switch (auto Result =
3527               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3528   case OR_Success:
3529   case OR_Deleted:
3530     // Record the standard conversion we used and the conversion function.
3531     if (CXXConstructorDecl *Constructor
3532           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3533       // C++ [over.ics.user]p1:
3534       //   If the user-defined conversion is specified by a
3535       //   constructor (12.3.1), the initial standard conversion
3536       //   sequence converts the source type to the type required by
3537       //   the argument of the constructor.
3538       //
3539       QualType ThisType = Constructor->getThisType();
3540       if (isa<InitListExpr>(From)) {
3541         // Initializer lists don't have conversions as such.
3542         User.Before.setAsIdentityConversion();
3543       } else {
3544         if (Best->Conversions[0].isEllipsis())
3545           User.EllipsisConversion = true;
3546         else {
3547           User.Before = Best->Conversions[0].Standard;
3548           User.EllipsisConversion = false;
3549         }
3550       }
3551       User.HadMultipleCandidates = HadMultipleCandidates;
3552       User.ConversionFunction = Constructor;
3553       User.FoundConversionFunction = Best->FoundDecl;
3554       User.After.setAsIdentityConversion();
3555       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3556       User.After.setAllToTypes(ToType);
3557       return Result;
3558     }
3559     if (CXXConversionDecl *Conversion
3560                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3561       // C++ [over.ics.user]p1:
3562       //
3563       //   [...] If the user-defined conversion is specified by a
3564       //   conversion function (12.3.2), the initial standard
3565       //   conversion sequence converts the source type to the
3566       //   implicit object parameter of the conversion function.
3567       User.Before = Best->Conversions[0].Standard;
3568       User.HadMultipleCandidates = HadMultipleCandidates;
3569       User.ConversionFunction = Conversion;
3570       User.FoundConversionFunction = Best->FoundDecl;
3571       User.EllipsisConversion = false;
3572
3573       // C++ [over.ics.user]p2:
3574       //   The second standard conversion sequence converts the
3575       //   result of the user-defined conversion to the target type
3576       //   for the sequence. Since an implicit conversion sequence
3577       //   is an initialization, the special rules for
3578       //   initialization by user-defined conversion apply when
3579       //   selecting the best user-defined conversion for a
3580       //   user-defined conversion sequence (see 13.3.3 and
3581       //   13.3.3.1).
3582       User.After = Best->FinalConversion;
3583       return Result;
3584     }
3585     llvm_unreachable("Not a constructor or conversion function?");
3586
3587   case OR_No_Viable_Function:
3588     return OR_No_Viable_Function;
3589
3590   case OR_Ambiguous:
3591     return OR_Ambiguous;
3592   }
3593
3594   llvm_unreachable("Invalid OverloadResult!");
3595 }
3596
3597 bool
3598 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3599   ImplicitConversionSequence ICS;
3600   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3601                                     OverloadCandidateSet::CSK_Normal);
3602   OverloadingResult OvResult =
3603     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3604                             CandidateSet, false, false);
3605
3606   if (!(OvResult == OR_Ambiguous ||
3607         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3608     return false;
3609
3610   auto Cands = CandidateSet.CompleteCandidates(
3611       *this,
3612       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3613       From);
3614   if (OvResult == OR_Ambiguous)
3615     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3616         << From->getType() << ToType << From->getSourceRange();
3617   else { // OR_No_Viable_Function && !CandidateSet.empty()
3618     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3619                              diag::err_typecheck_nonviable_condition_incomplete,
3620                              From->getType(), From->getSourceRange()))
3621       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3622           << false << From->getType() << From->getSourceRange() << ToType;
3623   }
3624
3625   CandidateSet.NoteCandidates(
3626                               *this, From, Cands);
3627   return true;
3628 }
3629
3630 /// Compare the user-defined conversion functions or constructors
3631 /// of two user-defined conversion sequences to determine whether any ordering
3632 /// is possible.
3633 static ImplicitConversionSequence::CompareKind
3634 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3635                            FunctionDecl *Function2) {
3636   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3637     return ImplicitConversionSequence::Indistinguishable;
3638
3639   // Objective-C++:
3640   //   If both conversion functions are implicitly-declared conversions from
3641   //   a lambda closure type to a function pointer and a block pointer,
3642   //   respectively, always prefer the conversion to a function pointer,
3643   //   because the function pointer is more lightweight and is more likely
3644   //   to keep code working.
3645   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3646   if (!Conv1)
3647     return ImplicitConversionSequence::Indistinguishable;
3648
3649   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3650   if (!Conv2)
3651     return ImplicitConversionSequence::Indistinguishable;
3652
3653   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3654     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3655     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3656     if (Block1 != Block2)
3657       return Block1 ? ImplicitConversionSequence::Worse
3658                     : ImplicitConversionSequence::Better;
3659   }
3660
3661   return ImplicitConversionSequence::Indistinguishable;
3662 }
3663
3664 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3665     const ImplicitConversionSequence &ICS) {
3666   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3667          (ICS.isUserDefined() &&
3668           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3669 }
3670
3671 /// CompareImplicitConversionSequences - Compare two implicit
3672 /// conversion sequences to determine whether one is better than the
3673 /// other or if they are indistinguishable (C++ 13.3.3.2).
3674 static ImplicitConversionSequence::CompareKind
3675 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3676                                    const ImplicitConversionSequence& ICS1,
3677                                    const ImplicitConversionSequence& ICS2)
3678 {
3679   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3680   // conversion sequences (as defined in 13.3.3.1)
3681   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3682   //      conversion sequence than a user-defined conversion sequence or
3683   //      an ellipsis conversion sequence, and
3684   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3685   //      conversion sequence than an ellipsis conversion sequence
3686   //      (13.3.3.1.3).
3687   //
3688   // C++0x [over.best.ics]p10:
3689   //   For the purpose of ranking implicit conversion sequences as
3690   //   described in 13.3.3.2, the ambiguous conversion sequence is
3691   //   treated as a user-defined sequence that is indistinguishable
3692   //   from any other user-defined conversion sequence.
3693
3694   // String literal to 'char *' conversion has been deprecated in C++03. It has
3695   // been removed from C++11. We still accept this conversion, if it happens at
3696   // the best viable function. Otherwise, this conversion is considered worse
3697   // than ellipsis conversion. Consider this as an extension; this is not in the
3698   // standard. For example:
3699   //
3700   // int &f(...);    // #1
3701   // void f(char*);  // #2
3702   // void g() { int &r = f("foo"); }
3703   //
3704   // In C++03, we pick #2 as the best viable function.
3705   // In C++11, we pick #1 as the best viable function, because ellipsis
3706   // conversion is better than string-literal to char* conversion (since there
3707   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3708   // convert arguments, #2 would be the best viable function in C++11.
3709   // If the best viable function has this conversion, a warning will be issued
3710   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3711
3712   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3713       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3714       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3715     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3716                ? ImplicitConversionSequence::Worse
3717                : ImplicitConversionSequence::Better;
3718
3719   if (ICS1.getKindRank() < ICS2.getKindRank())
3720     return ImplicitConversionSequence::Better;
3721   if (ICS2.getKindRank() < ICS1.getKindRank())
3722     return ImplicitConversionSequence::Worse;
3723
3724   // The following checks require both conversion sequences to be of
3725   // the same kind.
3726   if (ICS1.getKind() != ICS2.getKind())
3727     return ImplicitConversionSequence::Indistinguishable;
3728
3729   ImplicitConversionSequence::CompareKind Result =
3730       ImplicitConversionSequence::Indistinguishable;
3731
3732   // Two implicit conversion sequences of the same form are
3733   // indistinguishable conversion sequences unless one of the
3734   // following rules apply: (C++ 13.3.3.2p3):
3735
3736   // List-initialization sequence L1 is a better conversion sequence than
3737   // list-initialization sequence L2 if:
3738   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3739   //   if not that,
3740   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3741   //   and N1 is smaller than N2.,
3742   // even if one of the other rules in this paragraph would otherwise apply.
3743   if (!ICS1.isBad()) {
3744     if (ICS1.isStdInitializerListElement() &&
3745         !ICS2.isStdInitializerListElement())
3746       return ImplicitConversionSequence::Better;
3747     if (!ICS1.isStdInitializerListElement() &&
3748         ICS2.isStdInitializerListElement())
3749       return ImplicitConversionSequence::Worse;
3750   }
3751
3752   if (ICS1.isStandard())
3753     // Standard conversion sequence S1 is a better conversion sequence than
3754     // standard conversion sequence S2 if [...]
3755     Result = CompareStandardConversionSequences(S, Loc,
3756                                                 ICS1.Standard, ICS2.Standard);
3757   else if (ICS1.isUserDefined()) {
3758     // User-defined conversion sequence U1 is a better conversion
3759     // sequence than another user-defined conversion sequence U2 if
3760     // they contain the same user-defined conversion function or
3761     // constructor and if the second standard conversion sequence of
3762     // U1 is better than the second standard conversion sequence of
3763     // U2 (C++ 13.3.3.2p3).
3764     if (ICS1.UserDefined.ConversionFunction ==
3765           ICS2.UserDefined.ConversionFunction)
3766       Result = CompareStandardConversionSequences(S, Loc,
3767                                                   ICS1.UserDefined.After,
3768                                                   ICS2.UserDefined.After);
3769     else
3770       Result = compareConversionFunctions(S,
3771                                           ICS1.UserDefined.ConversionFunction,
3772                                           ICS2.UserDefined.ConversionFunction);
3773   }
3774
3775   return Result;
3776 }
3777
3778 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3779 // determine if one is a proper subset of the other.
3780 static ImplicitConversionSequence::CompareKind
3781 compareStandardConversionSubsets(ASTContext &Context,
3782                                  const StandardConversionSequence& SCS1,
3783                                  const StandardConversionSequence& SCS2) {
3784   ImplicitConversionSequence::CompareKind Result
3785     = ImplicitConversionSequence::Indistinguishable;
3786
3787   // the identity conversion sequence is considered to be a subsequence of
3788   // any non-identity conversion sequence
3789   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3790     return ImplicitConversionSequence::Better;
3791   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3792     return ImplicitConversionSequence::Worse;
3793
3794   if (SCS1.Second != SCS2.Second) {
3795     if (SCS1.Second == ICK_Identity)
3796       Result = ImplicitConversionSequence::Better;
3797     else if (SCS2.Second == ICK_Identity)
3798       Result = ImplicitConversionSequence::Worse;
3799     else
3800       return ImplicitConversionSequence::Indistinguishable;
3801   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3802     return ImplicitConversionSequence::Indistinguishable;
3803
3804   if (SCS1.Third == SCS2.Third) {
3805     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3806                              : ImplicitConversionSequence::Indistinguishable;
3807   }
3808
3809   if (SCS1.Third == ICK_Identity)
3810     return Result == ImplicitConversionSequence::Worse
3811              ? ImplicitConversionSequence::Indistinguishable
3812              : ImplicitConversionSequence::Better;
3813
3814   if (SCS2.Third == ICK_Identity)
3815     return Result == ImplicitConversionSequence::Better
3816              ? ImplicitConversionSequence::Indistinguishable
3817              : ImplicitConversionSequence::Worse;
3818
3819   return ImplicitConversionSequence::Indistinguishable;
3820 }
3821
3822 /// Determine whether one of the given reference bindings is better
3823 /// than the other based on what kind of bindings they are.
3824 static bool
3825 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3826                              const StandardConversionSequence &SCS2) {
3827   // C++0x [over.ics.rank]p3b4:
3828   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3829   //      implicit object parameter of a non-static member function declared
3830   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3831   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3832   //      lvalue reference to a function lvalue and S2 binds an rvalue
3833   //      reference*.
3834   //
3835   // FIXME: Rvalue references. We're going rogue with the above edits,
3836   // because the semantics in the current C++0x working paper (N3225 at the
3837   // time of this writing) break the standard definition of std::forward
3838   // and std::reference_wrapper when dealing with references to functions.
3839   // Proposed wording changes submitted to CWG for consideration.
3840   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3841       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3842     return false;
3843
3844   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3845           SCS2.IsLvalueReference) ||
3846          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3847           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3848 }
3849
3850 enum class FixedEnumPromotion {
3851   None,
3852   ToUnderlyingType,
3853   ToPromotedUnderlyingType
3854 };
3855
3856 /// Returns kind of fixed enum promotion the \a SCS uses.
3857 static FixedEnumPromotion
3858 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3859
3860   if (SCS.Second != ICK_Integral_Promotion)
3861     return FixedEnumPromotion::None;
3862
3863   QualType FromType = SCS.getFromType();
3864   if (!FromType->isEnumeralType())
3865     return FixedEnumPromotion::None;
3866
3867   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3868   if (!Enum->isFixed())
3869     return FixedEnumPromotion::None;
3870
3871   QualType UnderlyingType = Enum->getIntegerType();
3872   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3873     return FixedEnumPromotion::ToUnderlyingType;
3874
3875   return FixedEnumPromotion::ToPromotedUnderlyingType;
3876 }
3877
3878 /// CompareStandardConversionSequences - Compare two standard
3879 /// conversion sequences to determine whether one is better than the
3880 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3881 static ImplicitConversionSequence::CompareKind
3882 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3883                                    const StandardConversionSequence& SCS1,
3884                                    const StandardConversionSequence& SCS2)
3885 {
3886   // Standard conversion sequence S1 is a better conversion sequence
3887   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3888
3889   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3890   //     sequences in the canonical form defined by 13.3.3.1.1,
3891   //     excluding any Lvalue Transformation; the identity conversion
3892   //     sequence is considered to be a subsequence of any
3893   //     non-identity conversion sequence) or, if not that,
3894   if (ImplicitConversionSequence::CompareKind CK
3895         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3896     return CK;
3897
3898   //  -- the rank of S1 is better than the rank of S2 (by the rules
3899   //     defined below), or, if not that,
3900   ImplicitConversionRank Rank1 = SCS1.getRank();
3901   ImplicitConversionRank Rank2 = SCS2.getRank();
3902   if (Rank1 < Rank2)
3903     return ImplicitConversionSequence::Better;
3904   else if (Rank2 < Rank1)
3905     return ImplicitConversionSequence::Worse;
3906
3907   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3908   // are indistinguishable unless one of the following rules
3909   // applies:
3910
3911   //   A conversion that is not a conversion of a pointer, or
3912   //   pointer to member, to bool is better than another conversion
3913   //   that is such a conversion.
3914   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3915     return SCS2.isPointerConversionToBool()
3916              ? ImplicitConversionSequence::Better
3917              : ImplicitConversionSequence::Worse;
3918
3919   // C++14 [over.ics.rank]p4b2:
3920   // This is retroactively applied to C++11 by CWG 1601.
3921   //
3922   //   A conversion that promotes an enumeration whose underlying type is fixed
3923   //   to its underlying type is better than one that promotes to the promoted
3924   //   underlying type, if the two are different.
3925   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3926   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3927   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3928       FEP1 != FEP2)
3929     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3930                ? ImplicitConversionSequence::Better
3931                : ImplicitConversionSequence::Worse;
3932
3933   // C++ [over.ics.rank]p4b2:
3934   //
3935   //   If class B is derived directly or indirectly from class A,
3936   //   conversion of B* to A* is better than conversion of B* to
3937   //   void*, and conversion of A* to void* is better than conversion
3938   //   of B* to void*.
3939   bool SCS1ConvertsToVoid
3940     = SCS1.isPointerConversionToVoidPointer(S.Context);
3941   bool SCS2ConvertsToVoid
3942     = SCS2.isPointerConversionToVoidPointer(S.Context);
3943   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3944     // Exactly one of the conversion sequences is a conversion to
3945     // a void pointer; it's the worse conversion.
3946     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3947                               : ImplicitConversionSequence::Worse;
3948   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3949     // Neither conversion sequence converts to a void pointer; compare
3950     // their derived-to-base conversions.
3951     if (ImplicitConversionSequence::CompareKind DerivedCK
3952           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3953       return DerivedCK;
3954   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3955              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3956     // Both conversion sequences are conversions to void
3957     // pointers. Compare the source types to determine if there's an
3958     // inheritance relationship in their sources.
3959     QualType FromType1 = SCS1.getFromType();
3960     QualType FromType2 = SCS2.getFromType();
3961
3962     // Adjust the types we're converting from via the array-to-pointer
3963     // conversion, if we need to.
3964     if (SCS1.First == ICK_Array_To_Pointer)
3965       FromType1 = S.Context.getArrayDecayedType(FromType1);
3966     if (SCS2.First == ICK_Array_To_Pointer)
3967       FromType2 = S.Context.getArrayDecayedType(FromType2);
3968
3969     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3970     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3971
3972     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3973       return ImplicitConversionSequence::Better;
3974     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3975       return ImplicitConversionSequence::Worse;
3976
3977     // Objective-C++: If one interface is more specific than the
3978     // other, it is the better one.
3979     const ObjCObjectPointerType* FromObjCPtr1
3980       = FromType1->getAs<ObjCObjectPointerType>();
3981     const ObjCObjectPointerType* FromObjCPtr2
3982       = FromType2->getAs<ObjCObjectPointerType>();
3983     if (FromObjCPtr1 && FromObjCPtr2) {
3984       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3985                                                           FromObjCPtr2);
3986       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3987                                                            FromObjCPtr1);
3988       if (AssignLeft != AssignRight) {
3989         return AssignLeft? ImplicitConversionSequence::Better
3990                          : ImplicitConversionSequence::Worse;
3991       }
3992     }
3993   }
3994
3995   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3996     // Check for a better reference binding based on the kind of bindings.
3997     if (isBetterReferenceBindingKind(SCS1, SCS2))
3998       return ImplicitConversionSequence::Better;
3999     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4000       return ImplicitConversionSequence::Worse;
4001   }
4002
4003   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4004   // bullet 3).
4005   if (ImplicitConversionSequence::CompareKind QualCK
4006         = CompareQualificationConversions(S, SCS1, SCS2))
4007     return QualCK;
4008
4009   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4010     // C++ [over.ics.rank]p3b4:
4011     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4012     //      which the references refer are the same type except for
4013     //      top-level cv-qualifiers, and the type to which the reference
4014     //      initialized by S2 refers is more cv-qualified than the type
4015     //      to which the reference initialized by S1 refers.
4016     QualType T1 = SCS1.getToType(2);
4017     QualType T2 = SCS2.getToType(2);
4018     T1 = S.Context.getCanonicalType(T1);
4019     T2 = S.Context.getCanonicalType(T2);
4020     Qualifiers T1Quals, T2Quals;
4021     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4022     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4023     if (UnqualT1 == UnqualT2) {
4024       // Objective-C++ ARC: If the references refer to objects with different
4025       // lifetimes, prefer bindings that don't change lifetime.
4026       if (SCS1.ObjCLifetimeConversionBinding !=
4027                                           SCS2.ObjCLifetimeConversionBinding) {
4028         return SCS1.ObjCLifetimeConversionBinding
4029                                            ? ImplicitConversionSequence::Worse
4030                                            : ImplicitConversionSequence::Better;
4031       }
4032
4033       // If the type is an array type, promote the element qualifiers to the
4034       // type for comparison.
4035       if (isa<ArrayType>(T1) && T1Quals)
4036         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4037       if (isa<ArrayType>(T2) && T2Quals)
4038         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4039       if (T2.isMoreQualifiedThan(T1))
4040         return ImplicitConversionSequence::Better;
4041       if (T1.isMoreQualifiedThan(T2))
4042         return ImplicitConversionSequence::Worse;
4043     }
4044   }
4045
4046   // In Microsoft mode, prefer an integral conversion to a
4047   // floating-to-integral conversion if the integral conversion
4048   // is between types of the same size.
4049   // For example:
4050   // void f(float);
4051   // void f(int);
4052   // int main {
4053   //    long a;
4054   //    f(a);
4055   // }
4056   // Here, MSVC will call f(int) instead of generating a compile error
4057   // as clang will do in standard mode.
4058   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4059       SCS2.Second == ICK_Floating_Integral &&
4060       S.Context.getTypeSize(SCS1.getFromType()) ==
4061           S.Context.getTypeSize(SCS1.getToType(2)))
4062     return ImplicitConversionSequence::Better;
4063
4064   // Prefer a compatible vector conversion over a lax vector conversion
4065   // For example:
4066   //
4067   // typedef float __v4sf __attribute__((__vector_size__(16)));
4068   // void f(vector float);
4069   // void f(vector signed int);
4070   // int main() {
4071   //   __v4sf a;
4072   //   f(a);
4073   // }
4074   // Here, we'd like to choose f(vector float) and not
4075   // report an ambiguous call error
4076   if (SCS1.Second == ICK_Vector_Conversion &&
4077       SCS2.Second == ICK_Vector_Conversion) {
4078     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4079         SCS1.getFromType(), SCS1.getToType(2));
4080     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4081         SCS2.getFromType(), SCS2.getToType(2));
4082
4083     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4084       return SCS1IsCompatibleVectorConversion
4085                  ? ImplicitConversionSequence::Better
4086                  : ImplicitConversionSequence::Worse;
4087   }
4088
4089   return ImplicitConversionSequence::Indistinguishable;
4090 }
4091
4092 /// CompareQualificationConversions - Compares two standard conversion
4093 /// sequences to determine whether they can be ranked based on their
4094 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4095 static ImplicitConversionSequence::CompareKind
4096 CompareQualificationConversions(Sema &S,
4097                                 const StandardConversionSequence& SCS1,
4098                                 const StandardConversionSequence& SCS2) {
4099   // C++ 13.3.3.2p3:
4100   //  -- S1 and S2 differ only in their qualification conversion and
4101   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4102   //     cv-qualification signature of type T1 is a proper subset of
4103   //     the cv-qualification signature of type T2, and S1 is not the
4104   //     deprecated string literal array-to-pointer conversion (4.2).
4105   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4106       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4107     return ImplicitConversionSequence::Indistinguishable;
4108
4109   // FIXME: the example in the standard doesn't use a qualification
4110   // conversion (!)
4111   QualType T1 = SCS1.getToType(2);
4112   QualType T2 = SCS2.getToType(2);
4113   T1 = S.Context.getCanonicalType(T1);
4114   T2 = S.Context.getCanonicalType(T2);
4115   assert(!T1->isReferenceType() && !T2->isReferenceType());
4116   Qualifiers T1Quals, T2Quals;
4117   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4118   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4119
4120   // If the types are the same, we won't learn anything by unwrapping
4121   // them.
4122   if (UnqualT1 == UnqualT2)
4123     return ImplicitConversionSequence::Indistinguishable;
4124
4125   ImplicitConversionSequence::CompareKind Result
4126     = ImplicitConversionSequence::Indistinguishable;
4127
4128   // Objective-C++ ARC:
4129   //   Prefer qualification conversions not involving a change in lifetime
4130   //   to qualification conversions that do not change lifetime.
4131   if (SCS1.QualificationIncludesObjCLifetime !=
4132                                       SCS2.QualificationIncludesObjCLifetime) {
4133     Result = SCS1.QualificationIncludesObjCLifetime
4134                ? ImplicitConversionSequence::Worse
4135                : ImplicitConversionSequence::Better;
4136   }
4137
4138   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4139     // Within each iteration of the loop, we check the qualifiers to
4140     // determine if this still looks like a qualification
4141     // conversion. Then, if all is well, we unwrap one more level of
4142     // pointers or pointers-to-members and do it all again
4143     // until there are no more pointers or pointers-to-members left
4144     // to unwrap. This essentially mimics what
4145     // IsQualificationConversion does, but here we're checking for a
4146     // strict subset of qualifiers.
4147     if (T1.getQualifiers().withoutObjCLifetime() ==
4148         T2.getQualifiers().withoutObjCLifetime())
4149       // The qualifiers are the same, so this doesn't tell us anything
4150       // about how the sequences rank.
4151       // ObjC ownership quals are omitted above as they interfere with
4152       // the ARC overload rule.
4153       ;
4154     else if (T2.isMoreQualifiedThan(T1)) {
4155       // T1 has fewer qualifiers, so it could be the better sequence.
4156       if (Result == ImplicitConversionSequence::Worse)
4157         // Neither has qualifiers that are a subset of the other's
4158         // qualifiers.
4159         return ImplicitConversionSequence::Indistinguishable;
4160
4161       Result = ImplicitConversionSequence::Better;
4162     } else if (T1.isMoreQualifiedThan(T2)) {
4163       // T2 has fewer qualifiers, so it could be the better sequence.
4164       if (Result == ImplicitConversionSequence::Better)
4165         // Neither has qualifiers that are a subset of the other's
4166         // qualifiers.
4167         return ImplicitConversionSequence::Indistinguishable;
4168
4169       Result = ImplicitConversionSequence::Worse;
4170     } else {
4171       // Qualifiers are disjoint.
4172       return ImplicitConversionSequence::Indistinguishable;
4173     }
4174
4175     // If the types after this point are equivalent, we're done.
4176     if (S.Context.hasSameUnqualifiedType(T1, T2))
4177       break;
4178   }
4179
4180   // Check that the winning standard conversion sequence isn't using
4181   // the deprecated string literal array to pointer conversion.
4182   switch (Result) {
4183   case ImplicitConversionSequence::Better:
4184     if (SCS1.DeprecatedStringLiteralToCharPtr)
4185       Result = ImplicitConversionSequence::Indistinguishable;
4186     break;
4187
4188   case ImplicitConversionSequence::Indistinguishable:
4189     break;
4190
4191   case ImplicitConversionSequence::Worse:
4192     if (SCS2.DeprecatedStringLiteralToCharPtr)
4193       Result = ImplicitConversionSequence::Indistinguishable;
4194     break;
4195   }
4196
4197   return Result;
4198 }
4199
4200 /// CompareDerivedToBaseConversions - Compares two standard conversion
4201 /// sequences to determine whether they can be ranked based on their
4202 /// various kinds of derived-to-base conversions (C++
4203 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4204 /// conversions between Objective-C interface types.
4205 static ImplicitConversionSequence::CompareKind
4206 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4207                                 const StandardConversionSequence& SCS1,
4208                                 const StandardConversionSequence& SCS2) {
4209   QualType FromType1 = SCS1.getFromType();
4210   QualType ToType1 = SCS1.getToType(1);
4211   QualType FromType2 = SCS2.getFromType();
4212   QualType ToType2 = SCS2.getToType(1);
4213
4214   // Adjust the types we're converting from via the array-to-pointer
4215   // conversion, if we need to.
4216   if (SCS1.First == ICK_Array_To_Pointer)
4217     FromType1 = S.Context.getArrayDecayedType(FromType1);
4218   if (SCS2.First == ICK_Array_To_Pointer)
4219     FromType2 = S.Context.getArrayDecayedType(FromType2);
4220
4221   // Canonicalize all of the types.
4222   FromType1 = S.Context.getCanonicalType(FromType1);
4223   ToType1 = S.Context.getCanonicalType(ToType1);
4224   FromType2 = S.Context.getCanonicalType(FromType2);
4225   ToType2 = S.Context.getCanonicalType(ToType2);
4226
4227   // C++ [over.ics.rank]p4b3:
4228   //
4229   //   If class B is derived directly or indirectly from class A and
4230   //   class C is derived directly or indirectly from B,
4231   //
4232   // Compare based on pointer conversions.
4233   if (SCS1.Second == ICK_Pointer_Conversion &&
4234       SCS2.Second == ICK_Pointer_Conversion &&
4235       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4236       FromType1->isPointerType() && FromType2->isPointerType() &&
4237       ToType1->isPointerType() && ToType2->isPointerType()) {
4238     QualType FromPointee1 =
4239         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4240     QualType ToPointee1 =
4241         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4242     QualType FromPointee2 =
4243         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4244     QualType ToPointee2 =
4245         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4246
4247     //   -- conversion of C* to B* is better than conversion of C* to A*,
4248     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4249       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4250         return ImplicitConversionSequence::Better;
4251       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4252         return ImplicitConversionSequence::Worse;
4253     }
4254
4255     //   -- conversion of B* to A* is better than conversion of C* to A*,
4256     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4257       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4258         return ImplicitConversionSequence::Better;
4259       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4260         return ImplicitConversionSequence::Worse;
4261     }
4262   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4263              SCS2.Second == ICK_Pointer_Conversion) {
4264     const ObjCObjectPointerType *FromPtr1
4265       = FromType1->getAs<ObjCObjectPointerType>();
4266     const ObjCObjectPointerType *FromPtr2
4267       = FromType2->getAs<ObjCObjectPointerType>();
4268     const ObjCObjectPointerType *ToPtr1
4269       = ToType1->getAs<ObjCObjectPointerType>();
4270     const ObjCObjectPointerType *ToPtr2
4271       = ToType2->getAs<ObjCObjectPointerType>();
4272
4273     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4274       // Apply the same conversion ranking rules for Objective-C pointer types
4275       // that we do for C++ pointers to class types. However, we employ the
4276       // Objective-C pseudo-subtyping relationship used for assignment of
4277       // Objective-C pointer types.
4278       bool FromAssignLeft
4279         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4280       bool FromAssignRight
4281         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4282       bool ToAssignLeft
4283         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4284       bool ToAssignRight
4285         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4286
4287       // A conversion to an a non-id object pointer type or qualified 'id'
4288       // type is better than a conversion to 'id'.
4289       if (ToPtr1->isObjCIdType() &&
4290           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4291         return ImplicitConversionSequence::Worse;
4292       if (ToPtr2->isObjCIdType() &&
4293           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4294         return ImplicitConversionSequence::Better;
4295
4296       // A conversion to a non-id object pointer type is better than a
4297       // conversion to a qualified 'id' type
4298       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4299         return ImplicitConversionSequence::Worse;
4300       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4301         return ImplicitConversionSequence::Better;
4302
4303       // A conversion to an a non-Class object pointer type or qualified 'Class'
4304       // type is better than a conversion to 'Class'.
4305       if (ToPtr1->isObjCClassType() &&
4306           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4307         return ImplicitConversionSequence::Worse;
4308       if (ToPtr2->isObjCClassType() &&
4309           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4310         return ImplicitConversionSequence::Better;
4311
4312       // A conversion to a non-Class object pointer type is better than a
4313       // conversion to a qualified 'Class' type.
4314       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4315         return ImplicitConversionSequence::Worse;
4316       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4317         return ImplicitConversionSequence::Better;
4318
4319       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4320       if (S.Context.hasSameType(FromType1, FromType2) &&
4321           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4322           (ToAssignLeft != ToAssignRight)) {
4323         if (FromPtr1->isSpecialized()) {
4324           // "conversion of B<A> * to B * is better than conversion of B * to
4325           // C *.
4326           bool IsFirstSame =
4327               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4328           bool IsSecondSame =
4329               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4330           if (IsFirstSame) {
4331             if (!IsSecondSame)
4332               return ImplicitConversionSequence::Better;
4333           } else if (IsSecondSame)
4334             return ImplicitConversionSequence::Worse;
4335         }
4336         return ToAssignLeft? ImplicitConversionSequence::Worse
4337                            : ImplicitConversionSequence::Better;
4338       }
4339
4340       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4341       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4342           (FromAssignLeft != FromAssignRight))
4343         return FromAssignLeft? ImplicitConversionSequence::Better
4344         : ImplicitConversionSequence::Worse;
4345     }
4346   }
4347
4348   // Ranking of member-pointer types.
4349   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4350       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4351       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4352     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4353     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4354     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4355     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4356     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4357     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4358     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4359     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4360     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4361     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4362     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4363     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4364     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4365     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4366       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4367         return ImplicitConversionSequence::Worse;
4368       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4369         return ImplicitConversionSequence::Better;
4370     }
4371     // conversion of B::* to C::* is better than conversion of A::* to C::*
4372     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4373       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4374         return ImplicitConversionSequence::Better;
4375       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4376         return ImplicitConversionSequence::Worse;
4377     }
4378   }
4379
4380   if (SCS1.Second == ICK_Derived_To_Base) {
4381     //   -- conversion of C to B is better than conversion of C to A,
4382     //   -- binding of an expression of type C to a reference of type
4383     //      B& is better than binding an expression of type C to a
4384     //      reference of type A&,
4385     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4386         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4387       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4388         return ImplicitConversionSequence::Better;
4389       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4390         return ImplicitConversionSequence::Worse;
4391     }
4392
4393     //   -- conversion of B to A is better than conversion of C to A.
4394     //   -- binding of an expression of type B to a reference of type
4395     //      A& is better than binding an expression of type C to a
4396     //      reference of type A&,
4397     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4398         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4399       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4400         return ImplicitConversionSequence::Better;
4401       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4402         return ImplicitConversionSequence::Worse;
4403     }
4404   }
4405
4406   return ImplicitConversionSequence::Indistinguishable;
4407 }
4408
4409 /// Determine whether the given type is valid, e.g., it is not an invalid
4410 /// C++ class.
4411 static bool isTypeValid(QualType T) {
4412   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4413     return !Record->isInvalidDecl();
4414
4415   return true;
4416 }
4417
4418 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4419   if (!T.getQualifiers().hasUnaligned())
4420     return T;
4421
4422   Qualifiers Q;
4423   T = Ctx.getUnqualifiedArrayType(T, Q);
4424   Q.removeUnaligned();
4425   return Ctx.getQualifiedType(T, Q);
4426 }
4427
4428 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4429 /// determine whether they are reference-compatible,
4430 /// reference-related, or incompatible, for use in C++ initialization by
4431 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4432 /// type, and the first type (T1) is the pointee type of the reference
4433 /// type being initialized.
4434 Sema::ReferenceCompareResult
4435 Sema::CompareReferenceRelationship(SourceLocation Loc,
4436                                    QualType OrigT1, QualType OrigT2,
4437                                    ReferenceConversions *ConvOut) {
4438   assert(!OrigT1->isReferenceType() &&
4439     "T1 must be the pointee type of the reference type");
4440   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4441
4442   QualType T1 = Context.getCanonicalType(OrigT1);
4443   QualType T2 = Context.getCanonicalType(OrigT2);
4444   Qualifiers T1Quals, T2Quals;
4445   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4446   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4447
4448   ReferenceConversions ConvTmp;
4449   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4450   Conv = ReferenceConversions();
4451
4452   // C++2a [dcl.init.ref]p4:
4453   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4454   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4455   //   T1 is a base class of T2.
4456   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4457   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4458   //   "pointer to cv1 T1" via a standard conversion sequence.
4459
4460   // Check for standard conversions we can apply to pointers: derived-to-base
4461   // conversions, ObjC pointer conversions, and function pointer conversions.
4462   // (Qualification conversions are checked last.)
4463   QualType ConvertedT2;
4464   if (UnqualT1 == UnqualT2) {
4465     // Nothing to do.
4466   } else if (isCompleteType(Loc, OrigT2) &&
4467              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4468              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4469     Conv |= ReferenceConversions::DerivedToBase;
4470   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4471            UnqualT2->isObjCObjectOrInterfaceType() &&
4472            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4473     Conv |= ReferenceConversions::ObjC;
4474   else if (UnqualT2->isFunctionType() &&
4475            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4476     Conv |= ReferenceConversions::Function;
4477     // No need to check qualifiers; function types don't have them.
4478     return Ref_Compatible;
4479   }
4480   bool ConvertedReferent = Conv != 0;
4481
4482   // We can have a qualification conversion. Compute whether the types are
4483   // similar at the same time.
4484   bool PreviousToQualsIncludeConst = true;
4485   bool TopLevel = true;
4486   do {
4487     if (T1 == T2)
4488       break;
4489
4490     // We will need a qualification conversion.
4491     Conv |= ReferenceConversions::Qualification;
4492
4493     // Track whether we performed a qualification conversion anywhere other
4494     // than the top level. This matters for ranking reference bindings in
4495     // overload resolution.
4496     if (!TopLevel)
4497       Conv |= ReferenceConversions::NestedQualification;
4498
4499     // MS compiler ignores __unaligned qualifier for references; do the same.
4500     T1 = withoutUnaligned(Context, T1);
4501     T2 = withoutUnaligned(Context, T2);
4502
4503     // If we find a qualifier mismatch, the types are not reference-compatible,
4504     // but are still be reference-related if they're similar.
4505     bool ObjCLifetimeConversion = false;
4506     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4507                                        PreviousToQualsIncludeConst,
4508                                        ObjCLifetimeConversion))
4509       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4510                  ? Ref_Related
4511                  : Ref_Incompatible;
4512
4513     // FIXME: Should we track this for any level other than the first?
4514     if (ObjCLifetimeConversion)
4515       Conv |= ReferenceConversions::ObjCLifetime;
4516
4517     TopLevel = false;
4518   } while (Context.UnwrapSimilarTypes(T1, T2));
4519
4520   // At this point, if the types are reference-related, we must either have the
4521   // same inner type (ignoring qualifiers), or must have already worked out how
4522   // to convert the referent.
4523   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4524              ? Ref_Compatible
4525              : Ref_Incompatible;
4526 }
4527
4528 /// Look for a user-defined conversion to a value reference-compatible
4529 ///        with DeclType. Return true if something definite is found.
4530 static bool
4531 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4532                          QualType DeclType, SourceLocation DeclLoc,
4533                          Expr *Init, QualType T2, bool AllowRvalues,
4534                          bool AllowExplicit) {
4535   assert(T2->isRecordType() && "Can only find conversions of record types.");
4536   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4537
4538   OverloadCandidateSet CandidateSet(
4539       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4540   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4541   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4542     NamedDecl *D = *I;
4543     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4544     if (isa<UsingShadowDecl>(D))
4545       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4546
4547     FunctionTemplateDecl *ConvTemplate
4548       = dyn_cast<FunctionTemplateDecl>(D);
4549     CXXConversionDecl *Conv;
4550     if (ConvTemplate)
4551       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4552     else
4553       Conv = cast<CXXConversionDecl>(D);
4554
4555     if (AllowRvalues) {
4556       // If we are initializing an rvalue reference, don't permit conversion
4557       // functions that return lvalues.
4558       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4559         const ReferenceType *RefType
4560           = Conv->getConversionType()->getAs<LValueReferenceType>();
4561         if (RefType && !RefType->getPointeeType()->isFunctionType())
4562           continue;
4563       }
4564
4565       if (!ConvTemplate &&
4566           S.CompareReferenceRelationship(
4567               DeclLoc,
4568               Conv->getConversionType()
4569                   .getNonReferenceType()
4570                   .getUnqualifiedType(),
4571               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4572               Sema::Ref_Incompatible)
4573         continue;
4574     } else {
4575       // If the conversion function doesn't return a reference type,
4576       // it can't be considered for this conversion. An rvalue reference
4577       // is only acceptable if its referencee is a function type.
4578
4579       const ReferenceType *RefType =
4580         Conv->getConversionType()->getAs<ReferenceType>();
4581       if (!RefType ||
4582           (!RefType->isLValueReferenceType() &&
4583            !RefType->getPointeeType()->isFunctionType()))
4584         continue;
4585     }
4586
4587     if (ConvTemplate)
4588       S.AddTemplateConversionCandidate(
4589           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4590           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4591     else
4592       S.AddConversionCandidate(
4593           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4594           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4595   }
4596
4597   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4598
4599   OverloadCandidateSet::iterator Best;
4600   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4601   case OR_Success:
4602     // C++ [over.ics.ref]p1:
4603     //
4604     //   [...] If the parameter binds directly to the result of
4605     //   applying a conversion function to the argument
4606     //   expression, the implicit conversion sequence is a
4607     //   user-defined conversion sequence (13.3.3.1.2), with the
4608     //   second standard conversion sequence either an identity
4609     //   conversion or, if the conversion function returns an
4610     //   entity of a type that is a derived class of the parameter
4611     //   type, a derived-to-base Conversion.
4612     if (!Best->FinalConversion.DirectBinding)
4613       return false;
4614
4615     ICS.setUserDefined();
4616     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4617     ICS.UserDefined.After = Best->FinalConversion;
4618     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4619     ICS.UserDefined.ConversionFunction = Best->Function;
4620     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4621     ICS.UserDefined.EllipsisConversion = false;
4622     assert(ICS.UserDefined.After.ReferenceBinding &&
4623            ICS.UserDefined.After.DirectBinding &&
4624            "Expected a direct reference binding!");
4625     return true;
4626
4627   case OR_Ambiguous:
4628     ICS.setAmbiguous();
4629     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4630          Cand != CandidateSet.end(); ++Cand)
4631       if (Cand->Best)
4632         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4633     return true;
4634
4635   case OR_No_Viable_Function:
4636   case OR_Deleted:
4637     // There was no suitable conversion, or we found a deleted
4638     // conversion; continue with other checks.
4639     return false;
4640   }
4641
4642   llvm_unreachable("Invalid OverloadResult!");
4643 }
4644
4645 /// Compute an implicit conversion sequence for reference
4646 /// initialization.
4647 static ImplicitConversionSequence
4648 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4649                  SourceLocation DeclLoc,
4650                  bool SuppressUserConversions,
4651                  bool AllowExplicit) {
4652   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4653
4654   // Most paths end in a failed conversion.
4655   ImplicitConversionSequence ICS;
4656   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4657
4658   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4659   QualType T2 = Init->getType();
4660
4661   // If the initializer is the address of an overloaded function, try
4662   // to resolve the overloaded function. If all goes well, T2 is the
4663   // type of the resulting function.
4664   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4665     DeclAccessPair Found;
4666     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4667                                                                 false, Found))
4668       T2 = Fn->getType();
4669   }
4670
4671   // Compute some basic properties of the types and the initializer.
4672   bool isRValRef = DeclType->isRValueReferenceType();
4673   Expr::Classification InitCategory = Init->Classify(S.Context);
4674
4675   Sema::ReferenceConversions RefConv;
4676   Sema::ReferenceCompareResult RefRelationship =
4677       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4678
4679   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4680     ICS.setStandard();
4681     ICS.Standard.First = ICK_Identity;
4682     // FIXME: A reference binding can be a function conversion too. We should
4683     // consider that when ordering reference-to-function bindings.
4684     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4685                               ? ICK_Derived_To_Base
4686                               : (RefConv & Sema::ReferenceConversions::ObjC)
4687                                     ? ICK_Compatible_Conversion
4688                                     : ICK_Identity;
4689     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4690     // a reference binding that performs a non-top-level qualification
4691     // conversion as a qualification conversion, not as an identity conversion.
4692     ICS.Standard.Third = (RefConv &
4693                               Sema::ReferenceConversions::NestedQualification)
4694                              ? ICK_Qualification
4695                              : ICK_Identity;
4696     ICS.Standard.setFromType(T2);
4697     ICS.Standard.setToType(0, T2);
4698     ICS.Standard.setToType(1, T1);
4699     ICS.Standard.setToType(2, T1);
4700     ICS.Standard.ReferenceBinding = true;
4701     ICS.Standard.DirectBinding = BindsDirectly;
4702     ICS.Standard.IsLvalueReference = !isRValRef;
4703     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4704     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4705     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4706     ICS.Standard.ObjCLifetimeConversionBinding =
4707         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4708     ICS.Standard.CopyConstructor = nullptr;
4709     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4710   };
4711
4712   // C++0x [dcl.init.ref]p5:
4713   //   A reference to type "cv1 T1" is initialized by an expression
4714   //   of type "cv2 T2" as follows:
4715
4716   //     -- If reference is an lvalue reference and the initializer expression
4717   if (!isRValRef) {
4718     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4719     //        reference-compatible with "cv2 T2," or
4720     //
4721     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4722     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4723       // C++ [over.ics.ref]p1:
4724       //   When a parameter of reference type binds directly (8.5.3)
4725       //   to an argument expression, the implicit conversion sequence
4726       //   is the identity conversion, unless the argument expression
4727       //   has a type that is a derived class of the parameter type,
4728       //   in which case the implicit conversion sequence is a
4729       //   derived-to-base Conversion (13.3.3.1).
4730       SetAsReferenceBinding(/*BindsDirectly=*/true);
4731
4732       // Nothing more to do: the inaccessibility/ambiguity check for
4733       // derived-to-base conversions is suppressed when we're
4734       // computing the implicit conversion sequence (C++
4735       // [over.best.ics]p2).
4736       return ICS;
4737     }
4738
4739     //       -- has a class type (i.e., T2 is a class type), where T1 is
4740     //          not reference-related to T2, and can be implicitly
4741     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4742     //          is reference-compatible with "cv3 T3" 92) (this
4743     //          conversion is selected by enumerating the applicable
4744     //          conversion functions (13.3.1.6) and choosing the best
4745     //          one through overload resolution (13.3)),
4746     if (!SuppressUserConversions && T2->isRecordType() &&
4747         S.isCompleteType(DeclLoc, T2) &&
4748         RefRelationship == Sema::Ref_Incompatible) {
4749       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4750                                    Init, T2, /*AllowRvalues=*/false,
4751                                    AllowExplicit))
4752         return ICS;
4753     }
4754   }
4755
4756   //     -- Otherwise, the reference shall be an lvalue reference to a
4757   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4758   //        shall be an rvalue reference.
4759   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4760     return ICS;
4761
4762   //       -- If the initializer expression
4763   //
4764   //            -- is an xvalue, class prvalue, array prvalue or function
4765   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4766   if (RefRelationship == Sema::Ref_Compatible &&
4767       (InitCategory.isXValue() ||
4768        (InitCategory.isPRValue() &&
4769           (T2->isRecordType() || T2->isArrayType())) ||
4770        (InitCategory.isLValue() && T2->isFunctionType()))) {
4771     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4772     // binding unless we're binding to a class prvalue.
4773     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4774     // allow the use of rvalue references in C++98/03 for the benefit of
4775     // standard library implementors; therefore, we need the xvalue check here.
4776     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4777                           !(InitCategory.isPRValue() || T2->isRecordType()));
4778     return ICS;
4779   }
4780
4781   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4782   //               reference-related to T2, and can be implicitly converted to
4783   //               an xvalue, class prvalue, or function lvalue of type
4784   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4785   //               "cv3 T3",
4786   //
4787   //          then the reference is bound to the value of the initializer
4788   //          expression in the first case and to the result of the conversion
4789   //          in the second case (or, in either case, to an appropriate base
4790   //          class subobject).
4791   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4792       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4793       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4794                                Init, T2, /*AllowRvalues=*/true,
4795                                AllowExplicit)) {
4796     // In the second case, if the reference is an rvalue reference
4797     // and the second standard conversion sequence of the
4798     // user-defined conversion sequence includes an lvalue-to-rvalue
4799     // conversion, the program is ill-formed.
4800     if (ICS.isUserDefined() && isRValRef &&
4801         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4802       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4803
4804     return ICS;
4805   }
4806
4807   // A temporary of function type cannot be created; don't even try.
4808   if (T1->isFunctionType())
4809     return ICS;
4810
4811   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4812   //          initialized from the initializer expression using the
4813   //          rules for a non-reference copy initialization (8.5). The
4814   //          reference is then bound to the temporary. If T1 is
4815   //          reference-related to T2, cv1 must be the same
4816   //          cv-qualification as, or greater cv-qualification than,
4817   //          cv2; otherwise, the program is ill-formed.
4818   if (RefRelationship == Sema::Ref_Related) {
4819     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4820     // we would be reference-compatible or reference-compatible with
4821     // added qualification. But that wasn't the case, so the reference
4822     // initialization fails.
4823     //
4824     // Note that we only want to check address spaces and cvr-qualifiers here.
4825     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4826     Qualifiers T1Quals = T1.getQualifiers();
4827     Qualifiers T2Quals = T2.getQualifiers();
4828     T1Quals.removeObjCGCAttr();
4829     T1Quals.removeObjCLifetime();
4830     T2Quals.removeObjCGCAttr();
4831     T2Quals.removeObjCLifetime();
4832     // MS compiler ignores __unaligned qualifier for references; do the same.
4833     T1Quals.removeUnaligned();
4834     T2Quals.removeUnaligned();
4835     if (!T1Quals.compatiblyIncludes(T2Quals))
4836       return ICS;
4837   }
4838
4839   // If at least one of the types is a class type, the types are not
4840   // related, and we aren't allowed any user conversions, the
4841   // reference binding fails. This case is important for breaking
4842   // recursion, since TryImplicitConversion below will attempt to
4843   // create a temporary through the use of a copy constructor.
4844   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4845       (T1->isRecordType() || T2->isRecordType()))
4846     return ICS;
4847
4848   // If T1 is reference-related to T2 and the reference is an rvalue
4849   // reference, the initializer expression shall not be an lvalue.
4850   if (RefRelationship >= Sema::Ref_Related &&
4851       isRValRef && Init->Classify(S.Context).isLValue())
4852     return ICS;
4853
4854   // C++ [over.ics.ref]p2:
4855   //   When a parameter of reference type is not bound directly to
4856   //   an argument expression, the conversion sequence is the one
4857   //   required to convert the argument expression to the
4858   //   underlying type of the reference according to
4859   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4860   //   to copy-initializing a temporary of the underlying type with
4861   //   the argument expression. Any difference in top-level
4862   //   cv-qualification is subsumed by the initialization itself
4863   //   and does not constitute a conversion.
4864   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4865                               /*AllowExplicit=*/false,
4866                               /*InOverloadResolution=*/false,
4867                               /*CStyle=*/false,
4868                               /*AllowObjCWritebackConversion=*/false,
4869                               /*AllowObjCConversionOnExplicit=*/false);
4870
4871   // Of course, that's still a reference binding.
4872   if (ICS.isStandard()) {
4873     ICS.Standard.ReferenceBinding = true;
4874     ICS.Standard.IsLvalueReference = !isRValRef;
4875     ICS.Standard.BindsToFunctionLvalue = false;
4876     ICS.Standard.BindsToRvalue = true;
4877     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4878     ICS.Standard.ObjCLifetimeConversionBinding = false;
4879   } else if (ICS.isUserDefined()) {
4880     const ReferenceType *LValRefType =
4881         ICS.UserDefined.ConversionFunction->getReturnType()
4882             ->getAs<LValueReferenceType>();
4883
4884     // C++ [over.ics.ref]p3:
4885     //   Except for an implicit object parameter, for which see 13.3.1, a
4886     //   standard conversion sequence cannot be formed if it requires [...]
4887     //   binding an rvalue reference to an lvalue other than a function
4888     //   lvalue.
4889     // Note that the function case is not possible here.
4890     if (DeclType->isRValueReferenceType() && LValRefType) {
4891       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4892       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4893       // reference to an rvalue!
4894       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4895       return ICS;
4896     }
4897
4898     ICS.UserDefined.After.ReferenceBinding = true;
4899     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4900     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4901     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4902     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4903     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4904   }
4905
4906   return ICS;
4907 }
4908
4909 static ImplicitConversionSequence
4910 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4911                       bool SuppressUserConversions,
4912                       bool InOverloadResolution,
4913                       bool AllowObjCWritebackConversion,
4914                       bool AllowExplicit = false);
4915
4916 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4917 /// initializer list From.
4918 static ImplicitConversionSequence
4919 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4920                   bool SuppressUserConversions,
4921                   bool InOverloadResolution,
4922                   bool AllowObjCWritebackConversion) {
4923   // C++11 [over.ics.list]p1:
4924   //   When an argument is an initializer list, it is not an expression and
4925   //   special rules apply for converting it to a parameter type.
4926
4927   ImplicitConversionSequence Result;
4928   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4929
4930   // We need a complete type for what follows. Incomplete types can never be
4931   // initialized from init lists.
4932   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4933     return Result;
4934
4935   // Per DR1467:
4936   //   If the parameter type is a class X and the initializer list has a single
4937   //   element of type cv U, where U is X or a class derived from X, the
4938   //   implicit conversion sequence is the one required to convert the element
4939   //   to the parameter type.
4940   //
4941   //   Otherwise, if the parameter type is a character array [... ]
4942   //   and the initializer list has a single element that is an
4943   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4944   //   implicit conversion sequence is the identity conversion.
4945   if (From->getNumInits() == 1) {
4946     if (ToType->isRecordType()) {
4947       QualType InitType = From->getInit(0)->getType();
4948       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4949           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4950         return TryCopyInitialization(S, From->getInit(0), ToType,
4951                                      SuppressUserConversions,
4952                                      InOverloadResolution,
4953                                      AllowObjCWritebackConversion);
4954     }
4955     // FIXME: Check the other conditions here: array of character type,
4956     // initializer is a string literal.
4957     if (ToType->isArrayType()) {
4958       InitializedEntity Entity =
4959         InitializedEntity::InitializeParameter(S.Context, ToType,
4960                                                /*Consumed=*/false);
4961       if (S.CanPerformCopyInitialization(Entity, From)) {
4962         Result.setStandard();
4963         Result.Standard.setAsIdentityConversion();
4964         Result.Standard.setFromType(ToType);
4965         Result.Standard.setAllToTypes(ToType);
4966         return Result;
4967       }
4968     }
4969   }
4970
4971   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4972   // C++11 [over.ics.list]p2:
4973   //   If the parameter type is std::initializer_list<X> or "array of X" and
4974   //   all the elements can be implicitly converted to X, the implicit
4975   //   conversion sequence is the worst conversion necessary to convert an
4976   //   element of the list to X.
4977   //
4978   // C++14 [over.ics.list]p3:
4979   //   Otherwise, if the parameter type is "array of N X", if the initializer
4980   //   list has exactly N elements or if it has fewer than N elements and X is
4981   //   default-constructible, and if all the elements of the initializer list
4982   //   can be implicitly converted to X, the implicit conversion sequence is
4983   //   the worst conversion necessary to convert an element of the list to X.
4984   //
4985   // FIXME: We're missing a lot of these checks.
4986   bool toStdInitializerList = false;
4987   QualType X;
4988   if (ToType->isArrayType())
4989     X = S.Context.getAsArrayType(ToType)->getElementType();
4990   else
4991     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4992   if (!X.isNull()) {
4993     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4994       Expr *Init = From->getInit(i);
4995       ImplicitConversionSequence ICS =
4996           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4997                                 InOverloadResolution,
4998                                 AllowObjCWritebackConversion);
4999       // If a single element isn't convertible, fail.
5000       if (ICS.isBad()) {
5001         Result = ICS;
5002         break;
5003       }
5004       // Otherwise, look for the worst conversion.
5005       if (Result.isBad() || CompareImplicitConversionSequences(
5006                                 S, From->getBeginLoc(), ICS, Result) ==
5007                                 ImplicitConversionSequence::Worse)
5008         Result = ICS;
5009     }
5010
5011     // For an empty list, we won't have computed any conversion sequence.
5012     // Introduce the identity conversion sequence.
5013     if (From->getNumInits() == 0) {
5014       Result.setStandard();
5015       Result.Standard.setAsIdentityConversion();
5016       Result.Standard.setFromType(ToType);
5017       Result.Standard.setAllToTypes(ToType);
5018     }
5019
5020     Result.setStdInitializerListElement(toStdInitializerList);
5021     return Result;
5022   }
5023
5024   // C++14 [over.ics.list]p4:
5025   // C++11 [over.ics.list]p3:
5026   //   Otherwise, if the parameter is a non-aggregate class X and overload
5027   //   resolution chooses a single best constructor [...] the implicit
5028   //   conversion sequence is a user-defined conversion sequence. If multiple
5029   //   constructors are viable but none is better than the others, the
5030   //   implicit conversion sequence is a user-defined conversion sequence.
5031   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5032     // This function can deal with initializer lists.
5033     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5034                                     /*AllowExplicit=*/false,
5035                                     InOverloadResolution, /*CStyle=*/false,
5036                                     AllowObjCWritebackConversion,
5037                                     /*AllowObjCConversionOnExplicit=*/false);
5038   }
5039
5040   // C++14 [over.ics.list]p5:
5041   // C++11 [over.ics.list]p4:
5042   //   Otherwise, if the parameter has an aggregate type which can be
5043   //   initialized from the initializer list [...] the implicit conversion
5044   //   sequence is a user-defined conversion sequence.
5045   if (ToType->isAggregateType()) {
5046     // Type is an aggregate, argument is an init list. At this point it comes
5047     // down to checking whether the initialization works.
5048     // FIXME: Find out whether this parameter is consumed or not.
5049     InitializedEntity Entity =
5050         InitializedEntity::InitializeParameter(S.Context, ToType,
5051                                                /*Consumed=*/false);
5052     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5053                                                                  From)) {
5054       Result.setUserDefined();
5055       Result.UserDefined.Before.setAsIdentityConversion();
5056       // Initializer lists don't have a type.
5057       Result.UserDefined.Before.setFromType(QualType());
5058       Result.UserDefined.Before.setAllToTypes(QualType());
5059
5060       Result.UserDefined.After.setAsIdentityConversion();
5061       Result.UserDefined.After.setFromType(ToType);
5062       Result.UserDefined.After.setAllToTypes(ToType);
5063       Result.UserDefined.ConversionFunction = nullptr;
5064     }
5065     return Result;
5066   }
5067
5068   // C++14 [over.ics.list]p6:
5069   // C++11 [over.ics.list]p5:
5070   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5071   if (ToType->isReferenceType()) {
5072     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5073     // mention initializer lists in any way. So we go by what list-
5074     // initialization would do and try to extrapolate from that.
5075
5076     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5077
5078     // If the initializer list has a single element that is reference-related
5079     // to the parameter type, we initialize the reference from that.
5080     if (From->getNumInits() == 1) {
5081       Expr *Init = From->getInit(0);
5082
5083       QualType T2 = Init->getType();
5084
5085       // If the initializer is the address of an overloaded function, try
5086       // to resolve the overloaded function. If all goes well, T2 is the
5087       // type of the resulting function.
5088       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5089         DeclAccessPair Found;
5090         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5091                                    Init, ToType, false, Found))
5092           T2 = Fn->getType();
5093       }
5094
5095       // Compute some basic properties of the types and the initializer.
5096       Sema::ReferenceCompareResult RefRelationship =
5097           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5098
5099       if (RefRelationship >= Sema::Ref_Related) {
5100         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5101                                 SuppressUserConversions,
5102                                 /*AllowExplicit=*/false);
5103       }
5104     }
5105
5106     // Otherwise, we bind the reference to a temporary created from the
5107     // initializer list.
5108     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5109                                InOverloadResolution,
5110                                AllowObjCWritebackConversion);
5111     if (Result.isFailure())
5112       return Result;
5113     assert(!Result.isEllipsis() &&
5114            "Sub-initialization cannot result in ellipsis conversion.");
5115
5116     // Can we even bind to a temporary?
5117     if (ToType->isRValueReferenceType() ||
5118         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5119       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5120                                             Result.UserDefined.After;
5121       SCS.ReferenceBinding = true;
5122       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5123       SCS.BindsToRvalue = true;
5124       SCS.BindsToFunctionLvalue = false;
5125       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5126       SCS.ObjCLifetimeConversionBinding = false;
5127     } else
5128       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5129                     From, ToType);
5130     return Result;
5131   }
5132
5133   // C++14 [over.ics.list]p7:
5134   // C++11 [over.ics.list]p6:
5135   //   Otherwise, if the parameter type is not a class:
5136   if (!ToType->isRecordType()) {
5137     //    - if the initializer list has one element that is not itself an
5138     //      initializer list, the implicit conversion sequence is the one
5139     //      required to convert the element to the parameter type.
5140     unsigned NumInits = From->getNumInits();
5141     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5142       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5143                                      SuppressUserConversions,
5144                                      InOverloadResolution,
5145                                      AllowObjCWritebackConversion);
5146     //    - if the initializer list has no elements, the implicit conversion
5147     //      sequence is the identity conversion.
5148     else if (NumInits == 0) {
5149       Result.setStandard();
5150       Result.Standard.setAsIdentityConversion();
5151       Result.Standard.setFromType(ToType);
5152       Result.Standard.setAllToTypes(ToType);
5153     }
5154     return Result;
5155   }
5156
5157   // C++14 [over.ics.list]p8:
5158   // C++11 [over.ics.list]p7:
5159   //   In all cases other than those enumerated above, no conversion is possible
5160   return Result;
5161 }
5162
5163 /// TryCopyInitialization - Try to copy-initialize a value of type
5164 /// ToType from the expression From. Return the implicit conversion
5165 /// sequence required to pass this argument, which may be a bad
5166 /// conversion sequence (meaning that the argument cannot be passed to
5167 /// a parameter of this type). If @p SuppressUserConversions, then we
5168 /// do not permit any user-defined conversion sequences.
5169 static ImplicitConversionSequence
5170 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5171                       bool SuppressUserConversions,
5172                       bool InOverloadResolution,
5173                       bool AllowObjCWritebackConversion,
5174                       bool AllowExplicit) {
5175   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5176     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5177                              InOverloadResolution,AllowObjCWritebackConversion);
5178
5179   if (ToType->isReferenceType())
5180     return TryReferenceInit(S, From, ToType,
5181                             /*FIXME:*/ From->getBeginLoc(),
5182                             SuppressUserConversions, AllowExplicit);
5183
5184   return TryImplicitConversion(S, From, ToType,
5185                                SuppressUserConversions,
5186                                /*AllowExplicit=*/false,
5187                                InOverloadResolution,
5188                                /*CStyle=*/false,
5189                                AllowObjCWritebackConversion,
5190                                /*AllowObjCConversionOnExplicit=*/false);
5191 }
5192
5193 static bool TryCopyInitialization(const CanQualType FromQTy,
5194                                   const CanQualType ToQTy,
5195                                   Sema &S,
5196                                   SourceLocation Loc,
5197                                   ExprValueKind FromVK) {
5198   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5199   ImplicitConversionSequence ICS =
5200     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5201
5202   return !ICS.isBad();
5203 }
5204
5205 /// TryObjectArgumentInitialization - Try to initialize the object
5206 /// parameter of the given member function (@c Method) from the
5207 /// expression @p From.
5208 static ImplicitConversionSequence
5209 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5210                                 Expr::Classification FromClassification,
5211                                 CXXMethodDecl *Method,
5212                                 CXXRecordDecl *ActingContext) {
5213   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5214   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5215   //                 const volatile object.
5216   Qualifiers Quals = Method->getMethodQualifiers();
5217   if (isa<CXXDestructorDecl>(Method)) {
5218     Quals.addConst();
5219     Quals.addVolatile();
5220   }
5221
5222   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5223
5224   // Set up the conversion sequence as a "bad" conversion, to allow us
5225   // to exit early.
5226   ImplicitConversionSequence ICS;
5227
5228   // We need to have an object of class type.
5229   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5230     FromType = PT->getPointeeType();
5231
5232     // When we had a pointer, it's implicitly dereferenced, so we
5233     // better have an lvalue.
5234     assert(FromClassification.isLValue());
5235   }
5236
5237   assert(FromType->isRecordType());
5238
5239   // C++0x [over.match.funcs]p4:
5240   //   For non-static member functions, the type of the implicit object
5241   //   parameter is
5242   //
5243   //     - "lvalue reference to cv X" for functions declared without a
5244   //        ref-qualifier or with the & ref-qualifier
5245   //     - "rvalue reference to cv X" for functions declared with the &&
5246   //        ref-qualifier
5247   //
5248   // where X is the class of which the function is a member and cv is the
5249   // cv-qualification on the member function declaration.
5250   //
5251   // However, when finding an implicit conversion sequence for the argument, we
5252   // are not allowed to perform user-defined conversions
5253   // (C++ [over.match.funcs]p5). We perform a simplified version of
5254   // reference binding here, that allows class rvalues to bind to
5255   // non-constant references.
5256
5257   // First check the qualifiers.
5258   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5259   if (ImplicitParamType.getCVRQualifiers()
5260                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5261       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5262     ICS.setBad(BadConversionSequence::bad_qualifiers,
5263                FromType, ImplicitParamType);
5264     return ICS;
5265   }
5266
5267   if (FromTypeCanon.hasAddressSpace()) {
5268     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5269     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5270     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5271       ICS.setBad(BadConversionSequence::bad_qualifiers,
5272                  FromType, ImplicitParamType);
5273       return ICS;
5274     }
5275   }
5276
5277   // Check that we have either the same type or a derived type. It
5278   // affects the conversion rank.
5279   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5280   ImplicitConversionKind SecondKind;
5281   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5282     SecondKind = ICK_Identity;
5283   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5284     SecondKind = ICK_Derived_To_Base;
5285   else {
5286     ICS.setBad(BadConversionSequence::unrelated_class,
5287                FromType, ImplicitParamType);
5288     return ICS;
5289   }
5290
5291   // Check the ref-qualifier.
5292   switch (Method->getRefQualifier()) {
5293   case RQ_None:
5294     // Do nothing; we don't care about lvalueness or rvalueness.
5295     break;
5296
5297   case RQ_LValue:
5298     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5299       // non-const lvalue reference cannot bind to an rvalue
5300       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5301                  ImplicitParamType);
5302       return ICS;
5303     }
5304     break;
5305
5306   case RQ_RValue:
5307     if (!FromClassification.isRValue()) {
5308       // rvalue reference cannot bind to an lvalue
5309       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5310                  ImplicitParamType);
5311       return ICS;
5312     }
5313     break;
5314   }
5315
5316   // Success. Mark this as a reference binding.
5317   ICS.setStandard();
5318   ICS.Standard.setAsIdentityConversion();
5319   ICS.Standard.Second = SecondKind;
5320   ICS.Standard.setFromType(FromType);
5321   ICS.Standard.setAllToTypes(ImplicitParamType);
5322   ICS.Standard.ReferenceBinding = true;
5323   ICS.Standard.DirectBinding = true;
5324   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5325   ICS.Standard.BindsToFunctionLvalue = false;
5326   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5327   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5328     = (Method->getRefQualifier() == RQ_None);
5329   return ICS;
5330 }
5331
5332 /// PerformObjectArgumentInitialization - Perform initialization of
5333 /// the implicit object parameter for the given Method with the given
5334 /// expression.
5335 ExprResult
5336 Sema::PerformObjectArgumentInitialization(Expr *From,
5337                                           NestedNameSpecifier *Qualifier,
5338                                           NamedDecl *FoundDecl,
5339                                           CXXMethodDecl *Method) {
5340   QualType FromRecordType, DestType;
5341   QualType ImplicitParamRecordType  =
5342     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5343
5344   Expr::Classification FromClassification;
5345   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5346     FromRecordType = PT->getPointeeType();
5347     DestType = Method->getThisType();
5348     FromClassification = Expr::Classification::makeSimpleLValue();
5349   } else {
5350     FromRecordType = From->getType();
5351     DestType = ImplicitParamRecordType;
5352     FromClassification = From->Classify(Context);
5353
5354     // When performing member access on an rvalue, materialize a temporary.
5355     if (From->isRValue()) {
5356       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5357                                             Method->getRefQualifier() !=
5358                                                 RefQualifierKind::RQ_RValue);
5359     }
5360   }
5361
5362   // Note that we always use the true parent context when performing
5363   // the actual argument initialization.
5364   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5365       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5366       Method->getParent());
5367   if (ICS.isBad()) {
5368     switch (ICS.Bad.Kind) {
5369     case BadConversionSequence::bad_qualifiers: {
5370       Qualifiers FromQs = FromRecordType.getQualifiers();
5371       Qualifiers ToQs = DestType.getQualifiers();
5372       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5373       if (CVR) {
5374         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5375             << Method->getDeclName() << FromRecordType << (CVR - 1)
5376             << From->getSourceRange();
5377         Diag(Method->getLocation(), diag::note_previous_decl)
5378           << Method->getDeclName();
5379         return ExprError();
5380       }
5381       break;
5382     }
5383
5384     case BadConversionSequence::lvalue_ref_to_rvalue:
5385     case BadConversionSequence::rvalue_ref_to_lvalue: {
5386       bool IsRValueQualified =
5387         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5388       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5389           << Method->getDeclName() << FromClassification.isRValue()
5390           << IsRValueQualified;
5391       Diag(Method->getLocation(), diag::note_previous_decl)
5392         << Method->getDeclName();
5393       return ExprError();
5394     }
5395
5396     case BadConversionSequence::no_conversion:
5397     case BadConversionSequence::unrelated_class:
5398       break;
5399     }
5400
5401     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5402            << ImplicitParamRecordType << FromRecordType
5403            << From->getSourceRange();
5404   }
5405
5406   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5407     ExprResult FromRes =
5408       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5409     if (FromRes.isInvalid())
5410       return ExprError();
5411     From = FromRes.get();
5412   }
5413
5414   if (!Context.hasSameType(From->getType(), DestType)) {
5415     CastKind CK;
5416     QualType PteeTy = DestType->getPointeeType();
5417     LangAS DestAS =
5418         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5419     if (FromRecordType.getAddressSpace() != DestAS)
5420       CK = CK_AddressSpaceConversion;
5421     else
5422       CK = CK_NoOp;
5423     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5424   }
5425   return From;
5426 }
5427
5428 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5429 /// expression From to bool (C++0x [conv]p3).
5430 static ImplicitConversionSequence
5431 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5432   return TryImplicitConversion(S, From, S.Context.BoolTy,
5433                                /*SuppressUserConversions=*/false,
5434                                /*AllowExplicit=*/true,
5435                                /*InOverloadResolution=*/false,
5436                                /*CStyle=*/false,
5437                                /*AllowObjCWritebackConversion=*/false,
5438                                /*AllowObjCConversionOnExplicit=*/false);
5439 }
5440
5441 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5442 /// of the expression From to bool (C++0x [conv]p3).
5443 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5444   if (checkPlaceholderForOverload(*this, From))
5445     return ExprError();
5446
5447   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5448   if (!ICS.isBad())
5449     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5450
5451   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5452     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5453            << From->getType() << From->getSourceRange();
5454   return ExprError();
5455 }
5456
5457 /// Check that the specified conversion is permitted in a converted constant
5458 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5459 /// is acceptable.
5460 static bool CheckConvertedConstantConversions(Sema &S,
5461                                               StandardConversionSequence &SCS) {
5462   // Since we know that the target type is an integral or unscoped enumeration
5463   // type, most conversion kinds are impossible. All possible First and Third
5464   // conversions are fine.
5465   switch (SCS.Second) {
5466   case ICK_Identity:
5467   case ICK_Function_Conversion:
5468   case ICK_Integral_Promotion:
5469   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5470   case ICK_Zero_Queue_Conversion:
5471     return true;
5472
5473   case ICK_Boolean_Conversion:
5474     // Conversion from an integral or unscoped enumeration type to bool is
5475     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5476     // conversion, so we allow it in a converted constant expression.
5477     //
5478     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5479     // a lot of popular code. We should at least add a warning for this
5480     // (non-conforming) extension.
5481     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5482            SCS.getToType(2)->isBooleanType();
5483
5484   case ICK_Pointer_Conversion:
5485   case ICK_Pointer_Member:
5486     // C++1z: null pointer conversions and null member pointer conversions are
5487     // only permitted if the source type is std::nullptr_t.
5488     return SCS.getFromType()->isNullPtrType();
5489
5490   case ICK_Floating_Promotion:
5491   case ICK_Complex_Promotion:
5492   case ICK_Floating_Conversion:
5493   case ICK_Complex_Conversion:
5494   case ICK_Floating_Integral:
5495   case ICK_Compatible_Conversion:
5496   case ICK_Derived_To_Base:
5497   case ICK_Vector_Conversion:
5498   case ICK_Vector_Splat:
5499   case ICK_Complex_Real:
5500   case ICK_Block_Pointer_Conversion:
5501   case ICK_TransparentUnionConversion:
5502   case ICK_Writeback_Conversion:
5503   case ICK_Zero_Event_Conversion:
5504   case ICK_C_Only_Conversion:
5505   case ICK_Incompatible_Pointer_Conversion:
5506     return false;
5507
5508   case ICK_Lvalue_To_Rvalue:
5509   case ICK_Array_To_Pointer:
5510   case ICK_Function_To_Pointer:
5511     llvm_unreachable("found a first conversion kind in Second");
5512
5513   case ICK_Qualification:
5514     llvm_unreachable("found a third conversion kind in Second");
5515
5516   case ICK_Num_Conversion_Kinds:
5517     break;
5518   }
5519
5520   llvm_unreachable("unknown conversion kind");
5521 }
5522
5523 /// CheckConvertedConstantExpression - Check that the expression From is a
5524 /// converted constant expression of type T, perform the conversion and produce
5525 /// the converted expression, per C++11 [expr.const]p3.
5526 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5527                                                    QualType T, APValue &Value,
5528                                                    Sema::CCEKind CCE,
5529                                                    bool RequireInt) {
5530   assert(S.getLangOpts().CPlusPlus11 &&
5531          "converted constant expression outside C++11");
5532
5533   if (checkPlaceholderForOverload(S, From))
5534     return ExprError();
5535
5536   // C++1z [expr.const]p3:
5537   //  A converted constant expression of type T is an expression,
5538   //  implicitly converted to type T, where the converted
5539   //  expression is a constant expression and the implicit conversion
5540   //  sequence contains only [... list of conversions ...].
5541   // C++1z [stmt.if]p2:
5542   //  If the if statement is of the form if constexpr, the value of the
5543   //  condition shall be a contextually converted constant expression of type
5544   //  bool.
5545   ImplicitConversionSequence ICS =
5546       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5547           ? TryContextuallyConvertToBool(S, From)
5548           : TryCopyInitialization(S, From, T,
5549                                   /*SuppressUserConversions=*/false,
5550                                   /*InOverloadResolution=*/false,
5551                                   /*AllowObjCWritebackConversion=*/false,
5552                                   /*AllowExplicit=*/false);
5553   StandardConversionSequence *SCS = nullptr;
5554   switch (ICS.getKind()) {
5555   case ImplicitConversionSequence::StandardConversion:
5556     SCS = &ICS.Standard;
5557     break;
5558   case ImplicitConversionSequence::UserDefinedConversion:
5559     // We are converting to a non-class type, so the Before sequence
5560     // must be trivial.
5561     SCS = &ICS.UserDefined.After;
5562     break;
5563   case ImplicitConversionSequence::AmbiguousConversion:
5564   case ImplicitConversionSequence::BadConversion:
5565     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5566       return S.Diag(From->getBeginLoc(),
5567                     diag::err_typecheck_converted_constant_expression)
5568              << From->getType() << From->getSourceRange() << T;
5569     return ExprError();
5570
5571   case ImplicitConversionSequence::EllipsisConversion:
5572     llvm_unreachable("ellipsis conversion in converted constant expression");
5573   }
5574
5575   // Check that we would only use permitted conversions.
5576   if (!CheckConvertedConstantConversions(S, *SCS)) {
5577     return S.Diag(From->getBeginLoc(),
5578                   diag::err_typecheck_converted_constant_expression_disallowed)
5579            << From->getType() << From->getSourceRange() << T;
5580   }
5581   // [...] and where the reference binding (if any) binds directly.
5582   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5583     return S.Diag(From->getBeginLoc(),
5584                   diag::err_typecheck_converted_constant_expression_indirect)
5585            << From->getType() << From->getSourceRange() << T;
5586   }
5587
5588   ExprResult Result =
5589       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5590   if (Result.isInvalid())
5591     return Result;
5592
5593   // C++2a [intro.execution]p5:
5594   //   A full-expression is [...] a constant-expression [...]
5595   Result =
5596       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5597                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5598   if (Result.isInvalid())
5599     return Result;
5600
5601   // Check for a narrowing implicit conversion.
5602   APValue PreNarrowingValue;
5603   QualType PreNarrowingType;
5604   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5605                                 PreNarrowingType)) {
5606   case NK_Dependent_Narrowing:
5607     // Implicit conversion to a narrower type, but the expression is
5608     // value-dependent so we can't tell whether it's actually narrowing.
5609   case NK_Variable_Narrowing:
5610     // Implicit conversion to a narrower type, and the value is not a constant
5611     // expression. We'll diagnose this in a moment.
5612   case NK_Not_Narrowing:
5613     break;
5614
5615   case NK_Constant_Narrowing:
5616     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5617         << CCE << /*Constant*/ 1
5618         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5619     break;
5620
5621   case NK_Type_Narrowing:
5622     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5623         << CCE << /*Constant*/ 0 << From->getType() << T;
5624     break;
5625   }
5626
5627   if (Result.get()->isValueDependent()) {
5628     Value = APValue();
5629     return Result;
5630   }
5631
5632   // Check the expression is a constant expression.
5633   SmallVector<PartialDiagnosticAt, 8> Notes;
5634   Expr::EvalResult Eval;
5635   Eval.Diag = &Notes;
5636   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5637                                    ? Expr::EvaluateForMangling
5638                                    : Expr::EvaluateForCodeGen;
5639
5640   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5641       (RequireInt && !Eval.Val.isInt())) {
5642     // The expression can't be folded, so we can't keep it at this position in
5643     // the AST.
5644     Result = ExprError();
5645   } else {
5646     Value = Eval.Val;
5647
5648     if (Notes.empty()) {
5649       // It's a constant expression.
5650       return ConstantExpr::Create(S.Context, Result.get(), Value);
5651     }
5652   }
5653
5654   // It's not a constant expression. Produce an appropriate diagnostic.
5655   if (Notes.size() == 1 &&
5656       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5657     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5658   else {
5659     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5660         << CCE << From->getSourceRange();
5661     for (unsigned I = 0; I < Notes.size(); ++I)
5662       S.Diag(Notes[I].first, Notes[I].second);
5663   }
5664   return ExprError();
5665 }
5666
5667 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5668                                                   APValue &Value, CCEKind CCE) {
5669   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5670 }
5671
5672 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5673                                                   llvm::APSInt &Value,
5674                                                   CCEKind CCE) {
5675   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5676
5677   APValue V;
5678   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5679   if (!R.isInvalid() && !R.get()->isValueDependent())
5680     Value = V.getInt();
5681   return R;
5682 }
5683
5684
5685 /// dropPointerConversions - If the given standard conversion sequence
5686 /// involves any pointer conversions, remove them.  This may change
5687 /// the result type of the conversion sequence.
5688 static void dropPointerConversion(StandardConversionSequence &SCS) {
5689   if (SCS.Second == ICK_Pointer_Conversion) {
5690     SCS.Second = ICK_Identity;
5691     SCS.Third = ICK_Identity;
5692     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5693   }
5694 }
5695
5696 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5697 /// convert the expression From to an Objective-C pointer type.
5698 static ImplicitConversionSequence
5699 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5700   // Do an implicit conversion to 'id'.
5701   QualType Ty = S.Context.getObjCIdType();
5702   ImplicitConversionSequence ICS
5703     = TryImplicitConversion(S, From, Ty,
5704                             // FIXME: Are these flags correct?
5705                             /*SuppressUserConversions=*/false,
5706                             /*AllowExplicit=*/true,
5707                             /*InOverloadResolution=*/false,
5708                             /*CStyle=*/false,
5709                             /*AllowObjCWritebackConversion=*/false,
5710                             /*AllowObjCConversionOnExplicit=*/true);
5711
5712   // Strip off any final conversions to 'id'.
5713   switch (ICS.getKind()) {
5714   case ImplicitConversionSequence::BadConversion:
5715   case ImplicitConversionSequence::AmbiguousConversion:
5716   case ImplicitConversionSequence::EllipsisConversion:
5717     break;
5718
5719   case ImplicitConversionSequence::UserDefinedConversion:
5720     dropPointerConversion(ICS.UserDefined.After);
5721     break;
5722
5723   case ImplicitConversionSequence::StandardConversion:
5724     dropPointerConversion(ICS.Standard);
5725     break;
5726   }
5727
5728   return ICS;
5729 }
5730
5731 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5732 /// conversion of the expression From to an Objective-C pointer type.
5733 /// Returns a valid but null ExprResult if no conversion sequence exists.
5734 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5735   if (checkPlaceholderForOverload(*this, From))
5736     return ExprError();
5737
5738   QualType Ty = Context.getObjCIdType();
5739   ImplicitConversionSequence ICS =
5740     TryContextuallyConvertToObjCPointer(*this, From);
5741   if (!ICS.isBad())
5742     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5743   return ExprResult();
5744 }
5745
5746 /// Determine whether the provided type is an integral type, or an enumeration
5747 /// type of a permitted flavor.
5748 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5749   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5750                                  : T->isIntegralOrUnscopedEnumerationType();
5751 }
5752
5753 static ExprResult
5754 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5755                             Sema::ContextualImplicitConverter &Converter,
5756                             QualType T, UnresolvedSetImpl &ViableConversions) {
5757
5758   if (Converter.Suppress)
5759     return ExprError();
5760
5761   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5762   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5763     CXXConversionDecl *Conv =
5764         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5765     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5766     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5767   }
5768   return From;
5769 }
5770
5771 static bool
5772 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5773                            Sema::ContextualImplicitConverter &Converter,
5774                            QualType T, bool HadMultipleCandidates,
5775                            UnresolvedSetImpl &ExplicitConversions) {
5776   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5777     DeclAccessPair Found = ExplicitConversions[0];
5778     CXXConversionDecl *Conversion =
5779         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5780
5781     // The user probably meant to invoke the given explicit
5782     // conversion; use it.
5783     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5784     std::string TypeStr;
5785     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5786
5787     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5788         << FixItHint::CreateInsertion(From->getBeginLoc(),
5789                                       "static_cast<" + TypeStr + ">(")
5790         << FixItHint::CreateInsertion(
5791                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5792     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5793
5794     // If we aren't in a SFINAE context, build a call to the
5795     // explicit conversion function.
5796     if (SemaRef.isSFINAEContext())
5797       return true;
5798
5799     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5800     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5801                                                        HadMultipleCandidates);
5802     if (Result.isInvalid())
5803       return true;
5804     // Record usage of conversion in an implicit cast.
5805     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5806                                     CK_UserDefinedConversion, Result.get(),
5807                                     nullptr, Result.get()->getValueKind());
5808   }
5809   return false;
5810 }
5811
5812 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5813                              Sema::ContextualImplicitConverter &Converter,
5814                              QualType T, bool HadMultipleCandidates,
5815                              DeclAccessPair &Found) {
5816   CXXConversionDecl *Conversion =
5817       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5818   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5819
5820   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5821   if (!Converter.SuppressConversion) {
5822     if (SemaRef.isSFINAEContext())
5823       return true;
5824
5825     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5826         << From->getSourceRange();
5827   }
5828
5829   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5830                                                      HadMultipleCandidates);
5831   if (Result.isInvalid())
5832     return true;
5833   // Record usage of conversion in an implicit cast.
5834   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5835                                   CK_UserDefinedConversion, Result.get(),
5836                                   nullptr, Result.get()->getValueKind());
5837   return false;
5838 }
5839
5840 static ExprResult finishContextualImplicitConversion(
5841     Sema &SemaRef, SourceLocation Loc, Expr *From,
5842     Sema::ContextualImplicitConverter &Converter) {
5843   if (!Converter.match(From->getType()) && !Converter.Suppress)
5844     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5845         << From->getSourceRange();
5846
5847   return SemaRef.DefaultLvalueConversion(From);
5848 }
5849
5850 static void
5851 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5852                                   UnresolvedSetImpl &ViableConversions,
5853                                   OverloadCandidateSet &CandidateSet) {
5854   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5855     DeclAccessPair FoundDecl = ViableConversions[I];
5856     NamedDecl *D = FoundDecl.getDecl();
5857     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5858     if (isa<UsingShadowDecl>(D))
5859       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5860
5861     CXXConversionDecl *Conv;
5862     FunctionTemplateDecl *ConvTemplate;
5863     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5864       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5865     else
5866       Conv = cast<CXXConversionDecl>(D);
5867
5868     if (ConvTemplate)
5869       SemaRef.AddTemplateConversionCandidate(
5870           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5871           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5872     else
5873       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5874                                      ToType, CandidateSet,
5875                                      /*AllowObjCConversionOnExplicit=*/false,
5876                                      /*AllowExplicit*/ true);
5877   }
5878 }
5879
5880 /// Attempt to convert the given expression to a type which is accepted
5881 /// by the given converter.
5882 ///
5883 /// This routine will attempt to convert an expression of class type to a
5884 /// type accepted by the specified converter. In C++11 and before, the class
5885 /// must have a single non-explicit conversion function converting to a matching
5886 /// type. In C++1y, there can be multiple such conversion functions, but only
5887 /// one target type.
5888 ///
5889 /// \param Loc The source location of the construct that requires the
5890 /// conversion.
5891 ///
5892 /// \param From The expression we're converting from.
5893 ///
5894 /// \param Converter Used to control and diagnose the conversion process.
5895 ///
5896 /// \returns The expression, converted to an integral or enumeration type if
5897 /// successful.
5898 ExprResult Sema::PerformContextualImplicitConversion(
5899     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5900   // We can't perform any more checking for type-dependent expressions.
5901   if (From->isTypeDependent())
5902     return From;
5903
5904   // Process placeholders immediately.
5905   if (From->hasPlaceholderType()) {
5906     ExprResult result = CheckPlaceholderExpr(From);
5907     if (result.isInvalid())
5908       return result;
5909     From = result.get();
5910   }
5911
5912   // If the expression already has a matching type, we're golden.
5913   QualType T = From->getType();
5914   if (Converter.match(T))
5915     return DefaultLvalueConversion(From);
5916
5917   // FIXME: Check for missing '()' if T is a function type?
5918
5919   // We can only perform contextual implicit conversions on objects of class
5920   // type.
5921   const RecordType *RecordTy = T->getAs<RecordType>();
5922   if (!RecordTy || !getLangOpts().CPlusPlus) {
5923     if (!Converter.Suppress)
5924       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5925     return From;
5926   }
5927
5928   // We must have a complete class type.
5929   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5930     ContextualImplicitConverter &Converter;
5931     Expr *From;
5932
5933     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5934         : Converter(Converter), From(From) {}
5935
5936     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5937       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5938     }
5939   } IncompleteDiagnoser(Converter, From);
5940
5941   if (Converter.Suppress ? !isCompleteType(Loc, T)
5942                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5943     return From;
5944
5945   // Look for a conversion to an integral or enumeration type.
5946   UnresolvedSet<4>
5947       ViableConversions; // These are *potentially* viable in C++1y.
5948   UnresolvedSet<4> ExplicitConversions;
5949   const auto &Conversions =
5950       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5951
5952   bool HadMultipleCandidates =
5953       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5954
5955   // To check that there is only one target type, in C++1y:
5956   QualType ToType;
5957   bool HasUniqueTargetType = true;
5958
5959   // Collect explicit or viable (potentially in C++1y) conversions.
5960   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5961     NamedDecl *D = (*I)->getUnderlyingDecl();
5962     CXXConversionDecl *Conversion;
5963     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5964     if (ConvTemplate) {
5965       if (getLangOpts().CPlusPlus14)
5966         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5967       else
5968         continue; // C++11 does not consider conversion operator templates(?).
5969     } else
5970       Conversion = cast<CXXConversionDecl>(D);
5971
5972     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5973            "Conversion operator templates are considered potentially "
5974            "viable in C++1y");
5975
5976     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5977     if (Converter.match(CurToType) || ConvTemplate) {
5978
5979       if (Conversion->isExplicit()) {
5980         // FIXME: For C++1y, do we need this restriction?
5981         // cf. diagnoseNoViableConversion()
5982         if (!ConvTemplate)
5983           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5984       } else {
5985         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5986           if (ToType.isNull())
5987             ToType = CurToType.getUnqualifiedType();
5988           else if (HasUniqueTargetType &&
5989                    (CurToType.getUnqualifiedType() != ToType))
5990             HasUniqueTargetType = false;
5991         }
5992         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5993       }
5994     }
5995   }
5996
5997   if (getLangOpts().CPlusPlus14) {
5998     // C++1y [conv]p6:
5999     // ... An expression e of class type E appearing in such a context
6000     // is said to be contextually implicitly converted to a specified
6001     // type T and is well-formed if and only if e can be implicitly
6002     // converted to a type T that is determined as follows: E is searched
6003     // for conversion functions whose return type is cv T or reference to
6004     // cv T such that T is allowed by the context. There shall be
6005     // exactly one such T.
6006
6007     // If no unique T is found:
6008     if (ToType.isNull()) {
6009       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6010                                      HadMultipleCandidates,
6011                                      ExplicitConversions))
6012         return ExprError();
6013       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6014     }
6015
6016     // If more than one unique Ts are found:
6017     if (!HasUniqueTargetType)
6018       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6019                                          ViableConversions);
6020
6021     // If one unique T is found:
6022     // First, build a candidate set from the previously recorded
6023     // potentially viable conversions.
6024     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6025     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6026                                       CandidateSet);
6027
6028     // Then, perform overload resolution over the candidate set.
6029     OverloadCandidateSet::iterator Best;
6030     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6031     case OR_Success: {
6032       // Apply this conversion.
6033       DeclAccessPair Found =
6034           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6035       if (recordConversion(*this, Loc, From, Converter, T,
6036                            HadMultipleCandidates, Found))
6037         return ExprError();
6038       break;
6039     }
6040     case OR_Ambiguous:
6041       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6042                                          ViableConversions);
6043     case OR_No_Viable_Function:
6044       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6045                                      HadMultipleCandidates,
6046                                      ExplicitConversions))
6047         return ExprError();
6048       LLVM_FALLTHROUGH;
6049     case OR_Deleted:
6050       // We'll complain below about a non-integral condition type.
6051       break;
6052     }
6053   } else {
6054     switch (ViableConversions.size()) {
6055     case 0: {
6056       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6057                                      HadMultipleCandidates,
6058                                      ExplicitConversions))
6059         return ExprError();
6060
6061       // We'll complain below about a non-integral condition type.
6062       break;
6063     }
6064     case 1: {
6065       // Apply this conversion.
6066       DeclAccessPair Found = ViableConversions[0];
6067       if (recordConversion(*this, Loc, From, Converter, T,
6068                            HadMultipleCandidates, Found))
6069         return ExprError();
6070       break;
6071     }
6072     default:
6073       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6074                                          ViableConversions);
6075     }
6076   }
6077
6078   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6079 }
6080
6081 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6082 /// an acceptable non-member overloaded operator for a call whose
6083 /// arguments have types T1 (and, if non-empty, T2). This routine
6084 /// implements the check in C++ [over.match.oper]p3b2 concerning
6085 /// enumeration types.
6086 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6087                                                    FunctionDecl *Fn,
6088                                                    ArrayRef<Expr *> Args) {
6089   QualType T1 = Args[0]->getType();
6090   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6091
6092   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6093     return true;
6094
6095   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6096     return true;
6097
6098   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6099   if (Proto->getNumParams() < 1)
6100     return false;
6101
6102   if (T1->isEnumeralType()) {
6103     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6104     if (Context.hasSameUnqualifiedType(T1, ArgType))
6105       return true;
6106   }
6107
6108   if (Proto->getNumParams() < 2)
6109     return false;
6110
6111   if (!T2.isNull() && T2->isEnumeralType()) {
6112     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6113     if (Context.hasSameUnqualifiedType(T2, ArgType))
6114       return true;
6115   }
6116
6117   return false;
6118 }
6119
6120 /// AddOverloadCandidate - Adds the given function to the set of
6121 /// candidate functions, using the given function call arguments.  If
6122 /// @p SuppressUserConversions, then don't allow user-defined
6123 /// conversions via constructors or conversion operators.
6124 ///
6125 /// \param PartialOverloading true if we are performing "partial" overloading
6126 /// based on an incomplete set of function arguments. This feature is used by
6127 /// code completion.
6128 void Sema::AddOverloadCandidate(
6129     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6130     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6131     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6132     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6133     OverloadCandidateParamOrder PO) {
6134   const FunctionProtoType *Proto
6135     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6136   assert(Proto && "Functions without a prototype cannot be overloaded");
6137   assert(!Function->getDescribedFunctionTemplate() &&
6138          "Use AddTemplateOverloadCandidate for function templates");
6139
6140   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6141     if (!isa<CXXConstructorDecl>(Method)) {
6142       // If we get here, it's because we're calling a member function
6143       // that is named without a member access expression (e.g.,
6144       // "this->f") that was either written explicitly or created
6145       // implicitly. This can happen with a qualified call to a member
6146       // function, e.g., X::f(). We use an empty type for the implied
6147       // object argument (C++ [over.call.func]p3), and the acting context
6148       // is irrelevant.
6149       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6150                          Expr::Classification::makeSimpleLValue(), Args,
6151                          CandidateSet, SuppressUserConversions,
6152                          PartialOverloading, EarlyConversions, PO);
6153       return;
6154     }
6155     // We treat a constructor like a non-member function, since its object
6156     // argument doesn't participate in overload resolution.
6157   }
6158
6159   if (!CandidateSet.isNewCandidate(Function, PO))
6160     return;
6161
6162   // C++11 [class.copy]p11: [DR1402]
6163   //   A defaulted move constructor that is defined as deleted is ignored by
6164   //   overload resolution.
6165   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6166   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6167       Constructor->isMoveConstructor())
6168     return;
6169
6170   // Overload resolution is always an unevaluated context.
6171   EnterExpressionEvaluationContext Unevaluated(
6172       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6173
6174   // C++ [over.match.oper]p3:
6175   //   if no operand has a class type, only those non-member functions in the
6176   //   lookup set that have a first parameter of type T1 or "reference to
6177   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6178   //   is a right operand) a second parameter of type T2 or "reference to
6179   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6180   //   candidate functions.
6181   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6182       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6183     return;
6184
6185   // Add this candidate
6186   OverloadCandidate &Candidate =
6187       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6188   Candidate.FoundDecl = FoundDecl;
6189   Candidate.Function = Function;
6190   Candidate.Viable = true;
6191   Candidate.RewriteKind =
6192       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6193   Candidate.IsSurrogate = false;
6194   Candidate.IsADLCandidate = IsADLCandidate;
6195   Candidate.IgnoreObjectArgument = false;
6196   Candidate.ExplicitCallArguments = Args.size();
6197
6198   // Explicit functions are not actually candidates at all if we're not
6199   // allowing them in this context, but keep them around so we can point
6200   // to them in diagnostics.
6201   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6202     Candidate.Viable = false;
6203     Candidate.FailureKind = ovl_fail_explicit;
6204     return;
6205   }
6206
6207   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6208       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6209     Candidate.Viable = false;
6210     Candidate.FailureKind = ovl_non_default_multiversion_function;
6211     return;
6212   }
6213
6214   if (Constructor) {
6215     // C++ [class.copy]p3:
6216     //   A member function template is never instantiated to perform the copy
6217     //   of a class object to an object of its class type.
6218     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6219     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6220         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6221          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6222                        ClassType))) {
6223       Candidate.Viable = false;
6224       Candidate.FailureKind = ovl_fail_illegal_constructor;
6225       return;
6226     }
6227
6228     // C++ [over.match.funcs]p8: (proposed DR resolution)
6229     //   A constructor inherited from class type C that has a first parameter
6230     //   of type "reference to P" (including such a constructor instantiated
6231     //   from a template) is excluded from the set of candidate functions when
6232     //   constructing an object of type cv D if the argument list has exactly
6233     //   one argument and D is reference-related to P and P is reference-related
6234     //   to C.
6235     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6236     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6237         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6238       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6239       QualType C = Context.getRecordType(Constructor->getParent());
6240       QualType D = Context.getRecordType(Shadow->getParent());
6241       SourceLocation Loc = Args.front()->getExprLoc();
6242       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6243           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6244         Candidate.Viable = false;
6245         Candidate.FailureKind = ovl_fail_inhctor_slice;
6246         return;
6247       }
6248     }
6249
6250     // Check that the constructor is capable of constructing an object in the
6251     // destination address space.
6252     if (!Qualifiers::isAddressSpaceSupersetOf(
6253             Constructor->getMethodQualifiers().getAddressSpace(),
6254             CandidateSet.getDestAS())) {
6255       Candidate.Viable = false;
6256       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6257     }
6258   }
6259
6260   unsigned NumParams = Proto->getNumParams();
6261
6262   // (C++ 13.3.2p2): A candidate function having fewer than m
6263   // parameters is viable only if it has an ellipsis in its parameter
6264   // list (8.3.5).
6265   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6266       !Proto->isVariadic()) {
6267     Candidate.Viable = false;
6268     Candidate.FailureKind = ovl_fail_too_many_arguments;
6269     return;
6270   }
6271
6272   // (C++ 13.3.2p2): A candidate function having more than m parameters
6273   // is viable only if the (m+1)st parameter has a default argument
6274   // (8.3.6). For the purposes of overload resolution, the
6275   // parameter list is truncated on the right, so that there are
6276   // exactly m parameters.
6277   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6278   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6279     // Not enough arguments.
6280     Candidate.Viable = false;
6281     Candidate.FailureKind = ovl_fail_too_few_arguments;
6282     return;
6283   }
6284
6285   // (CUDA B.1): Check for invalid calls between targets.
6286   if (getLangOpts().CUDA)
6287     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6288       // Skip the check for callers that are implicit members, because in this
6289       // case we may not yet know what the member's target is; the target is
6290       // inferred for the member automatically, based on the bases and fields of
6291       // the class.
6292       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6293         Candidate.Viable = false;
6294         Candidate.FailureKind = ovl_fail_bad_target;
6295         return;
6296       }
6297
6298   if (Function->getTrailingRequiresClause()) {
6299     ConstraintSatisfaction Satisfaction;
6300     if (CheckFunctionConstraints(Function, Satisfaction) ||
6301         !Satisfaction.IsSatisfied) {
6302       Candidate.Viable = false;
6303       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6304       return;
6305     }
6306   }
6307
6308   // Determine the implicit conversion sequences for each of the
6309   // arguments.
6310   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6311     unsigned ConvIdx =
6312         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6313     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6314       // We already formed a conversion sequence for this parameter during
6315       // template argument deduction.
6316     } else if (ArgIdx < NumParams) {
6317       // (C++ 13.3.2p3): for F to be a viable function, there shall
6318       // exist for each argument an implicit conversion sequence
6319       // (13.3.3.1) that converts that argument to the corresponding
6320       // parameter of F.
6321       QualType ParamType = Proto->getParamType(ArgIdx);
6322       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6323           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6324           /*InOverloadResolution=*/true,
6325           /*AllowObjCWritebackConversion=*/
6326           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6327       if (Candidate.Conversions[ConvIdx].isBad()) {
6328         Candidate.Viable = false;
6329         Candidate.FailureKind = ovl_fail_bad_conversion;
6330         return;
6331       }
6332     } else {
6333       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6334       // argument for which there is no corresponding parameter is
6335       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6336       Candidate.Conversions[ConvIdx].setEllipsis();
6337     }
6338   }
6339
6340   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6341     Candidate.Viable = false;
6342     Candidate.FailureKind = ovl_fail_enable_if;
6343     Candidate.DeductionFailure.Data = FailedAttr;
6344     return;
6345   }
6346
6347   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6348     Candidate.Viable = false;
6349     Candidate.FailureKind = ovl_fail_ext_disabled;
6350     return;
6351   }
6352 }
6353
6354 ObjCMethodDecl *
6355 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6356                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6357   if (Methods.size() <= 1)
6358     return nullptr;
6359
6360   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6361     bool Match = true;
6362     ObjCMethodDecl *Method = Methods[b];
6363     unsigned NumNamedArgs = Sel.getNumArgs();
6364     // Method might have more arguments than selector indicates. This is due
6365     // to addition of c-style arguments in method.
6366     if (Method->param_size() > NumNamedArgs)
6367       NumNamedArgs = Method->param_size();
6368     if (Args.size() < NumNamedArgs)
6369       continue;
6370
6371     for (unsigned i = 0; i < NumNamedArgs; i++) {
6372       // We can't do any type-checking on a type-dependent argument.
6373       if (Args[i]->isTypeDependent()) {
6374         Match = false;
6375         break;
6376       }
6377
6378       ParmVarDecl *param = Method->parameters()[i];
6379       Expr *argExpr = Args[i];
6380       assert(argExpr && "SelectBestMethod(): missing expression");
6381
6382       // Strip the unbridged-cast placeholder expression off unless it's
6383       // a consumed argument.
6384       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6385           !param->hasAttr<CFConsumedAttr>())
6386         argExpr = stripARCUnbridgedCast(argExpr);
6387
6388       // If the parameter is __unknown_anytype, move on to the next method.
6389       if (param->getType() == Context.UnknownAnyTy) {
6390         Match = false;
6391         break;
6392       }
6393
6394       ImplicitConversionSequence ConversionState
6395         = TryCopyInitialization(*this, argExpr, param->getType(),
6396                                 /*SuppressUserConversions*/false,
6397                                 /*InOverloadResolution=*/true,
6398                                 /*AllowObjCWritebackConversion=*/
6399                                 getLangOpts().ObjCAutoRefCount,
6400                                 /*AllowExplicit*/false);
6401       // This function looks for a reasonably-exact match, so we consider
6402       // incompatible pointer conversions to be a failure here.
6403       if (ConversionState.isBad() ||
6404           (ConversionState.isStandard() &&
6405            ConversionState.Standard.Second ==
6406                ICK_Incompatible_Pointer_Conversion)) {
6407         Match = false;
6408         break;
6409       }
6410     }
6411     // Promote additional arguments to variadic methods.
6412     if (Match && Method->isVariadic()) {
6413       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6414         if (Args[i]->isTypeDependent()) {
6415           Match = false;
6416           break;
6417         }
6418         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6419                                                           nullptr);
6420         if (Arg.isInvalid()) {
6421           Match = false;
6422           break;
6423         }
6424       }
6425     } else {
6426       // Check for extra arguments to non-variadic methods.
6427       if (Args.size() != NumNamedArgs)
6428         Match = false;
6429       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6430         // Special case when selectors have no argument. In this case, select
6431         // one with the most general result type of 'id'.
6432         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6433           QualType ReturnT = Methods[b]->getReturnType();
6434           if (ReturnT->isObjCIdType())
6435             return Methods[b];
6436         }
6437       }
6438     }
6439
6440     if (Match)
6441       return Method;
6442   }
6443   return nullptr;
6444 }
6445
6446 static bool
6447 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6448                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6449                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6450                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6451   if (ThisArg) {
6452     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6453     assert(!isa<CXXConstructorDecl>(Method) &&
6454            "Shouldn't have `this` for ctors!");
6455     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6456     ExprResult R = S.PerformObjectArgumentInitialization(
6457         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6458     if (R.isInvalid())
6459       return false;
6460     ConvertedThis = R.get();
6461   } else {
6462     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6463       (void)MD;
6464       assert((MissingImplicitThis || MD->isStatic() ||
6465               isa<CXXConstructorDecl>(MD)) &&
6466              "Expected `this` for non-ctor instance methods");
6467     }
6468     ConvertedThis = nullptr;
6469   }
6470
6471   // Ignore any variadic arguments. Converting them is pointless, since the
6472   // user can't refer to them in the function condition.
6473   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6474
6475   // Convert the arguments.
6476   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6477     ExprResult R;
6478     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6479                                         S.Context, Function->getParamDecl(I)),
6480                                     SourceLocation(), Args[I]);
6481
6482     if (R.isInvalid())
6483       return false;
6484
6485     ConvertedArgs.push_back(R.get());
6486   }
6487
6488   if (Trap.hasErrorOccurred())
6489     return false;
6490
6491   // Push default arguments if needed.
6492   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6493     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6494       ParmVarDecl *P = Function->getParamDecl(i);
6495       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6496                          ? P->getUninstantiatedDefaultArg()
6497                          : P->getDefaultArg();
6498       // This can only happen in code completion, i.e. when PartialOverloading
6499       // is true.
6500       if (!DefArg)
6501         return false;
6502       ExprResult R =
6503           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6504                                           S.Context, Function->getParamDecl(i)),
6505                                       SourceLocation(), DefArg);
6506       if (R.isInvalid())
6507         return false;
6508       ConvertedArgs.push_back(R.get());
6509     }
6510
6511     if (Trap.hasErrorOccurred())
6512       return false;
6513   }
6514   return true;
6515 }
6516
6517 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6518                                   bool MissingImplicitThis) {
6519   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6520   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6521     return nullptr;
6522
6523   SFINAETrap Trap(*this);
6524   SmallVector<Expr *, 16> ConvertedArgs;
6525   // FIXME: We should look into making enable_if late-parsed.
6526   Expr *DiscardedThis;
6527   if (!convertArgsForAvailabilityChecks(
6528           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6529           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6530     return *EnableIfAttrs.begin();
6531
6532   for (auto *EIA : EnableIfAttrs) {
6533     APValue Result;
6534     // FIXME: This doesn't consider value-dependent cases, because doing so is
6535     // very difficult. Ideally, we should handle them more gracefully.
6536     if (EIA->getCond()->isValueDependent() ||
6537         !EIA->getCond()->EvaluateWithSubstitution(
6538             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6539       return EIA;
6540
6541     if (!Result.isInt() || !Result.getInt().getBoolValue())
6542       return EIA;
6543   }
6544   return nullptr;
6545 }
6546
6547 template <typename CheckFn>
6548 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6549                                         bool ArgDependent, SourceLocation Loc,
6550                                         CheckFn &&IsSuccessful) {
6551   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6552   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6553     if (ArgDependent == DIA->getArgDependent())
6554       Attrs.push_back(DIA);
6555   }
6556
6557   // Common case: No diagnose_if attributes, so we can quit early.
6558   if (Attrs.empty())
6559     return false;
6560
6561   auto WarningBegin = std::stable_partition(
6562       Attrs.begin(), Attrs.end(),
6563       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6564
6565   // Note that diagnose_if attributes are late-parsed, so they appear in the
6566   // correct order (unlike enable_if attributes).
6567   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6568                                IsSuccessful);
6569   if (ErrAttr != WarningBegin) {
6570     const DiagnoseIfAttr *DIA = *ErrAttr;
6571     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6572     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6573         << DIA->getParent() << DIA->getCond()->getSourceRange();
6574     return true;
6575   }
6576
6577   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6578     if (IsSuccessful(DIA)) {
6579       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6580       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6581           << DIA->getParent() << DIA->getCond()->getSourceRange();
6582     }
6583
6584   return false;
6585 }
6586
6587 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6588                                                const Expr *ThisArg,
6589                                                ArrayRef<const Expr *> Args,
6590                                                SourceLocation Loc) {
6591   return diagnoseDiagnoseIfAttrsWith(
6592       *this, Function, /*ArgDependent=*/true, Loc,
6593       [&](const DiagnoseIfAttr *DIA) {
6594         APValue Result;
6595         // It's sane to use the same Args for any redecl of this function, since
6596         // EvaluateWithSubstitution only cares about the position of each
6597         // argument in the arg list, not the ParmVarDecl* it maps to.
6598         if (!DIA->getCond()->EvaluateWithSubstitution(
6599                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6600           return false;
6601         return Result.isInt() && Result.getInt().getBoolValue();
6602       });
6603 }
6604
6605 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6606                                                  SourceLocation Loc) {
6607   return diagnoseDiagnoseIfAttrsWith(
6608       *this, ND, /*ArgDependent=*/false, Loc,
6609       [&](const DiagnoseIfAttr *DIA) {
6610         bool Result;
6611         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6612                Result;
6613       });
6614 }
6615
6616 /// Add all of the function declarations in the given function set to
6617 /// the overload candidate set.
6618 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6619                                  ArrayRef<Expr *> Args,
6620                                  OverloadCandidateSet &CandidateSet,
6621                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6622                                  bool SuppressUserConversions,
6623                                  bool PartialOverloading,
6624                                  bool FirstArgumentIsBase) {
6625   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6626     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6627     ArrayRef<Expr *> FunctionArgs = Args;
6628
6629     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6630     FunctionDecl *FD =
6631         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6632
6633     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6634       QualType ObjectType;
6635       Expr::Classification ObjectClassification;
6636       if (Args.size() > 0) {
6637         if (Expr *E = Args[0]) {
6638           // Use the explicit base to restrict the lookup:
6639           ObjectType = E->getType();
6640           // Pointers in the object arguments are implicitly dereferenced, so we
6641           // always classify them as l-values.
6642           if (!ObjectType.isNull() && ObjectType->isPointerType())
6643             ObjectClassification = Expr::Classification::makeSimpleLValue();
6644           else
6645             ObjectClassification = E->Classify(Context);
6646         } // .. else there is an implicit base.
6647         FunctionArgs = Args.slice(1);
6648       }
6649       if (FunTmpl) {
6650         AddMethodTemplateCandidate(
6651             FunTmpl, F.getPair(),
6652             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6653             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6654             FunctionArgs, CandidateSet, SuppressUserConversions,
6655             PartialOverloading);
6656       } else {
6657         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6658                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6659                            ObjectClassification, FunctionArgs, CandidateSet,
6660                            SuppressUserConversions, PartialOverloading);
6661       }
6662     } else {
6663       // This branch handles both standalone functions and static methods.
6664
6665       // Slice the first argument (which is the base) when we access
6666       // static method as non-static.
6667       if (Args.size() > 0 &&
6668           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6669                         !isa<CXXConstructorDecl>(FD)))) {
6670         assert(cast<CXXMethodDecl>(FD)->isStatic());
6671         FunctionArgs = Args.slice(1);
6672       }
6673       if (FunTmpl) {
6674         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6675                                      ExplicitTemplateArgs, FunctionArgs,
6676                                      CandidateSet, SuppressUserConversions,
6677                                      PartialOverloading);
6678       } else {
6679         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6680                              SuppressUserConversions, PartialOverloading);
6681       }
6682     }
6683   }
6684 }
6685
6686 /// AddMethodCandidate - Adds a named decl (which is some kind of
6687 /// method) as a method candidate to the given overload set.
6688 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6689                               Expr::Classification ObjectClassification,
6690                               ArrayRef<Expr *> Args,
6691                               OverloadCandidateSet &CandidateSet,
6692                               bool SuppressUserConversions,
6693                               OverloadCandidateParamOrder PO) {
6694   NamedDecl *Decl = FoundDecl.getDecl();
6695   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6696
6697   if (isa<UsingShadowDecl>(Decl))
6698     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6699
6700   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6701     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6702            "Expected a member function template");
6703     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6704                                /*ExplicitArgs*/ nullptr, ObjectType,
6705                                ObjectClassification, Args, CandidateSet,
6706                                SuppressUserConversions, false, PO);
6707   } else {
6708     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6709                        ObjectType, ObjectClassification, Args, CandidateSet,
6710                        SuppressUserConversions, false, None, PO);
6711   }
6712 }
6713
6714 /// AddMethodCandidate - Adds the given C++ member function to the set
6715 /// of candidate functions, using the given function call arguments
6716 /// and the object argument (@c Object). For example, in a call
6717 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6718 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6719 /// allow user-defined conversions via constructors or conversion
6720 /// operators.
6721 void
6722 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6723                          CXXRecordDecl *ActingContext, QualType ObjectType,
6724                          Expr::Classification ObjectClassification,
6725                          ArrayRef<Expr *> Args,
6726                          OverloadCandidateSet &CandidateSet,
6727                          bool SuppressUserConversions,
6728                          bool PartialOverloading,
6729                          ConversionSequenceList EarlyConversions,
6730                          OverloadCandidateParamOrder PO) {
6731   const FunctionProtoType *Proto
6732     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6733   assert(Proto && "Methods without a prototype cannot be overloaded");
6734   assert(!isa<CXXConstructorDecl>(Method) &&
6735          "Use AddOverloadCandidate for constructors");
6736
6737   if (!CandidateSet.isNewCandidate(Method, PO))
6738     return;
6739
6740   // C++11 [class.copy]p23: [DR1402]
6741   //   A defaulted move assignment operator that is defined as deleted is
6742   //   ignored by overload resolution.
6743   if (Method->isDefaulted() && Method->isDeleted() &&
6744       Method->isMoveAssignmentOperator())
6745     return;
6746
6747   // Overload resolution is always an unevaluated context.
6748   EnterExpressionEvaluationContext Unevaluated(
6749       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6750
6751   // Add this candidate
6752   OverloadCandidate &Candidate =
6753       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6754   Candidate.FoundDecl = FoundDecl;
6755   Candidate.Function = Method;
6756   Candidate.RewriteKind =
6757       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6758   Candidate.IsSurrogate = false;
6759   Candidate.IgnoreObjectArgument = false;
6760   Candidate.ExplicitCallArguments = Args.size();
6761
6762   unsigned NumParams = Proto->getNumParams();
6763
6764   // (C++ 13.3.2p2): A candidate function having fewer than m
6765   // parameters is viable only if it has an ellipsis in its parameter
6766   // list (8.3.5).
6767   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6768       !Proto->isVariadic()) {
6769     Candidate.Viable = false;
6770     Candidate.FailureKind = ovl_fail_too_many_arguments;
6771     return;
6772   }
6773
6774   // (C++ 13.3.2p2): A candidate function having more than m parameters
6775   // is viable only if the (m+1)st parameter has a default argument
6776   // (8.3.6). For the purposes of overload resolution, the
6777   // parameter list is truncated on the right, so that there are
6778   // exactly m parameters.
6779   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6780   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6781     // Not enough arguments.
6782     Candidate.Viable = false;
6783     Candidate.FailureKind = ovl_fail_too_few_arguments;
6784     return;
6785   }
6786
6787   Candidate.Viable = true;
6788
6789   if (Method->isStatic() || ObjectType.isNull())
6790     // The implicit object argument is ignored.
6791     Candidate.IgnoreObjectArgument = true;
6792   else {
6793     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6794     // Determine the implicit conversion sequence for the object
6795     // parameter.
6796     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6797         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6798         Method, ActingContext);
6799     if (Candidate.Conversions[ConvIdx].isBad()) {
6800       Candidate.Viable = false;
6801       Candidate.FailureKind = ovl_fail_bad_conversion;
6802       return;
6803     }
6804   }
6805
6806   // (CUDA B.1): Check for invalid calls between targets.
6807   if (getLangOpts().CUDA)
6808     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6809       if (!IsAllowedCUDACall(Caller, Method)) {
6810         Candidate.Viable = false;
6811         Candidate.FailureKind = ovl_fail_bad_target;
6812         return;
6813       }
6814
6815   if (Method->getTrailingRequiresClause()) {
6816     ConstraintSatisfaction Satisfaction;
6817     if (CheckFunctionConstraints(Method, Satisfaction) ||
6818         !Satisfaction.IsSatisfied) {
6819       Candidate.Viable = false;
6820       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6821       return;
6822     }
6823   }
6824
6825   // Determine the implicit conversion sequences for each of the
6826   // arguments.
6827   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6828     unsigned ConvIdx =
6829         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6830     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6831       // We already formed a conversion sequence for this parameter during
6832       // template argument deduction.
6833     } else if (ArgIdx < NumParams) {
6834       // (C++ 13.3.2p3): for F to be a viable function, there shall
6835       // exist for each argument an implicit conversion sequence
6836       // (13.3.3.1) that converts that argument to the corresponding
6837       // parameter of F.
6838       QualType ParamType = Proto->getParamType(ArgIdx);
6839       Candidate.Conversions[ConvIdx]
6840         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6841                                 SuppressUserConversions,
6842                                 /*InOverloadResolution=*/true,
6843                                 /*AllowObjCWritebackConversion=*/
6844                                   getLangOpts().ObjCAutoRefCount);
6845       if (Candidate.Conversions[ConvIdx].isBad()) {
6846         Candidate.Viable = false;
6847         Candidate.FailureKind = ovl_fail_bad_conversion;
6848         return;
6849       }
6850     } else {
6851       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6852       // argument for which there is no corresponding parameter is
6853       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6854       Candidate.Conversions[ConvIdx].setEllipsis();
6855     }
6856   }
6857
6858   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6859     Candidate.Viable = false;
6860     Candidate.FailureKind = ovl_fail_enable_if;
6861     Candidate.DeductionFailure.Data = FailedAttr;
6862     return;
6863   }
6864
6865   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6866       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6867     Candidate.Viable = false;
6868     Candidate.FailureKind = ovl_non_default_multiversion_function;
6869   }
6870 }
6871
6872 /// Add a C++ member function template as a candidate to the candidate
6873 /// set, using template argument deduction to produce an appropriate member
6874 /// function template specialization.
6875 void Sema::AddMethodTemplateCandidate(
6876     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6877     CXXRecordDecl *ActingContext,
6878     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6879     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6880     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6881     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6882   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6883     return;
6884
6885   // C++ [over.match.funcs]p7:
6886   //   In each case where a candidate is a function template, candidate
6887   //   function template specializations are generated using template argument
6888   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6889   //   candidate functions in the usual way.113) A given name can refer to one
6890   //   or more function templates and also to a set of overloaded non-template
6891   //   functions. In such a case, the candidate functions generated from each
6892   //   function template are combined with the set of non-template candidate
6893   //   functions.
6894   TemplateDeductionInfo Info(CandidateSet.getLocation());
6895   FunctionDecl *Specialization = nullptr;
6896   ConversionSequenceList Conversions;
6897   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6898           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6899           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6900             return CheckNonDependentConversions(
6901                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6902                 SuppressUserConversions, ActingContext, ObjectType,
6903                 ObjectClassification, PO);
6904           })) {
6905     OverloadCandidate &Candidate =
6906         CandidateSet.addCandidate(Conversions.size(), Conversions);
6907     Candidate.FoundDecl = FoundDecl;
6908     Candidate.Function = MethodTmpl->getTemplatedDecl();
6909     Candidate.Viable = false;
6910     Candidate.RewriteKind =
6911       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6912     Candidate.IsSurrogate = false;
6913     Candidate.IgnoreObjectArgument =
6914         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6915         ObjectType.isNull();
6916     Candidate.ExplicitCallArguments = Args.size();
6917     if (Result == TDK_NonDependentConversionFailure)
6918       Candidate.FailureKind = ovl_fail_bad_conversion;
6919     else {
6920       Candidate.FailureKind = ovl_fail_bad_deduction;
6921       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6922                                                             Info);
6923     }
6924     return;
6925   }
6926
6927   // Add the function template specialization produced by template argument
6928   // deduction as a candidate.
6929   assert(Specialization && "Missing member function template specialization?");
6930   assert(isa<CXXMethodDecl>(Specialization) &&
6931          "Specialization is not a member function?");
6932   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6933                      ActingContext, ObjectType, ObjectClassification, Args,
6934                      CandidateSet, SuppressUserConversions, PartialOverloading,
6935                      Conversions, PO);
6936 }
6937
6938 /// Determine whether a given function template has a simple explicit specifier
6939 /// or a non-value-dependent explicit-specification that evaluates to true.
6940 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6941   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6942 }
6943
6944 /// Add a C++ function template specialization as a candidate
6945 /// in the candidate set, using template argument deduction to produce
6946 /// an appropriate function template specialization.
6947 void Sema::AddTemplateOverloadCandidate(
6948     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6949     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6950     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6951     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6952     OverloadCandidateParamOrder PO) {
6953   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6954     return;
6955
6956   // If the function template has a non-dependent explicit specification,
6957   // exclude it now if appropriate; we are not permitted to perform deduction
6958   // and substitution in this case.
6959   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6960     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6961     Candidate.FoundDecl = FoundDecl;
6962     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6963     Candidate.Viable = false;
6964     Candidate.FailureKind = ovl_fail_explicit;
6965     return;
6966   }
6967
6968   // C++ [over.match.funcs]p7:
6969   //   In each case where a candidate is a function template, candidate
6970   //   function template specializations are generated using template argument
6971   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6972   //   candidate functions in the usual way.113) A given name can refer to one
6973   //   or more function templates and also to a set of overloaded non-template
6974   //   functions. In such a case, the candidate functions generated from each
6975   //   function template are combined with the set of non-template candidate
6976   //   functions.
6977   TemplateDeductionInfo Info(CandidateSet.getLocation());
6978   FunctionDecl *Specialization = nullptr;
6979   ConversionSequenceList Conversions;
6980   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6981           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6982           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6983             return CheckNonDependentConversions(
6984                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6985                 SuppressUserConversions, nullptr, QualType(), {}, PO);
6986           })) {
6987     OverloadCandidate &Candidate =
6988         CandidateSet.addCandidate(Conversions.size(), Conversions);
6989     Candidate.FoundDecl = FoundDecl;
6990     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6991     Candidate.Viable = false;
6992     Candidate.RewriteKind =
6993       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6994     Candidate.IsSurrogate = false;
6995     Candidate.IsADLCandidate = IsADLCandidate;
6996     // Ignore the object argument if there is one, since we don't have an object
6997     // type.
6998     Candidate.IgnoreObjectArgument =
6999         isa<CXXMethodDecl>(Candidate.Function) &&
7000         !isa<CXXConstructorDecl>(Candidate.Function);
7001     Candidate.ExplicitCallArguments = Args.size();
7002     if (Result == TDK_NonDependentConversionFailure)
7003       Candidate.FailureKind = ovl_fail_bad_conversion;
7004     else {
7005       Candidate.FailureKind = ovl_fail_bad_deduction;
7006       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7007                                                             Info);
7008     }
7009     return;
7010   }
7011
7012   // Add the function template specialization produced by template argument
7013   // deduction as a candidate.
7014   assert(Specialization && "Missing function template specialization?");
7015   AddOverloadCandidate(
7016       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7017       PartialOverloading, AllowExplicit,
7018       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7019 }
7020
7021 /// Check that implicit conversion sequences can be formed for each argument
7022 /// whose corresponding parameter has a non-dependent type, per DR1391's
7023 /// [temp.deduct.call]p10.
7024 bool Sema::CheckNonDependentConversions(
7025     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7026     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7027     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7028     CXXRecordDecl *ActingContext, QualType ObjectType,
7029     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7030   // FIXME: The cases in which we allow explicit conversions for constructor
7031   // arguments never consider calling a constructor template. It's not clear
7032   // that is correct.
7033   const bool AllowExplicit = false;
7034
7035   auto *FD = FunctionTemplate->getTemplatedDecl();
7036   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7037   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7038   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7039
7040   Conversions =
7041       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7042
7043   // Overload resolution is always an unevaluated context.
7044   EnterExpressionEvaluationContext Unevaluated(
7045       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7046
7047   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7048   // require that, but this check should never result in a hard error, and
7049   // overload resolution is permitted to sidestep instantiations.
7050   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7051       !ObjectType.isNull()) {
7052     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7053     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7054         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7055         Method, ActingContext);
7056     if (Conversions[ConvIdx].isBad())
7057       return true;
7058   }
7059
7060   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7061        ++I) {
7062     QualType ParamType = ParamTypes[I];
7063     if (!ParamType->isDependentType()) {
7064       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7065                              ? 0
7066                              : (ThisConversions + I);
7067       Conversions[ConvIdx]
7068         = TryCopyInitialization(*this, Args[I], ParamType,
7069                                 SuppressUserConversions,
7070                                 /*InOverloadResolution=*/true,
7071                                 /*AllowObjCWritebackConversion=*/
7072                                   getLangOpts().ObjCAutoRefCount,
7073                                 AllowExplicit);
7074       if (Conversions[ConvIdx].isBad())
7075         return true;
7076     }
7077   }
7078
7079   return false;
7080 }
7081
7082 /// Determine whether this is an allowable conversion from the result
7083 /// of an explicit conversion operator to the expected type, per C++
7084 /// [over.match.conv]p1 and [over.match.ref]p1.
7085 ///
7086 /// \param ConvType The return type of the conversion function.
7087 ///
7088 /// \param ToType The type we are converting to.
7089 ///
7090 /// \param AllowObjCPointerConversion Allow a conversion from one
7091 /// Objective-C pointer to another.
7092 ///
7093 /// \returns true if the conversion is allowable, false otherwise.
7094 static bool isAllowableExplicitConversion(Sema &S,
7095                                           QualType ConvType, QualType ToType,
7096                                           bool AllowObjCPointerConversion) {
7097   QualType ToNonRefType = ToType.getNonReferenceType();
7098
7099   // Easy case: the types are the same.
7100   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7101     return true;
7102
7103   // Allow qualification conversions.
7104   bool ObjCLifetimeConversion;
7105   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7106                                   ObjCLifetimeConversion))
7107     return true;
7108
7109   // If we're not allowed to consider Objective-C pointer conversions,
7110   // we're done.
7111   if (!AllowObjCPointerConversion)
7112     return false;
7113
7114   // Is this an Objective-C pointer conversion?
7115   bool IncompatibleObjC = false;
7116   QualType ConvertedType;
7117   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7118                                    IncompatibleObjC);
7119 }
7120
7121 /// AddConversionCandidate - Add a C++ conversion function as a
7122 /// candidate in the candidate set (C++ [over.match.conv],
7123 /// C++ [over.match.copy]). From is the expression we're converting from,
7124 /// and ToType is the type that we're eventually trying to convert to
7125 /// (which may or may not be the same type as the type that the
7126 /// conversion function produces).
7127 void Sema::AddConversionCandidate(
7128     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7129     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7130     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7131     bool AllowExplicit, bool AllowResultConversion) {
7132   assert(!Conversion->getDescribedFunctionTemplate() &&
7133          "Conversion function templates use AddTemplateConversionCandidate");
7134   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7135   if (!CandidateSet.isNewCandidate(Conversion))
7136     return;
7137
7138   // If the conversion function has an undeduced return type, trigger its
7139   // deduction now.
7140   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7141     if (DeduceReturnType(Conversion, From->getExprLoc()))
7142       return;
7143     ConvType = Conversion->getConversionType().getNonReferenceType();
7144   }
7145
7146   // If we don't allow any conversion of the result type, ignore conversion
7147   // functions that don't convert to exactly (possibly cv-qualified) T.
7148   if (!AllowResultConversion &&
7149       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7150     return;
7151
7152   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7153   // operator is only a candidate if its return type is the target type or
7154   // can be converted to the target type with a qualification conversion.
7155   //
7156   // FIXME: Include such functions in the candidate list and explain why we
7157   // can't select them.
7158   if (Conversion->isExplicit() &&
7159       !isAllowableExplicitConversion(*this, ConvType, ToType,
7160                                      AllowObjCConversionOnExplicit))
7161     return;
7162
7163   // Overload resolution is always an unevaluated context.
7164   EnterExpressionEvaluationContext Unevaluated(
7165       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7166
7167   // Add this candidate
7168   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7169   Candidate.FoundDecl = FoundDecl;
7170   Candidate.Function = Conversion;
7171   Candidate.IsSurrogate = false;
7172   Candidate.IgnoreObjectArgument = false;
7173   Candidate.FinalConversion.setAsIdentityConversion();
7174   Candidate.FinalConversion.setFromType(ConvType);
7175   Candidate.FinalConversion.setAllToTypes(ToType);
7176   Candidate.Viable = true;
7177   Candidate.ExplicitCallArguments = 1;
7178
7179   // Explicit functions are not actually candidates at all if we're not
7180   // allowing them in this context, but keep them around so we can point
7181   // to them in diagnostics.
7182   if (!AllowExplicit && Conversion->isExplicit()) {
7183     Candidate.Viable = false;
7184     Candidate.FailureKind = ovl_fail_explicit;
7185     return;
7186   }
7187
7188   // C++ [over.match.funcs]p4:
7189   //   For conversion functions, the function is considered to be a member of
7190   //   the class of the implicit implied object argument for the purpose of
7191   //   defining the type of the implicit object parameter.
7192   //
7193   // Determine the implicit conversion sequence for the implicit
7194   // object parameter.
7195   QualType ImplicitParamType = From->getType();
7196   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7197     ImplicitParamType = FromPtrType->getPointeeType();
7198   CXXRecordDecl *ConversionContext
7199     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7200
7201   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7202       *this, CandidateSet.getLocation(), From->getType(),
7203       From->Classify(Context), Conversion, ConversionContext);
7204
7205   if (Candidate.Conversions[0].isBad()) {
7206     Candidate.Viable = false;
7207     Candidate.FailureKind = ovl_fail_bad_conversion;
7208     return;
7209   }
7210
7211   if (Conversion->getTrailingRequiresClause()) {
7212     ConstraintSatisfaction Satisfaction;
7213     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7214         !Satisfaction.IsSatisfied) {
7215       Candidate.Viable = false;
7216       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7217       return;
7218     }
7219   }
7220
7221   // We won't go through a user-defined type conversion function to convert a
7222   // derived to base as such conversions are given Conversion Rank. They only
7223   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7224   QualType FromCanon
7225     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7226   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7227   if (FromCanon == ToCanon ||
7228       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7229     Candidate.Viable = false;
7230     Candidate.FailureKind = ovl_fail_trivial_conversion;
7231     return;
7232   }
7233
7234   // To determine what the conversion from the result of calling the
7235   // conversion function to the type we're eventually trying to
7236   // convert to (ToType), we need to synthesize a call to the
7237   // conversion function and attempt copy initialization from it. This
7238   // makes sure that we get the right semantics with respect to
7239   // lvalues/rvalues and the type. Fortunately, we can allocate this
7240   // call on the stack and we don't need its arguments to be
7241   // well-formed.
7242   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7243                             VK_LValue, From->getBeginLoc());
7244   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7245                                 Context.getPointerType(Conversion->getType()),
7246                                 CK_FunctionToPointerDecay,
7247                                 &ConversionRef, VK_RValue);
7248
7249   QualType ConversionType = Conversion->getConversionType();
7250   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7251     Candidate.Viable = false;
7252     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7253     return;
7254   }
7255
7256   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7257
7258   // Note that it is safe to allocate CallExpr on the stack here because
7259   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7260   // allocator).
7261   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7262
7263   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7264   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7265       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7266
7267   ImplicitConversionSequence ICS =
7268       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7269                             /*SuppressUserConversions=*/true,
7270                             /*InOverloadResolution=*/false,
7271                             /*AllowObjCWritebackConversion=*/false);
7272
7273   switch (ICS.getKind()) {
7274   case ImplicitConversionSequence::StandardConversion:
7275     Candidate.FinalConversion = ICS.Standard;
7276
7277     // C++ [over.ics.user]p3:
7278     //   If the user-defined conversion is specified by a specialization of a
7279     //   conversion function template, the second standard conversion sequence
7280     //   shall have exact match rank.
7281     if (Conversion->getPrimaryTemplate() &&
7282         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7283       Candidate.Viable = false;
7284       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7285       return;
7286     }
7287
7288     // C++0x [dcl.init.ref]p5:
7289     //    In the second case, if the reference is an rvalue reference and
7290     //    the second standard conversion sequence of the user-defined
7291     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7292     //    program is ill-formed.
7293     if (ToType->isRValueReferenceType() &&
7294         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7295       Candidate.Viable = false;
7296       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7297       return;
7298     }
7299     break;
7300
7301   case ImplicitConversionSequence::BadConversion:
7302     Candidate.Viable = false;
7303     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7304     return;
7305
7306   default:
7307     llvm_unreachable(
7308            "Can only end up with a standard conversion sequence or failure");
7309   }
7310
7311   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7312     Candidate.Viable = false;
7313     Candidate.FailureKind = ovl_fail_enable_if;
7314     Candidate.DeductionFailure.Data = FailedAttr;
7315     return;
7316   }
7317
7318   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7319       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7320     Candidate.Viable = false;
7321     Candidate.FailureKind = ovl_non_default_multiversion_function;
7322   }
7323 }
7324
7325 /// Adds a conversion function template specialization
7326 /// candidate to the overload set, using template argument deduction
7327 /// to deduce the template arguments of the conversion function
7328 /// template from the type that we are converting to (C++
7329 /// [temp.deduct.conv]).
7330 void Sema::AddTemplateConversionCandidate(
7331     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7332     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7333     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7334     bool AllowExplicit, bool AllowResultConversion) {
7335   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7336          "Only conversion function templates permitted here");
7337
7338   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7339     return;
7340
7341   // If the function template has a non-dependent explicit specification,
7342   // exclude it now if appropriate; we are not permitted to perform deduction
7343   // and substitution in this case.
7344   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7345     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7346     Candidate.FoundDecl = FoundDecl;
7347     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7348     Candidate.Viable = false;
7349     Candidate.FailureKind = ovl_fail_explicit;
7350     return;
7351   }
7352
7353   TemplateDeductionInfo Info(CandidateSet.getLocation());
7354   CXXConversionDecl *Specialization = nullptr;
7355   if (TemplateDeductionResult Result
7356         = DeduceTemplateArguments(FunctionTemplate, ToType,
7357                                   Specialization, Info)) {
7358     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7359     Candidate.FoundDecl = FoundDecl;
7360     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7361     Candidate.Viable = false;
7362     Candidate.FailureKind = ovl_fail_bad_deduction;
7363     Candidate.IsSurrogate = false;
7364     Candidate.IgnoreObjectArgument = false;
7365     Candidate.ExplicitCallArguments = 1;
7366     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7367                                                           Info);
7368     return;
7369   }
7370
7371   // Add the conversion function template specialization produced by
7372   // template argument deduction as a candidate.
7373   assert(Specialization && "Missing function template specialization?");
7374   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7375                          CandidateSet, AllowObjCConversionOnExplicit,
7376                          AllowExplicit, AllowResultConversion);
7377 }
7378
7379 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7380 /// converts the given @c Object to a function pointer via the
7381 /// conversion function @c Conversion, and then attempts to call it
7382 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7383 /// the type of function that we'll eventually be calling.
7384 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7385                                  DeclAccessPair FoundDecl,
7386                                  CXXRecordDecl *ActingContext,
7387                                  const FunctionProtoType *Proto,
7388                                  Expr *Object,
7389                                  ArrayRef<Expr *> Args,
7390                                  OverloadCandidateSet& CandidateSet) {
7391   if (!CandidateSet.isNewCandidate(Conversion))
7392     return;
7393
7394   // Overload resolution is always an unevaluated context.
7395   EnterExpressionEvaluationContext Unevaluated(
7396       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7397
7398   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7399   Candidate.FoundDecl = FoundDecl;
7400   Candidate.Function = nullptr;
7401   Candidate.Surrogate = Conversion;
7402   Candidate.Viable = true;
7403   Candidate.IsSurrogate = true;
7404   Candidate.IgnoreObjectArgument = false;
7405   Candidate.ExplicitCallArguments = Args.size();
7406
7407   // Determine the implicit conversion sequence for the implicit
7408   // object parameter.
7409   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7410       *this, CandidateSet.getLocation(), Object->getType(),
7411       Object->Classify(Context), Conversion, ActingContext);
7412   if (ObjectInit.isBad()) {
7413     Candidate.Viable = false;
7414     Candidate.FailureKind = ovl_fail_bad_conversion;
7415     Candidate.Conversions[0] = ObjectInit;
7416     return;
7417   }
7418
7419   // The first conversion is actually a user-defined conversion whose
7420   // first conversion is ObjectInit's standard conversion (which is
7421   // effectively a reference binding). Record it as such.
7422   Candidate.Conversions[0].setUserDefined();
7423   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7424   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7425   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7426   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7427   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7428   Candidate.Conversions[0].UserDefined.After
7429     = Candidate.Conversions[0].UserDefined.Before;
7430   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7431
7432   // Find the
7433   unsigned NumParams = Proto->getNumParams();
7434
7435   // (C++ 13.3.2p2): A candidate function having fewer than m
7436   // parameters is viable only if it has an ellipsis in its parameter
7437   // list (8.3.5).
7438   if (Args.size() > NumParams && !Proto->isVariadic()) {
7439     Candidate.Viable = false;
7440     Candidate.FailureKind = ovl_fail_too_many_arguments;
7441     return;
7442   }
7443
7444   // Function types don't have any default arguments, so just check if
7445   // we have enough arguments.
7446   if (Args.size() < NumParams) {
7447     // Not enough arguments.
7448     Candidate.Viable = false;
7449     Candidate.FailureKind = ovl_fail_too_few_arguments;
7450     return;
7451   }
7452
7453   // Determine the implicit conversion sequences for each of the
7454   // arguments.
7455   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7456     if (ArgIdx < NumParams) {
7457       // (C++ 13.3.2p3): for F to be a viable function, there shall
7458       // exist for each argument an implicit conversion sequence
7459       // (13.3.3.1) that converts that argument to the corresponding
7460       // parameter of F.
7461       QualType ParamType = Proto->getParamType(ArgIdx);
7462       Candidate.Conversions[ArgIdx + 1]
7463         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7464                                 /*SuppressUserConversions=*/false,
7465                                 /*InOverloadResolution=*/false,
7466                                 /*AllowObjCWritebackConversion=*/
7467                                   getLangOpts().ObjCAutoRefCount);
7468       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7469         Candidate.Viable = false;
7470         Candidate.FailureKind = ovl_fail_bad_conversion;
7471         return;
7472       }
7473     } else {
7474       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7475       // argument for which there is no corresponding parameter is
7476       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7477       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7478     }
7479   }
7480
7481   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7482     Candidate.Viable = false;
7483     Candidate.FailureKind = ovl_fail_enable_if;
7484     Candidate.DeductionFailure.Data = FailedAttr;
7485     return;
7486   }
7487 }
7488
7489 /// Add all of the non-member operator function declarations in the given
7490 /// function set to the overload candidate set.
7491 void Sema::AddNonMemberOperatorCandidates(
7492     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7493     OverloadCandidateSet &CandidateSet,
7494     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7495   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7496     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7497     ArrayRef<Expr *> FunctionArgs = Args;
7498
7499     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7500     FunctionDecl *FD =
7501         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7502
7503     // Don't consider rewritten functions if we're not rewriting.
7504     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7505       continue;
7506
7507     assert(!isa<CXXMethodDecl>(FD) &&
7508            "unqualified operator lookup found a member function");
7509
7510     if (FunTmpl) {
7511       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7512                                    FunctionArgs, CandidateSet);
7513       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7514         AddTemplateOverloadCandidate(
7515             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7516             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7517             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7518     } else {
7519       if (ExplicitTemplateArgs)
7520         continue;
7521       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7522       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7523         AddOverloadCandidate(FD, F.getPair(),
7524                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7525                              false, false, true, false, ADLCallKind::NotADL,
7526                              None, OverloadCandidateParamOrder::Reversed);
7527     }
7528   }
7529 }
7530
7531 /// Add overload candidates for overloaded operators that are
7532 /// member functions.
7533 ///
7534 /// Add the overloaded operator candidates that are member functions
7535 /// for the operator Op that was used in an operator expression such
7536 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7537 /// CandidateSet will store the added overload candidates. (C++
7538 /// [over.match.oper]).
7539 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7540                                        SourceLocation OpLoc,
7541                                        ArrayRef<Expr *> Args,
7542                                        OverloadCandidateSet &CandidateSet,
7543                                        OverloadCandidateParamOrder PO) {
7544   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7545
7546   // C++ [over.match.oper]p3:
7547   //   For a unary operator @ with an operand of a type whose
7548   //   cv-unqualified version is T1, and for a binary operator @ with
7549   //   a left operand of a type whose cv-unqualified version is T1 and
7550   //   a right operand of a type whose cv-unqualified version is T2,
7551   //   three sets of candidate functions, designated member
7552   //   candidates, non-member candidates and built-in candidates, are
7553   //   constructed as follows:
7554   QualType T1 = Args[0]->getType();
7555
7556   //     -- If T1 is a complete class type or a class currently being
7557   //        defined, the set of member candidates is the result of the
7558   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7559   //        the set of member candidates is empty.
7560   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7561     // Complete the type if it can be completed.
7562     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7563       return;
7564     // If the type is neither complete nor being defined, bail out now.
7565     if (!T1Rec->getDecl()->getDefinition())
7566       return;
7567
7568     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7569     LookupQualifiedName(Operators, T1Rec->getDecl());
7570     Operators.suppressDiagnostics();
7571
7572     for (LookupResult::iterator Oper = Operators.begin(),
7573                              OperEnd = Operators.end();
7574          Oper != OperEnd;
7575          ++Oper)
7576       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7577                          Args[0]->Classify(Context), Args.slice(1),
7578                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7579   }
7580 }
7581
7582 /// AddBuiltinCandidate - Add a candidate for a built-in
7583 /// operator. ResultTy and ParamTys are the result and parameter types
7584 /// of the built-in candidate, respectively. Args and NumArgs are the
7585 /// arguments being passed to the candidate. IsAssignmentOperator
7586 /// should be true when this built-in candidate is an assignment
7587 /// operator. NumContextualBoolArguments is the number of arguments
7588 /// (at the beginning of the argument list) that will be contextually
7589 /// converted to bool.
7590 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7591                                OverloadCandidateSet& CandidateSet,
7592                                bool IsAssignmentOperator,
7593                                unsigned NumContextualBoolArguments) {
7594   // Overload resolution is always an unevaluated context.
7595   EnterExpressionEvaluationContext Unevaluated(
7596       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7597
7598   // Add this candidate
7599   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7600   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7601   Candidate.Function = nullptr;
7602   Candidate.IsSurrogate = false;
7603   Candidate.IgnoreObjectArgument = false;
7604   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7605
7606   // Determine the implicit conversion sequences for each of the
7607   // arguments.
7608   Candidate.Viable = true;
7609   Candidate.ExplicitCallArguments = Args.size();
7610   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7611     // C++ [over.match.oper]p4:
7612     //   For the built-in assignment operators, conversions of the
7613     //   left operand are restricted as follows:
7614     //     -- no temporaries are introduced to hold the left operand, and
7615     //     -- no user-defined conversions are applied to the left
7616     //        operand to achieve a type match with the left-most
7617     //        parameter of a built-in candidate.
7618     //
7619     // We block these conversions by turning off user-defined
7620     // conversions, since that is the only way that initialization of
7621     // a reference to a non-class type can occur from something that
7622     // is not of the same type.
7623     if (ArgIdx < NumContextualBoolArguments) {
7624       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7625              "Contextual conversion to bool requires bool type");
7626       Candidate.Conversions[ArgIdx]
7627         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7628     } else {
7629       Candidate.Conversions[ArgIdx]
7630         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7631                                 ArgIdx == 0 && IsAssignmentOperator,
7632                                 /*InOverloadResolution=*/false,
7633                                 /*AllowObjCWritebackConversion=*/
7634                                   getLangOpts().ObjCAutoRefCount);
7635     }
7636     if (Candidate.Conversions[ArgIdx].isBad()) {
7637       Candidate.Viable = false;
7638       Candidate.FailureKind = ovl_fail_bad_conversion;
7639       break;
7640     }
7641   }
7642 }
7643
7644 namespace {
7645
7646 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7647 /// candidate operator functions for built-in operators (C++
7648 /// [over.built]). The types are separated into pointer types and
7649 /// enumeration types.
7650 class BuiltinCandidateTypeSet  {
7651   /// TypeSet - A set of types.
7652   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7653                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7654
7655   /// PointerTypes - The set of pointer types that will be used in the
7656   /// built-in candidates.
7657   TypeSet PointerTypes;
7658
7659   /// MemberPointerTypes - The set of member pointer types that will be
7660   /// used in the built-in candidates.
7661   TypeSet MemberPointerTypes;
7662
7663   /// EnumerationTypes - The set of enumeration types that will be
7664   /// used in the built-in candidates.
7665   TypeSet EnumerationTypes;
7666
7667   /// The set of vector types that will be used in the built-in
7668   /// candidates.
7669   TypeSet VectorTypes;
7670
7671   /// A flag indicating non-record types are viable candidates
7672   bool HasNonRecordTypes;
7673
7674   /// A flag indicating whether either arithmetic or enumeration types
7675   /// were present in the candidate set.
7676   bool HasArithmeticOrEnumeralTypes;
7677
7678   /// A flag indicating whether the nullptr type was present in the
7679   /// candidate set.
7680   bool HasNullPtrType;
7681
7682   /// Sema - The semantic analysis instance where we are building the
7683   /// candidate type set.
7684   Sema &SemaRef;
7685
7686   /// Context - The AST context in which we will build the type sets.
7687   ASTContext &Context;
7688
7689   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7690                                                const Qualifiers &VisibleQuals);
7691   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7692
7693 public:
7694   /// iterator - Iterates through the types that are part of the set.
7695   typedef TypeSet::iterator iterator;
7696
7697   BuiltinCandidateTypeSet(Sema &SemaRef)
7698     : HasNonRecordTypes(false),
7699       HasArithmeticOrEnumeralTypes(false),
7700       HasNullPtrType(false),
7701       SemaRef(SemaRef),
7702       Context(SemaRef.Context) { }
7703
7704   void AddTypesConvertedFrom(QualType Ty,
7705                              SourceLocation Loc,
7706                              bool AllowUserConversions,
7707                              bool AllowExplicitConversions,
7708                              const Qualifiers &VisibleTypeConversionsQuals);
7709
7710   /// pointer_begin - First pointer type found;
7711   iterator pointer_begin() { return PointerTypes.begin(); }
7712
7713   /// pointer_end - Past the last pointer type found;
7714   iterator pointer_end() { return PointerTypes.end(); }
7715
7716   /// member_pointer_begin - First member pointer type found;
7717   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7718
7719   /// member_pointer_end - Past the last member pointer type found;
7720   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7721
7722   /// enumeration_begin - First enumeration type found;
7723   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7724
7725   /// enumeration_end - Past the last enumeration type found;
7726   iterator enumeration_end() { return EnumerationTypes.end(); }
7727
7728   iterator vector_begin() { return VectorTypes.begin(); }
7729   iterator vector_end() { return VectorTypes.end(); }
7730
7731   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7732   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7733   bool hasNullPtrType() const { return HasNullPtrType; }
7734 };
7735
7736 } // end anonymous namespace
7737
7738 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7739 /// the set of pointer types along with any more-qualified variants of
7740 /// that type. For example, if @p Ty is "int const *", this routine
7741 /// will add "int const *", "int const volatile *", "int const
7742 /// restrict *", and "int const volatile restrict *" to the set of
7743 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7744 /// false otherwise.
7745 ///
7746 /// FIXME: what to do about extended qualifiers?
7747 bool
7748 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7749                                              const Qualifiers &VisibleQuals) {
7750
7751   // Insert this type.
7752   if (!PointerTypes.insert(Ty))
7753     return false;
7754
7755   QualType PointeeTy;
7756   const PointerType *PointerTy = Ty->getAs<PointerType>();
7757   bool buildObjCPtr = false;
7758   if (!PointerTy) {
7759     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7760     PointeeTy = PTy->getPointeeType();
7761     buildObjCPtr = true;
7762   } else {
7763     PointeeTy = PointerTy->getPointeeType();
7764   }
7765
7766   // Don't add qualified variants of arrays. For one, they're not allowed
7767   // (the qualifier would sink to the element type), and for another, the
7768   // only overload situation where it matters is subscript or pointer +- int,
7769   // and those shouldn't have qualifier variants anyway.
7770   if (PointeeTy->isArrayType())
7771     return true;
7772
7773   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7774   bool hasVolatile = VisibleQuals.hasVolatile();
7775   bool hasRestrict = VisibleQuals.hasRestrict();
7776
7777   // Iterate through all strict supersets of BaseCVR.
7778   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7779     if ((CVR | BaseCVR) != CVR) continue;
7780     // Skip over volatile if no volatile found anywhere in the types.
7781     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7782
7783     // Skip over restrict if no restrict found anywhere in the types, or if
7784     // the type cannot be restrict-qualified.
7785     if ((CVR & Qualifiers::Restrict) &&
7786         (!hasRestrict ||
7787          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7788       continue;
7789
7790     // Build qualified pointee type.
7791     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7792
7793     // Build qualified pointer type.
7794     QualType QPointerTy;
7795     if (!buildObjCPtr)
7796       QPointerTy = Context.getPointerType(QPointeeTy);
7797     else
7798       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7799
7800     // Insert qualified pointer type.
7801     PointerTypes.insert(QPointerTy);
7802   }
7803
7804   return true;
7805 }
7806
7807 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7808 /// to the set of pointer types along with any more-qualified variants of
7809 /// that type. For example, if @p Ty is "int const *", this routine
7810 /// will add "int const *", "int const volatile *", "int const
7811 /// restrict *", and "int const volatile restrict *" to the set of
7812 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7813 /// false otherwise.
7814 ///
7815 /// FIXME: what to do about extended qualifiers?
7816 bool
7817 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7818     QualType Ty) {
7819   // Insert this type.
7820   if (!MemberPointerTypes.insert(Ty))
7821     return false;
7822
7823   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7824   assert(PointerTy && "type was not a member pointer type!");
7825
7826   QualType PointeeTy = PointerTy->getPointeeType();
7827   // Don't add qualified variants of arrays. For one, they're not allowed
7828   // (the qualifier would sink to the element type), and for another, the
7829   // only overload situation where it matters is subscript or pointer +- int,
7830   // and those shouldn't have qualifier variants anyway.
7831   if (PointeeTy->isArrayType())
7832     return true;
7833   const Type *ClassTy = PointerTy->getClass();
7834
7835   // Iterate through all strict supersets of the pointee type's CVR
7836   // qualifiers.
7837   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7838   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7839     if ((CVR | BaseCVR) != CVR) continue;
7840
7841     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7842     MemberPointerTypes.insert(
7843       Context.getMemberPointerType(QPointeeTy, ClassTy));
7844   }
7845
7846   return true;
7847 }
7848
7849 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7850 /// Ty can be implicit converted to the given set of @p Types. We're
7851 /// primarily interested in pointer types and enumeration types. We also
7852 /// take member pointer types, for the conditional operator.
7853 /// AllowUserConversions is true if we should look at the conversion
7854 /// functions of a class type, and AllowExplicitConversions if we
7855 /// should also include the explicit conversion functions of a class
7856 /// type.
7857 void
7858 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7859                                                SourceLocation Loc,
7860                                                bool AllowUserConversions,
7861                                                bool AllowExplicitConversions,
7862                                                const Qualifiers &VisibleQuals) {
7863   // Only deal with canonical types.
7864   Ty = Context.getCanonicalType(Ty);
7865
7866   // Look through reference types; they aren't part of the type of an
7867   // expression for the purposes of conversions.
7868   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7869     Ty = RefTy->getPointeeType();
7870
7871   // If we're dealing with an array type, decay to the pointer.
7872   if (Ty->isArrayType())
7873     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7874
7875   // Otherwise, we don't care about qualifiers on the type.
7876   Ty = Ty.getLocalUnqualifiedType();
7877
7878   // Flag if we ever add a non-record type.
7879   const RecordType *TyRec = Ty->getAs<RecordType>();
7880   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7881
7882   // Flag if we encounter an arithmetic type.
7883   HasArithmeticOrEnumeralTypes =
7884     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7885
7886   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7887     PointerTypes.insert(Ty);
7888   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7889     // Insert our type, and its more-qualified variants, into the set
7890     // of types.
7891     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7892       return;
7893   } else if (Ty->isMemberPointerType()) {
7894     // Member pointers are far easier, since the pointee can't be converted.
7895     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7896       return;
7897   } else if (Ty->isEnumeralType()) {
7898     HasArithmeticOrEnumeralTypes = true;
7899     EnumerationTypes.insert(Ty);
7900   } else if (Ty->isVectorType()) {
7901     // We treat vector types as arithmetic types in many contexts as an
7902     // extension.
7903     HasArithmeticOrEnumeralTypes = true;
7904     VectorTypes.insert(Ty);
7905   } else if (Ty->isNullPtrType()) {
7906     HasNullPtrType = true;
7907   } else if (AllowUserConversions && TyRec) {
7908     // No conversion functions in incomplete types.
7909     if (!SemaRef.isCompleteType(Loc, Ty))
7910       return;
7911
7912     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7913     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7914       if (isa<UsingShadowDecl>(D))
7915         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7916
7917       // Skip conversion function templates; they don't tell us anything
7918       // about which builtin types we can convert to.
7919       if (isa<FunctionTemplateDecl>(D))
7920         continue;
7921
7922       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7923       if (AllowExplicitConversions || !Conv->isExplicit()) {
7924         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7925                               VisibleQuals);
7926       }
7927     }
7928   }
7929 }
7930 /// Helper function for adjusting address spaces for the pointer or reference
7931 /// operands of builtin operators depending on the argument.
7932 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7933                                                         Expr *Arg) {
7934   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7935 }
7936
7937 /// Helper function for AddBuiltinOperatorCandidates() that adds
7938 /// the volatile- and non-volatile-qualified assignment operators for the
7939 /// given type to the candidate set.
7940 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7941                                                    QualType T,
7942                                                    ArrayRef<Expr *> Args,
7943                                     OverloadCandidateSet &CandidateSet) {
7944   QualType ParamTypes[2];
7945
7946   // T& operator=(T&, T)
7947   ParamTypes[0] = S.Context.getLValueReferenceType(
7948       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7949   ParamTypes[1] = T;
7950   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7951                         /*IsAssignmentOperator=*/true);
7952
7953   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7954     // volatile T& operator=(volatile T&, T)
7955     ParamTypes[0] = S.Context.getLValueReferenceType(
7956         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7957                                                 Args[0]));
7958     ParamTypes[1] = T;
7959     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7960                           /*IsAssignmentOperator=*/true);
7961   }
7962 }
7963
7964 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7965 /// if any, found in visible type conversion functions found in ArgExpr's type.
7966 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7967     Qualifiers VRQuals;
7968     const RecordType *TyRec;
7969     if (const MemberPointerType *RHSMPType =
7970         ArgExpr->getType()->getAs<MemberPointerType>())
7971       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7972     else
7973       TyRec = ArgExpr->getType()->getAs<RecordType>();
7974     if (!TyRec) {
7975       // Just to be safe, assume the worst case.
7976       VRQuals.addVolatile();
7977       VRQuals.addRestrict();
7978       return VRQuals;
7979     }
7980
7981     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7982     if (!ClassDecl->hasDefinition())
7983       return VRQuals;
7984
7985     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7986       if (isa<UsingShadowDecl>(D))
7987         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7988       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7989         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7990         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7991           CanTy = ResTypeRef->getPointeeType();
7992         // Need to go down the pointer/mempointer chain and add qualifiers
7993         // as see them.
7994         bool done = false;
7995         while (!done) {
7996           if (CanTy.isRestrictQualified())
7997             VRQuals.addRestrict();
7998           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7999             CanTy = ResTypePtr->getPointeeType();
8000           else if (const MemberPointerType *ResTypeMPtr =
8001                 CanTy->getAs<MemberPointerType>())
8002             CanTy = ResTypeMPtr->getPointeeType();
8003           else
8004             done = true;
8005           if (CanTy.isVolatileQualified())
8006             VRQuals.addVolatile();
8007           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8008             return VRQuals;
8009         }
8010       }
8011     }
8012     return VRQuals;
8013 }
8014
8015 namespace {
8016
8017 /// Helper class to manage the addition of builtin operator overload
8018 /// candidates. It provides shared state and utility methods used throughout
8019 /// the process, as well as a helper method to add each group of builtin
8020 /// operator overloads from the standard to a candidate set.
8021 class BuiltinOperatorOverloadBuilder {
8022   // Common instance state available to all overload candidate addition methods.
8023   Sema &S;
8024   ArrayRef<Expr *> Args;
8025   Qualifiers VisibleTypeConversionsQuals;
8026   bool HasArithmeticOrEnumeralCandidateType;
8027   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8028   OverloadCandidateSet &CandidateSet;
8029
8030   static constexpr int ArithmeticTypesCap = 24;
8031   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8032
8033   // Define some indices used to iterate over the arithmetic types in
8034   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8035   // types are that preserved by promotion (C++ [over.built]p2).
8036   unsigned FirstIntegralType,
8037            LastIntegralType;
8038   unsigned FirstPromotedIntegralType,
8039            LastPromotedIntegralType;
8040   unsigned FirstPromotedArithmeticType,
8041            LastPromotedArithmeticType;
8042   unsigned NumArithmeticTypes;
8043
8044   void InitArithmeticTypes() {
8045     // Start of promoted types.
8046     FirstPromotedArithmeticType = 0;
8047     ArithmeticTypes.push_back(S.Context.FloatTy);
8048     ArithmeticTypes.push_back(S.Context.DoubleTy);
8049     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8050     if (S.Context.getTargetInfo().hasFloat128Type())
8051       ArithmeticTypes.push_back(S.Context.Float128Ty);
8052
8053     // Start of integral types.
8054     FirstIntegralType = ArithmeticTypes.size();
8055     FirstPromotedIntegralType = ArithmeticTypes.size();
8056     ArithmeticTypes.push_back(S.Context.IntTy);
8057     ArithmeticTypes.push_back(S.Context.LongTy);
8058     ArithmeticTypes.push_back(S.Context.LongLongTy);
8059     if (S.Context.getTargetInfo().hasInt128Type())
8060       ArithmeticTypes.push_back(S.Context.Int128Ty);
8061     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8062     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8063     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8064     if (S.Context.getTargetInfo().hasInt128Type())
8065       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8066     LastPromotedIntegralType = ArithmeticTypes.size();
8067     LastPromotedArithmeticType = ArithmeticTypes.size();
8068     // End of promoted types.
8069
8070     ArithmeticTypes.push_back(S.Context.BoolTy);
8071     ArithmeticTypes.push_back(S.Context.CharTy);
8072     ArithmeticTypes.push_back(S.Context.WCharTy);
8073     if (S.Context.getLangOpts().Char8)
8074       ArithmeticTypes.push_back(S.Context.Char8Ty);
8075     ArithmeticTypes.push_back(S.Context.Char16Ty);
8076     ArithmeticTypes.push_back(S.Context.Char32Ty);
8077     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8078     ArithmeticTypes.push_back(S.Context.ShortTy);
8079     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8080     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8081     LastIntegralType = ArithmeticTypes.size();
8082     NumArithmeticTypes = ArithmeticTypes.size();
8083     // End of integral types.
8084     // FIXME: What about complex? What about half?
8085
8086     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8087            "Enough inline storage for all arithmetic types.");
8088   }
8089
8090   /// Helper method to factor out the common pattern of adding overloads
8091   /// for '++' and '--' builtin operators.
8092   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8093                                            bool HasVolatile,
8094                                            bool HasRestrict) {
8095     QualType ParamTypes[2] = {
8096       S.Context.getLValueReferenceType(CandidateTy),
8097       S.Context.IntTy
8098     };
8099
8100     // Non-volatile version.
8101     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8102
8103     // Use a heuristic to reduce number of builtin candidates in the set:
8104     // add volatile version only if there are conversions to a volatile type.
8105     if (HasVolatile) {
8106       ParamTypes[0] =
8107         S.Context.getLValueReferenceType(
8108           S.Context.getVolatileType(CandidateTy));
8109       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8110     }
8111
8112     // Add restrict version only if there are conversions to a restrict type
8113     // and our candidate type is a non-restrict-qualified pointer.
8114     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8115         !CandidateTy.isRestrictQualified()) {
8116       ParamTypes[0]
8117         = S.Context.getLValueReferenceType(
8118             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8119       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8120
8121       if (HasVolatile) {
8122         ParamTypes[0]
8123           = S.Context.getLValueReferenceType(
8124               S.Context.getCVRQualifiedType(CandidateTy,
8125                                             (Qualifiers::Volatile |
8126                                              Qualifiers::Restrict)));
8127         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8128       }
8129     }
8130
8131   }
8132
8133 public:
8134   BuiltinOperatorOverloadBuilder(
8135     Sema &S, ArrayRef<Expr *> Args,
8136     Qualifiers VisibleTypeConversionsQuals,
8137     bool HasArithmeticOrEnumeralCandidateType,
8138     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8139     OverloadCandidateSet &CandidateSet)
8140     : S(S), Args(Args),
8141       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8142       HasArithmeticOrEnumeralCandidateType(
8143         HasArithmeticOrEnumeralCandidateType),
8144       CandidateTypes(CandidateTypes),
8145       CandidateSet(CandidateSet) {
8146
8147     InitArithmeticTypes();
8148   }
8149
8150   // Increment is deprecated for bool since C++17.
8151   //
8152   // C++ [over.built]p3:
8153   //
8154   //   For every pair (T, VQ), where T is an arithmetic type other
8155   //   than bool, and VQ is either volatile or empty, there exist
8156   //   candidate operator functions of the form
8157   //
8158   //       VQ T&      operator++(VQ T&);
8159   //       T          operator++(VQ T&, int);
8160   //
8161   // C++ [over.built]p4:
8162   //
8163   //   For every pair (T, VQ), where T is an arithmetic type other
8164   //   than bool, and VQ is either volatile or empty, there exist
8165   //   candidate operator functions of the form
8166   //
8167   //       VQ T&      operator--(VQ T&);
8168   //       T          operator--(VQ T&, int);
8169   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8170     if (!HasArithmeticOrEnumeralCandidateType)
8171       return;
8172
8173     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8174       const auto TypeOfT = ArithmeticTypes[Arith];
8175       if (TypeOfT == S.Context.BoolTy) {
8176         if (Op == OO_MinusMinus)
8177           continue;
8178         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8179           continue;
8180       }
8181       addPlusPlusMinusMinusStyleOverloads(
8182         TypeOfT,
8183         VisibleTypeConversionsQuals.hasVolatile(),
8184         VisibleTypeConversionsQuals.hasRestrict());
8185     }
8186   }
8187
8188   // C++ [over.built]p5:
8189   //
8190   //   For every pair (T, VQ), where T is a cv-qualified or
8191   //   cv-unqualified object type, and VQ is either volatile or
8192   //   empty, there exist candidate operator functions of the form
8193   //
8194   //       T*VQ&      operator++(T*VQ&);
8195   //       T*VQ&      operator--(T*VQ&);
8196   //       T*         operator++(T*VQ&, int);
8197   //       T*         operator--(T*VQ&, int);
8198   void addPlusPlusMinusMinusPointerOverloads() {
8199     for (BuiltinCandidateTypeSet::iterator
8200               Ptr = CandidateTypes[0].pointer_begin(),
8201            PtrEnd = CandidateTypes[0].pointer_end();
8202          Ptr != PtrEnd; ++Ptr) {
8203       // Skip pointer types that aren't pointers to object types.
8204       if (!(*Ptr)->getPointeeType()->isObjectType())
8205         continue;
8206
8207       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8208         (!(*Ptr).isVolatileQualified() &&
8209          VisibleTypeConversionsQuals.hasVolatile()),
8210         (!(*Ptr).isRestrictQualified() &&
8211          VisibleTypeConversionsQuals.hasRestrict()));
8212     }
8213   }
8214
8215   // C++ [over.built]p6:
8216   //   For every cv-qualified or cv-unqualified object type T, there
8217   //   exist candidate operator functions of the form
8218   //
8219   //       T&         operator*(T*);
8220   //
8221   // C++ [over.built]p7:
8222   //   For every function type T that does not have cv-qualifiers or a
8223   //   ref-qualifier, there exist candidate operator functions of the form
8224   //       T&         operator*(T*);
8225   void addUnaryStarPointerOverloads() {
8226     for (BuiltinCandidateTypeSet::iterator
8227               Ptr = CandidateTypes[0].pointer_begin(),
8228            PtrEnd = CandidateTypes[0].pointer_end();
8229          Ptr != PtrEnd; ++Ptr) {
8230       QualType ParamTy = *Ptr;
8231       QualType PointeeTy = ParamTy->getPointeeType();
8232       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8233         continue;
8234
8235       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8236         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8237           continue;
8238
8239       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8240     }
8241   }
8242
8243   // C++ [over.built]p9:
8244   //  For every promoted arithmetic type T, there exist candidate
8245   //  operator functions of the form
8246   //
8247   //       T         operator+(T);
8248   //       T         operator-(T);
8249   void addUnaryPlusOrMinusArithmeticOverloads() {
8250     if (!HasArithmeticOrEnumeralCandidateType)
8251       return;
8252
8253     for (unsigned Arith = FirstPromotedArithmeticType;
8254          Arith < LastPromotedArithmeticType; ++Arith) {
8255       QualType ArithTy = ArithmeticTypes[Arith];
8256       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8257     }
8258
8259     // Extension: We also add these operators for vector types.
8260     for (BuiltinCandidateTypeSet::iterator
8261               Vec = CandidateTypes[0].vector_begin(),
8262            VecEnd = CandidateTypes[0].vector_end();
8263          Vec != VecEnd; ++Vec) {
8264       QualType VecTy = *Vec;
8265       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8266     }
8267   }
8268
8269   // C++ [over.built]p8:
8270   //   For every type T, there exist candidate operator functions of
8271   //   the form
8272   //
8273   //       T*         operator+(T*);
8274   void addUnaryPlusPointerOverloads() {
8275     for (BuiltinCandidateTypeSet::iterator
8276               Ptr = CandidateTypes[0].pointer_begin(),
8277            PtrEnd = CandidateTypes[0].pointer_end();
8278          Ptr != PtrEnd; ++Ptr) {
8279       QualType ParamTy = *Ptr;
8280       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8281     }
8282   }
8283
8284   // C++ [over.built]p10:
8285   //   For every promoted integral type T, there exist candidate
8286   //   operator functions of the form
8287   //
8288   //        T         operator~(T);
8289   void addUnaryTildePromotedIntegralOverloads() {
8290     if (!HasArithmeticOrEnumeralCandidateType)
8291       return;
8292
8293     for (unsigned Int = FirstPromotedIntegralType;
8294          Int < LastPromotedIntegralType; ++Int) {
8295       QualType IntTy = ArithmeticTypes[Int];
8296       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8297     }
8298
8299     // Extension: We also add this operator for vector types.
8300     for (BuiltinCandidateTypeSet::iterator
8301               Vec = CandidateTypes[0].vector_begin(),
8302            VecEnd = CandidateTypes[0].vector_end();
8303          Vec != VecEnd; ++Vec) {
8304       QualType VecTy = *Vec;
8305       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8306     }
8307   }
8308
8309   // C++ [over.match.oper]p16:
8310   //   For every pointer to member type T or type std::nullptr_t, there
8311   //   exist candidate operator functions of the form
8312   //
8313   //        bool operator==(T,T);
8314   //        bool operator!=(T,T);
8315   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8316     /// Set of (canonical) types that we've already handled.
8317     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8318
8319     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8320       for (BuiltinCandidateTypeSet::iterator
8321                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8322              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8323            MemPtr != MemPtrEnd;
8324            ++MemPtr) {
8325         // Don't add the same builtin candidate twice.
8326         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8327           continue;
8328
8329         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8330         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8331       }
8332
8333       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8334         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8335         if (AddedTypes.insert(NullPtrTy).second) {
8336           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8337           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8338         }
8339       }
8340     }
8341   }
8342
8343   // C++ [over.built]p15:
8344   //
8345   //   For every T, where T is an enumeration type or a pointer type,
8346   //   there exist candidate operator functions of the form
8347   //
8348   //        bool       operator<(T, T);
8349   //        bool       operator>(T, T);
8350   //        bool       operator<=(T, T);
8351   //        bool       operator>=(T, T);
8352   //        bool       operator==(T, T);
8353   //        bool       operator!=(T, T);
8354   //           R       operator<=>(T, T)
8355   void addGenericBinaryPointerOrEnumeralOverloads() {
8356     // C++ [over.match.oper]p3:
8357     //   [...]the built-in candidates include all of the candidate operator
8358     //   functions defined in 13.6 that, compared to the given operator, [...]
8359     //   do not have the same parameter-type-list as any non-template non-member
8360     //   candidate.
8361     //
8362     // Note that in practice, this only affects enumeration types because there
8363     // aren't any built-in candidates of record type, and a user-defined operator
8364     // must have an operand of record or enumeration type. Also, the only other
8365     // overloaded operator with enumeration arguments, operator=,
8366     // cannot be overloaded for enumeration types, so this is the only place
8367     // where we must suppress candidates like this.
8368     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8369       UserDefinedBinaryOperators;
8370
8371     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8372       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8373           CandidateTypes[ArgIdx].enumeration_end()) {
8374         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8375                                          CEnd = CandidateSet.end();
8376              C != CEnd; ++C) {
8377           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8378             continue;
8379
8380           if (C->Function->isFunctionTemplateSpecialization())
8381             continue;
8382
8383           // We interpret "same parameter-type-list" as applying to the
8384           // "synthesized candidate, with the order of the two parameters
8385           // reversed", not to the original function.
8386           bool Reversed = C->RewriteKind & CRK_Reversed;
8387           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8388                                         ->getType()
8389                                         .getUnqualifiedType();
8390           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8391                                          ->getType()
8392                                          .getUnqualifiedType();
8393
8394           // Skip if either parameter isn't of enumeral type.
8395           if (!FirstParamType->isEnumeralType() ||
8396               !SecondParamType->isEnumeralType())
8397             continue;
8398
8399           // Add this operator to the set of known user-defined operators.
8400           UserDefinedBinaryOperators.insert(
8401             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8402                            S.Context.getCanonicalType(SecondParamType)));
8403         }
8404       }
8405     }
8406
8407     /// Set of (canonical) types that we've already handled.
8408     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8409
8410     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8411       for (BuiltinCandidateTypeSet::iterator
8412                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8413              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8414            Ptr != PtrEnd; ++Ptr) {
8415         // Don't add the same builtin candidate twice.
8416         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8417           continue;
8418
8419         QualType ParamTypes[2] = { *Ptr, *Ptr };
8420         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8421       }
8422       for (BuiltinCandidateTypeSet::iterator
8423                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8424              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8425            Enum != EnumEnd; ++Enum) {
8426         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8427
8428         // Don't add the same builtin candidate twice, or if a user defined
8429         // candidate exists.
8430         if (!AddedTypes.insert(CanonType).second ||
8431             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8432                                                             CanonType)))
8433           continue;
8434         QualType ParamTypes[2] = { *Enum, *Enum };
8435         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8436       }
8437     }
8438   }
8439
8440   // C++ [over.built]p13:
8441   //
8442   //   For every cv-qualified or cv-unqualified object type T
8443   //   there exist candidate operator functions of the form
8444   //
8445   //      T*         operator+(T*, ptrdiff_t);
8446   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8447   //      T*         operator-(T*, ptrdiff_t);
8448   //      T*         operator+(ptrdiff_t, T*);
8449   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8450   //
8451   // C++ [over.built]p14:
8452   //
8453   //   For every T, where T is a pointer to object type, there
8454   //   exist candidate operator functions of the form
8455   //
8456   //      ptrdiff_t  operator-(T, T);
8457   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8458     /// Set of (canonical) types that we've already handled.
8459     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8460
8461     for (int Arg = 0; Arg < 2; ++Arg) {
8462       QualType AsymmetricParamTypes[2] = {
8463         S.Context.getPointerDiffType(),
8464         S.Context.getPointerDiffType(),
8465       };
8466       for (BuiltinCandidateTypeSet::iterator
8467                 Ptr = CandidateTypes[Arg].pointer_begin(),
8468              PtrEnd = CandidateTypes[Arg].pointer_end();
8469            Ptr != PtrEnd; ++Ptr) {
8470         QualType PointeeTy = (*Ptr)->getPointeeType();
8471         if (!PointeeTy->isObjectType())
8472           continue;
8473
8474         AsymmetricParamTypes[Arg] = *Ptr;
8475         if (Arg == 0 || Op == OO_Plus) {
8476           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8477           // T* operator+(ptrdiff_t, T*);
8478           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8479         }
8480         if (Op == OO_Minus) {
8481           // ptrdiff_t operator-(T, T);
8482           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8483             continue;
8484
8485           QualType ParamTypes[2] = { *Ptr, *Ptr };
8486           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8487         }
8488       }
8489     }
8490   }
8491
8492   // C++ [over.built]p12:
8493   //
8494   //   For every pair of promoted arithmetic types L and R, there
8495   //   exist candidate operator functions of the form
8496   //
8497   //        LR         operator*(L, R);
8498   //        LR         operator/(L, R);
8499   //        LR         operator+(L, R);
8500   //        LR         operator-(L, R);
8501   //        bool       operator<(L, R);
8502   //        bool       operator>(L, R);
8503   //        bool       operator<=(L, R);
8504   //        bool       operator>=(L, R);
8505   //        bool       operator==(L, R);
8506   //        bool       operator!=(L, R);
8507   //
8508   //   where LR is the result of the usual arithmetic conversions
8509   //   between types L and R.
8510   //
8511   // C++ [over.built]p24:
8512   //
8513   //   For every pair of promoted arithmetic types L and R, there exist
8514   //   candidate operator functions of the form
8515   //
8516   //        LR       operator?(bool, L, R);
8517   //
8518   //   where LR is the result of the usual arithmetic conversions
8519   //   between types L and R.
8520   // Our candidates ignore the first parameter.
8521   void addGenericBinaryArithmeticOverloads() {
8522     if (!HasArithmeticOrEnumeralCandidateType)
8523       return;
8524
8525     for (unsigned Left = FirstPromotedArithmeticType;
8526          Left < LastPromotedArithmeticType; ++Left) {
8527       for (unsigned Right = FirstPromotedArithmeticType;
8528            Right < LastPromotedArithmeticType; ++Right) {
8529         QualType LandR[2] = { ArithmeticTypes[Left],
8530                               ArithmeticTypes[Right] };
8531         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8532       }
8533     }
8534
8535     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8536     // conditional operator for vector types.
8537     for (BuiltinCandidateTypeSet::iterator
8538               Vec1 = CandidateTypes[0].vector_begin(),
8539            Vec1End = CandidateTypes[0].vector_end();
8540          Vec1 != Vec1End; ++Vec1) {
8541       for (BuiltinCandidateTypeSet::iterator
8542                 Vec2 = CandidateTypes[1].vector_begin(),
8543              Vec2End = CandidateTypes[1].vector_end();
8544            Vec2 != Vec2End; ++Vec2) {
8545         QualType LandR[2] = { *Vec1, *Vec2 };
8546         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8547       }
8548     }
8549   }
8550
8551   // C++2a [over.built]p14:
8552   //
8553   //   For every integral type T there exists a candidate operator function
8554   //   of the form
8555   //
8556   //        std::strong_ordering operator<=>(T, T)
8557   //
8558   // C++2a [over.built]p15:
8559   //
8560   //   For every pair of floating-point types L and R, there exists a candidate
8561   //   operator function of the form
8562   //
8563   //       std::partial_ordering operator<=>(L, R);
8564   //
8565   // FIXME: The current specification for integral types doesn't play nice with
8566   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8567   // comparisons. Under the current spec this can lead to ambiguity during
8568   // overload resolution. For example:
8569   //
8570   //   enum A : int {a};
8571   //   auto x = (a <=> (long)42);
8572   //
8573   //   error: call is ambiguous for arguments 'A' and 'long'.
8574   //   note: candidate operator<=>(int, int)
8575   //   note: candidate operator<=>(long, long)
8576   //
8577   // To avoid this error, this function deviates from the specification and adds
8578   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8579   // arithmetic types (the same as the generic relational overloads).
8580   //
8581   // For now this function acts as a placeholder.
8582   void addThreeWayArithmeticOverloads() {
8583     addGenericBinaryArithmeticOverloads();
8584   }
8585
8586   // C++ [over.built]p17:
8587   //
8588   //   For every pair of promoted integral types L and R, there
8589   //   exist candidate operator functions of the form
8590   //
8591   //      LR         operator%(L, R);
8592   //      LR         operator&(L, R);
8593   //      LR         operator^(L, R);
8594   //      LR         operator|(L, R);
8595   //      L          operator<<(L, R);
8596   //      L          operator>>(L, R);
8597   //
8598   //   where LR is the result of the usual arithmetic conversions
8599   //   between types L and R.
8600   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8601     if (!HasArithmeticOrEnumeralCandidateType)
8602       return;
8603
8604     for (unsigned Left = FirstPromotedIntegralType;
8605          Left < LastPromotedIntegralType; ++Left) {
8606       for (unsigned Right = FirstPromotedIntegralType;
8607            Right < LastPromotedIntegralType; ++Right) {
8608         QualType LandR[2] = { ArithmeticTypes[Left],
8609                               ArithmeticTypes[Right] };
8610         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8611       }
8612     }
8613   }
8614
8615   // C++ [over.built]p20:
8616   //
8617   //   For every pair (T, VQ), where T is an enumeration or
8618   //   pointer to member type and VQ is either volatile or
8619   //   empty, there exist candidate operator functions of the form
8620   //
8621   //        VQ T&      operator=(VQ T&, T);
8622   void addAssignmentMemberPointerOrEnumeralOverloads() {
8623     /// Set of (canonical) types that we've already handled.
8624     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8625
8626     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8627       for (BuiltinCandidateTypeSet::iterator
8628                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8629              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8630            Enum != EnumEnd; ++Enum) {
8631         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8632           continue;
8633
8634         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8635       }
8636
8637       for (BuiltinCandidateTypeSet::iterator
8638                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8639              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8640            MemPtr != MemPtrEnd; ++MemPtr) {
8641         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8642           continue;
8643
8644         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8645       }
8646     }
8647   }
8648
8649   // C++ [over.built]p19:
8650   //
8651   //   For every pair (T, VQ), where T is any type and VQ is either
8652   //   volatile or empty, there exist candidate operator functions
8653   //   of the form
8654   //
8655   //        T*VQ&      operator=(T*VQ&, T*);
8656   //
8657   // C++ [over.built]p21:
8658   //
8659   //   For every pair (T, VQ), where T is a cv-qualified or
8660   //   cv-unqualified object type and VQ is either volatile or
8661   //   empty, there exist candidate operator functions of the form
8662   //
8663   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8664   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8665   void addAssignmentPointerOverloads(bool isEqualOp) {
8666     /// Set of (canonical) types that we've already handled.
8667     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8668
8669     for (BuiltinCandidateTypeSet::iterator
8670               Ptr = CandidateTypes[0].pointer_begin(),
8671            PtrEnd = CandidateTypes[0].pointer_end();
8672          Ptr != PtrEnd; ++Ptr) {
8673       // If this is operator=, keep track of the builtin candidates we added.
8674       if (isEqualOp)
8675         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8676       else if (!(*Ptr)->getPointeeType()->isObjectType())
8677         continue;
8678
8679       // non-volatile version
8680       QualType ParamTypes[2] = {
8681         S.Context.getLValueReferenceType(*Ptr),
8682         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8683       };
8684       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8685                             /*IsAssignmentOperator=*/ isEqualOp);
8686
8687       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8688                           VisibleTypeConversionsQuals.hasVolatile();
8689       if (NeedVolatile) {
8690         // volatile version
8691         ParamTypes[0] =
8692           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8693         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8694                               /*IsAssignmentOperator=*/isEqualOp);
8695       }
8696
8697       if (!(*Ptr).isRestrictQualified() &&
8698           VisibleTypeConversionsQuals.hasRestrict()) {
8699         // restrict version
8700         ParamTypes[0]
8701           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8702         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8703                               /*IsAssignmentOperator=*/isEqualOp);
8704
8705         if (NeedVolatile) {
8706           // volatile restrict version
8707           ParamTypes[0]
8708             = S.Context.getLValueReferenceType(
8709                 S.Context.getCVRQualifiedType(*Ptr,
8710                                               (Qualifiers::Volatile |
8711                                                Qualifiers::Restrict)));
8712           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8713                                 /*IsAssignmentOperator=*/isEqualOp);
8714         }
8715       }
8716     }
8717
8718     if (isEqualOp) {
8719       for (BuiltinCandidateTypeSet::iterator
8720                 Ptr = CandidateTypes[1].pointer_begin(),
8721              PtrEnd = CandidateTypes[1].pointer_end();
8722            Ptr != PtrEnd; ++Ptr) {
8723         // Make sure we don't add the same candidate twice.
8724         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8725           continue;
8726
8727         QualType ParamTypes[2] = {
8728           S.Context.getLValueReferenceType(*Ptr),
8729           *Ptr,
8730         };
8731
8732         // non-volatile version
8733         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8734                               /*IsAssignmentOperator=*/true);
8735
8736         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8737                            VisibleTypeConversionsQuals.hasVolatile();
8738         if (NeedVolatile) {
8739           // volatile version
8740           ParamTypes[0] =
8741             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8742           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8743                                 /*IsAssignmentOperator=*/true);
8744         }
8745
8746         if (!(*Ptr).isRestrictQualified() &&
8747             VisibleTypeConversionsQuals.hasRestrict()) {
8748           // restrict version
8749           ParamTypes[0]
8750             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8751           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8752                                 /*IsAssignmentOperator=*/true);
8753
8754           if (NeedVolatile) {
8755             // volatile restrict version
8756             ParamTypes[0]
8757               = S.Context.getLValueReferenceType(
8758                   S.Context.getCVRQualifiedType(*Ptr,
8759                                                 (Qualifiers::Volatile |
8760                                                  Qualifiers::Restrict)));
8761             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8762                                   /*IsAssignmentOperator=*/true);
8763           }
8764         }
8765       }
8766     }
8767   }
8768
8769   // C++ [over.built]p18:
8770   //
8771   //   For every triple (L, VQ, R), where L is an arithmetic type,
8772   //   VQ is either volatile or empty, and R is a promoted
8773   //   arithmetic type, there exist candidate operator functions of
8774   //   the form
8775   //
8776   //        VQ L&      operator=(VQ L&, R);
8777   //        VQ L&      operator*=(VQ L&, R);
8778   //        VQ L&      operator/=(VQ L&, R);
8779   //        VQ L&      operator+=(VQ L&, R);
8780   //        VQ L&      operator-=(VQ L&, R);
8781   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8782     if (!HasArithmeticOrEnumeralCandidateType)
8783       return;
8784
8785     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8786       for (unsigned Right = FirstPromotedArithmeticType;
8787            Right < LastPromotedArithmeticType; ++Right) {
8788         QualType ParamTypes[2];
8789         ParamTypes[1] = ArithmeticTypes[Right];
8790         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8791             S, ArithmeticTypes[Left], Args[0]);
8792         // Add this built-in operator as a candidate (VQ is empty).
8793         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8794         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8795                               /*IsAssignmentOperator=*/isEqualOp);
8796
8797         // Add this built-in operator as a candidate (VQ is 'volatile').
8798         if (VisibleTypeConversionsQuals.hasVolatile()) {
8799           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8800           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8801           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8802                                 /*IsAssignmentOperator=*/isEqualOp);
8803         }
8804       }
8805     }
8806
8807     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8808     for (BuiltinCandidateTypeSet::iterator
8809               Vec1 = CandidateTypes[0].vector_begin(),
8810            Vec1End = CandidateTypes[0].vector_end();
8811          Vec1 != Vec1End; ++Vec1) {
8812       for (BuiltinCandidateTypeSet::iterator
8813                 Vec2 = CandidateTypes[1].vector_begin(),
8814              Vec2End = CandidateTypes[1].vector_end();
8815            Vec2 != Vec2End; ++Vec2) {
8816         QualType ParamTypes[2];
8817         ParamTypes[1] = *Vec2;
8818         // Add this built-in operator as a candidate (VQ is empty).
8819         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8820         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8821                               /*IsAssignmentOperator=*/isEqualOp);
8822
8823         // Add this built-in operator as a candidate (VQ is 'volatile').
8824         if (VisibleTypeConversionsQuals.hasVolatile()) {
8825           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8826           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8827           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8828                                 /*IsAssignmentOperator=*/isEqualOp);
8829         }
8830       }
8831     }
8832   }
8833
8834   // C++ [over.built]p22:
8835   //
8836   //   For every triple (L, VQ, R), where L is an integral type, VQ
8837   //   is either volatile or empty, and R is a promoted integral
8838   //   type, there exist candidate operator functions of the form
8839   //
8840   //        VQ L&       operator%=(VQ L&, R);
8841   //        VQ L&       operator<<=(VQ L&, R);
8842   //        VQ L&       operator>>=(VQ L&, R);
8843   //        VQ L&       operator&=(VQ L&, R);
8844   //        VQ L&       operator^=(VQ L&, R);
8845   //        VQ L&       operator|=(VQ L&, R);
8846   void addAssignmentIntegralOverloads() {
8847     if (!HasArithmeticOrEnumeralCandidateType)
8848       return;
8849
8850     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8851       for (unsigned Right = FirstPromotedIntegralType;
8852            Right < LastPromotedIntegralType; ++Right) {
8853         QualType ParamTypes[2];
8854         ParamTypes[1] = ArithmeticTypes[Right];
8855         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8856             S, ArithmeticTypes[Left], Args[0]);
8857         // Add this built-in operator as a candidate (VQ is empty).
8858         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8859         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8860         if (VisibleTypeConversionsQuals.hasVolatile()) {
8861           // Add this built-in operator as a candidate (VQ is 'volatile').
8862           ParamTypes[0] = LeftBaseTy;
8863           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8864           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8865           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8866         }
8867       }
8868     }
8869   }
8870
8871   // C++ [over.operator]p23:
8872   //
8873   //   There also exist candidate operator functions of the form
8874   //
8875   //        bool        operator!(bool);
8876   //        bool        operator&&(bool, bool);
8877   //        bool        operator||(bool, bool);
8878   void addExclaimOverload() {
8879     QualType ParamTy = S.Context.BoolTy;
8880     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8881                           /*IsAssignmentOperator=*/false,
8882                           /*NumContextualBoolArguments=*/1);
8883   }
8884   void addAmpAmpOrPipePipeOverload() {
8885     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8886     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8887                           /*IsAssignmentOperator=*/false,
8888                           /*NumContextualBoolArguments=*/2);
8889   }
8890
8891   // C++ [over.built]p13:
8892   //
8893   //   For every cv-qualified or cv-unqualified object type T there
8894   //   exist candidate operator functions of the form
8895   //
8896   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8897   //        T&         operator[](T*, ptrdiff_t);
8898   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8899   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8900   //        T&         operator[](ptrdiff_t, T*);
8901   void addSubscriptOverloads() {
8902     for (BuiltinCandidateTypeSet::iterator
8903               Ptr = CandidateTypes[0].pointer_begin(),
8904            PtrEnd = CandidateTypes[0].pointer_end();
8905          Ptr != PtrEnd; ++Ptr) {
8906       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8907       QualType PointeeType = (*Ptr)->getPointeeType();
8908       if (!PointeeType->isObjectType())
8909         continue;
8910
8911       // T& operator[](T*, ptrdiff_t)
8912       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8913     }
8914
8915     for (BuiltinCandidateTypeSet::iterator
8916               Ptr = CandidateTypes[1].pointer_begin(),
8917            PtrEnd = CandidateTypes[1].pointer_end();
8918          Ptr != PtrEnd; ++Ptr) {
8919       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8920       QualType PointeeType = (*Ptr)->getPointeeType();
8921       if (!PointeeType->isObjectType())
8922         continue;
8923
8924       // T& operator[](ptrdiff_t, T*)
8925       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8926     }
8927   }
8928
8929   // C++ [over.built]p11:
8930   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8931   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8932   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8933   //    there exist candidate operator functions of the form
8934   //
8935   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8936   //
8937   //    where CV12 is the union of CV1 and CV2.
8938   void addArrowStarOverloads() {
8939     for (BuiltinCandidateTypeSet::iterator
8940              Ptr = CandidateTypes[0].pointer_begin(),
8941            PtrEnd = CandidateTypes[0].pointer_end();
8942          Ptr != PtrEnd; ++Ptr) {
8943       QualType C1Ty = (*Ptr);
8944       QualType C1;
8945       QualifierCollector Q1;
8946       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8947       if (!isa<RecordType>(C1))
8948         continue;
8949       // heuristic to reduce number of builtin candidates in the set.
8950       // Add volatile/restrict version only if there are conversions to a
8951       // volatile/restrict type.
8952       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8953         continue;
8954       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8955         continue;
8956       for (BuiltinCandidateTypeSet::iterator
8957                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8958              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8959            MemPtr != MemPtrEnd; ++MemPtr) {
8960         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8961         QualType C2 = QualType(mptr->getClass(), 0);
8962         C2 = C2.getUnqualifiedType();
8963         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8964           break;
8965         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8966         // build CV12 T&
8967         QualType T = mptr->getPointeeType();
8968         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8969             T.isVolatileQualified())
8970           continue;
8971         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8972             T.isRestrictQualified())
8973           continue;
8974         T = Q1.apply(S.Context, T);
8975         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8976       }
8977     }
8978   }
8979
8980   // Note that we don't consider the first argument, since it has been
8981   // contextually converted to bool long ago. The candidates below are
8982   // therefore added as binary.
8983   //
8984   // C++ [over.built]p25:
8985   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8986   //   enumeration type, there exist candidate operator functions of the form
8987   //
8988   //        T        operator?(bool, T, T);
8989   //
8990   void addConditionalOperatorOverloads() {
8991     /// Set of (canonical) types that we've already handled.
8992     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8993
8994     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8995       for (BuiltinCandidateTypeSet::iterator
8996                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8997              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8998            Ptr != PtrEnd; ++Ptr) {
8999         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9000           continue;
9001
9002         QualType ParamTypes[2] = { *Ptr, *Ptr };
9003         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9004       }
9005
9006       for (BuiltinCandidateTypeSet::iterator
9007                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9008              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9009            MemPtr != MemPtrEnd; ++MemPtr) {
9010         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9011           continue;
9012
9013         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9014         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9015       }
9016
9017       if (S.getLangOpts().CPlusPlus11) {
9018         for (BuiltinCandidateTypeSet::iterator
9019                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9020                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9021              Enum != EnumEnd; ++Enum) {
9022           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9023             continue;
9024
9025           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9026             continue;
9027
9028           QualType ParamTypes[2] = { *Enum, *Enum };
9029           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9030         }
9031       }
9032     }
9033   }
9034 };
9035
9036 } // end anonymous namespace
9037
9038 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9039 /// operator overloads to the candidate set (C++ [over.built]), based
9040 /// on the operator @p Op and the arguments given. For example, if the
9041 /// operator is a binary '+', this routine might add "int
9042 /// operator+(int, int)" to cover integer addition.
9043 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9044                                         SourceLocation OpLoc,
9045                                         ArrayRef<Expr *> Args,
9046                                         OverloadCandidateSet &CandidateSet) {
9047   // Find all of the types that the arguments can convert to, but only
9048   // if the operator we're looking at has built-in operator candidates
9049   // that make use of these types. Also record whether we encounter non-record
9050   // candidate types or either arithmetic or enumeral candidate types.
9051   Qualifiers VisibleTypeConversionsQuals;
9052   VisibleTypeConversionsQuals.addConst();
9053   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9054     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9055
9056   bool HasNonRecordCandidateType = false;
9057   bool HasArithmeticOrEnumeralCandidateType = false;
9058   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9059   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9060     CandidateTypes.emplace_back(*this);
9061     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9062                                                  OpLoc,
9063                                                  true,
9064                                                  (Op == OO_Exclaim ||
9065                                                   Op == OO_AmpAmp ||
9066                                                   Op == OO_PipePipe),
9067                                                  VisibleTypeConversionsQuals);
9068     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9069         CandidateTypes[ArgIdx].hasNonRecordTypes();
9070     HasArithmeticOrEnumeralCandidateType =
9071         HasArithmeticOrEnumeralCandidateType ||
9072         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9073   }
9074
9075   // Exit early when no non-record types have been added to the candidate set
9076   // for any of the arguments to the operator.
9077   //
9078   // We can't exit early for !, ||, or &&, since there we have always have
9079   // 'bool' overloads.
9080   if (!HasNonRecordCandidateType &&
9081       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9082     return;
9083
9084   // Setup an object to manage the common state for building overloads.
9085   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9086                                            VisibleTypeConversionsQuals,
9087                                            HasArithmeticOrEnumeralCandidateType,
9088                                            CandidateTypes, CandidateSet);
9089
9090   // Dispatch over the operation to add in only those overloads which apply.
9091   switch (Op) {
9092   case OO_None:
9093   case NUM_OVERLOADED_OPERATORS:
9094     llvm_unreachable("Expected an overloaded operator");
9095
9096   case OO_New:
9097   case OO_Delete:
9098   case OO_Array_New:
9099   case OO_Array_Delete:
9100   case OO_Call:
9101     llvm_unreachable(
9102                     "Special operators don't use AddBuiltinOperatorCandidates");
9103
9104   case OO_Comma:
9105   case OO_Arrow:
9106   case OO_Coawait:
9107     // C++ [over.match.oper]p3:
9108     //   -- For the operator ',', the unary operator '&', the
9109     //      operator '->', or the operator 'co_await', the
9110     //      built-in candidates set is empty.
9111     break;
9112
9113   case OO_Plus: // '+' is either unary or binary
9114     if (Args.size() == 1)
9115       OpBuilder.addUnaryPlusPointerOverloads();
9116     LLVM_FALLTHROUGH;
9117
9118   case OO_Minus: // '-' is either unary or binary
9119     if (Args.size() == 1) {
9120       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9121     } else {
9122       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9123       OpBuilder.addGenericBinaryArithmeticOverloads();
9124     }
9125     break;
9126
9127   case OO_Star: // '*' is either unary or binary
9128     if (Args.size() == 1)
9129       OpBuilder.addUnaryStarPointerOverloads();
9130     else
9131       OpBuilder.addGenericBinaryArithmeticOverloads();
9132     break;
9133
9134   case OO_Slash:
9135     OpBuilder.addGenericBinaryArithmeticOverloads();
9136     break;
9137
9138   case OO_PlusPlus:
9139   case OO_MinusMinus:
9140     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9141     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9142     break;
9143
9144   case OO_EqualEqual:
9145   case OO_ExclaimEqual:
9146     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9147     LLVM_FALLTHROUGH;
9148
9149   case OO_Less:
9150   case OO_Greater:
9151   case OO_LessEqual:
9152   case OO_GreaterEqual:
9153     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9154     OpBuilder.addGenericBinaryArithmeticOverloads();
9155     break;
9156
9157   case OO_Spaceship:
9158     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9159     OpBuilder.addThreeWayArithmeticOverloads();
9160     break;
9161
9162   case OO_Percent:
9163   case OO_Caret:
9164   case OO_Pipe:
9165   case OO_LessLess:
9166   case OO_GreaterGreater:
9167     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9168     break;
9169
9170   case OO_Amp: // '&' is either unary or binary
9171     if (Args.size() == 1)
9172       // C++ [over.match.oper]p3:
9173       //   -- For the operator ',', the unary operator '&', or the
9174       //      operator '->', the built-in candidates set is empty.
9175       break;
9176
9177     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9178     break;
9179
9180   case OO_Tilde:
9181     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9182     break;
9183
9184   case OO_Equal:
9185     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9186     LLVM_FALLTHROUGH;
9187
9188   case OO_PlusEqual:
9189   case OO_MinusEqual:
9190     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9191     LLVM_FALLTHROUGH;
9192
9193   case OO_StarEqual:
9194   case OO_SlashEqual:
9195     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9196     break;
9197
9198   case OO_PercentEqual:
9199   case OO_LessLessEqual:
9200   case OO_GreaterGreaterEqual:
9201   case OO_AmpEqual:
9202   case OO_CaretEqual:
9203   case OO_PipeEqual:
9204     OpBuilder.addAssignmentIntegralOverloads();
9205     break;
9206
9207   case OO_Exclaim:
9208     OpBuilder.addExclaimOverload();
9209     break;
9210
9211   case OO_AmpAmp:
9212   case OO_PipePipe:
9213     OpBuilder.addAmpAmpOrPipePipeOverload();
9214     break;
9215
9216   case OO_Subscript:
9217     OpBuilder.addSubscriptOverloads();
9218     break;
9219
9220   case OO_ArrowStar:
9221     OpBuilder.addArrowStarOverloads();
9222     break;
9223
9224   case OO_Conditional:
9225     OpBuilder.addConditionalOperatorOverloads();
9226     OpBuilder.addGenericBinaryArithmeticOverloads();
9227     break;
9228   }
9229 }
9230
9231 /// Add function candidates found via argument-dependent lookup
9232 /// to the set of overloading candidates.
9233 ///
9234 /// This routine performs argument-dependent name lookup based on the
9235 /// given function name (which may also be an operator name) and adds
9236 /// all of the overload candidates found by ADL to the overload
9237 /// candidate set (C++ [basic.lookup.argdep]).
9238 void
9239 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9240                                            SourceLocation Loc,
9241                                            ArrayRef<Expr *> Args,
9242                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9243                                            OverloadCandidateSet& CandidateSet,
9244                                            bool PartialOverloading) {
9245   ADLResult Fns;
9246
9247   // FIXME: This approach for uniquing ADL results (and removing
9248   // redundant candidates from the set) relies on pointer-equality,
9249   // which means we need to key off the canonical decl.  However,
9250   // always going back to the canonical decl might not get us the
9251   // right set of default arguments.  What default arguments are
9252   // we supposed to consider on ADL candidates, anyway?
9253
9254   // FIXME: Pass in the explicit template arguments?
9255   ArgumentDependentLookup(Name, Loc, Args, Fns);
9256
9257   // Erase all of the candidates we already knew about.
9258   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9259                                    CandEnd = CandidateSet.end();
9260        Cand != CandEnd; ++Cand)
9261     if (Cand->Function) {
9262       Fns.erase(Cand->Function);
9263       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9264         Fns.erase(FunTmpl);
9265     }
9266
9267   // For each of the ADL candidates we found, add it to the overload
9268   // set.
9269   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9270     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9271
9272     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9273       if (ExplicitTemplateArgs)
9274         continue;
9275
9276       AddOverloadCandidate(
9277           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9278           PartialOverloading, /*AllowExplicit=*/true,
9279           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9280       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9281         AddOverloadCandidate(
9282             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9283             /*SuppressUserConversions=*/false, PartialOverloading,
9284             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9285             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9286       }
9287     } else {
9288       auto *FTD = cast<FunctionTemplateDecl>(*I);
9289       AddTemplateOverloadCandidate(
9290           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9291           /*SuppressUserConversions=*/false, PartialOverloading,
9292           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9293       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9294               Context, FTD->getTemplatedDecl())) {
9295         AddTemplateOverloadCandidate(
9296             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9297             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9298             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9299             OverloadCandidateParamOrder::Reversed);
9300       }
9301     }
9302   }
9303 }
9304
9305 namespace {
9306 enum class Comparison { Equal, Better, Worse };
9307 }
9308
9309 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9310 /// overload resolution.
9311 ///
9312 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9313 /// Cand1's first N enable_if attributes have precisely the same conditions as
9314 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9315 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9316 ///
9317 /// Note that you can have a pair of candidates such that Cand1's enable_if
9318 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9319 /// worse than Cand1's.
9320 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9321                                        const FunctionDecl *Cand2) {
9322   // Common case: One (or both) decls don't have enable_if attrs.
9323   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9324   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9325   if (!Cand1Attr || !Cand2Attr) {
9326     if (Cand1Attr == Cand2Attr)
9327       return Comparison::Equal;
9328     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9329   }
9330
9331   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9332   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9333
9334   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9335   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9336     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9337     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9338
9339     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9340     // has fewer enable_if attributes than Cand2, and vice versa.
9341     if (!Cand1A)
9342       return Comparison::Worse;
9343     if (!Cand2A)
9344       return Comparison::Better;
9345
9346     Cand1ID.clear();
9347     Cand2ID.clear();
9348
9349     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9350     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9351     if (Cand1ID != Cand2ID)
9352       return Comparison::Worse;
9353   }
9354
9355   return Comparison::Equal;
9356 }
9357
9358 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9359                                           const OverloadCandidate &Cand2) {
9360   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9361       !Cand2.Function->isMultiVersion())
9362     return false;
9363
9364   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9365   // is obviously better.
9366   if (Cand1.Function->isInvalidDecl()) return false;
9367   if (Cand2.Function->isInvalidDecl()) return true;
9368
9369   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9370   // cpu_dispatch, else arbitrarily based on the identifiers.
9371   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9372   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9373   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9374   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9375
9376   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9377     return false;
9378
9379   if (Cand1CPUDisp && !Cand2CPUDisp)
9380     return true;
9381   if (Cand2CPUDisp && !Cand1CPUDisp)
9382     return false;
9383
9384   if (Cand1CPUSpec && Cand2CPUSpec) {
9385     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9386       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9387
9388     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9389         FirstDiff = std::mismatch(
9390             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9391             Cand2CPUSpec->cpus_begin(),
9392             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9393               return LHS->getName() == RHS->getName();
9394             });
9395
9396     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9397            "Two different cpu-specific versions should not have the same "
9398            "identifier list, otherwise they'd be the same decl!");
9399     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9400   }
9401   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9402 }
9403
9404 /// isBetterOverloadCandidate - Determines whether the first overload
9405 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9406 bool clang::isBetterOverloadCandidate(
9407     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9408     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9409   // Define viable functions to be better candidates than non-viable
9410   // functions.
9411   if (!Cand2.Viable)
9412     return Cand1.Viable;
9413   else if (!Cand1.Viable)
9414     return false;
9415
9416   // C++ [over.match.best]p1:
9417   //
9418   //   -- if F is a static member function, ICS1(F) is defined such
9419   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9420   //      any function G, and, symmetrically, ICS1(G) is neither
9421   //      better nor worse than ICS1(F).
9422   unsigned StartArg = 0;
9423   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9424     StartArg = 1;
9425
9426   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9427     // We don't allow incompatible pointer conversions in C++.
9428     if (!S.getLangOpts().CPlusPlus)
9429       return ICS.isStandard() &&
9430              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9431
9432     // The only ill-formed conversion we allow in C++ is the string literal to
9433     // char* conversion, which is only considered ill-formed after C++11.
9434     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9435            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9436   };
9437
9438   // Define functions that don't require ill-formed conversions for a given
9439   // argument to be better candidates than functions that do.
9440   unsigned NumArgs = Cand1.Conversions.size();
9441   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9442   bool HasBetterConversion = false;
9443   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9444     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9445     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9446     if (Cand1Bad != Cand2Bad) {
9447       if (Cand1Bad)
9448         return false;
9449       HasBetterConversion = true;
9450     }
9451   }
9452
9453   if (HasBetterConversion)
9454     return true;
9455
9456   // C++ [over.match.best]p1:
9457   //   A viable function F1 is defined to be a better function than another
9458   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9459   //   conversion sequence than ICSi(F2), and then...
9460   bool HasWorseConversion = false;
9461   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9462     switch (CompareImplicitConversionSequences(S, Loc,
9463                                                Cand1.Conversions[ArgIdx],
9464                                                Cand2.Conversions[ArgIdx])) {
9465     case ImplicitConversionSequence::Better:
9466       // Cand1 has a better conversion sequence.
9467       HasBetterConversion = true;
9468       break;
9469
9470     case ImplicitConversionSequence::Worse:
9471       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9472           (Cand2.RewriteKind & CRK_Reversed) != 0) {
9473         // Work around large-scale breakage caused by considering reversed
9474         // forms of operator== in C++20:
9475         //
9476         // When comparing a function against its reversed form, if we have a
9477         // better conversion for one argument and a worse conversion for the
9478         // other, we prefer the non-reversed form.
9479         //
9480         // This prevents a conversion function from being considered ambiguous
9481         // with its own reversed form in various where it's only incidentally
9482         // heterogeneous.
9483         //
9484         // We diagnose this as an extension from CreateOverloadedBinOp.
9485         HasWorseConversion = true;
9486         break;
9487       }
9488
9489       // Cand1 can't be better than Cand2.
9490       return false;
9491
9492     case ImplicitConversionSequence::Indistinguishable:
9493       // Do nothing.
9494       break;
9495     }
9496   }
9497
9498   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9499   //       ICSj(F2), or, if not that,
9500   if (HasBetterConversion)
9501     return true;
9502   if (HasWorseConversion)
9503     return false;
9504
9505   //   -- the context is an initialization by user-defined conversion
9506   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9507   //      from the return type of F1 to the destination type (i.e.,
9508   //      the type of the entity being initialized) is a better
9509   //      conversion sequence than the standard conversion sequence
9510   //      from the return type of F2 to the destination type.
9511   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9512       Cand1.Function && Cand2.Function &&
9513       isa<CXXConversionDecl>(Cand1.Function) &&
9514       isa<CXXConversionDecl>(Cand2.Function)) {
9515     // First check whether we prefer one of the conversion functions over the
9516     // other. This only distinguishes the results in non-standard, extension
9517     // cases such as the conversion from a lambda closure type to a function
9518     // pointer or block.
9519     ImplicitConversionSequence::CompareKind Result =
9520         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9521     if (Result == ImplicitConversionSequence::Indistinguishable)
9522       Result = CompareStandardConversionSequences(S, Loc,
9523                                                   Cand1.FinalConversion,
9524                                                   Cand2.FinalConversion);
9525
9526     if (Result != ImplicitConversionSequence::Indistinguishable)
9527       return Result == ImplicitConversionSequence::Better;
9528
9529     // FIXME: Compare kind of reference binding if conversion functions
9530     // convert to a reference type used in direct reference binding, per
9531     // C++14 [over.match.best]p1 section 2 bullet 3.
9532   }
9533
9534   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9535   // as combined with the resolution to CWG issue 243.
9536   //
9537   // When the context is initialization by constructor ([over.match.ctor] or
9538   // either phase of [over.match.list]), a constructor is preferred over
9539   // a conversion function.
9540   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9541       Cand1.Function && Cand2.Function &&
9542       isa<CXXConstructorDecl>(Cand1.Function) !=
9543           isa<CXXConstructorDecl>(Cand2.Function))
9544     return isa<CXXConstructorDecl>(Cand1.Function);
9545
9546   //    -- F1 is a non-template function and F2 is a function template
9547   //       specialization, or, if not that,
9548   bool Cand1IsSpecialization = Cand1.Function &&
9549                                Cand1.Function->getPrimaryTemplate();
9550   bool Cand2IsSpecialization = Cand2.Function &&
9551                                Cand2.Function->getPrimaryTemplate();
9552   if (Cand1IsSpecialization != Cand2IsSpecialization)
9553     return Cand2IsSpecialization;
9554
9555   //   -- F1 and F2 are function template specializations, and the function
9556   //      template for F1 is more specialized than the template for F2
9557   //      according to the partial ordering rules described in 14.5.5.2, or,
9558   //      if not that,
9559   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9560     if (FunctionTemplateDecl *BetterTemplate
9561           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9562                                          Cand2.Function->getPrimaryTemplate(),
9563                                          Loc,
9564                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9565                                                              : TPOC_Call,
9566                                          Cand1.ExplicitCallArguments,
9567                                          Cand2.ExplicitCallArguments))
9568       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9569   }
9570
9571   //   -— F1 and F2 are non-template functions with the same
9572   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9573   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9574       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9575       Cand2.Function->hasPrototype()) {
9576     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9577     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9578     if (PT1->getNumParams() == PT2->getNumParams() &&
9579         PT1->isVariadic() == PT2->isVariadic() &&
9580         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9581       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9582       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9583       if (RC1 && RC2) {
9584         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9585         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9586                                      {RC2}, AtLeastAsConstrained1) ||
9587             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9588                                      {RC1}, AtLeastAsConstrained2))
9589           return false;
9590         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9591           return AtLeastAsConstrained1;
9592       } else if (RC1 || RC2) {
9593         return RC1 != nullptr;
9594       }
9595     }
9596   }
9597
9598   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9599   //      class B of D, and for all arguments the corresponding parameters of
9600   //      F1 and F2 have the same type.
9601   // FIXME: Implement the "all parameters have the same type" check.
9602   bool Cand1IsInherited =
9603       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9604   bool Cand2IsInherited =
9605       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9606   if (Cand1IsInherited != Cand2IsInherited)
9607     return Cand2IsInherited;
9608   else if (Cand1IsInherited) {
9609     assert(Cand2IsInherited);
9610     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9611     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9612     if (Cand1Class->isDerivedFrom(Cand2Class))
9613       return true;
9614     if (Cand2Class->isDerivedFrom(Cand1Class))
9615       return false;
9616     // Inherited from sibling base classes: still ambiguous.
9617   }
9618
9619   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9620   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9621   //      with reversed order of parameters and F1 is not
9622   //
9623   // We rank reversed + different operator as worse than just reversed, but
9624   // that comparison can never happen, because we only consider reversing for
9625   // the maximally-rewritten operator (== or <=>).
9626   if (Cand1.RewriteKind != Cand2.RewriteKind)
9627     return Cand1.RewriteKind < Cand2.RewriteKind;
9628
9629   // Check C++17 tie-breakers for deduction guides.
9630   {
9631     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9632     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9633     if (Guide1 && Guide2) {
9634       //  -- F1 is generated from a deduction-guide and F2 is not
9635       if (Guide1->isImplicit() != Guide2->isImplicit())
9636         return Guide2->isImplicit();
9637
9638       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9639       if (Guide1->isCopyDeductionCandidate())
9640         return true;
9641     }
9642   }
9643
9644   // Check for enable_if value-based overload resolution.
9645   if (Cand1.Function && Cand2.Function) {
9646     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9647     if (Cmp != Comparison::Equal)
9648       return Cmp == Comparison::Better;
9649   }
9650
9651   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9652     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9653     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9654            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9655   }
9656
9657   bool HasPS1 = Cand1.Function != nullptr &&
9658                 functionHasPassObjectSizeParams(Cand1.Function);
9659   bool HasPS2 = Cand2.Function != nullptr &&
9660                 functionHasPassObjectSizeParams(Cand2.Function);
9661   if (HasPS1 != HasPS2 && HasPS1)
9662     return true;
9663
9664   return isBetterMultiversionCandidate(Cand1, Cand2);
9665 }
9666
9667 /// Determine whether two declarations are "equivalent" for the purposes of
9668 /// name lookup and overload resolution. This applies when the same internal/no
9669 /// linkage entity is defined by two modules (probably by textually including
9670 /// the same header). In such a case, we don't consider the declarations to
9671 /// declare the same entity, but we also don't want lookups with both
9672 /// declarations visible to be ambiguous in some cases (this happens when using
9673 /// a modularized libstdc++).
9674 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9675                                                   const NamedDecl *B) {
9676   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9677   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9678   if (!VA || !VB)
9679     return false;
9680
9681   // The declarations must be declaring the same name as an internal linkage
9682   // entity in different modules.
9683   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9684           VB->getDeclContext()->getRedeclContext()) ||
9685       getOwningModule(VA) == getOwningModule(VB) ||
9686       VA->isExternallyVisible() || VB->isExternallyVisible())
9687     return false;
9688
9689   // Check that the declarations appear to be equivalent.
9690   //
9691   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9692   // For constants and functions, we should check the initializer or body is
9693   // the same. For non-constant variables, we shouldn't allow it at all.
9694   if (Context.hasSameType(VA->getType(), VB->getType()))
9695     return true;
9696
9697   // Enum constants within unnamed enumerations will have different types, but
9698   // may still be similar enough to be interchangeable for our purposes.
9699   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9700     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9701       // Only handle anonymous enums. If the enumerations were named and
9702       // equivalent, they would have been merged to the same type.
9703       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9704       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9705       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9706           !Context.hasSameType(EnumA->getIntegerType(),
9707                                EnumB->getIntegerType()))
9708         return false;
9709       // Allow this only if the value is the same for both enumerators.
9710       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9711     }
9712   }
9713
9714   // Nothing else is sufficiently similar.
9715   return false;
9716 }
9717
9718 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9719     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9720   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9721
9722   Module *M = getOwningModule(D);
9723   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9724       << !M << (M ? M->getFullModuleName() : "");
9725
9726   for (auto *E : Equiv) {
9727     Module *M = getOwningModule(E);
9728     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9729         << !M << (M ? M->getFullModuleName() : "");
9730   }
9731 }
9732
9733 /// Computes the best viable function (C++ 13.3.3)
9734 /// within an overload candidate set.
9735 ///
9736 /// \param Loc The location of the function name (or operator symbol) for
9737 /// which overload resolution occurs.
9738 ///
9739 /// \param Best If overload resolution was successful or found a deleted
9740 /// function, \p Best points to the candidate function found.
9741 ///
9742 /// \returns The result of overload resolution.
9743 OverloadingResult
9744 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9745                                          iterator &Best) {
9746   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9747   std::transform(begin(), end(), std::back_inserter(Candidates),
9748                  [](OverloadCandidate &Cand) { return &Cand; });
9749
9750   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9751   // are accepted by both clang and NVCC. However, during a particular
9752   // compilation mode only one call variant is viable. We need to
9753   // exclude non-viable overload candidates from consideration based
9754   // only on their host/device attributes. Specifically, if one
9755   // candidate call is WrongSide and the other is SameSide, we ignore
9756   // the WrongSide candidate.
9757   if (S.getLangOpts().CUDA) {
9758     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9759     bool ContainsSameSideCandidate =
9760         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9761           // Check viable function only.
9762           return Cand->Viable && Cand->Function &&
9763                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9764                      Sema::CFP_SameSide;
9765         });
9766     if (ContainsSameSideCandidate) {
9767       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9768         // Check viable function only to avoid unnecessary data copying/moving.
9769         return Cand->Viable && Cand->Function &&
9770                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9771                    Sema::CFP_WrongSide;
9772       };
9773       llvm::erase_if(Candidates, IsWrongSideCandidate);
9774     }
9775   }
9776
9777   // Find the best viable function.
9778   Best = end();
9779   for (auto *Cand : Candidates) {
9780     Cand->Best = false;
9781     if (Cand->Viable)
9782       if (Best == end() ||
9783           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9784         Best = Cand;
9785   }
9786
9787   // If we didn't find any viable functions, abort.
9788   if (Best == end())
9789     return OR_No_Viable_Function;
9790
9791   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9792
9793   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9794   PendingBest.push_back(&*Best);
9795   Best->Best = true;
9796
9797   // Make sure that this function is better than every other viable
9798   // function. If not, we have an ambiguity.
9799   while (!PendingBest.empty()) {
9800     auto *Curr = PendingBest.pop_back_val();
9801     for (auto *Cand : Candidates) {
9802       if (Cand->Viable && !Cand->Best &&
9803           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9804         PendingBest.push_back(Cand);
9805         Cand->Best = true;
9806
9807         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9808                                                      Curr->Function))
9809           EquivalentCands.push_back(Cand->Function);
9810         else
9811           Best = end();
9812       }
9813     }
9814   }
9815
9816   // If we found more than one best candidate, this is ambiguous.
9817   if (Best == end())
9818     return OR_Ambiguous;
9819
9820   // Best is the best viable function.
9821   if (Best->Function && Best->Function->isDeleted())
9822     return OR_Deleted;
9823
9824   if (!EquivalentCands.empty())
9825     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9826                                                     EquivalentCands);
9827
9828   return OR_Success;
9829 }
9830
9831 namespace {
9832
9833 enum OverloadCandidateKind {
9834   oc_function,
9835   oc_method,
9836   oc_reversed_binary_operator,
9837   oc_constructor,
9838   oc_implicit_default_constructor,
9839   oc_implicit_copy_constructor,
9840   oc_implicit_move_constructor,
9841   oc_implicit_copy_assignment,
9842   oc_implicit_move_assignment,
9843   oc_implicit_equality_comparison,
9844   oc_inherited_constructor
9845 };
9846
9847 enum OverloadCandidateSelect {
9848   ocs_non_template,
9849   ocs_template,
9850   ocs_described_template,
9851 };
9852
9853 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9854 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9855                           OverloadCandidateRewriteKind CRK,
9856                           std::string &Description) {
9857
9858   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9859   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9860     isTemplate = true;
9861     Description = S.getTemplateArgumentBindingsText(
9862         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9863   }
9864
9865   OverloadCandidateSelect Select = [&]() {
9866     if (!Description.empty())
9867       return ocs_described_template;
9868     return isTemplate ? ocs_template : ocs_non_template;
9869   }();
9870
9871   OverloadCandidateKind Kind = [&]() {
9872     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9873       return oc_implicit_equality_comparison;
9874
9875     if (CRK & CRK_Reversed)
9876       return oc_reversed_binary_operator;
9877
9878     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9879       if (!Ctor->isImplicit()) {
9880         if (isa<ConstructorUsingShadowDecl>(Found))
9881           return oc_inherited_constructor;
9882         else
9883           return oc_constructor;
9884       }
9885
9886       if (Ctor->isDefaultConstructor())
9887         return oc_implicit_default_constructor;
9888
9889       if (Ctor->isMoveConstructor())
9890         return oc_implicit_move_constructor;
9891
9892       assert(Ctor->isCopyConstructor() &&
9893              "unexpected sort of implicit constructor");
9894       return oc_implicit_copy_constructor;
9895     }
9896
9897     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9898       // This actually gets spelled 'candidate function' for now, but
9899       // it doesn't hurt to split it out.
9900       if (!Meth->isImplicit())
9901         return oc_method;
9902
9903       if (Meth->isMoveAssignmentOperator())
9904         return oc_implicit_move_assignment;
9905
9906       if (Meth->isCopyAssignmentOperator())
9907         return oc_implicit_copy_assignment;
9908
9909       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9910       return oc_method;
9911     }
9912
9913     return oc_function;
9914   }();
9915
9916   return std::make_pair(Kind, Select);
9917 }
9918
9919 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9920   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9921   // set.
9922   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9923     S.Diag(FoundDecl->getLocation(),
9924            diag::note_ovl_candidate_inherited_constructor)
9925       << Shadow->getNominatedBaseClass();
9926 }
9927
9928 } // end anonymous namespace
9929
9930 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9931                                     const FunctionDecl *FD) {
9932   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9933     bool AlwaysTrue;
9934     if (EnableIf->getCond()->isValueDependent() ||
9935         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9936       return false;
9937     if (!AlwaysTrue)
9938       return false;
9939   }
9940   return true;
9941 }
9942
9943 /// Returns true if we can take the address of the function.
9944 ///
9945 /// \param Complain - If true, we'll emit a diagnostic
9946 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9947 ///   we in overload resolution?
9948 /// \param Loc - The location of the statement we're complaining about. Ignored
9949 ///   if we're not complaining, or if we're in overload resolution.
9950 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9951                                               bool Complain,
9952                                               bool InOverloadResolution,
9953                                               SourceLocation Loc) {
9954   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9955     if (Complain) {
9956       if (InOverloadResolution)
9957         S.Diag(FD->getBeginLoc(),
9958                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9959       else
9960         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9961     }
9962     return false;
9963   }
9964
9965   if (FD->getTrailingRequiresClause()) {
9966     ConstraintSatisfaction Satisfaction;
9967     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
9968       return false;
9969     if (!Satisfaction.IsSatisfied) {
9970       if (Complain) {
9971         if (InOverloadResolution)
9972           S.Diag(FD->getBeginLoc(),
9973                  diag::note_ovl_candidate_unsatisfied_constraints);
9974         else
9975           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9976               << FD;
9977         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9978       }
9979       return false;
9980     }
9981   }
9982
9983   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9984     return P->hasAttr<PassObjectSizeAttr>();
9985   });
9986   if (I == FD->param_end())
9987     return true;
9988
9989   if (Complain) {
9990     // Add one to ParamNo because it's user-facing
9991     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9992     if (InOverloadResolution)
9993       S.Diag(FD->getLocation(),
9994              diag::note_ovl_candidate_has_pass_object_size_params)
9995           << ParamNo;
9996     else
9997       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9998           << FD << ParamNo;
9999   }
10000   return false;
10001 }
10002
10003 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10004                                                const FunctionDecl *FD) {
10005   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10006                                            /*InOverloadResolution=*/true,
10007                                            /*Loc=*/SourceLocation());
10008 }
10009
10010 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10011                                              bool Complain,
10012                                              SourceLocation Loc) {
10013   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10014                                              /*InOverloadResolution=*/false,
10015                                              Loc);
10016 }
10017
10018 // Notes the location of an overload candidate.
10019 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10020                                  OverloadCandidateRewriteKind RewriteKind,
10021                                  QualType DestType, bool TakingAddress) {
10022   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10023     return;
10024   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10025       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10026     return;
10027
10028   std::string FnDesc;
10029   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10030       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10031   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10032                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10033                          << Fn << FnDesc;
10034
10035   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10036   Diag(Fn->getLocation(), PD);
10037   MaybeEmitInheritedConstructorNote(*this, Found);
10038 }
10039
10040 static void
10041 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10042   // Perhaps the ambiguity was caused by two atomic constraints that are
10043   // 'identical' but not equivalent:
10044   //
10045   // void foo() requires (sizeof(T) > 4) { } // #1
10046   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10047   //
10048   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10049   // #2 to subsume #1, but these constraint are not considered equivalent
10050   // according to the subsumption rules because they are not the same
10051   // source-level construct. This behavior is quite confusing and we should try
10052   // to help the user figure out what happened.
10053
10054   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10055   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10056   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10057     if (!I->Function)
10058       continue;
10059     SmallVector<const Expr *, 3> AC;
10060     if (auto *Template = I->Function->getPrimaryTemplate())
10061       Template->getAssociatedConstraints(AC);
10062     else
10063       I->Function->getAssociatedConstraints(AC);
10064     if (AC.empty())
10065       continue;
10066     if (FirstCand == nullptr) {
10067       FirstCand = I->Function;
10068       FirstAC = AC;
10069     } else if (SecondCand == nullptr) {
10070       SecondCand = I->Function;
10071       SecondAC = AC;
10072     } else {
10073       // We have more than one pair of constrained functions - this check is
10074       // expensive and we'd rather not try to diagnose it.
10075       return;
10076     }
10077   }
10078   if (!SecondCand)
10079     return;
10080   // The diagnostic can only happen if there are associated constraints on
10081   // both sides (there needs to be some identical atomic constraint).
10082   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10083                                                       SecondCand, SecondAC))
10084     // Just show the user one diagnostic, they'll probably figure it out
10085     // from here.
10086     return;
10087 }
10088
10089 // Notes the location of all overload candidates designated through
10090 // OverloadedExpr
10091 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10092                                      bool TakingAddress) {
10093   assert(OverloadedExpr->getType() == Context.OverloadTy);
10094
10095   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10096   OverloadExpr *OvlExpr = Ovl.Expression;
10097
10098   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10099                             IEnd = OvlExpr->decls_end();
10100        I != IEnd; ++I) {
10101     if (FunctionTemplateDecl *FunTmpl =
10102                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10103       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10104                             TakingAddress);
10105     } else if (FunctionDecl *Fun
10106                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10107       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10108     }
10109   }
10110 }
10111
10112 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10113 /// "lead" diagnostic; it will be given two arguments, the source and
10114 /// target types of the conversion.
10115 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10116                                  Sema &S,
10117                                  SourceLocation CaretLoc,
10118                                  const PartialDiagnostic &PDiag) const {
10119   S.Diag(CaretLoc, PDiag)
10120     << Ambiguous.getFromType() << Ambiguous.getToType();
10121   // FIXME: The note limiting machinery is borrowed from
10122   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10123   // refactoring here.
10124   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10125   unsigned CandsShown = 0;
10126   AmbiguousConversionSequence::const_iterator I, E;
10127   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10128     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10129       break;
10130     ++CandsShown;
10131     S.NoteOverloadCandidate(I->first, I->second);
10132   }
10133   if (I != E)
10134     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10135 }
10136
10137 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10138                                   unsigned I, bool TakingCandidateAddress) {
10139   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10140   assert(Conv.isBad());
10141   assert(Cand->Function && "for now, candidate must be a function");
10142   FunctionDecl *Fn = Cand->Function;
10143
10144   // There's a conversion slot for the object argument if this is a
10145   // non-constructor method.  Note that 'I' corresponds the
10146   // conversion-slot index.
10147   bool isObjectArgument = false;
10148   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10149     if (I == 0)
10150       isObjectArgument = true;
10151     else
10152       I--;
10153   }
10154
10155   std::string FnDesc;
10156   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10157       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10158                                 FnDesc);
10159
10160   Expr *FromExpr = Conv.Bad.FromExpr;
10161   QualType FromTy = Conv.Bad.getFromType();
10162   QualType ToTy = Conv.Bad.getToType();
10163
10164   if (FromTy == S.Context.OverloadTy) {
10165     assert(FromExpr && "overload set argument came from implicit argument?");
10166     Expr *E = FromExpr->IgnoreParens();
10167     if (isa<UnaryOperator>(E))
10168       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10169     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10170
10171     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10172         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10173         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10174         << Name << I + 1;
10175     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10176     return;
10177   }
10178
10179   // Do some hand-waving analysis to see if the non-viability is due
10180   // to a qualifier mismatch.
10181   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10182   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10183   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10184     CToTy = RT->getPointeeType();
10185   else {
10186     // TODO: detect and diagnose the full richness of const mismatches.
10187     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10188       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10189         CFromTy = FromPT->getPointeeType();
10190         CToTy = ToPT->getPointeeType();
10191       }
10192   }
10193
10194   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10195       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10196     Qualifiers FromQs = CFromTy.getQualifiers();
10197     Qualifiers ToQs = CToTy.getQualifiers();
10198
10199     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10200       if (isObjectArgument)
10201         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10202             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10203             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10204             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10205       else
10206         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10207             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10208             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10209             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10210             << ToTy->isReferenceType() << I + 1;
10211       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10212       return;
10213     }
10214
10215     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10216       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10217           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10218           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10219           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10220           << (unsigned)isObjectArgument << I + 1;
10221       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10222       return;
10223     }
10224
10225     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10226       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10227           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10228           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10229           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10230           << (unsigned)isObjectArgument << I + 1;
10231       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10232       return;
10233     }
10234
10235     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10236       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10237           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10238           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10239           << FromQs.hasUnaligned() << I + 1;
10240       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10241       return;
10242     }
10243
10244     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10245     assert(CVR && "unexpected qualifiers mismatch");
10246
10247     if (isObjectArgument) {
10248       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10249           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10250           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10251           << (CVR - 1);
10252     } else {
10253       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10254           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10255           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10256           << (CVR - 1) << I + 1;
10257     }
10258     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10259     return;
10260   }
10261
10262   // Special diagnostic for failure to convert an initializer list, since
10263   // telling the user that it has type void is not useful.
10264   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10265     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10266         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10267         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10268         << ToTy << (unsigned)isObjectArgument << I + 1;
10269     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10270     return;
10271   }
10272
10273   // Diagnose references or pointers to incomplete types differently,
10274   // since it's far from impossible that the incompleteness triggered
10275   // the failure.
10276   QualType TempFromTy = FromTy.getNonReferenceType();
10277   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10278     TempFromTy = PTy->getPointeeType();
10279   if (TempFromTy->isIncompleteType()) {
10280     // Emit the generic diagnostic and, optionally, add the hints to it.
10281     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10282         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10283         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10284         << ToTy << (unsigned)isObjectArgument << I + 1
10285         << (unsigned)(Cand->Fix.Kind);
10286
10287     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10288     return;
10289   }
10290
10291   // Diagnose base -> derived pointer conversions.
10292   unsigned BaseToDerivedConversion = 0;
10293   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10294     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10295       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10296                                                FromPtrTy->getPointeeType()) &&
10297           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10298           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10299           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10300                           FromPtrTy->getPointeeType()))
10301         BaseToDerivedConversion = 1;
10302     }
10303   } else if (const ObjCObjectPointerType *FromPtrTy
10304                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10305     if (const ObjCObjectPointerType *ToPtrTy
10306                                         = ToTy->getAs<ObjCObjectPointerType>())
10307       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10308         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10309           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10310                                                 FromPtrTy->getPointeeType()) &&
10311               FromIface->isSuperClassOf(ToIface))
10312             BaseToDerivedConversion = 2;
10313   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10314     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10315         !FromTy->isIncompleteType() &&
10316         !ToRefTy->getPointeeType()->isIncompleteType() &&
10317         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10318       BaseToDerivedConversion = 3;
10319     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10320                ToTy.getNonReferenceType().getCanonicalType() ==
10321                FromTy.getNonReferenceType().getCanonicalType()) {
10322       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10323           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10324           << (unsigned)isObjectArgument << I + 1
10325           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10326       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10327       return;
10328     }
10329   }
10330
10331   if (BaseToDerivedConversion) {
10332     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10333         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10334         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10335         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10336     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10337     return;
10338   }
10339
10340   if (isa<ObjCObjectPointerType>(CFromTy) &&
10341       isa<PointerType>(CToTy)) {
10342       Qualifiers FromQs = CFromTy.getQualifiers();
10343       Qualifiers ToQs = CToTy.getQualifiers();
10344       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10345         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10346             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10347             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10348             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10349         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10350         return;
10351       }
10352   }
10353
10354   if (TakingCandidateAddress &&
10355       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10356     return;
10357
10358   // Emit the generic diagnostic and, optionally, add the hints to it.
10359   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10360   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10361         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10362         << ToTy << (unsigned)isObjectArgument << I + 1
10363         << (unsigned)(Cand->Fix.Kind);
10364
10365   // If we can fix the conversion, suggest the FixIts.
10366   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10367        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10368     FDiag << *HI;
10369   S.Diag(Fn->getLocation(), FDiag);
10370
10371   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10372 }
10373
10374 /// Additional arity mismatch diagnosis specific to a function overload
10375 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10376 /// over a candidate in any candidate set.
10377 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10378                                unsigned NumArgs) {
10379   FunctionDecl *Fn = Cand->Function;
10380   unsigned MinParams = Fn->getMinRequiredArguments();
10381
10382   // With invalid overloaded operators, it's possible that we think we
10383   // have an arity mismatch when in fact it looks like we have the
10384   // right number of arguments, because only overloaded operators have
10385   // the weird behavior of overloading member and non-member functions.
10386   // Just don't report anything.
10387   if (Fn->isInvalidDecl() &&
10388       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10389     return true;
10390
10391   if (NumArgs < MinParams) {
10392     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10393            (Cand->FailureKind == ovl_fail_bad_deduction &&
10394             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10395   } else {
10396     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10397            (Cand->FailureKind == ovl_fail_bad_deduction &&
10398             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10399   }
10400
10401   return false;
10402 }
10403
10404 /// General arity mismatch diagnosis over a candidate in a candidate set.
10405 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10406                                   unsigned NumFormalArgs) {
10407   assert(isa<FunctionDecl>(D) &&
10408       "The templated declaration should at least be a function"
10409       " when diagnosing bad template argument deduction due to too many"
10410       " or too few arguments");
10411
10412   FunctionDecl *Fn = cast<FunctionDecl>(D);
10413
10414   // TODO: treat calls to a missing default constructor as a special case
10415   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10416   unsigned MinParams = Fn->getMinRequiredArguments();
10417
10418   // at least / at most / exactly
10419   unsigned mode, modeCount;
10420   if (NumFormalArgs < MinParams) {
10421     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10422         FnTy->isTemplateVariadic())
10423       mode = 0; // "at least"
10424     else
10425       mode = 2; // "exactly"
10426     modeCount = MinParams;
10427   } else {
10428     if (MinParams != FnTy->getNumParams())
10429       mode = 1; // "at most"
10430     else
10431       mode = 2; // "exactly"
10432     modeCount = FnTy->getNumParams();
10433   }
10434
10435   std::string Description;
10436   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10437       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10438
10439   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10440     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10441         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10442         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10443   else
10444     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10445         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10446         << Description << mode << modeCount << NumFormalArgs;
10447
10448   MaybeEmitInheritedConstructorNote(S, Found);
10449 }
10450
10451 /// Arity mismatch diagnosis specific to a function overload candidate.
10452 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10453                                   unsigned NumFormalArgs) {
10454   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10455     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10456 }
10457
10458 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10459   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10460     return TD;
10461   llvm_unreachable("Unsupported: Getting the described template declaration"
10462                    " for bad deduction diagnosis");
10463 }
10464
10465 /// Diagnose a failed template-argument deduction.
10466 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10467                                  DeductionFailureInfo &DeductionFailure,
10468                                  unsigned NumArgs,
10469                                  bool TakingCandidateAddress) {
10470   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10471   NamedDecl *ParamD;
10472   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10473   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10474   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10475   switch (DeductionFailure.Result) {
10476   case Sema::TDK_Success:
10477     llvm_unreachable("TDK_success while diagnosing bad deduction");
10478
10479   case Sema::TDK_Incomplete: {
10480     assert(ParamD && "no parameter found for incomplete deduction result");
10481     S.Diag(Templated->getLocation(),
10482            diag::note_ovl_candidate_incomplete_deduction)
10483         << ParamD->getDeclName();
10484     MaybeEmitInheritedConstructorNote(S, Found);
10485     return;
10486   }
10487
10488   case Sema::TDK_IncompletePack: {
10489     assert(ParamD && "no parameter found for incomplete deduction result");
10490     S.Diag(Templated->getLocation(),
10491            diag::note_ovl_candidate_incomplete_deduction_pack)
10492         << ParamD->getDeclName()
10493         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10494         << *DeductionFailure.getFirstArg();
10495     MaybeEmitInheritedConstructorNote(S, Found);
10496     return;
10497   }
10498
10499   case Sema::TDK_Underqualified: {
10500     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10501     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10502
10503     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10504
10505     // Param will have been canonicalized, but it should just be a
10506     // qualified version of ParamD, so move the qualifiers to that.
10507     QualifierCollector Qs;
10508     Qs.strip(Param);
10509     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10510     assert(S.Context.hasSameType(Param, NonCanonParam));
10511
10512     // Arg has also been canonicalized, but there's nothing we can do
10513     // about that.  It also doesn't matter as much, because it won't
10514     // have any template parameters in it (because deduction isn't
10515     // done on dependent types).
10516     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10517
10518     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10519         << ParamD->getDeclName() << Arg << NonCanonParam;
10520     MaybeEmitInheritedConstructorNote(S, Found);
10521     return;
10522   }
10523
10524   case Sema::TDK_Inconsistent: {
10525     assert(ParamD && "no parameter found for inconsistent deduction result");
10526     int which = 0;
10527     if (isa<TemplateTypeParmDecl>(ParamD))
10528       which = 0;
10529     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10530       // Deduction might have failed because we deduced arguments of two
10531       // different types for a non-type template parameter.
10532       // FIXME: Use a different TDK value for this.
10533       QualType T1 =
10534           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10535       QualType T2 =
10536           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10537       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10538         S.Diag(Templated->getLocation(),
10539                diag::note_ovl_candidate_inconsistent_deduction_types)
10540           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10541           << *DeductionFailure.getSecondArg() << T2;
10542         MaybeEmitInheritedConstructorNote(S, Found);
10543         return;
10544       }
10545
10546       which = 1;
10547     } else {
10548       which = 2;
10549     }
10550
10551     // Tweak the diagnostic if the problem is that we deduced packs of
10552     // different arities. We'll print the actual packs anyway in case that
10553     // includes additional useful information.
10554     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10555         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10556         DeductionFailure.getFirstArg()->pack_size() !=
10557             DeductionFailure.getSecondArg()->pack_size()) {
10558       which = 3;
10559     }
10560
10561     S.Diag(Templated->getLocation(),
10562            diag::note_ovl_candidate_inconsistent_deduction)
10563         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10564         << *DeductionFailure.getSecondArg();
10565     MaybeEmitInheritedConstructorNote(S, Found);
10566     return;
10567   }
10568
10569   case Sema::TDK_InvalidExplicitArguments:
10570     assert(ParamD && "no parameter found for invalid explicit arguments");
10571     if (ParamD->getDeclName())
10572       S.Diag(Templated->getLocation(),
10573              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10574           << ParamD->getDeclName();
10575     else {
10576       int index = 0;
10577       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10578         index = TTP->getIndex();
10579       else if (NonTypeTemplateParmDecl *NTTP
10580                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10581         index = NTTP->getIndex();
10582       else
10583         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10584       S.Diag(Templated->getLocation(),
10585              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10586           << (index + 1);
10587     }
10588     MaybeEmitInheritedConstructorNote(S, Found);
10589     return;
10590
10591   case Sema::TDK_ConstraintsNotSatisfied: {
10592     // Format the template argument list into the argument string.
10593     SmallString<128> TemplateArgString;
10594     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10595     TemplateArgString = " ";
10596     TemplateArgString += S.getTemplateArgumentBindingsText(
10597         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10598     if (TemplateArgString.size() == 1)
10599       TemplateArgString.clear();
10600     S.Diag(Templated->getLocation(),
10601            diag::note_ovl_candidate_unsatisfied_constraints)
10602         << TemplateArgString;
10603
10604     S.DiagnoseUnsatisfiedConstraint(
10605         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10606     return;
10607   }
10608   case Sema::TDK_TooManyArguments:
10609   case Sema::TDK_TooFewArguments:
10610     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10611     return;
10612
10613   case Sema::TDK_InstantiationDepth:
10614     S.Diag(Templated->getLocation(),
10615            diag::note_ovl_candidate_instantiation_depth);
10616     MaybeEmitInheritedConstructorNote(S, Found);
10617     return;
10618
10619   case Sema::TDK_SubstitutionFailure: {
10620     // Format the template argument list into the argument string.
10621     SmallString<128> TemplateArgString;
10622     if (TemplateArgumentList *Args =
10623             DeductionFailure.getTemplateArgumentList()) {
10624       TemplateArgString = " ";
10625       TemplateArgString += S.getTemplateArgumentBindingsText(
10626           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10627       if (TemplateArgString.size() == 1)
10628         TemplateArgString.clear();
10629     }
10630
10631     // If this candidate was disabled by enable_if, say so.
10632     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10633     if (PDiag && PDiag->second.getDiagID() ==
10634           diag::err_typename_nested_not_found_enable_if) {
10635       // FIXME: Use the source range of the condition, and the fully-qualified
10636       //        name of the enable_if template. These are both present in PDiag.
10637       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10638         << "'enable_if'" << TemplateArgString;
10639       return;
10640     }
10641
10642     // We found a specific requirement that disabled the enable_if.
10643     if (PDiag && PDiag->second.getDiagID() ==
10644         diag::err_typename_nested_not_found_requirement) {
10645       S.Diag(Templated->getLocation(),
10646              diag::note_ovl_candidate_disabled_by_requirement)
10647         << PDiag->second.getStringArg(0) << TemplateArgString;
10648       return;
10649     }
10650
10651     // Format the SFINAE diagnostic into the argument string.
10652     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10653     //        formatted message in another diagnostic.
10654     SmallString<128> SFINAEArgString;
10655     SourceRange R;
10656     if (PDiag) {
10657       SFINAEArgString = ": ";
10658       R = SourceRange(PDiag->first, PDiag->first);
10659       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10660     }
10661
10662     S.Diag(Templated->getLocation(),
10663            diag::note_ovl_candidate_substitution_failure)
10664         << TemplateArgString << SFINAEArgString << R;
10665     MaybeEmitInheritedConstructorNote(S, Found);
10666     return;
10667   }
10668
10669   case Sema::TDK_DeducedMismatch:
10670   case Sema::TDK_DeducedMismatchNested: {
10671     // Format the template argument list into the argument string.
10672     SmallString<128> TemplateArgString;
10673     if (TemplateArgumentList *Args =
10674             DeductionFailure.getTemplateArgumentList()) {
10675       TemplateArgString = " ";
10676       TemplateArgString += S.getTemplateArgumentBindingsText(
10677           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10678       if (TemplateArgString.size() == 1)
10679         TemplateArgString.clear();
10680     }
10681
10682     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10683         << (*DeductionFailure.getCallArgIndex() + 1)
10684         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10685         << TemplateArgString
10686         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10687     break;
10688   }
10689
10690   case Sema::TDK_NonDeducedMismatch: {
10691     // FIXME: Provide a source location to indicate what we couldn't match.
10692     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10693     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10694     if (FirstTA.getKind() == TemplateArgument::Template &&
10695         SecondTA.getKind() == TemplateArgument::Template) {
10696       TemplateName FirstTN = FirstTA.getAsTemplate();
10697       TemplateName SecondTN = SecondTA.getAsTemplate();
10698       if (FirstTN.getKind() == TemplateName::Template &&
10699           SecondTN.getKind() == TemplateName::Template) {
10700         if (FirstTN.getAsTemplateDecl()->getName() ==
10701             SecondTN.getAsTemplateDecl()->getName()) {
10702           // FIXME: This fixes a bad diagnostic where both templates are named
10703           // the same.  This particular case is a bit difficult since:
10704           // 1) It is passed as a string to the diagnostic printer.
10705           // 2) The diagnostic printer only attempts to find a better
10706           //    name for types, not decls.
10707           // Ideally, this should folded into the diagnostic printer.
10708           S.Diag(Templated->getLocation(),
10709                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10710               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10711           return;
10712         }
10713       }
10714     }
10715
10716     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10717         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10718       return;
10719
10720     // FIXME: For generic lambda parameters, check if the function is a lambda
10721     // call operator, and if so, emit a prettier and more informative
10722     // diagnostic that mentions 'auto' and lambda in addition to
10723     // (or instead of?) the canonical template type parameters.
10724     S.Diag(Templated->getLocation(),
10725            diag::note_ovl_candidate_non_deduced_mismatch)
10726         << FirstTA << SecondTA;
10727     return;
10728   }
10729   // TODO: diagnose these individually, then kill off
10730   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10731   case Sema::TDK_MiscellaneousDeductionFailure:
10732     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10733     MaybeEmitInheritedConstructorNote(S, Found);
10734     return;
10735   case Sema::TDK_CUDATargetMismatch:
10736     S.Diag(Templated->getLocation(),
10737            diag::note_cuda_ovl_candidate_target_mismatch);
10738     return;
10739   }
10740 }
10741
10742 /// Diagnose a failed template-argument deduction, for function calls.
10743 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10744                                  unsigned NumArgs,
10745                                  bool TakingCandidateAddress) {
10746   unsigned TDK = Cand->DeductionFailure.Result;
10747   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10748     if (CheckArityMismatch(S, Cand, NumArgs))
10749       return;
10750   }
10751   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10752                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10753 }
10754
10755 /// CUDA: diagnose an invalid call across targets.
10756 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10757   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10758   FunctionDecl *Callee = Cand->Function;
10759
10760   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10761                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10762
10763   std::string FnDesc;
10764   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10765       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10766                                 Cand->getRewriteKind(), FnDesc);
10767
10768   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10769       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10770       << FnDesc /* Ignored */
10771       << CalleeTarget << CallerTarget;
10772
10773   // This could be an implicit constructor for which we could not infer the
10774   // target due to a collsion. Diagnose that case.
10775   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10776   if (Meth != nullptr && Meth->isImplicit()) {
10777     CXXRecordDecl *ParentClass = Meth->getParent();
10778     Sema::CXXSpecialMember CSM;
10779
10780     switch (FnKindPair.first) {
10781     default:
10782       return;
10783     case oc_implicit_default_constructor:
10784       CSM = Sema::CXXDefaultConstructor;
10785       break;
10786     case oc_implicit_copy_constructor:
10787       CSM = Sema::CXXCopyConstructor;
10788       break;
10789     case oc_implicit_move_constructor:
10790       CSM = Sema::CXXMoveConstructor;
10791       break;
10792     case oc_implicit_copy_assignment:
10793       CSM = Sema::CXXCopyAssignment;
10794       break;
10795     case oc_implicit_move_assignment:
10796       CSM = Sema::CXXMoveAssignment;
10797       break;
10798     };
10799
10800     bool ConstRHS = false;
10801     if (Meth->getNumParams()) {
10802       if (const ReferenceType *RT =
10803               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10804         ConstRHS = RT->getPointeeType().isConstQualified();
10805       }
10806     }
10807
10808     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10809                                               /* ConstRHS */ ConstRHS,
10810                                               /* Diagnose */ true);
10811   }
10812 }
10813
10814 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10815   FunctionDecl *Callee = Cand->Function;
10816   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10817
10818   S.Diag(Callee->getLocation(),
10819          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10820       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10821 }
10822
10823 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10824   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10825   assert(ES.isExplicit() && "not an explicit candidate");
10826
10827   unsigned Kind;
10828   switch (Cand->Function->getDeclKind()) {
10829   case Decl::Kind::CXXConstructor:
10830     Kind = 0;
10831     break;
10832   case Decl::Kind::CXXConversion:
10833     Kind = 1;
10834     break;
10835   case Decl::Kind::CXXDeductionGuide:
10836     Kind = Cand->Function->isImplicit() ? 0 : 2;
10837     break;
10838   default:
10839     llvm_unreachable("invalid Decl");
10840   }
10841
10842   // Note the location of the first (in-class) declaration; a redeclaration
10843   // (particularly an out-of-class definition) will typically lack the
10844   // 'explicit' specifier.
10845   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10846   FunctionDecl *First = Cand->Function->getFirstDecl();
10847   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10848     First = Pattern->getFirstDecl();
10849
10850   S.Diag(First->getLocation(),
10851          diag::note_ovl_candidate_explicit)
10852       << Kind << (ES.getExpr() ? 1 : 0)
10853       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10854 }
10855
10856 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10857   FunctionDecl *Callee = Cand->Function;
10858
10859   S.Diag(Callee->getLocation(),
10860          diag::note_ovl_candidate_disabled_by_extension)
10861     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10862 }
10863
10864 /// Generates a 'note' diagnostic for an overload candidate.  We've
10865 /// already generated a primary error at the call site.
10866 ///
10867 /// It really does need to be a single diagnostic with its caret
10868 /// pointed at the candidate declaration.  Yes, this creates some
10869 /// major challenges of technical writing.  Yes, this makes pointing
10870 /// out problems with specific arguments quite awkward.  It's still
10871 /// better than generating twenty screens of text for every failed
10872 /// overload.
10873 ///
10874 /// It would be great to be able to express per-candidate problems
10875 /// more richly for those diagnostic clients that cared, but we'd
10876 /// still have to be just as careful with the default diagnostics.
10877 /// \param CtorDestAS Addr space of object being constructed (for ctor
10878 /// candidates only).
10879 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10880                                   unsigned NumArgs,
10881                                   bool TakingCandidateAddress,
10882                                   LangAS CtorDestAS = LangAS::Default) {
10883   FunctionDecl *Fn = Cand->Function;
10884
10885   // Note deleted candidates, but only if they're viable.
10886   if (Cand->Viable) {
10887     if (Fn->isDeleted()) {
10888       std::string FnDesc;
10889       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10890           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10891                                     Cand->getRewriteKind(), FnDesc);
10892
10893       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10894           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10895           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10896       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10897       return;
10898     }
10899
10900     // We don't really have anything else to say about viable candidates.
10901     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10902     return;
10903   }
10904
10905   switch (Cand->FailureKind) {
10906   case ovl_fail_too_many_arguments:
10907   case ovl_fail_too_few_arguments:
10908     return DiagnoseArityMismatch(S, Cand, NumArgs);
10909
10910   case ovl_fail_bad_deduction:
10911     return DiagnoseBadDeduction(S, Cand, NumArgs,
10912                                 TakingCandidateAddress);
10913
10914   case ovl_fail_illegal_constructor: {
10915     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10916       << (Fn->getPrimaryTemplate() ? 1 : 0);
10917     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10918     return;
10919   }
10920
10921   case ovl_fail_object_addrspace_mismatch: {
10922     Qualifiers QualsForPrinting;
10923     QualsForPrinting.setAddressSpace(CtorDestAS);
10924     S.Diag(Fn->getLocation(),
10925            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10926         << QualsForPrinting;
10927     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10928     return;
10929   }
10930
10931   case ovl_fail_trivial_conversion:
10932   case ovl_fail_bad_final_conversion:
10933   case ovl_fail_final_conversion_not_exact:
10934     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10935
10936   case ovl_fail_bad_conversion: {
10937     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10938     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10939       if (Cand->Conversions[I].isBad())
10940         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10941
10942     // FIXME: this currently happens when we're called from SemaInit
10943     // when user-conversion overload fails.  Figure out how to handle
10944     // those conditions and diagnose them well.
10945     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10946   }
10947
10948   case ovl_fail_bad_target:
10949     return DiagnoseBadTarget(S, Cand);
10950
10951   case ovl_fail_enable_if:
10952     return DiagnoseFailedEnableIfAttr(S, Cand);
10953
10954   case ovl_fail_explicit:
10955     return DiagnoseFailedExplicitSpec(S, Cand);
10956
10957   case ovl_fail_ext_disabled:
10958     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10959
10960   case ovl_fail_inhctor_slice:
10961     // It's generally not interesting to note copy/move constructors here.
10962     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10963       return;
10964     S.Diag(Fn->getLocation(),
10965            diag::note_ovl_candidate_inherited_constructor_slice)
10966       << (Fn->getPrimaryTemplate() ? 1 : 0)
10967       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10968     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10969     return;
10970
10971   case ovl_fail_addr_not_available: {
10972     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10973     (void)Available;
10974     assert(!Available);
10975     break;
10976   }
10977   case ovl_non_default_multiversion_function:
10978     // Do nothing, these should simply be ignored.
10979     break;
10980
10981   case ovl_fail_constraints_not_satisfied: {
10982     std::string FnDesc;
10983     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10984         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10985                                   Cand->getRewriteKind(), FnDesc);
10986
10987     S.Diag(Fn->getLocation(),
10988            diag::note_ovl_candidate_constraints_not_satisfied)
10989         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10990         << FnDesc /* Ignored */;
10991     ConstraintSatisfaction Satisfaction;
10992     if (S.CheckFunctionConstraints(Fn, Satisfaction))
10993       break;
10994     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10995   }
10996   }
10997 }
10998
10999 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11000   // Desugar the type of the surrogate down to a function type,
11001   // retaining as many typedefs as possible while still showing
11002   // the function type (and, therefore, its parameter types).
11003   QualType FnType = Cand->Surrogate->getConversionType();
11004   bool isLValueReference = false;
11005   bool isRValueReference = false;
11006   bool isPointer = false;
11007   if (const LValueReferenceType *FnTypeRef =
11008         FnType->getAs<LValueReferenceType>()) {
11009     FnType = FnTypeRef->getPointeeType();
11010     isLValueReference = true;
11011   } else if (const RValueReferenceType *FnTypeRef =
11012                FnType->getAs<RValueReferenceType>()) {
11013     FnType = FnTypeRef->getPointeeType();
11014     isRValueReference = true;
11015   }
11016   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11017     FnType = FnTypePtr->getPointeeType();
11018     isPointer = true;
11019   }
11020   // Desugar down to a function type.
11021   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11022   // Reconstruct the pointer/reference as appropriate.
11023   if (isPointer) FnType = S.Context.getPointerType(FnType);
11024   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11025   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11026
11027   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11028     << FnType;
11029 }
11030
11031 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11032                                          SourceLocation OpLoc,
11033                                          OverloadCandidate *Cand) {
11034   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11035   std::string TypeStr("operator");
11036   TypeStr += Opc;
11037   TypeStr += "(";
11038   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11039   if (Cand->Conversions.size() == 1) {
11040     TypeStr += ")";
11041     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11042   } else {
11043     TypeStr += ", ";
11044     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11045     TypeStr += ")";
11046     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11047   }
11048 }
11049
11050 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11051                                          OverloadCandidate *Cand) {
11052   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11053     if (ICS.isBad()) break; // all meaningless after first invalid
11054     if (!ICS.isAmbiguous()) continue;
11055
11056     ICS.DiagnoseAmbiguousConversion(
11057         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11058   }
11059 }
11060
11061 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11062   if (Cand->Function)
11063     return Cand->Function->getLocation();
11064   if (Cand->IsSurrogate)
11065     return Cand->Surrogate->getLocation();
11066   return SourceLocation();
11067 }
11068
11069 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11070   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11071   case Sema::TDK_Success:
11072   case Sema::TDK_NonDependentConversionFailure:
11073     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11074
11075   case Sema::TDK_Invalid:
11076   case Sema::TDK_Incomplete:
11077   case Sema::TDK_IncompletePack:
11078     return 1;
11079
11080   case Sema::TDK_Underqualified:
11081   case Sema::TDK_Inconsistent:
11082     return 2;
11083
11084   case Sema::TDK_SubstitutionFailure:
11085   case Sema::TDK_DeducedMismatch:
11086   case Sema::TDK_ConstraintsNotSatisfied:
11087   case Sema::TDK_DeducedMismatchNested:
11088   case Sema::TDK_NonDeducedMismatch:
11089   case Sema::TDK_MiscellaneousDeductionFailure:
11090   case Sema::TDK_CUDATargetMismatch:
11091     return 3;
11092
11093   case Sema::TDK_InstantiationDepth:
11094     return 4;
11095
11096   case Sema::TDK_InvalidExplicitArguments:
11097     return 5;
11098
11099   case Sema::TDK_TooManyArguments:
11100   case Sema::TDK_TooFewArguments:
11101     return 6;
11102   }
11103   llvm_unreachable("Unhandled deduction result");
11104 }
11105
11106 namespace {
11107 struct CompareOverloadCandidatesForDisplay {
11108   Sema &S;
11109   SourceLocation Loc;
11110   size_t NumArgs;
11111   OverloadCandidateSet::CandidateSetKind CSK;
11112
11113   CompareOverloadCandidatesForDisplay(
11114       Sema &S, SourceLocation Loc, size_t NArgs,
11115       OverloadCandidateSet::CandidateSetKind CSK)
11116       : S(S), NumArgs(NArgs), CSK(CSK) {}
11117
11118   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11119     // If there are too many or too few arguments, that's the high-order bit we
11120     // want to sort by, even if the immediate failure kind was something else.
11121     if (C->FailureKind == ovl_fail_too_many_arguments ||
11122         C->FailureKind == ovl_fail_too_few_arguments)
11123       return static_cast<OverloadFailureKind>(C->FailureKind);
11124
11125     if (C->Function) {
11126       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11127         return ovl_fail_too_many_arguments;
11128       if (NumArgs < C->Function->getMinRequiredArguments())
11129         return ovl_fail_too_few_arguments;
11130     }
11131
11132     return static_cast<OverloadFailureKind>(C->FailureKind);
11133   }
11134
11135   bool operator()(const OverloadCandidate *L,
11136                   const OverloadCandidate *R) {
11137     // Fast-path this check.
11138     if (L == R) return false;
11139
11140     // Order first by viability.
11141     if (L->Viable) {
11142       if (!R->Viable) return true;
11143
11144       // TODO: introduce a tri-valued comparison for overload
11145       // candidates.  Would be more worthwhile if we had a sort
11146       // that could exploit it.
11147       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11148         return true;
11149       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11150         return false;
11151     } else if (R->Viable)
11152       return false;
11153
11154     assert(L->Viable == R->Viable);
11155
11156     // Criteria by which we can sort non-viable candidates:
11157     if (!L->Viable) {
11158       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11159       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11160
11161       // 1. Arity mismatches come after other candidates.
11162       if (LFailureKind == ovl_fail_too_many_arguments ||
11163           LFailureKind == ovl_fail_too_few_arguments) {
11164         if (RFailureKind == ovl_fail_too_many_arguments ||
11165             RFailureKind == ovl_fail_too_few_arguments) {
11166           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11167           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11168           if (LDist == RDist) {
11169             if (LFailureKind == RFailureKind)
11170               // Sort non-surrogates before surrogates.
11171               return !L->IsSurrogate && R->IsSurrogate;
11172             // Sort candidates requiring fewer parameters than there were
11173             // arguments given after candidates requiring more parameters
11174             // than there were arguments given.
11175             return LFailureKind == ovl_fail_too_many_arguments;
11176           }
11177           return LDist < RDist;
11178         }
11179         return false;
11180       }
11181       if (RFailureKind == ovl_fail_too_many_arguments ||
11182           RFailureKind == ovl_fail_too_few_arguments)
11183         return true;
11184
11185       // 2. Bad conversions come first and are ordered by the number
11186       // of bad conversions and quality of good conversions.
11187       if (LFailureKind == ovl_fail_bad_conversion) {
11188         if (RFailureKind != ovl_fail_bad_conversion)
11189           return true;
11190
11191         // The conversion that can be fixed with a smaller number of changes,
11192         // comes first.
11193         unsigned numLFixes = L->Fix.NumConversionsFixed;
11194         unsigned numRFixes = R->Fix.NumConversionsFixed;
11195         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11196         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11197         if (numLFixes != numRFixes) {
11198           return numLFixes < numRFixes;
11199         }
11200
11201         // If there's any ordering between the defined conversions...
11202         // FIXME: this might not be transitive.
11203         assert(L->Conversions.size() == R->Conversions.size());
11204
11205         int leftBetter = 0;
11206         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11207         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11208           switch (CompareImplicitConversionSequences(S, Loc,
11209                                                      L->Conversions[I],
11210                                                      R->Conversions[I])) {
11211           case ImplicitConversionSequence::Better:
11212             leftBetter++;
11213             break;
11214
11215           case ImplicitConversionSequence::Worse:
11216             leftBetter--;
11217             break;
11218
11219           case ImplicitConversionSequence::Indistinguishable:
11220             break;
11221           }
11222         }
11223         if (leftBetter > 0) return true;
11224         if (leftBetter < 0) return false;
11225
11226       } else if (RFailureKind == ovl_fail_bad_conversion)
11227         return false;
11228
11229       if (LFailureKind == ovl_fail_bad_deduction) {
11230         if (RFailureKind != ovl_fail_bad_deduction)
11231           return true;
11232
11233         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11234           return RankDeductionFailure(L->DeductionFailure)
11235                < RankDeductionFailure(R->DeductionFailure);
11236       } else if (RFailureKind == ovl_fail_bad_deduction)
11237         return false;
11238
11239       // TODO: others?
11240     }
11241
11242     // Sort everything else by location.
11243     SourceLocation LLoc = GetLocationForCandidate(L);
11244     SourceLocation RLoc = GetLocationForCandidate(R);
11245
11246     // Put candidates without locations (e.g. builtins) at the end.
11247     if (LLoc.isInvalid()) return false;
11248     if (RLoc.isInvalid()) return true;
11249
11250     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11251   }
11252 };
11253 }
11254
11255 /// CompleteNonViableCandidate - Normally, overload resolution only
11256 /// computes up to the first bad conversion. Produces the FixIt set if
11257 /// possible.
11258 static void
11259 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11260                            ArrayRef<Expr *> Args,
11261                            OverloadCandidateSet::CandidateSetKind CSK) {
11262   assert(!Cand->Viable);
11263
11264   // Don't do anything on failures other than bad conversion.
11265   if (Cand->FailureKind != ovl_fail_bad_conversion)
11266     return;
11267
11268   // We only want the FixIts if all the arguments can be corrected.
11269   bool Unfixable = false;
11270   // Use a implicit copy initialization to check conversion fixes.
11271   Cand->Fix.setConversionChecker(TryCopyInitialization);
11272
11273   // Attempt to fix the bad conversion.
11274   unsigned ConvCount = Cand->Conversions.size();
11275   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11276        ++ConvIdx) {
11277     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11278     if (Cand->Conversions[ConvIdx].isInitialized() &&
11279         Cand->Conversions[ConvIdx].isBad()) {
11280       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11281       break;
11282     }
11283   }
11284
11285   // FIXME: this should probably be preserved from the overload
11286   // operation somehow.
11287   bool SuppressUserConversions = false;
11288
11289   unsigned ConvIdx = 0;
11290   unsigned ArgIdx = 0;
11291   ArrayRef<QualType> ParamTypes;
11292   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11293
11294   if (Cand->IsSurrogate) {
11295     QualType ConvType
11296       = Cand->Surrogate->getConversionType().getNonReferenceType();
11297     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11298       ConvType = ConvPtrType->getPointeeType();
11299     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11300     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11301     ConvIdx = 1;
11302   } else if (Cand->Function) {
11303     ParamTypes =
11304         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11305     if (isa<CXXMethodDecl>(Cand->Function) &&
11306         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11307       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11308       ConvIdx = 1;
11309       if (CSK == OverloadCandidateSet::CSK_Operator &&
11310           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11311         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11312         ArgIdx = 1;
11313     }
11314   } else {
11315     // Builtin operator.
11316     assert(ConvCount <= 3);
11317     ParamTypes = Cand->BuiltinParamTypes;
11318   }
11319
11320   // Fill in the rest of the conversions.
11321   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11322        ConvIdx != ConvCount;
11323        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11324     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11325     if (Cand->Conversions[ConvIdx].isInitialized()) {
11326       // We've already checked this conversion.
11327     } else if (ParamIdx < ParamTypes.size()) {
11328       if (ParamTypes[ParamIdx]->isDependentType())
11329         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11330             Args[ArgIdx]->getType());
11331       else {
11332         Cand->Conversions[ConvIdx] =
11333             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11334                                   SuppressUserConversions,
11335                                   /*InOverloadResolution=*/true,
11336                                   /*AllowObjCWritebackConversion=*/
11337                                   S.getLangOpts().ObjCAutoRefCount);
11338         // Store the FixIt in the candidate if it exists.
11339         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11340           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11341       }
11342     } else
11343       Cand->Conversions[ConvIdx].setEllipsis();
11344   }
11345 }
11346
11347 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11348     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11349     SourceLocation OpLoc,
11350     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11351   // Sort the candidates by viability and position.  Sorting directly would
11352   // be prohibitive, so we make a set of pointers and sort those.
11353   SmallVector<OverloadCandidate*, 32> Cands;
11354   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11355   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11356     if (!Filter(*Cand))
11357       continue;
11358     switch (OCD) {
11359     case OCD_AllCandidates:
11360       if (!Cand->Viable) {
11361         if (!Cand->Function && !Cand->IsSurrogate) {
11362           // This a non-viable builtin candidate.  We do not, in general,
11363           // want to list every possible builtin candidate.
11364           continue;
11365         }
11366         CompleteNonViableCandidate(S, Cand, Args, Kind);
11367       }
11368       break;
11369
11370     case OCD_ViableCandidates:
11371       if (!Cand->Viable)
11372         continue;
11373       break;
11374
11375     case OCD_AmbiguousCandidates:
11376       if (!Cand->Best)
11377         continue;
11378       break;
11379     }
11380
11381     Cands.push_back(Cand);
11382   }
11383
11384   llvm::stable_sort(
11385       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11386
11387   return Cands;
11388 }
11389
11390 /// When overload resolution fails, prints diagnostic messages containing the
11391 /// candidates in the candidate set.
11392 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11393     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11394     StringRef Opc, SourceLocation OpLoc,
11395     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11396
11397   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11398
11399   S.Diag(PD.first, PD.second);
11400
11401   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11402
11403   if (OCD == OCD_AmbiguousCandidates)
11404     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11405 }
11406
11407 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11408                                           ArrayRef<OverloadCandidate *> Cands,
11409                                           StringRef Opc, SourceLocation OpLoc) {
11410   bool ReportedAmbiguousConversions = false;
11411
11412   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11413   unsigned CandsShown = 0;
11414   auto I = Cands.begin(), E = Cands.end();
11415   for (; I != E; ++I) {
11416     OverloadCandidate *Cand = *I;
11417
11418     // Set an arbitrary limit on the number of candidate functions we'll spam
11419     // the user with.  FIXME: This limit should depend on details of the
11420     // candidate list.
11421     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11422       break;
11423     }
11424     ++CandsShown;
11425
11426     if (Cand->Function)
11427       NoteFunctionCandidate(S, Cand, Args.size(),
11428                             /*TakingCandidateAddress=*/false, DestAS);
11429     else if (Cand->IsSurrogate)
11430       NoteSurrogateCandidate(S, Cand);
11431     else {
11432       assert(Cand->Viable &&
11433              "Non-viable built-in candidates are not added to Cands.");
11434       // Generally we only see ambiguities including viable builtin
11435       // operators if overload resolution got screwed up by an
11436       // ambiguous user-defined conversion.
11437       //
11438       // FIXME: It's quite possible for different conversions to see
11439       // different ambiguities, though.
11440       if (!ReportedAmbiguousConversions) {
11441         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11442         ReportedAmbiguousConversions = true;
11443       }
11444
11445       // If this is a viable builtin, print it.
11446       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11447     }
11448   }
11449
11450   if (I != E)
11451     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11452 }
11453
11454 static SourceLocation
11455 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11456   return Cand->Specialization ? Cand->Specialization->getLocation()
11457                               : SourceLocation();
11458 }
11459
11460 namespace {
11461 struct CompareTemplateSpecCandidatesForDisplay {
11462   Sema &S;
11463   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11464
11465   bool operator()(const TemplateSpecCandidate *L,
11466                   const TemplateSpecCandidate *R) {
11467     // Fast-path this check.
11468     if (L == R)
11469       return false;
11470
11471     // Assuming that both candidates are not matches...
11472
11473     // Sort by the ranking of deduction failures.
11474     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11475       return RankDeductionFailure(L->DeductionFailure) <
11476              RankDeductionFailure(R->DeductionFailure);
11477
11478     // Sort everything else by location.
11479     SourceLocation LLoc = GetLocationForCandidate(L);
11480     SourceLocation RLoc = GetLocationForCandidate(R);
11481
11482     // Put candidates without locations (e.g. builtins) at the end.
11483     if (LLoc.isInvalid())
11484       return false;
11485     if (RLoc.isInvalid())
11486       return true;
11487
11488     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11489   }
11490 };
11491 }
11492
11493 /// Diagnose a template argument deduction failure.
11494 /// We are treating these failures as overload failures due to bad
11495 /// deductions.
11496 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11497                                                  bool ForTakingAddress) {
11498   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11499                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11500 }
11501
11502 void TemplateSpecCandidateSet::destroyCandidates() {
11503   for (iterator i = begin(), e = end(); i != e; ++i) {
11504     i->DeductionFailure.Destroy();
11505   }
11506 }
11507
11508 void TemplateSpecCandidateSet::clear() {
11509   destroyCandidates();
11510   Candidates.clear();
11511 }
11512
11513 /// NoteCandidates - When no template specialization match is found, prints
11514 /// diagnostic messages containing the non-matching specializations that form
11515 /// the candidate set.
11516 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11517 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11518 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11519   // Sort the candidates by position (assuming no candidate is a match).
11520   // Sorting directly would be prohibitive, so we make a set of pointers
11521   // and sort those.
11522   SmallVector<TemplateSpecCandidate *, 32> Cands;
11523   Cands.reserve(size());
11524   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11525     if (Cand->Specialization)
11526       Cands.push_back(Cand);
11527     // Otherwise, this is a non-matching builtin candidate.  We do not,
11528     // in general, want to list every possible builtin candidate.
11529   }
11530
11531   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11532
11533   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11534   // for generalization purposes (?).
11535   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11536
11537   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11538   unsigned CandsShown = 0;
11539   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11540     TemplateSpecCandidate *Cand = *I;
11541
11542     // Set an arbitrary limit on the number of candidates we'll spam
11543     // the user with.  FIXME: This limit should depend on details of the
11544     // candidate list.
11545     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11546       break;
11547     ++CandsShown;
11548
11549     assert(Cand->Specialization &&
11550            "Non-matching built-in candidates are not added to Cands.");
11551     Cand->NoteDeductionFailure(S, ForTakingAddress);
11552   }
11553
11554   if (I != E)
11555     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11556 }
11557
11558 // [PossiblyAFunctionType]  -->   [Return]
11559 // NonFunctionType --> NonFunctionType
11560 // R (A) --> R(A)
11561 // R (*)(A) --> R (A)
11562 // R (&)(A) --> R (A)
11563 // R (S::*)(A) --> R (A)
11564 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11565   QualType Ret = PossiblyAFunctionType;
11566   if (const PointerType *ToTypePtr =
11567     PossiblyAFunctionType->getAs<PointerType>())
11568     Ret = ToTypePtr->getPointeeType();
11569   else if (const ReferenceType *ToTypeRef =
11570     PossiblyAFunctionType->getAs<ReferenceType>())
11571     Ret = ToTypeRef->getPointeeType();
11572   else if (const MemberPointerType *MemTypePtr =
11573     PossiblyAFunctionType->getAs<MemberPointerType>())
11574     Ret = MemTypePtr->getPointeeType();
11575   Ret =
11576     Context.getCanonicalType(Ret).getUnqualifiedType();
11577   return Ret;
11578 }
11579
11580 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11581                                  bool Complain = true) {
11582   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11583       S.DeduceReturnType(FD, Loc, Complain))
11584     return true;
11585
11586   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11587   if (S.getLangOpts().CPlusPlus17 &&
11588       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11589       !S.ResolveExceptionSpec(Loc, FPT))
11590     return true;
11591
11592   return false;
11593 }
11594
11595 namespace {
11596 // A helper class to help with address of function resolution
11597 // - allows us to avoid passing around all those ugly parameters
11598 class AddressOfFunctionResolver {
11599   Sema& S;
11600   Expr* SourceExpr;
11601   const QualType& TargetType;
11602   QualType TargetFunctionType; // Extracted function type from target type
11603
11604   bool Complain;
11605   //DeclAccessPair& ResultFunctionAccessPair;
11606   ASTContext& Context;
11607
11608   bool TargetTypeIsNonStaticMemberFunction;
11609   bool FoundNonTemplateFunction;
11610   bool StaticMemberFunctionFromBoundPointer;
11611   bool HasComplained;
11612
11613   OverloadExpr::FindResult OvlExprInfo;
11614   OverloadExpr *OvlExpr;
11615   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11616   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11617   TemplateSpecCandidateSet FailedCandidates;
11618
11619 public:
11620   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11621                             const QualType &TargetType, bool Complain)
11622       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11623         Complain(Complain), Context(S.getASTContext()),
11624         TargetTypeIsNonStaticMemberFunction(
11625             !!TargetType->getAs<MemberPointerType>()),
11626         FoundNonTemplateFunction(false),
11627         StaticMemberFunctionFromBoundPointer(false),
11628         HasComplained(false),
11629         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11630         OvlExpr(OvlExprInfo.Expression),
11631         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11632     ExtractUnqualifiedFunctionTypeFromTargetType();
11633
11634     if (TargetFunctionType->isFunctionType()) {
11635       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11636         if (!UME->isImplicitAccess() &&
11637             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11638           StaticMemberFunctionFromBoundPointer = true;
11639     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11640       DeclAccessPair dap;
11641       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11642               OvlExpr, false, &dap)) {
11643         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11644           if (!Method->isStatic()) {
11645             // If the target type is a non-function type and the function found
11646             // is a non-static member function, pretend as if that was the
11647             // target, it's the only possible type to end up with.
11648             TargetTypeIsNonStaticMemberFunction = true;
11649
11650             // And skip adding the function if its not in the proper form.
11651             // We'll diagnose this due to an empty set of functions.
11652             if (!OvlExprInfo.HasFormOfMemberPointer)
11653               return;
11654           }
11655
11656         Matches.push_back(std::make_pair(dap, Fn));
11657       }
11658       return;
11659     }
11660
11661     if (OvlExpr->hasExplicitTemplateArgs())
11662       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11663
11664     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11665       // C++ [over.over]p4:
11666       //   If more than one function is selected, [...]
11667       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11668         if (FoundNonTemplateFunction)
11669           EliminateAllTemplateMatches();
11670         else
11671           EliminateAllExceptMostSpecializedTemplate();
11672       }
11673     }
11674
11675     if (S.getLangOpts().CUDA && Matches.size() > 1)
11676       EliminateSuboptimalCudaMatches();
11677   }
11678
11679   bool hasComplained() const { return HasComplained; }
11680
11681 private:
11682   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11683     QualType Discard;
11684     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11685            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11686   }
11687
11688   /// \return true if A is considered a better overload candidate for the
11689   /// desired type than B.
11690   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11691     // If A doesn't have exactly the correct type, we don't want to classify it
11692     // as "better" than anything else. This way, the user is required to
11693     // disambiguate for us if there are multiple candidates and no exact match.
11694     return candidateHasExactlyCorrectType(A) &&
11695            (!candidateHasExactlyCorrectType(B) ||
11696             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11697   }
11698
11699   /// \return true if we were able to eliminate all but one overload candidate,
11700   /// false otherwise.
11701   bool eliminiateSuboptimalOverloadCandidates() {
11702     // Same algorithm as overload resolution -- one pass to pick the "best",
11703     // another pass to be sure that nothing is better than the best.
11704     auto Best = Matches.begin();
11705     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11706       if (isBetterCandidate(I->second, Best->second))
11707         Best = I;
11708
11709     const FunctionDecl *BestFn = Best->second;
11710     auto IsBestOrInferiorToBest = [this, BestFn](
11711         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11712       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11713     };
11714
11715     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11716     // option, so we can potentially give the user a better error
11717     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11718       return false;
11719     Matches[0] = *Best;
11720     Matches.resize(1);
11721     return true;
11722   }
11723
11724   bool isTargetTypeAFunction() const {
11725     return TargetFunctionType->isFunctionType();
11726   }
11727
11728   // [ToType]     [Return]
11729
11730   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11731   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11732   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11733   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11734     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11735   }
11736
11737   // return true if any matching specializations were found
11738   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11739                                    const DeclAccessPair& CurAccessFunPair) {
11740     if (CXXMethodDecl *Method
11741               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11742       // Skip non-static function templates when converting to pointer, and
11743       // static when converting to member pointer.
11744       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11745         return false;
11746     }
11747     else if (TargetTypeIsNonStaticMemberFunction)
11748       return false;
11749
11750     // C++ [over.over]p2:
11751     //   If the name is a function template, template argument deduction is
11752     //   done (14.8.2.2), and if the argument deduction succeeds, the
11753     //   resulting template argument list is used to generate a single
11754     //   function template specialization, which is added to the set of
11755     //   overloaded functions considered.
11756     FunctionDecl *Specialization = nullptr;
11757     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11758     if (Sema::TemplateDeductionResult Result
11759           = S.DeduceTemplateArguments(FunctionTemplate,
11760                                       &OvlExplicitTemplateArgs,
11761                                       TargetFunctionType, Specialization,
11762                                       Info, /*IsAddressOfFunction*/true)) {
11763       // Make a note of the failed deduction for diagnostics.
11764       FailedCandidates.addCandidate()
11765           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11766                MakeDeductionFailureInfo(Context, Result, Info));
11767       return false;
11768     }
11769
11770     // Template argument deduction ensures that we have an exact match or
11771     // compatible pointer-to-function arguments that would be adjusted by ICS.
11772     // This function template specicalization works.
11773     assert(S.isSameOrCompatibleFunctionType(
11774               Context.getCanonicalType(Specialization->getType()),
11775               Context.getCanonicalType(TargetFunctionType)));
11776
11777     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11778       return false;
11779
11780     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11781     return true;
11782   }
11783
11784   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11785                                       const DeclAccessPair& CurAccessFunPair) {
11786     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11787       // Skip non-static functions when converting to pointer, and static
11788       // when converting to member pointer.
11789       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11790         return false;
11791     }
11792     else if (TargetTypeIsNonStaticMemberFunction)
11793       return false;
11794
11795     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11796       if (S.getLangOpts().CUDA)
11797         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11798           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11799             return false;
11800       if (FunDecl->isMultiVersion()) {
11801         const auto *TA = FunDecl->getAttr<TargetAttr>();
11802         if (TA && !TA->isDefaultVersion())
11803           return false;
11804       }
11805
11806       // If any candidate has a placeholder return type, trigger its deduction
11807       // now.
11808       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11809                                Complain)) {
11810         HasComplained |= Complain;
11811         return false;
11812       }
11813
11814       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11815         return false;
11816
11817       // If we're in C, we need to support types that aren't exactly identical.
11818       if (!S.getLangOpts().CPlusPlus ||
11819           candidateHasExactlyCorrectType(FunDecl)) {
11820         Matches.push_back(std::make_pair(
11821             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11822         FoundNonTemplateFunction = true;
11823         return true;
11824       }
11825     }
11826
11827     return false;
11828   }
11829
11830   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11831     bool Ret = false;
11832
11833     // If the overload expression doesn't have the form of a pointer to
11834     // member, don't try to convert it to a pointer-to-member type.
11835     if (IsInvalidFormOfPointerToMemberFunction())
11836       return false;
11837
11838     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11839                                E = OvlExpr->decls_end();
11840          I != E; ++I) {
11841       // Look through any using declarations to find the underlying function.
11842       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11843
11844       // C++ [over.over]p3:
11845       //   Non-member functions and static member functions match
11846       //   targets of type "pointer-to-function" or "reference-to-function."
11847       //   Nonstatic member functions match targets of
11848       //   type "pointer-to-member-function."
11849       // Note that according to DR 247, the containing class does not matter.
11850       if (FunctionTemplateDecl *FunctionTemplate
11851                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11852         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11853           Ret = true;
11854       }
11855       // If we have explicit template arguments supplied, skip non-templates.
11856       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11857                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11858         Ret = true;
11859     }
11860     assert(Ret || Matches.empty());
11861     return Ret;
11862   }
11863
11864   void EliminateAllExceptMostSpecializedTemplate() {
11865     //   [...] and any given function template specialization F1 is
11866     //   eliminated if the set contains a second function template
11867     //   specialization whose function template is more specialized
11868     //   than the function template of F1 according to the partial
11869     //   ordering rules of 14.5.5.2.
11870
11871     // The algorithm specified above is quadratic. We instead use a
11872     // two-pass algorithm (similar to the one used to identify the
11873     // best viable function in an overload set) that identifies the
11874     // best function template (if it exists).
11875
11876     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11877     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11878       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11879
11880     // TODO: It looks like FailedCandidates does not serve much purpose
11881     // here, since the no_viable diagnostic has index 0.
11882     UnresolvedSetIterator Result = S.getMostSpecialized(
11883         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11884         SourceExpr->getBeginLoc(), S.PDiag(),
11885         S.PDiag(diag::err_addr_ovl_ambiguous)
11886             << Matches[0].second->getDeclName(),
11887         S.PDiag(diag::note_ovl_candidate)
11888             << (unsigned)oc_function << (unsigned)ocs_described_template,
11889         Complain, TargetFunctionType);
11890
11891     if (Result != MatchesCopy.end()) {
11892       // Make it the first and only element
11893       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11894       Matches[0].second = cast<FunctionDecl>(*Result);
11895       Matches.resize(1);
11896     } else
11897       HasComplained |= Complain;
11898   }
11899
11900   void EliminateAllTemplateMatches() {
11901     //   [...] any function template specializations in the set are
11902     //   eliminated if the set also contains a non-template function, [...]
11903     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11904       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11905         ++I;
11906       else {
11907         Matches[I] = Matches[--N];
11908         Matches.resize(N);
11909       }
11910     }
11911   }
11912
11913   void EliminateSuboptimalCudaMatches() {
11914     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11915   }
11916
11917 public:
11918   void ComplainNoMatchesFound() const {
11919     assert(Matches.empty());
11920     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11921         << OvlExpr->getName() << TargetFunctionType
11922         << OvlExpr->getSourceRange();
11923     if (FailedCandidates.empty())
11924       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11925                                   /*TakingAddress=*/true);
11926     else {
11927       // We have some deduction failure messages. Use them to diagnose
11928       // the function templates, and diagnose the non-template candidates
11929       // normally.
11930       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11931                                  IEnd = OvlExpr->decls_end();
11932            I != IEnd; ++I)
11933         if (FunctionDecl *Fun =
11934                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11935           if (!functionHasPassObjectSizeParams(Fun))
11936             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11937                                     /*TakingAddress=*/true);
11938       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11939     }
11940   }
11941
11942   bool IsInvalidFormOfPointerToMemberFunction() const {
11943     return TargetTypeIsNonStaticMemberFunction &&
11944       !OvlExprInfo.HasFormOfMemberPointer;
11945   }
11946
11947   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11948       // TODO: Should we condition this on whether any functions might
11949       // have matched, or is it more appropriate to do that in callers?
11950       // TODO: a fixit wouldn't hurt.
11951       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11952         << TargetType << OvlExpr->getSourceRange();
11953   }
11954
11955   bool IsStaticMemberFunctionFromBoundPointer() const {
11956     return StaticMemberFunctionFromBoundPointer;
11957   }
11958
11959   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11960     S.Diag(OvlExpr->getBeginLoc(),
11961            diag::err_invalid_form_pointer_member_function)
11962         << OvlExpr->getSourceRange();
11963   }
11964
11965   void ComplainOfInvalidConversion() const {
11966     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11967         << OvlExpr->getName() << TargetType;
11968   }
11969
11970   void ComplainMultipleMatchesFound() const {
11971     assert(Matches.size() > 1);
11972     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11973         << OvlExpr->getName() << OvlExpr->getSourceRange();
11974     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11975                                 /*TakingAddress=*/true);
11976   }
11977
11978   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11979
11980   int getNumMatches() const { return Matches.size(); }
11981
11982   FunctionDecl* getMatchingFunctionDecl() const {
11983     if (Matches.size() != 1) return nullptr;
11984     return Matches[0].second;
11985   }
11986
11987   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11988     if (Matches.size() != 1) return nullptr;
11989     return &Matches[0].first;
11990   }
11991 };
11992 }
11993
11994 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11995 /// an overloaded function (C++ [over.over]), where @p From is an
11996 /// expression with overloaded function type and @p ToType is the type
11997 /// we're trying to resolve to. For example:
11998 ///
11999 /// @code
12000 /// int f(double);
12001 /// int f(int);
12002 ///
12003 /// int (*pfd)(double) = f; // selects f(double)
12004 /// @endcode
12005 ///
12006 /// This routine returns the resulting FunctionDecl if it could be
12007 /// resolved, and NULL otherwise. When @p Complain is true, this
12008 /// routine will emit diagnostics if there is an error.
12009 FunctionDecl *
12010 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12011                                          QualType TargetType,
12012                                          bool Complain,
12013                                          DeclAccessPair &FoundResult,
12014                                          bool *pHadMultipleCandidates) {
12015   assert(AddressOfExpr->getType() == Context.OverloadTy);
12016
12017   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12018                                      Complain);
12019   int NumMatches = Resolver.getNumMatches();
12020   FunctionDecl *Fn = nullptr;
12021   bool ShouldComplain = Complain && !Resolver.hasComplained();
12022   if (NumMatches == 0 && ShouldComplain) {
12023     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12024       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12025     else
12026       Resolver.ComplainNoMatchesFound();
12027   }
12028   else if (NumMatches > 1 && ShouldComplain)
12029     Resolver.ComplainMultipleMatchesFound();
12030   else if (NumMatches == 1) {
12031     Fn = Resolver.getMatchingFunctionDecl();
12032     assert(Fn);
12033     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12034       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12035     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12036     if (Complain) {
12037       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12038         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12039       else
12040         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12041     }
12042   }
12043
12044   if (pHadMultipleCandidates)
12045     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12046   return Fn;
12047 }
12048
12049 /// Given an expression that refers to an overloaded function, try to
12050 /// resolve that function to a single function that can have its address taken.
12051 /// This will modify `Pair` iff it returns non-null.
12052 ///
12053 /// This routine can only succeed if from all of the candidates in the overload
12054 /// set for SrcExpr that can have their addresses taken, there is one candidate
12055 /// that is more constrained than the rest.
12056 FunctionDecl *
12057 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12058   OverloadExpr::FindResult R = OverloadExpr::find(E);
12059   OverloadExpr *Ovl = R.Expression;
12060   bool IsResultAmbiguous = false;
12061   FunctionDecl *Result = nullptr;
12062   DeclAccessPair DAP;
12063   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12064
12065   auto CheckMoreConstrained =
12066       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12067         SmallVector<const Expr *, 1> AC1, AC2;
12068         FD1->getAssociatedConstraints(AC1);
12069         FD2->getAssociatedConstraints(AC2);
12070         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12071         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12072           return None;
12073         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12074           return None;
12075         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12076           return None;
12077         return AtLeastAsConstrained1;
12078       };
12079
12080   // Don't use the AddressOfResolver because we're specifically looking for
12081   // cases where we have one overload candidate that lacks
12082   // enable_if/pass_object_size/...
12083   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12084     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12085     if (!FD)
12086       return nullptr;
12087
12088     if (!checkAddressOfFunctionIsAvailable(FD))
12089       continue;
12090
12091     // We have more than one result - see if it is more constrained than the
12092     // previous one.
12093     if (Result) {
12094       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12095                                                                         Result);
12096       if (!MoreConstrainedThanPrevious) {
12097         IsResultAmbiguous = true;
12098         AmbiguousDecls.push_back(FD);
12099         continue;
12100       }
12101       if (!*MoreConstrainedThanPrevious)
12102         continue;
12103       // FD is more constrained - replace Result with it.
12104     }
12105     IsResultAmbiguous = false;
12106     DAP = I.getPair();
12107     Result = FD;
12108   }
12109
12110   if (IsResultAmbiguous)
12111     return nullptr;
12112
12113   if (Result) {
12114     SmallVector<const Expr *, 1> ResultAC;
12115     // We skipped over some ambiguous declarations which might be ambiguous with
12116     // the selected result.
12117     for (FunctionDecl *Skipped : AmbiguousDecls)
12118       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12119         return nullptr;
12120     Pair = DAP;
12121   }
12122   return Result;
12123 }
12124
12125 /// Given an overloaded function, tries to turn it into a non-overloaded
12126 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12127 /// will perform access checks, diagnose the use of the resultant decl, and, if
12128 /// requested, potentially perform a function-to-pointer decay.
12129 ///
12130 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12131 /// Otherwise, returns true. This may emit diagnostics and return true.
12132 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12133     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12134   Expr *E = SrcExpr.get();
12135   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12136
12137   DeclAccessPair DAP;
12138   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12139   if (!Found || Found->isCPUDispatchMultiVersion() ||
12140       Found->isCPUSpecificMultiVersion())
12141     return false;
12142
12143   // Emitting multiple diagnostics for a function that is both inaccessible and
12144   // unavailable is consistent with our behavior elsewhere. So, always check
12145   // for both.
12146   DiagnoseUseOfDecl(Found, E->getExprLoc());
12147   CheckAddressOfMemberAccess(E, DAP);
12148   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12149   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12150     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12151   else
12152     SrcExpr = Fixed;
12153   return true;
12154 }
12155
12156 /// Given an expression that refers to an overloaded function, try to
12157 /// resolve that overloaded function expression down to a single function.
12158 ///
12159 /// This routine can only resolve template-ids that refer to a single function
12160 /// template, where that template-id refers to a single template whose template
12161 /// arguments are either provided by the template-id or have defaults,
12162 /// as described in C++0x [temp.arg.explicit]p3.
12163 ///
12164 /// If no template-ids are found, no diagnostics are emitted and NULL is
12165 /// returned.
12166 FunctionDecl *
12167 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12168                                                   bool Complain,
12169                                                   DeclAccessPair *FoundResult) {
12170   // C++ [over.over]p1:
12171   //   [...] [Note: any redundant set of parentheses surrounding the
12172   //   overloaded function name is ignored (5.1). ]
12173   // C++ [over.over]p1:
12174   //   [...] The overloaded function name can be preceded by the &
12175   //   operator.
12176
12177   // If we didn't actually find any template-ids, we're done.
12178   if (!ovl->hasExplicitTemplateArgs())
12179     return nullptr;
12180
12181   TemplateArgumentListInfo ExplicitTemplateArgs;
12182   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12183   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12184
12185   // Look through all of the overloaded functions, searching for one
12186   // whose type matches exactly.
12187   FunctionDecl *Matched = nullptr;
12188   for (UnresolvedSetIterator I = ovl->decls_begin(),
12189          E = ovl->decls_end(); I != E; ++I) {
12190     // C++0x [temp.arg.explicit]p3:
12191     //   [...] In contexts where deduction is done and fails, or in contexts
12192     //   where deduction is not done, if a template argument list is
12193     //   specified and it, along with any default template arguments,
12194     //   identifies a single function template specialization, then the
12195     //   template-id is an lvalue for the function template specialization.
12196     FunctionTemplateDecl *FunctionTemplate
12197       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12198
12199     // C++ [over.over]p2:
12200     //   If the name is a function template, template argument deduction is
12201     //   done (14.8.2.2), and if the argument deduction succeeds, the
12202     //   resulting template argument list is used to generate a single
12203     //   function template specialization, which is added to the set of
12204     //   overloaded functions considered.
12205     FunctionDecl *Specialization = nullptr;
12206     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12207     if (TemplateDeductionResult Result
12208           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12209                                     Specialization, Info,
12210                                     /*IsAddressOfFunction*/true)) {
12211       // Make a note of the failed deduction for diagnostics.
12212       // TODO: Actually use the failed-deduction info?
12213       FailedCandidates.addCandidate()
12214           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12215                MakeDeductionFailureInfo(Context, Result, Info));
12216       continue;
12217     }
12218
12219     assert(Specialization && "no specialization and no error?");
12220
12221     // Multiple matches; we can't resolve to a single declaration.
12222     if (Matched) {
12223       if (Complain) {
12224         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12225           << ovl->getName();
12226         NoteAllOverloadCandidates(ovl);
12227       }
12228       return nullptr;
12229     }
12230
12231     Matched = Specialization;
12232     if (FoundResult) *FoundResult = I.getPair();
12233   }
12234
12235   if (Matched &&
12236       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12237     return nullptr;
12238
12239   return Matched;
12240 }
12241
12242 // Resolve and fix an overloaded expression that can be resolved
12243 // because it identifies a single function template specialization.
12244 //
12245 // Last three arguments should only be supplied if Complain = true
12246 //
12247 // Return true if it was logically possible to so resolve the
12248 // expression, regardless of whether or not it succeeded.  Always
12249 // returns true if 'complain' is set.
12250 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12251                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12252                       bool complain, SourceRange OpRangeForComplaining,
12253                                            QualType DestTypeForComplaining,
12254                                             unsigned DiagIDForComplaining) {
12255   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12256
12257   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12258
12259   DeclAccessPair found;
12260   ExprResult SingleFunctionExpression;
12261   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12262                            ovl.Expression, /*complain*/ false, &found)) {
12263     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12264       SrcExpr = ExprError();
12265       return true;
12266     }
12267
12268     // It is only correct to resolve to an instance method if we're
12269     // resolving a form that's permitted to be a pointer to member.
12270     // Otherwise we'll end up making a bound member expression, which
12271     // is illegal in all the contexts we resolve like this.
12272     if (!ovl.HasFormOfMemberPointer &&
12273         isa<CXXMethodDecl>(fn) &&
12274         cast<CXXMethodDecl>(fn)->isInstance()) {
12275       if (!complain) return false;
12276
12277       Diag(ovl.Expression->getExprLoc(),
12278            diag::err_bound_member_function)
12279         << 0 << ovl.Expression->getSourceRange();
12280
12281       // TODO: I believe we only end up here if there's a mix of
12282       // static and non-static candidates (otherwise the expression
12283       // would have 'bound member' type, not 'overload' type).
12284       // Ideally we would note which candidate was chosen and why
12285       // the static candidates were rejected.
12286       SrcExpr = ExprError();
12287       return true;
12288     }
12289
12290     // Fix the expression to refer to 'fn'.
12291     SingleFunctionExpression =
12292         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12293
12294     // If desired, do function-to-pointer decay.
12295     if (doFunctionPointerConverion) {
12296       SingleFunctionExpression =
12297         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12298       if (SingleFunctionExpression.isInvalid()) {
12299         SrcExpr = ExprError();
12300         return true;
12301       }
12302     }
12303   }
12304
12305   if (!SingleFunctionExpression.isUsable()) {
12306     if (complain) {
12307       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12308         << ovl.Expression->getName()
12309         << DestTypeForComplaining
12310         << OpRangeForComplaining
12311         << ovl.Expression->getQualifierLoc().getSourceRange();
12312       NoteAllOverloadCandidates(SrcExpr.get());
12313
12314       SrcExpr = ExprError();
12315       return true;
12316     }
12317
12318     return false;
12319   }
12320
12321   SrcExpr = SingleFunctionExpression;
12322   return true;
12323 }
12324
12325 /// Add a single candidate to the overload set.
12326 static void AddOverloadedCallCandidate(Sema &S,
12327                                        DeclAccessPair FoundDecl,
12328                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12329                                        ArrayRef<Expr *> Args,
12330                                        OverloadCandidateSet &CandidateSet,
12331                                        bool PartialOverloading,
12332                                        bool KnownValid) {
12333   NamedDecl *Callee = FoundDecl.getDecl();
12334   if (isa<UsingShadowDecl>(Callee))
12335     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12336
12337   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12338     if (ExplicitTemplateArgs) {
12339       assert(!KnownValid && "Explicit template arguments?");
12340       return;
12341     }
12342     // Prevent ill-formed function decls to be added as overload candidates.
12343     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12344       return;
12345
12346     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12347                            /*SuppressUserConversions=*/false,
12348                            PartialOverloading);
12349     return;
12350   }
12351
12352   if (FunctionTemplateDecl *FuncTemplate
12353       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12354     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12355                                    ExplicitTemplateArgs, Args, CandidateSet,
12356                                    /*SuppressUserConversions=*/false,
12357                                    PartialOverloading);
12358     return;
12359   }
12360
12361   assert(!KnownValid && "unhandled case in overloaded call candidate");
12362 }
12363
12364 /// Add the overload candidates named by callee and/or found by argument
12365 /// dependent lookup to the given overload set.
12366 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12367                                        ArrayRef<Expr *> Args,
12368                                        OverloadCandidateSet &CandidateSet,
12369                                        bool PartialOverloading) {
12370
12371 #ifndef NDEBUG
12372   // Verify that ArgumentDependentLookup is consistent with the rules
12373   // in C++0x [basic.lookup.argdep]p3:
12374   //
12375   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12376   //   and let Y be the lookup set produced by argument dependent
12377   //   lookup (defined as follows). If X contains
12378   //
12379   //     -- a declaration of a class member, or
12380   //
12381   //     -- a block-scope function declaration that is not a
12382   //        using-declaration, or
12383   //
12384   //     -- a declaration that is neither a function or a function
12385   //        template
12386   //
12387   //   then Y is empty.
12388
12389   if (ULE->requiresADL()) {
12390     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12391            E = ULE->decls_end(); I != E; ++I) {
12392       assert(!(*I)->getDeclContext()->isRecord());
12393       assert(isa<UsingShadowDecl>(*I) ||
12394              !(*I)->getDeclContext()->isFunctionOrMethod());
12395       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12396     }
12397   }
12398 #endif
12399
12400   // It would be nice to avoid this copy.
12401   TemplateArgumentListInfo TABuffer;
12402   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12403   if (ULE->hasExplicitTemplateArgs()) {
12404     ULE->copyTemplateArgumentsInto(TABuffer);
12405     ExplicitTemplateArgs = &TABuffer;
12406   }
12407
12408   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12409          E = ULE->decls_end(); I != E; ++I)
12410     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12411                                CandidateSet, PartialOverloading,
12412                                /*KnownValid*/ true);
12413
12414   if (ULE->requiresADL())
12415     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12416                                          Args, ExplicitTemplateArgs,
12417                                          CandidateSet, PartialOverloading);
12418 }
12419
12420 /// Determine whether a declaration with the specified name could be moved into
12421 /// a different namespace.
12422 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12423   switch (Name.getCXXOverloadedOperator()) {
12424   case OO_New: case OO_Array_New:
12425   case OO_Delete: case OO_Array_Delete:
12426     return false;
12427
12428   default:
12429     return true;
12430   }
12431 }
12432
12433 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12434 /// template, where the non-dependent name was declared after the template
12435 /// was defined. This is common in code written for a compilers which do not
12436 /// correctly implement two-stage name lookup.
12437 ///
12438 /// Returns true if a viable candidate was found and a diagnostic was issued.
12439 static bool
12440 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12441                        const CXXScopeSpec &SS, LookupResult &R,
12442                        OverloadCandidateSet::CandidateSetKind CSK,
12443                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12444                        ArrayRef<Expr *> Args,
12445                        bool *DoDiagnoseEmptyLookup = nullptr) {
12446   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12447     return false;
12448
12449   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12450     if (DC->isTransparentContext())
12451       continue;
12452
12453     SemaRef.LookupQualifiedName(R, DC);
12454
12455     if (!R.empty()) {
12456       R.suppressDiagnostics();
12457
12458       if (isa<CXXRecordDecl>(DC)) {
12459         // Don't diagnose names we find in classes; we get much better
12460         // diagnostics for these from DiagnoseEmptyLookup.
12461         R.clear();
12462         if (DoDiagnoseEmptyLookup)
12463           *DoDiagnoseEmptyLookup = true;
12464         return false;
12465       }
12466
12467       OverloadCandidateSet Candidates(FnLoc, CSK);
12468       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12469         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12470                                    ExplicitTemplateArgs, Args,
12471                                    Candidates, false, /*KnownValid*/ false);
12472
12473       OverloadCandidateSet::iterator Best;
12474       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12475         // No viable functions. Don't bother the user with notes for functions
12476         // which don't work and shouldn't be found anyway.
12477         R.clear();
12478         return false;
12479       }
12480
12481       // Find the namespaces where ADL would have looked, and suggest
12482       // declaring the function there instead.
12483       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12484       Sema::AssociatedClassSet AssociatedClasses;
12485       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12486                                                  AssociatedNamespaces,
12487                                                  AssociatedClasses);
12488       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12489       if (canBeDeclaredInNamespace(R.getLookupName())) {
12490         DeclContext *Std = SemaRef.getStdNamespace();
12491         for (Sema::AssociatedNamespaceSet::iterator
12492                it = AssociatedNamespaces.begin(),
12493                end = AssociatedNamespaces.end(); it != end; ++it) {
12494           // Never suggest declaring a function within namespace 'std'.
12495           if (Std && Std->Encloses(*it))
12496             continue;
12497
12498           // Never suggest declaring a function within a namespace with a
12499           // reserved name, like __gnu_cxx.
12500           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12501           if (NS &&
12502               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12503             continue;
12504
12505           SuggestedNamespaces.insert(*it);
12506         }
12507       }
12508
12509       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12510         << R.getLookupName();
12511       if (SuggestedNamespaces.empty()) {
12512         SemaRef.Diag(Best->Function->getLocation(),
12513                      diag::note_not_found_by_two_phase_lookup)
12514           << R.getLookupName() << 0;
12515       } else if (SuggestedNamespaces.size() == 1) {
12516         SemaRef.Diag(Best->Function->getLocation(),
12517                      diag::note_not_found_by_two_phase_lookup)
12518           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12519       } else {
12520         // FIXME: It would be useful to list the associated namespaces here,
12521         // but the diagnostics infrastructure doesn't provide a way to produce
12522         // a localized representation of a list of items.
12523         SemaRef.Diag(Best->Function->getLocation(),
12524                      diag::note_not_found_by_two_phase_lookup)
12525           << R.getLookupName() << 2;
12526       }
12527
12528       // Try to recover by calling this function.
12529       return true;
12530     }
12531
12532     R.clear();
12533   }
12534
12535   return false;
12536 }
12537
12538 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12539 /// template, where the non-dependent operator was declared after the template
12540 /// was defined.
12541 ///
12542 /// Returns true if a viable candidate was found and a diagnostic was issued.
12543 static bool
12544 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12545                                SourceLocation OpLoc,
12546                                ArrayRef<Expr *> Args) {
12547   DeclarationName OpName =
12548     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12549   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12550   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12551                                 OverloadCandidateSet::CSK_Operator,
12552                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12553 }
12554
12555 namespace {
12556 class BuildRecoveryCallExprRAII {
12557   Sema &SemaRef;
12558 public:
12559   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12560     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12561     SemaRef.IsBuildingRecoveryCallExpr = true;
12562   }
12563
12564   ~BuildRecoveryCallExprRAII() {
12565     SemaRef.IsBuildingRecoveryCallExpr = false;
12566   }
12567 };
12568
12569 }
12570
12571 /// Attempts to recover from a call where no functions were found.
12572 ///
12573 /// Returns true if new candidates were found.
12574 static ExprResult
12575 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12576                       UnresolvedLookupExpr *ULE,
12577                       SourceLocation LParenLoc,
12578                       MutableArrayRef<Expr *> Args,
12579                       SourceLocation RParenLoc,
12580                       bool EmptyLookup, bool AllowTypoCorrection) {
12581   // Do not try to recover if it is already building a recovery call.
12582   // This stops infinite loops for template instantiations like
12583   //
12584   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12585   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12586   //
12587   if (SemaRef.IsBuildingRecoveryCallExpr)
12588     return ExprError();
12589   BuildRecoveryCallExprRAII RCE(SemaRef);
12590
12591   CXXScopeSpec SS;
12592   SS.Adopt(ULE->getQualifierLoc());
12593   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12594
12595   TemplateArgumentListInfo TABuffer;
12596   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12597   if (ULE->hasExplicitTemplateArgs()) {
12598     ULE->copyTemplateArgumentsInto(TABuffer);
12599     ExplicitTemplateArgs = &TABuffer;
12600   }
12601
12602   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12603                  Sema::LookupOrdinaryName);
12604   bool DoDiagnoseEmptyLookup = EmptyLookup;
12605   if (!DiagnoseTwoPhaseLookup(
12606           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12607           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12608     NoTypoCorrectionCCC NoTypoValidator{};
12609     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12610                                                 ExplicitTemplateArgs != nullptr,
12611                                                 dyn_cast<MemberExpr>(Fn));
12612     CorrectionCandidateCallback &Validator =
12613         AllowTypoCorrection
12614             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12615             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12616     if (!DoDiagnoseEmptyLookup ||
12617         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12618                                     Args))
12619       return ExprError();
12620   }
12621
12622   assert(!R.empty() && "lookup results empty despite recovery");
12623
12624   // If recovery created an ambiguity, just bail out.
12625   if (R.isAmbiguous()) {
12626     R.suppressDiagnostics();
12627     return ExprError();
12628   }
12629
12630   // Build an implicit member call if appropriate.  Just drop the
12631   // casts and such from the call, we don't really care.
12632   ExprResult NewFn = ExprError();
12633   if ((*R.begin())->isCXXClassMember())
12634     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12635                                                     ExplicitTemplateArgs, S);
12636   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12637     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12638                                         ExplicitTemplateArgs);
12639   else
12640     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12641
12642   if (NewFn.isInvalid())
12643     return ExprError();
12644
12645   // This shouldn't cause an infinite loop because we're giving it
12646   // an expression with viable lookup results, which should never
12647   // end up here.
12648   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12649                                MultiExprArg(Args.data(), Args.size()),
12650                                RParenLoc);
12651 }
12652
12653 /// Constructs and populates an OverloadedCandidateSet from
12654 /// the given function.
12655 /// \returns true when an the ExprResult output parameter has been set.
12656 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12657                                   UnresolvedLookupExpr *ULE,
12658                                   MultiExprArg Args,
12659                                   SourceLocation RParenLoc,
12660                                   OverloadCandidateSet *CandidateSet,
12661                                   ExprResult *Result) {
12662 #ifndef NDEBUG
12663   if (ULE->requiresADL()) {
12664     // To do ADL, we must have found an unqualified name.
12665     assert(!ULE->getQualifier() && "qualified name with ADL");
12666
12667     // We don't perform ADL for implicit declarations of builtins.
12668     // Verify that this was correctly set up.
12669     FunctionDecl *F;
12670     if (ULE->decls_begin() != ULE->decls_end() &&
12671         ULE->decls_begin() + 1 == ULE->decls_end() &&
12672         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12673         F->getBuiltinID() && F->isImplicit())
12674       llvm_unreachable("performing ADL for builtin");
12675
12676     // We don't perform ADL in C.
12677     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12678   }
12679 #endif
12680
12681   UnbridgedCastsSet UnbridgedCasts;
12682   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12683     *Result = ExprError();
12684     return true;
12685   }
12686
12687   // Add the functions denoted by the callee to the set of candidate
12688   // functions, including those from argument-dependent lookup.
12689   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12690
12691   if (getLangOpts().MSVCCompat &&
12692       CurContext->isDependentContext() && !isSFINAEContext() &&
12693       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12694
12695     OverloadCandidateSet::iterator Best;
12696     if (CandidateSet->empty() ||
12697         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12698             OR_No_Viable_Function) {
12699       // In Microsoft mode, if we are inside a template class member function
12700       // then create a type dependent CallExpr. The goal is to postpone name
12701       // lookup to instantiation time to be able to search into type dependent
12702       // base classes.
12703       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12704                                       VK_RValue, RParenLoc);
12705       CE->setTypeDependent(true);
12706       CE->setValueDependent(true);
12707       CE->setInstantiationDependent(true);
12708       *Result = CE;
12709       return true;
12710     }
12711   }
12712
12713   if (CandidateSet->empty())
12714     return false;
12715
12716   UnbridgedCasts.restore();
12717   return false;
12718 }
12719
12720 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12721 /// the completed call expression. If overload resolution fails, emits
12722 /// diagnostics and returns ExprError()
12723 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12724                                            UnresolvedLookupExpr *ULE,
12725                                            SourceLocation LParenLoc,
12726                                            MultiExprArg Args,
12727                                            SourceLocation RParenLoc,
12728                                            Expr *ExecConfig,
12729                                            OverloadCandidateSet *CandidateSet,
12730                                            OverloadCandidateSet::iterator *Best,
12731                                            OverloadingResult OverloadResult,
12732                                            bool AllowTypoCorrection) {
12733   if (CandidateSet->empty())
12734     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12735                                  RParenLoc, /*EmptyLookup=*/true,
12736                                  AllowTypoCorrection);
12737
12738   switch (OverloadResult) {
12739   case OR_Success: {
12740     FunctionDecl *FDecl = (*Best)->Function;
12741     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12742     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12743       return ExprError();
12744     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12745     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12746                                          ExecConfig, /*IsExecConfig=*/false,
12747                                          (*Best)->IsADLCandidate);
12748   }
12749
12750   case OR_No_Viable_Function: {
12751     // Try to recover by looking for viable functions which the user might
12752     // have meant to call.
12753     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12754                                                 Args, RParenLoc,
12755                                                 /*EmptyLookup=*/false,
12756                                                 AllowTypoCorrection);
12757     if (!Recovery.isInvalid())
12758       return Recovery;
12759
12760     // If the user passes in a function that we can't take the address of, we
12761     // generally end up emitting really bad error messages. Here, we attempt to
12762     // emit better ones.
12763     for (const Expr *Arg : Args) {
12764       if (!Arg->getType()->isFunctionType())
12765         continue;
12766       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12767         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12768         if (FD &&
12769             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12770                                                        Arg->getExprLoc()))
12771           return ExprError();
12772       }
12773     }
12774
12775     CandidateSet->NoteCandidates(
12776         PartialDiagnosticAt(
12777             Fn->getBeginLoc(),
12778             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12779                 << ULE->getName() << Fn->getSourceRange()),
12780         SemaRef, OCD_AllCandidates, Args);
12781     break;
12782   }
12783
12784   case OR_Ambiguous:
12785     CandidateSet->NoteCandidates(
12786         PartialDiagnosticAt(Fn->getBeginLoc(),
12787                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12788                                 << ULE->getName() << Fn->getSourceRange()),
12789         SemaRef, OCD_AmbiguousCandidates, Args);
12790     break;
12791
12792   case OR_Deleted: {
12793     CandidateSet->NoteCandidates(
12794         PartialDiagnosticAt(Fn->getBeginLoc(),
12795                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12796                                 << ULE->getName() << Fn->getSourceRange()),
12797         SemaRef, OCD_AllCandidates, Args);
12798
12799     // We emitted an error for the unavailable/deleted function call but keep
12800     // the call in the AST.
12801     FunctionDecl *FDecl = (*Best)->Function;
12802     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12803     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12804                                          ExecConfig, /*IsExecConfig=*/false,
12805                                          (*Best)->IsADLCandidate);
12806   }
12807   }
12808
12809   // Overload resolution failed.
12810   return ExprError();
12811 }
12812
12813 static void markUnaddressableCandidatesUnviable(Sema &S,
12814                                                 OverloadCandidateSet &CS) {
12815   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12816     if (I->Viable &&
12817         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12818       I->Viable = false;
12819       I->FailureKind = ovl_fail_addr_not_available;
12820     }
12821   }
12822 }
12823
12824 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12825 /// (which eventually refers to the declaration Func) and the call
12826 /// arguments Args/NumArgs, attempt to resolve the function call down
12827 /// to a specific function. If overload resolution succeeds, returns
12828 /// the call expression produced by overload resolution.
12829 /// Otherwise, emits diagnostics and returns ExprError.
12830 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12831                                          UnresolvedLookupExpr *ULE,
12832                                          SourceLocation LParenLoc,
12833                                          MultiExprArg Args,
12834                                          SourceLocation RParenLoc,
12835                                          Expr *ExecConfig,
12836                                          bool AllowTypoCorrection,
12837                                          bool CalleesAddressIsTaken) {
12838   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12839                                     OverloadCandidateSet::CSK_Normal);
12840   ExprResult result;
12841
12842   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12843                              &result))
12844     return result;
12845
12846   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12847   // functions that aren't addressible are considered unviable.
12848   if (CalleesAddressIsTaken)
12849     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12850
12851   OverloadCandidateSet::iterator Best;
12852   OverloadingResult OverloadResult =
12853       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12854
12855   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12856                                   ExecConfig, &CandidateSet, &Best,
12857                                   OverloadResult, AllowTypoCorrection);
12858 }
12859
12860 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12861   return Functions.size() > 1 ||
12862     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12863 }
12864
12865 /// Create a unary operation that may resolve to an overloaded
12866 /// operator.
12867 ///
12868 /// \param OpLoc The location of the operator itself (e.g., '*').
12869 ///
12870 /// \param Opc The UnaryOperatorKind that describes this operator.
12871 ///
12872 /// \param Fns The set of non-member functions that will be
12873 /// considered by overload resolution. The caller needs to build this
12874 /// set based on the context using, e.g.,
12875 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12876 /// set should not contain any member functions; those will be added
12877 /// by CreateOverloadedUnaryOp().
12878 ///
12879 /// \param Input The input argument.
12880 ExprResult
12881 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12882                               const UnresolvedSetImpl &Fns,
12883                               Expr *Input, bool PerformADL) {
12884   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12885   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12886   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12887   // TODO: provide better source location info.
12888   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12889
12890   if (checkPlaceholderForOverload(*this, Input))
12891     return ExprError();
12892
12893   Expr *Args[2] = { Input, nullptr };
12894   unsigned NumArgs = 1;
12895
12896   // For post-increment and post-decrement, add the implicit '0' as
12897   // the second argument, so that we know this is a post-increment or
12898   // post-decrement.
12899   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12900     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12901     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12902                                      SourceLocation());
12903     NumArgs = 2;
12904   }
12905
12906   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12907
12908   if (Input->isTypeDependent()) {
12909     if (Fns.empty())
12910       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12911                                          VK_RValue, OK_Ordinary, OpLoc, false);
12912
12913     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12914     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12915         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12916         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12917     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12918                                        Context.DependentTy, VK_RValue, OpLoc,
12919                                        FPOptions());
12920   }
12921
12922   // Build an empty overload set.
12923   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12924
12925   // Add the candidates from the given function set.
12926   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12927
12928   // Add operator candidates that are member functions.
12929   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12930
12931   // Add candidates from ADL.
12932   if (PerformADL) {
12933     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12934                                          /*ExplicitTemplateArgs*/nullptr,
12935                                          CandidateSet);
12936   }
12937
12938   // Add builtin operator candidates.
12939   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12940
12941   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12942
12943   // Perform overload resolution.
12944   OverloadCandidateSet::iterator Best;
12945   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12946   case OR_Success: {
12947     // We found a built-in operator or an overloaded operator.
12948     FunctionDecl *FnDecl = Best->Function;
12949
12950     if (FnDecl) {
12951       Expr *Base = nullptr;
12952       // We matched an overloaded operator. Build a call to that
12953       // operator.
12954
12955       // Convert the arguments.
12956       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12957         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12958
12959         ExprResult InputRes =
12960           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12961                                               Best->FoundDecl, Method);
12962         if (InputRes.isInvalid())
12963           return ExprError();
12964         Base = Input = InputRes.get();
12965       } else {
12966         // Convert the arguments.
12967         ExprResult InputInit
12968           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12969                                                       Context,
12970                                                       FnDecl->getParamDecl(0)),
12971                                       SourceLocation(),
12972                                       Input);
12973         if (InputInit.isInvalid())
12974           return ExprError();
12975         Input = InputInit.get();
12976       }
12977
12978       // Build the actual expression node.
12979       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12980                                                 Base, HadMultipleCandidates,
12981                                                 OpLoc);
12982       if (FnExpr.isInvalid())
12983         return ExprError();
12984
12985       // Determine the result type.
12986       QualType ResultTy = FnDecl->getReturnType();
12987       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12988       ResultTy = ResultTy.getNonLValueExprType(Context);
12989
12990       Args[0] = Input;
12991       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12992           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12993           FPOptions(), Best->IsADLCandidate);
12994
12995       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12996         return ExprError();
12997
12998       if (CheckFunctionCall(FnDecl, TheCall,
12999                             FnDecl->getType()->castAs<FunctionProtoType>()))
13000         return ExprError();
13001
13002       return MaybeBindToTemporary(TheCall);
13003     } else {
13004       // We matched a built-in operator. Convert the arguments, then
13005       // break out so that we will build the appropriate built-in
13006       // operator node.
13007       ExprResult InputRes = PerformImplicitConversion(
13008           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13009           CCK_ForBuiltinOverloadedOp);
13010       if (InputRes.isInvalid())
13011         return ExprError();
13012       Input = InputRes.get();
13013       break;
13014     }
13015   }
13016
13017   case OR_No_Viable_Function:
13018     // This is an erroneous use of an operator which can be overloaded by
13019     // a non-member function. Check for non-member operators which were
13020     // defined too late to be candidates.
13021     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13022       // FIXME: Recover by calling the found function.
13023       return ExprError();
13024
13025     // No viable function; fall through to handling this as a
13026     // built-in operator, which will produce an error message for us.
13027     break;
13028
13029   case OR_Ambiguous:
13030     CandidateSet.NoteCandidates(
13031         PartialDiagnosticAt(OpLoc,
13032                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13033                                 << UnaryOperator::getOpcodeStr(Opc)
13034                                 << Input->getType() << Input->getSourceRange()),
13035         *this, OCD_AmbiguousCandidates, ArgsArray,
13036         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13037     return ExprError();
13038
13039   case OR_Deleted:
13040     CandidateSet.NoteCandidates(
13041         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13042                                        << UnaryOperator::getOpcodeStr(Opc)
13043                                        << Input->getSourceRange()),
13044         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13045         OpLoc);
13046     return ExprError();
13047   }
13048
13049   // Either we found no viable overloaded operator or we matched a
13050   // built-in operator. In either case, fall through to trying to
13051   // build a built-in operation.
13052   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13053 }
13054
13055 /// Perform lookup for an overloaded binary operator.
13056 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13057                                  OverloadedOperatorKind Op,
13058                                  const UnresolvedSetImpl &Fns,
13059                                  ArrayRef<Expr *> Args, bool PerformADL) {
13060   SourceLocation OpLoc = CandidateSet.getLocation();
13061
13062   OverloadedOperatorKind ExtraOp =
13063       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13064           ? getRewrittenOverloadedOperator(Op)
13065           : OO_None;
13066
13067   // Add the candidates from the given function set. This also adds the
13068   // rewritten candidates using these functions if necessary.
13069   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13070
13071   // Add operator candidates that are member functions.
13072   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13073   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13074     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13075                                 OverloadCandidateParamOrder::Reversed);
13076
13077   // In C++20, also add any rewritten member candidates.
13078   if (ExtraOp) {
13079     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13080     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13081       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13082                                   CandidateSet,
13083                                   OverloadCandidateParamOrder::Reversed);
13084   }
13085
13086   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13087   // performed for an assignment operator (nor for operator[] nor operator->,
13088   // which don't get here).
13089   if (Op != OO_Equal && PerformADL) {
13090     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13091     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13092                                          /*ExplicitTemplateArgs*/ nullptr,
13093                                          CandidateSet);
13094     if (ExtraOp) {
13095       DeclarationName ExtraOpName =
13096           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13097       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13098                                            /*ExplicitTemplateArgs*/ nullptr,
13099                                            CandidateSet);
13100     }
13101   }
13102
13103   // Add builtin operator candidates.
13104   //
13105   // FIXME: We don't add any rewritten candidates here. This is strictly
13106   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13107   // resulting in our selecting a rewritten builtin candidate. For example:
13108   //
13109   //   enum class E { e };
13110   //   bool operator!=(E, E) requires false;
13111   //   bool k = E::e != E::e;
13112   //
13113   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13114   // it seems unreasonable to consider rewritten builtin candidates. A core
13115   // issue has been filed proposing to removed this requirement.
13116   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13117 }
13118
13119 /// Create a binary operation that may resolve to an overloaded
13120 /// operator.
13121 ///
13122 /// \param OpLoc The location of the operator itself (e.g., '+').
13123 ///
13124 /// \param Opc The BinaryOperatorKind that describes this operator.
13125 ///
13126 /// \param Fns The set of non-member functions that will be
13127 /// considered by overload resolution. The caller needs to build this
13128 /// set based on the context using, e.g.,
13129 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13130 /// set should not contain any member functions; those will be added
13131 /// by CreateOverloadedBinOp().
13132 ///
13133 /// \param LHS Left-hand argument.
13134 /// \param RHS Right-hand argument.
13135 /// \param PerformADL Whether to consider operator candidates found by ADL.
13136 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13137 ///        C++20 operator rewrites.
13138 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13139 ///        the function in question. Such a function is never a candidate in
13140 ///        our overload resolution. This also enables synthesizing a three-way
13141 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13142 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13143                                        BinaryOperatorKind Opc,
13144                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13145                                        Expr *RHS, bool PerformADL,
13146                                        bool AllowRewrittenCandidates,
13147                                        FunctionDecl *DefaultedFn) {
13148   Expr *Args[2] = { LHS, RHS };
13149   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13150
13151   if (!getLangOpts().CPlusPlus2a)
13152     AllowRewrittenCandidates = false;
13153
13154   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13155
13156   // If either side is type-dependent, create an appropriate dependent
13157   // expression.
13158   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13159     if (Fns.empty()) {
13160       // If there are no functions to store, just build a dependent
13161       // BinaryOperator or CompoundAssignment.
13162       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13163         return new (Context) BinaryOperator(
13164             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13165             OpLoc, FPFeatures);
13166
13167       return new (Context) CompoundAssignOperator(
13168           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13169           Context.DependentTy, Context.DependentTy, OpLoc,
13170           FPFeatures);
13171     }
13172
13173     // FIXME: save results of ADL from here?
13174     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13175     // TODO: provide better source location info in DNLoc component.
13176     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13177     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13178     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13179         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13180         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13181     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13182                                        Context.DependentTy, VK_RValue, OpLoc,
13183                                        FPFeatures);
13184   }
13185
13186   // Always do placeholder-like conversions on the RHS.
13187   if (checkPlaceholderForOverload(*this, Args[1]))
13188     return ExprError();
13189
13190   // Do placeholder-like conversion on the LHS; note that we should
13191   // not get here with a PseudoObject LHS.
13192   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13193   if (checkPlaceholderForOverload(*this, Args[0]))
13194     return ExprError();
13195
13196   // If this is the assignment operator, we only perform overload resolution
13197   // if the left-hand side is a class or enumeration type. This is actually
13198   // a hack. The standard requires that we do overload resolution between the
13199   // various built-in candidates, but as DR507 points out, this can lead to
13200   // problems. So we do it this way, which pretty much follows what GCC does.
13201   // Note that we go the traditional code path for compound assignment forms.
13202   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13203     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13204
13205   // If this is the .* operator, which is not overloadable, just
13206   // create a built-in binary operator.
13207   if (Opc == BO_PtrMemD)
13208     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13209
13210   // Build the overload set.
13211   OverloadCandidateSet CandidateSet(
13212       OpLoc, OverloadCandidateSet::CSK_Operator,
13213       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13214   if (DefaultedFn)
13215     CandidateSet.exclude(DefaultedFn);
13216   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13217
13218   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13219
13220   // Perform overload resolution.
13221   OverloadCandidateSet::iterator Best;
13222   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13223     case OR_Success: {
13224       // We found a built-in operator or an overloaded operator.
13225       FunctionDecl *FnDecl = Best->Function;
13226
13227       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13228       if (IsReversed)
13229         std::swap(Args[0], Args[1]);
13230
13231       if (FnDecl) {
13232         Expr *Base = nullptr;
13233         // We matched an overloaded operator. Build a call to that
13234         // operator.
13235
13236         OverloadedOperatorKind ChosenOp =
13237             FnDecl->getDeclName().getCXXOverloadedOperator();
13238
13239         // C++2a [over.match.oper]p9:
13240         //   If a rewritten operator== candidate is selected by overload
13241         //   resolution for an operator@, its return type shall be cv bool
13242         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13243             !FnDecl->getReturnType()->isBooleanType()) {
13244           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13245               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13246               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13247           Diag(FnDecl->getLocation(), diag::note_declared_at);
13248           return ExprError();
13249         }
13250
13251         if (AllowRewrittenCandidates && !IsReversed &&
13252             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13253           // We could have reversed this operator, but didn't. Check if the
13254           // reversed form was a viable candidate, and if so, if it had a
13255           // better conversion for either parameter. If so, this call is
13256           // formally ambiguous, and allowing it is an extension.
13257           for (OverloadCandidate &Cand : CandidateSet) {
13258             if (Cand.Viable && Cand.Function == FnDecl &&
13259                 Cand.RewriteKind & CRK_Reversed) {
13260               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13261                 if (CompareImplicitConversionSequences(
13262                         *this, OpLoc, Cand.Conversions[ArgIdx],
13263                         Best->Conversions[ArgIdx]) ==
13264                     ImplicitConversionSequence::Better) {
13265                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13266                       << BinaryOperator::getOpcodeStr(Opc)
13267                       << Args[0]->getType() << Args[1]->getType()
13268                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13269                   Diag(FnDecl->getLocation(),
13270                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13271                 }
13272               }
13273               break;
13274             }
13275           }
13276         }
13277
13278         // Convert the arguments.
13279         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13280           // Best->Access is only meaningful for class members.
13281           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13282
13283           ExprResult Arg1 =
13284             PerformCopyInitialization(
13285               InitializedEntity::InitializeParameter(Context,
13286                                                      FnDecl->getParamDecl(0)),
13287               SourceLocation(), Args[1]);
13288           if (Arg1.isInvalid())
13289             return ExprError();
13290
13291           ExprResult Arg0 =
13292             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13293                                                 Best->FoundDecl, Method);
13294           if (Arg0.isInvalid())
13295             return ExprError();
13296           Base = Args[0] = Arg0.getAs<Expr>();
13297           Args[1] = RHS = Arg1.getAs<Expr>();
13298         } else {
13299           // Convert the arguments.
13300           ExprResult Arg0 = PerformCopyInitialization(
13301             InitializedEntity::InitializeParameter(Context,
13302                                                    FnDecl->getParamDecl(0)),
13303             SourceLocation(), Args[0]);
13304           if (Arg0.isInvalid())
13305             return ExprError();
13306
13307           ExprResult Arg1 =
13308             PerformCopyInitialization(
13309               InitializedEntity::InitializeParameter(Context,
13310                                                      FnDecl->getParamDecl(1)),
13311               SourceLocation(), Args[1]);
13312           if (Arg1.isInvalid())
13313             return ExprError();
13314           Args[0] = LHS = Arg0.getAs<Expr>();
13315           Args[1] = RHS = Arg1.getAs<Expr>();
13316         }
13317
13318         // Build the actual expression node.
13319         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13320                                                   Best->FoundDecl, Base,
13321                                                   HadMultipleCandidates, OpLoc);
13322         if (FnExpr.isInvalid())
13323           return ExprError();
13324
13325         // Determine the result type.
13326         QualType ResultTy = FnDecl->getReturnType();
13327         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13328         ResultTy = ResultTy.getNonLValueExprType(Context);
13329
13330         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13331             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13332             FPFeatures, Best->IsADLCandidate);
13333
13334         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13335                                 FnDecl))
13336           return ExprError();
13337
13338         ArrayRef<const Expr *> ArgsArray(Args, 2);
13339         const Expr *ImplicitThis = nullptr;
13340         // Cut off the implicit 'this'.
13341         if (isa<CXXMethodDecl>(FnDecl)) {
13342           ImplicitThis = ArgsArray[0];
13343           ArgsArray = ArgsArray.slice(1);
13344         }
13345
13346         // Check for a self move.
13347         if (Op == OO_Equal)
13348           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13349
13350         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13351                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13352                   VariadicDoesNotApply);
13353
13354         ExprResult R = MaybeBindToTemporary(TheCall);
13355         if (R.isInvalid())
13356           return ExprError();
13357
13358         // For a rewritten candidate, we've already reversed the arguments
13359         // if needed. Perform the rest of the rewrite now.
13360         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13361             (Op == OO_Spaceship && IsReversed)) {
13362           if (Op == OO_ExclaimEqual) {
13363             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13364             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13365           } else {
13366             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13367             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13368             Expr *ZeroLiteral =
13369                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13370
13371             Sema::CodeSynthesisContext Ctx;
13372             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13373             Ctx.Entity = FnDecl;
13374             pushCodeSynthesisContext(Ctx);
13375
13376             R = CreateOverloadedBinOp(
13377                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13378                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13379                 /*AllowRewrittenCandidates=*/false);
13380
13381             popCodeSynthesisContext();
13382           }
13383           if (R.isInvalid())
13384             return ExprError();
13385         } else {
13386           assert(ChosenOp == Op && "unexpected operator name");
13387         }
13388
13389         // Make a note in the AST if we did any rewriting.
13390         if (Best->RewriteKind != CRK_None)
13391           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13392
13393         return R;
13394       } else {
13395         // We matched a built-in operator. Convert the arguments, then
13396         // break out so that we will build the appropriate built-in
13397         // operator node.
13398         ExprResult ArgsRes0 = PerformImplicitConversion(
13399             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13400             AA_Passing, CCK_ForBuiltinOverloadedOp);
13401         if (ArgsRes0.isInvalid())
13402           return ExprError();
13403         Args[0] = ArgsRes0.get();
13404
13405         ExprResult ArgsRes1 = PerformImplicitConversion(
13406             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13407             AA_Passing, CCK_ForBuiltinOverloadedOp);
13408         if (ArgsRes1.isInvalid())
13409           return ExprError();
13410         Args[1] = ArgsRes1.get();
13411         break;
13412       }
13413     }
13414
13415     case OR_No_Viable_Function: {
13416       // C++ [over.match.oper]p9:
13417       //   If the operator is the operator , [...] and there are no
13418       //   viable functions, then the operator is assumed to be the
13419       //   built-in operator and interpreted according to clause 5.
13420       if (Opc == BO_Comma)
13421         break;
13422
13423       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13424       // compare result using '==' and '<'.
13425       if (DefaultedFn && Opc == BO_Cmp) {
13426         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13427                                                           Args[1], DefaultedFn);
13428         if (E.isInvalid() || E.isUsable())
13429           return E;
13430       }
13431
13432       // For class as left operand for assignment or compound assignment
13433       // operator do not fall through to handling in built-in, but report that
13434       // no overloaded assignment operator found
13435       ExprResult Result = ExprError();
13436       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13437       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13438                                                    Args, OpLoc);
13439       if (Args[0]->getType()->isRecordType() &&
13440           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13441         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13442              << BinaryOperator::getOpcodeStr(Opc)
13443              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13444         if (Args[0]->getType()->isIncompleteType()) {
13445           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13446             << Args[0]->getType()
13447             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13448         }
13449       } else {
13450         // This is an erroneous use of an operator which can be overloaded by
13451         // a non-member function. Check for non-member operators which were
13452         // defined too late to be candidates.
13453         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13454           // FIXME: Recover by calling the found function.
13455           return ExprError();
13456
13457         // No viable function; try to create a built-in operation, which will
13458         // produce an error. Then, show the non-viable candidates.
13459         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13460       }
13461       assert(Result.isInvalid() &&
13462              "C++ binary operator overloading is missing candidates!");
13463       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13464       return Result;
13465     }
13466
13467     case OR_Ambiguous:
13468       CandidateSet.NoteCandidates(
13469           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13470                                          << BinaryOperator::getOpcodeStr(Opc)
13471                                          << Args[0]->getType()
13472                                          << Args[1]->getType()
13473                                          << Args[0]->getSourceRange()
13474                                          << Args[1]->getSourceRange()),
13475           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13476           OpLoc);
13477       return ExprError();
13478
13479     case OR_Deleted:
13480       if (isImplicitlyDeleted(Best->Function)) {
13481         FunctionDecl *DeletedFD = Best->Function;
13482         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13483         if (DFK.isSpecialMember()) {
13484           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13485             << Args[0]->getType() << DFK.asSpecialMember();
13486         } else {
13487           assert(DFK.isComparison());
13488           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13489             << Args[0]->getType() << DeletedFD;
13490         }
13491
13492         // The user probably meant to call this special member. Just
13493         // explain why it's deleted.
13494         NoteDeletedFunction(DeletedFD);
13495         return ExprError();
13496       }
13497       CandidateSet.NoteCandidates(
13498           PartialDiagnosticAt(
13499               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13500                          << getOperatorSpelling(Best->Function->getDeclName()
13501                                                     .getCXXOverloadedOperator())
13502                          << Args[0]->getSourceRange()
13503                          << Args[1]->getSourceRange()),
13504           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13505           OpLoc);
13506       return ExprError();
13507   }
13508
13509   // We matched a built-in operator; build it.
13510   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13511 }
13512
13513 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13514     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13515     FunctionDecl *DefaultedFn) {
13516   const ComparisonCategoryInfo *Info =
13517       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13518   // If we're not producing a known comparison category type, we can't
13519   // synthesize a three-way comparison. Let the caller diagnose this.
13520   if (!Info)
13521     return ExprResult((Expr*)nullptr);
13522
13523   // If we ever want to perform this synthesis more generally, we will need to
13524   // apply the temporary materialization conversion to the operands.
13525   assert(LHS->isGLValue() && RHS->isGLValue() &&
13526          "cannot use prvalue expressions more than once");
13527   Expr *OrigLHS = LHS;
13528   Expr *OrigRHS = RHS;
13529
13530   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13531   // each of them multiple times below.
13532   LHS = new (Context)
13533       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13534                       LHS->getObjectKind(), LHS);
13535   RHS = new (Context)
13536       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13537                       RHS->getObjectKind(), RHS);
13538
13539   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13540                                         DefaultedFn);
13541   if (Eq.isInvalid())
13542     return ExprError();
13543
13544   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13545                                           true, DefaultedFn);
13546   if (Less.isInvalid())
13547     return ExprError();
13548
13549   ExprResult Greater;
13550   if (Info->isPartial()) {
13551     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13552                                     DefaultedFn);
13553     if (Greater.isInvalid())
13554       return ExprError();
13555   }
13556
13557   // Form the list of comparisons we're going to perform.
13558   struct Comparison {
13559     ExprResult Cmp;
13560     ComparisonCategoryResult Result;
13561   } Comparisons[4] =
13562   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13563                           : ComparisonCategoryResult::Equivalent},
13564     {Less, ComparisonCategoryResult::Less},
13565     {Greater, ComparisonCategoryResult::Greater},
13566     {ExprResult(), ComparisonCategoryResult::Unordered},
13567   };
13568
13569   int I = Info->isPartial() ? 3 : 2;
13570
13571   // Combine the comparisons with suitable conditional expressions.
13572   ExprResult Result;
13573   for (; I >= 0; --I) {
13574     // Build a reference to the comparison category constant.
13575     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13576     // FIXME: Missing a constant for a comparison category. Diagnose this?
13577     if (!VI)
13578       return ExprResult((Expr*)nullptr);
13579     ExprResult ThisResult =
13580         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13581     if (ThisResult.isInvalid())
13582       return ExprError();
13583
13584     // Build a conditional unless this is the final case.
13585     if (Result.get()) {
13586       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13587                                   ThisResult.get(), Result.get());
13588       if (Result.isInvalid())
13589         return ExprError();
13590     } else {
13591       Result = ThisResult;
13592     }
13593   }
13594
13595   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13596   // bind the OpaqueValueExprs before they're (repeatedly) used.
13597   Expr *SyntacticForm = new (Context)
13598       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13599                      Result.get()->getValueKind(),
13600                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13601   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13602   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13603 }
13604
13605 ExprResult
13606 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13607                                          SourceLocation RLoc,
13608                                          Expr *Base, Expr *Idx) {
13609   Expr *Args[2] = { Base, Idx };
13610   DeclarationName OpName =
13611       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13612
13613   // If either side is type-dependent, create an appropriate dependent
13614   // expression.
13615   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13616
13617     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13618     // CHECKME: no 'operator' keyword?
13619     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13620     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13621     UnresolvedLookupExpr *Fn
13622       = UnresolvedLookupExpr::Create(Context, NamingClass,
13623                                      NestedNameSpecifierLoc(), OpNameInfo,
13624                                      /*ADL*/ true, /*Overloaded*/ false,
13625                                      UnresolvedSetIterator(),
13626                                      UnresolvedSetIterator());
13627     // Can't add any actual overloads yet
13628
13629     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13630                                        Context.DependentTy, VK_RValue, RLoc,
13631                                        FPOptions());
13632   }
13633
13634   // Handle placeholders on both operands.
13635   if (checkPlaceholderForOverload(*this, Args[0]))
13636     return ExprError();
13637   if (checkPlaceholderForOverload(*this, Args[1]))
13638     return ExprError();
13639
13640   // Build an empty overload set.
13641   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13642
13643   // Subscript can only be overloaded as a member function.
13644
13645   // Add operator candidates that are member functions.
13646   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13647
13648   // Add builtin operator candidates.
13649   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13650
13651   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13652
13653   // Perform overload resolution.
13654   OverloadCandidateSet::iterator Best;
13655   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13656     case OR_Success: {
13657       // We found a built-in operator or an overloaded operator.
13658       FunctionDecl *FnDecl = Best->Function;
13659
13660       if (FnDecl) {
13661         // We matched an overloaded operator. Build a call to that
13662         // operator.
13663
13664         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13665
13666         // Convert the arguments.
13667         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13668         ExprResult Arg0 =
13669           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13670                                               Best->FoundDecl, Method);
13671         if (Arg0.isInvalid())
13672           return ExprError();
13673         Args[0] = Arg0.get();
13674
13675         // Convert the arguments.
13676         ExprResult InputInit
13677           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13678                                                       Context,
13679                                                       FnDecl->getParamDecl(0)),
13680                                       SourceLocation(),
13681                                       Args[1]);
13682         if (InputInit.isInvalid())
13683           return ExprError();
13684
13685         Args[1] = InputInit.getAs<Expr>();
13686
13687         // Build the actual expression node.
13688         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13689         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13690         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13691                                                   Best->FoundDecl,
13692                                                   Base,
13693                                                   HadMultipleCandidates,
13694                                                   OpLocInfo.getLoc(),
13695                                                   OpLocInfo.getInfo());
13696         if (FnExpr.isInvalid())
13697           return ExprError();
13698
13699         // Determine the result type
13700         QualType ResultTy = FnDecl->getReturnType();
13701         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13702         ResultTy = ResultTy.getNonLValueExprType(Context);
13703
13704         CXXOperatorCallExpr *TheCall =
13705             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13706                                         Args, ResultTy, VK, RLoc, FPOptions());
13707
13708         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13709           return ExprError();
13710
13711         if (CheckFunctionCall(Method, TheCall,
13712                               Method->getType()->castAs<FunctionProtoType>()))
13713           return ExprError();
13714
13715         return MaybeBindToTemporary(TheCall);
13716       } else {
13717         // We matched a built-in operator. Convert the arguments, then
13718         // break out so that we will build the appropriate built-in
13719         // operator node.
13720         ExprResult ArgsRes0 = PerformImplicitConversion(
13721             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13722             AA_Passing, CCK_ForBuiltinOverloadedOp);
13723         if (ArgsRes0.isInvalid())
13724           return ExprError();
13725         Args[0] = ArgsRes0.get();
13726
13727         ExprResult ArgsRes1 = PerformImplicitConversion(
13728             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13729             AA_Passing, CCK_ForBuiltinOverloadedOp);
13730         if (ArgsRes1.isInvalid())
13731           return ExprError();
13732         Args[1] = ArgsRes1.get();
13733
13734         break;
13735       }
13736     }
13737
13738     case OR_No_Viable_Function: {
13739       PartialDiagnostic PD = CandidateSet.empty()
13740           ? (PDiag(diag::err_ovl_no_oper)
13741              << Args[0]->getType() << /*subscript*/ 0
13742              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13743           : (PDiag(diag::err_ovl_no_viable_subscript)
13744              << Args[0]->getType() << Args[0]->getSourceRange()
13745              << Args[1]->getSourceRange());
13746       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13747                                   OCD_AllCandidates, Args, "[]", LLoc);
13748       return ExprError();
13749     }
13750
13751     case OR_Ambiguous:
13752       CandidateSet.NoteCandidates(
13753           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13754                                         << "[]" << Args[0]->getType()
13755                                         << Args[1]->getType()
13756                                         << Args[0]->getSourceRange()
13757                                         << Args[1]->getSourceRange()),
13758           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13759       return ExprError();
13760
13761     case OR_Deleted:
13762       CandidateSet.NoteCandidates(
13763           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13764                                         << "[]" << Args[0]->getSourceRange()
13765                                         << Args[1]->getSourceRange()),
13766           *this, OCD_AllCandidates, Args, "[]", LLoc);
13767       return ExprError();
13768     }
13769
13770   // We matched a built-in operator; build it.
13771   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13772 }
13773
13774 /// BuildCallToMemberFunction - Build a call to a member
13775 /// function. MemExpr is the expression that refers to the member
13776 /// function (and includes the object parameter), Args/NumArgs are the
13777 /// arguments to the function call (not including the object
13778 /// parameter). The caller needs to validate that the member
13779 /// expression refers to a non-static member function or an overloaded
13780 /// member function.
13781 ExprResult
13782 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13783                                 SourceLocation LParenLoc,
13784                                 MultiExprArg Args,
13785                                 SourceLocation RParenLoc) {
13786   assert(MemExprE->getType() == Context.BoundMemberTy ||
13787          MemExprE->getType() == Context.OverloadTy);
13788
13789   // Dig out the member expression. This holds both the object
13790   // argument and the member function we're referring to.
13791   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13792
13793   // Determine whether this is a call to a pointer-to-member function.
13794   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13795     assert(op->getType() == Context.BoundMemberTy);
13796     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13797
13798     QualType fnType =
13799       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13800
13801     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13802     QualType resultType = proto->getCallResultType(Context);
13803     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13804
13805     // Check that the object type isn't more qualified than the
13806     // member function we're calling.
13807     Qualifiers funcQuals = proto->getMethodQuals();
13808
13809     QualType objectType = op->getLHS()->getType();
13810     if (op->getOpcode() == BO_PtrMemI)
13811       objectType = objectType->castAs<PointerType>()->getPointeeType();
13812     Qualifiers objectQuals = objectType.getQualifiers();
13813
13814     Qualifiers difference = objectQuals - funcQuals;
13815     difference.removeObjCGCAttr();
13816     difference.removeAddressSpace();
13817     if (difference) {
13818       std::string qualsString = difference.getAsString();
13819       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13820         << fnType.getUnqualifiedType()
13821         << qualsString
13822         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13823     }
13824
13825     CXXMemberCallExpr *call =
13826         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13827                                   valueKind, RParenLoc, proto->getNumParams());
13828
13829     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13830                             call, nullptr))
13831       return ExprError();
13832
13833     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13834       return ExprError();
13835
13836     if (CheckOtherCall(call, proto))
13837       return ExprError();
13838
13839     return MaybeBindToTemporary(call);
13840   }
13841
13842   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13843     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13844                             RParenLoc);
13845
13846   UnbridgedCastsSet UnbridgedCasts;
13847   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13848     return ExprError();
13849
13850   MemberExpr *MemExpr;
13851   CXXMethodDecl *Method = nullptr;
13852   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13853   NestedNameSpecifier *Qualifier = nullptr;
13854   if (isa<MemberExpr>(NakedMemExpr)) {
13855     MemExpr = cast<MemberExpr>(NakedMemExpr);
13856     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13857     FoundDecl = MemExpr->getFoundDecl();
13858     Qualifier = MemExpr->getQualifier();
13859     UnbridgedCasts.restore();
13860   } else {
13861     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13862     Qualifier = UnresExpr->getQualifier();
13863
13864     QualType ObjectType = UnresExpr->getBaseType();
13865     Expr::Classification ObjectClassification
13866       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13867                             : UnresExpr->getBase()->Classify(Context);
13868
13869     // Add overload candidates
13870     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13871                                       OverloadCandidateSet::CSK_Normal);
13872
13873     // FIXME: avoid copy.
13874     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13875     if (UnresExpr->hasExplicitTemplateArgs()) {
13876       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13877       TemplateArgs = &TemplateArgsBuffer;
13878     }
13879
13880     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13881            E = UnresExpr->decls_end(); I != E; ++I) {
13882
13883       NamedDecl *Func = *I;
13884       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13885       if (isa<UsingShadowDecl>(Func))
13886         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13887
13888
13889       // Microsoft supports direct constructor calls.
13890       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13891         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13892                              CandidateSet,
13893                              /*SuppressUserConversions*/ false);
13894       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13895         // If explicit template arguments were provided, we can't call a
13896         // non-template member function.
13897         if (TemplateArgs)
13898           continue;
13899
13900         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13901                            ObjectClassification, Args, CandidateSet,
13902                            /*SuppressUserConversions=*/false);
13903       } else {
13904         AddMethodTemplateCandidate(
13905             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13906             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13907             /*SuppressUserConversions=*/false);
13908       }
13909     }
13910
13911     DeclarationName DeclName = UnresExpr->getMemberName();
13912
13913     UnbridgedCasts.restore();
13914
13915     OverloadCandidateSet::iterator Best;
13916     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13917                                             Best)) {
13918     case OR_Success:
13919       Method = cast<CXXMethodDecl>(Best->Function);
13920       FoundDecl = Best->FoundDecl;
13921       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13922       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13923         return ExprError();
13924       // If FoundDecl is different from Method (such as if one is a template
13925       // and the other a specialization), make sure DiagnoseUseOfDecl is
13926       // called on both.
13927       // FIXME: This would be more comprehensively addressed by modifying
13928       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13929       // being used.
13930       if (Method != FoundDecl.getDecl() &&
13931                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13932         return ExprError();
13933       break;
13934
13935     case OR_No_Viable_Function:
13936       CandidateSet.NoteCandidates(
13937           PartialDiagnosticAt(
13938               UnresExpr->getMemberLoc(),
13939               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13940                   << DeclName << MemExprE->getSourceRange()),
13941           *this, OCD_AllCandidates, Args);
13942       // FIXME: Leaking incoming expressions!
13943       return ExprError();
13944
13945     case OR_Ambiguous:
13946       CandidateSet.NoteCandidates(
13947           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13948                               PDiag(diag::err_ovl_ambiguous_member_call)
13949                                   << DeclName << MemExprE->getSourceRange()),
13950           *this, OCD_AmbiguousCandidates, Args);
13951       // FIXME: Leaking incoming expressions!
13952       return ExprError();
13953
13954     case OR_Deleted:
13955       CandidateSet.NoteCandidates(
13956           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13957                               PDiag(diag::err_ovl_deleted_member_call)
13958                                   << DeclName << MemExprE->getSourceRange()),
13959           *this, OCD_AllCandidates, Args);
13960       // FIXME: Leaking incoming expressions!
13961       return ExprError();
13962     }
13963
13964     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13965
13966     // If overload resolution picked a static member, build a
13967     // non-member call based on that function.
13968     if (Method->isStatic()) {
13969       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13970                                    RParenLoc);
13971     }
13972
13973     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13974   }
13975
13976   QualType ResultType = Method->getReturnType();
13977   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13978   ResultType = ResultType.getNonLValueExprType(Context);
13979
13980   assert(Method && "Member call to something that isn't a method?");
13981   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
13982   CXXMemberCallExpr *TheCall =
13983       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13984                                 RParenLoc, Proto->getNumParams());
13985
13986   // Check for a valid return type.
13987   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13988                           TheCall, Method))
13989     return ExprError();
13990
13991   // Convert the object argument (for a non-static member function call).
13992   // We only need to do this if there was actually an overload; otherwise
13993   // it was done at lookup.
13994   if (!Method->isStatic()) {
13995     ExprResult ObjectArg =
13996       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13997                                           FoundDecl, Method);
13998     if (ObjectArg.isInvalid())
13999       return ExprError();
14000     MemExpr->setBase(ObjectArg.get());
14001   }
14002
14003   // Convert the rest of the arguments
14004   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14005                               RParenLoc))
14006     return ExprError();
14007
14008   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14009
14010   if (CheckFunctionCall(Method, TheCall, Proto))
14011     return ExprError();
14012
14013   // In the case the method to call was not selected by the overloading
14014   // resolution process, we still need to handle the enable_if attribute. Do
14015   // that here, so it will not hide previous -- and more relevant -- errors.
14016   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14017     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14018       Diag(MemE->getMemberLoc(),
14019            diag::err_ovl_no_viable_member_function_in_call)
14020           << Method << Method->getSourceRange();
14021       Diag(Method->getLocation(),
14022            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14023           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14024       return ExprError();
14025     }
14026   }
14027
14028   if ((isa<CXXConstructorDecl>(CurContext) ||
14029        isa<CXXDestructorDecl>(CurContext)) &&
14030       TheCall->getMethodDecl()->isPure()) {
14031     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14032
14033     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14034         MemExpr->performsVirtualDispatch(getLangOpts())) {
14035       Diag(MemExpr->getBeginLoc(),
14036            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14037           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14038           << MD->getParent()->getDeclName();
14039
14040       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14041       if (getLangOpts().AppleKext)
14042         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14043             << MD->getParent()->getDeclName() << MD->getDeclName();
14044     }
14045   }
14046
14047   if (CXXDestructorDecl *DD =
14048           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14049     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14050     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14051     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14052                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14053                          MemExpr->getMemberLoc());
14054   }
14055
14056   return MaybeBindToTemporary(TheCall);
14057 }
14058
14059 /// BuildCallToObjectOfClassType - Build a call to an object of class
14060 /// type (C++ [over.call.object]), which can end up invoking an
14061 /// overloaded function call operator (@c operator()) or performing a
14062 /// user-defined conversion on the object argument.
14063 ExprResult
14064 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14065                                    SourceLocation LParenLoc,
14066                                    MultiExprArg Args,
14067                                    SourceLocation RParenLoc) {
14068   if (checkPlaceholderForOverload(*this, Obj))
14069     return ExprError();
14070   ExprResult Object = Obj;
14071
14072   UnbridgedCastsSet UnbridgedCasts;
14073   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14074     return ExprError();
14075
14076   assert(Object.get()->getType()->isRecordType() &&
14077          "Requires object type argument");
14078
14079   // C++ [over.call.object]p1:
14080   //  If the primary-expression E in the function call syntax
14081   //  evaluates to a class object of type "cv T", then the set of
14082   //  candidate functions includes at least the function call
14083   //  operators of T. The function call operators of T are obtained by
14084   //  ordinary lookup of the name operator() in the context of
14085   //  (E).operator().
14086   OverloadCandidateSet CandidateSet(LParenLoc,
14087                                     OverloadCandidateSet::CSK_Operator);
14088   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14089
14090   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14091                           diag::err_incomplete_object_call, Object.get()))
14092     return true;
14093
14094   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14095   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14096   LookupQualifiedName(R, Record->getDecl());
14097   R.suppressDiagnostics();
14098
14099   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14100        Oper != OperEnd; ++Oper) {
14101     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14102                        Object.get()->Classify(Context), Args, CandidateSet,
14103                        /*SuppressUserConversion=*/false);
14104   }
14105
14106   // C++ [over.call.object]p2:
14107   //   In addition, for each (non-explicit in C++0x) conversion function
14108   //   declared in T of the form
14109   //
14110   //        operator conversion-type-id () cv-qualifier;
14111   //
14112   //   where cv-qualifier is the same cv-qualification as, or a
14113   //   greater cv-qualification than, cv, and where conversion-type-id
14114   //   denotes the type "pointer to function of (P1,...,Pn) returning
14115   //   R", or the type "reference to pointer to function of
14116   //   (P1,...,Pn) returning R", or the type "reference to function
14117   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14118   //   is also considered as a candidate function. Similarly,
14119   //   surrogate call functions are added to the set of candidate
14120   //   functions for each conversion function declared in an
14121   //   accessible base class provided the function is not hidden
14122   //   within T by another intervening declaration.
14123   const auto &Conversions =
14124       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14125   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14126     NamedDecl *D = *I;
14127     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14128     if (isa<UsingShadowDecl>(D))
14129       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14130
14131     // Skip over templated conversion functions; they aren't
14132     // surrogates.
14133     if (isa<FunctionTemplateDecl>(D))
14134       continue;
14135
14136     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14137     if (!Conv->isExplicit()) {
14138       // Strip the reference type (if any) and then the pointer type (if
14139       // any) to get down to what might be a function type.
14140       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14141       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14142         ConvType = ConvPtrType->getPointeeType();
14143
14144       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14145       {
14146         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14147                               Object.get(), Args, CandidateSet);
14148       }
14149     }
14150   }
14151
14152   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14153
14154   // Perform overload resolution.
14155   OverloadCandidateSet::iterator Best;
14156   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14157                                           Best)) {
14158   case OR_Success:
14159     // Overload resolution succeeded; we'll build the appropriate call
14160     // below.
14161     break;
14162
14163   case OR_No_Viable_Function: {
14164     PartialDiagnostic PD =
14165         CandidateSet.empty()
14166             ? (PDiag(diag::err_ovl_no_oper)
14167                << Object.get()->getType() << /*call*/ 1
14168                << Object.get()->getSourceRange())
14169             : (PDiag(diag::err_ovl_no_viable_object_call)
14170                << Object.get()->getType() << Object.get()->getSourceRange());
14171     CandidateSet.NoteCandidates(
14172         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14173         OCD_AllCandidates, Args);
14174     break;
14175   }
14176   case OR_Ambiguous:
14177     CandidateSet.NoteCandidates(
14178         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14179                             PDiag(diag::err_ovl_ambiguous_object_call)
14180                                 << Object.get()->getType()
14181                                 << Object.get()->getSourceRange()),
14182         *this, OCD_AmbiguousCandidates, Args);
14183     break;
14184
14185   case OR_Deleted:
14186     CandidateSet.NoteCandidates(
14187         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14188                             PDiag(diag::err_ovl_deleted_object_call)
14189                                 << Object.get()->getType()
14190                                 << Object.get()->getSourceRange()),
14191         *this, OCD_AllCandidates, Args);
14192     break;
14193   }
14194
14195   if (Best == CandidateSet.end())
14196     return true;
14197
14198   UnbridgedCasts.restore();
14199
14200   if (Best->Function == nullptr) {
14201     // Since there is no function declaration, this is one of the
14202     // surrogate candidates. Dig out the conversion function.
14203     CXXConversionDecl *Conv
14204       = cast<CXXConversionDecl>(
14205                          Best->Conversions[0].UserDefined.ConversionFunction);
14206
14207     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14208                               Best->FoundDecl);
14209     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14210       return ExprError();
14211     assert(Conv == Best->FoundDecl.getDecl() &&
14212              "Found Decl & conversion-to-functionptr should be same, right?!");
14213     // We selected one of the surrogate functions that converts the
14214     // object parameter to a function pointer. Perform the conversion
14215     // on the object argument, then let BuildCallExpr finish the job.
14216
14217     // Create an implicit member expr to refer to the conversion operator.
14218     // and then call it.
14219     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14220                                              Conv, HadMultipleCandidates);
14221     if (Call.isInvalid())
14222       return ExprError();
14223     // Record usage of conversion in an implicit cast.
14224     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14225                                     CK_UserDefinedConversion, Call.get(),
14226                                     nullptr, VK_RValue);
14227
14228     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14229   }
14230
14231   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14232
14233   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14234   // that calls this method, using Object for the implicit object
14235   // parameter and passing along the remaining arguments.
14236   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14237
14238   // An error diagnostic has already been printed when parsing the declaration.
14239   if (Method->isInvalidDecl())
14240     return ExprError();
14241
14242   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14243   unsigned NumParams = Proto->getNumParams();
14244
14245   DeclarationNameInfo OpLocInfo(
14246                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14247   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14248   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14249                                            Obj, HadMultipleCandidates,
14250                                            OpLocInfo.getLoc(),
14251                                            OpLocInfo.getInfo());
14252   if (NewFn.isInvalid())
14253     return true;
14254
14255   // The number of argument slots to allocate in the call. If we have default
14256   // arguments we need to allocate space for them as well. We additionally
14257   // need one more slot for the object parameter.
14258   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14259
14260   // Build the full argument list for the method call (the implicit object
14261   // parameter is placed at the beginning of the list).
14262   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14263
14264   bool IsError = false;
14265
14266   // Initialize the implicit object parameter.
14267   ExprResult ObjRes =
14268     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14269                                         Best->FoundDecl, Method);
14270   if (ObjRes.isInvalid())
14271     IsError = true;
14272   else
14273     Object = ObjRes;
14274   MethodArgs[0] = Object.get();
14275
14276   // Check the argument types.
14277   for (unsigned i = 0; i != NumParams; i++) {
14278     Expr *Arg;
14279     if (i < Args.size()) {
14280       Arg = Args[i];
14281
14282       // Pass the argument.
14283
14284       ExprResult InputInit
14285         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14286                                                     Context,
14287                                                     Method->getParamDecl(i)),
14288                                     SourceLocation(), Arg);
14289
14290       IsError |= InputInit.isInvalid();
14291       Arg = InputInit.getAs<Expr>();
14292     } else {
14293       ExprResult DefArg
14294         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14295       if (DefArg.isInvalid()) {
14296         IsError = true;
14297         break;
14298       }
14299
14300       Arg = DefArg.getAs<Expr>();
14301     }
14302
14303     MethodArgs[i + 1] = Arg;
14304   }
14305
14306   // If this is a variadic call, handle args passed through "...".
14307   if (Proto->isVariadic()) {
14308     // Promote the arguments (C99 6.5.2.2p7).
14309     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14310       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14311                                                         nullptr);
14312       IsError |= Arg.isInvalid();
14313       MethodArgs[i + 1] = Arg.get();
14314     }
14315   }
14316
14317   if (IsError)
14318     return true;
14319
14320   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14321
14322   // Once we've built TheCall, all of the expressions are properly owned.
14323   QualType ResultTy = Method->getReturnType();
14324   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14325   ResultTy = ResultTy.getNonLValueExprType(Context);
14326
14327   CXXOperatorCallExpr *TheCall =
14328       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14329                                   ResultTy, VK, RParenLoc, FPOptions());
14330
14331   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14332     return true;
14333
14334   if (CheckFunctionCall(Method, TheCall, Proto))
14335     return true;
14336
14337   return MaybeBindToTemporary(TheCall);
14338 }
14339
14340 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14341 ///  (if one exists), where @c Base is an expression of class type and
14342 /// @c Member is the name of the member we're trying to find.
14343 ExprResult
14344 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14345                                bool *NoArrowOperatorFound) {
14346   assert(Base->getType()->isRecordType() &&
14347          "left-hand side must have class type");
14348
14349   if (checkPlaceholderForOverload(*this, Base))
14350     return ExprError();
14351
14352   SourceLocation Loc = Base->getExprLoc();
14353
14354   // C++ [over.ref]p1:
14355   //
14356   //   [...] An expression x->m is interpreted as (x.operator->())->m
14357   //   for a class object x of type T if T::operator->() exists and if
14358   //   the operator is selected as the best match function by the
14359   //   overload resolution mechanism (13.3).
14360   DeclarationName OpName =
14361     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14362   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14363
14364   if (RequireCompleteType(Loc, Base->getType(),
14365                           diag::err_typecheck_incomplete_tag, Base))
14366     return ExprError();
14367
14368   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14369   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14370   R.suppressDiagnostics();
14371
14372   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14373        Oper != OperEnd; ++Oper) {
14374     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14375                        None, CandidateSet, /*SuppressUserConversion=*/false);
14376   }
14377
14378   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14379
14380   // Perform overload resolution.
14381   OverloadCandidateSet::iterator Best;
14382   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14383   case OR_Success:
14384     // Overload resolution succeeded; we'll build the call below.
14385     break;
14386
14387   case OR_No_Viable_Function: {
14388     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14389     if (CandidateSet.empty()) {
14390       QualType BaseType = Base->getType();
14391       if (NoArrowOperatorFound) {
14392         // Report this specific error to the caller instead of emitting a
14393         // diagnostic, as requested.
14394         *NoArrowOperatorFound = true;
14395         return ExprError();
14396       }
14397       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14398         << BaseType << Base->getSourceRange();
14399       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14400         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14401           << FixItHint::CreateReplacement(OpLoc, ".");
14402       }
14403     } else
14404       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14405         << "operator->" << Base->getSourceRange();
14406     CandidateSet.NoteCandidates(*this, Base, Cands);
14407     return ExprError();
14408   }
14409   case OR_Ambiguous:
14410     CandidateSet.NoteCandidates(
14411         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14412                                        << "->" << Base->getType()
14413                                        << Base->getSourceRange()),
14414         *this, OCD_AmbiguousCandidates, Base);
14415     return ExprError();
14416
14417   case OR_Deleted:
14418     CandidateSet.NoteCandidates(
14419         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14420                                        << "->" << Base->getSourceRange()),
14421         *this, OCD_AllCandidates, Base);
14422     return ExprError();
14423   }
14424
14425   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14426
14427   // Convert the object parameter.
14428   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14429   ExprResult BaseResult =
14430     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14431                                         Best->FoundDecl, Method);
14432   if (BaseResult.isInvalid())
14433     return ExprError();
14434   Base = BaseResult.get();
14435
14436   // Build the operator call.
14437   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14438                                             Base, HadMultipleCandidates, OpLoc);
14439   if (FnExpr.isInvalid())
14440     return ExprError();
14441
14442   QualType ResultTy = Method->getReturnType();
14443   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14444   ResultTy = ResultTy.getNonLValueExprType(Context);
14445   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14446       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14447
14448   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14449     return ExprError();
14450
14451   if (CheckFunctionCall(Method, TheCall,
14452                         Method->getType()->castAs<FunctionProtoType>()))
14453     return ExprError();
14454
14455   return MaybeBindToTemporary(TheCall);
14456 }
14457
14458 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14459 /// a literal operator described by the provided lookup results.
14460 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14461                                           DeclarationNameInfo &SuffixInfo,
14462                                           ArrayRef<Expr*> Args,
14463                                           SourceLocation LitEndLoc,
14464                                        TemplateArgumentListInfo *TemplateArgs) {
14465   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14466
14467   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14468                                     OverloadCandidateSet::CSK_Normal);
14469   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14470                                  TemplateArgs);
14471
14472   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14473
14474   // Perform overload resolution. This will usually be trivial, but might need
14475   // to perform substitutions for a literal operator template.
14476   OverloadCandidateSet::iterator Best;
14477   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14478   case OR_Success:
14479   case OR_Deleted:
14480     break;
14481
14482   case OR_No_Viable_Function:
14483     CandidateSet.NoteCandidates(
14484         PartialDiagnosticAt(UDSuffixLoc,
14485                             PDiag(diag::err_ovl_no_viable_function_in_call)
14486                                 << R.getLookupName()),
14487         *this, OCD_AllCandidates, Args);
14488     return ExprError();
14489
14490   case OR_Ambiguous:
14491     CandidateSet.NoteCandidates(
14492         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14493                                                 << R.getLookupName()),
14494         *this, OCD_AmbiguousCandidates, Args);
14495     return ExprError();
14496   }
14497
14498   FunctionDecl *FD = Best->Function;
14499   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14500                                         nullptr, HadMultipleCandidates,
14501                                         SuffixInfo.getLoc(),
14502                                         SuffixInfo.getInfo());
14503   if (Fn.isInvalid())
14504     return true;
14505
14506   // Check the argument types. This should almost always be a no-op, except
14507   // that array-to-pointer decay is applied to string literals.
14508   Expr *ConvArgs[2];
14509   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14510     ExprResult InputInit = PerformCopyInitialization(
14511       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14512       SourceLocation(), Args[ArgIdx]);
14513     if (InputInit.isInvalid())
14514       return true;
14515     ConvArgs[ArgIdx] = InputInit.get();
14516   }
14517
14518   QualType ResultTy = FD->getReturnType();
14519   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14520   ResultTy = ResultTy.getNonLValueExprType(Context);
14521
14522   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14523       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14524       VK, LitEndLoc, UDSuffixLoc);
14525
14526   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14527     return ExprError();
14528
14529   if (CheckFunctionCall(FD, UDL, nullptr))
14530     return ExprError();
14531
14532   return MaybeBindToTemporary(UDL);
14533 }
14534
14535 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14536 /// given LookupResult is non-empty, it is assumed to describe a member which
14537 /// will be invoked. Otherwise, the function will be found via argument
14538 /// dependent lookup.
14539 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14540 /// otherwise CallExpr is set to ExprError() and some non-success value
14541 /// is returned.
14542 Sema::ForRangeStatus
14543 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14544                                 SourceLocation RangeLoc,
14545                                 const DeclarationNameInfo &NameInfo,
14546                                 LookupResult &MemberLookup,
14547                                 OverloadCandidateSet *CandidateSet,
14548                                 Expr *Range, ExprResult *CallExpr) {
14549   Scope *S = nullptr;
14550
14551   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14552   if (!MemberLookup.empty()) {
14553     ExprResult MemberRef =
14554         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14555                                  /*IsPtr=*/false, CXXScopeSpec(),
14556                                  /*TemplateKWLoc=*/SourceLocation(),
14557                                  /*FirstQualifierInScope=*/nullptr,
14558                                  MemberLookup,
14559                                  /*TemplateArgs=*/nullptr, S);
14560     if (MemberRef.isInvalid()) {
14561       *CallExpr = ExprError();
14562       return FRS_DiagnosticIssued;
14563     }
14564     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14565     if (CallExpr->isInvalid()) {
14566       *CallExpr = ExprError();
14567       return FRS_DiagnosticIssued;
14568     }
14569   } else {
14570     UnresolvedSet<0> FoundNames;
14571     UnresolvedLookupExpr *Fn =
14572       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14573                                    NestedNameSpecifierLoc(), NameInfo,
14574                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14575                                    FoundNames.begin(), FoundNames.end());
14576
14577     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14578                                                     CandidateSet, CallExpr);
14579     if (CandidateSet->empty() || CandidateSetError) {
14580       *CallExpr = ExprError();
14581       return FRS_NoViableFunction;
14582     }
14583     OverloadCandidateSet::iterator Best;
14584     OverloadingResult OverloadResult =
14585         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14586
14587     if (OverloadResult == OR_No_Viable_Function) {
14588       *CallExpr = ExprError();
14589       return FRS_NoViableFunction;
14590     }
14591     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14592                                          Loc, nullptr, CandidateSet, &Best,
14593                                          OverloadResult,
14594                                          /*AllowTypoCorrection=*/false);
14595     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14596       *CallExpr = ExprError();
14597       return FRS_DiagnosticIssued;
14598     }
14599   }
14600   return FRS_Success;
14601 }
14602
14603
14604 /// FixOverloadedFunctionReference - E is an expression that refers to
14605 /// a C++ overloaded function (possibly with some parentheses and
14606 /// perhaps a '&' around it). We have resolved the overloaded function
14607 /// to the function declaration Fn, so patch up the expression E to
14608 /// refer (possibly indirectly) to Fn. Returns the new expr.
14609 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14610                                            FunctionDecl *Fn) {
14611   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14612     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14613                                                    Found, Fn);
14614     if (SubExpr == PE->getSubExpr())
14615       return PE;
14616
14617     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14618   }
14619
14620   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14621     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14622                                                    Found, Fn);
14623     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14624                                SubExpr->getType()) &&
14625            "Implicit cast type cannot be determined from overload");
14626     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14627     if (SubExpr == ICE->getSubExpr())
14628       return ICE;
14629
14630     return ImplicitCastExpr::Create(Context, ICE->getType(),
14631                                     ICE->getCastKind(),
14632                                     SubExpr, nullptr,
14633                                     ICE->getValueKind());
14634   }
14635
14636   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14637     if (!GSE->isResultDependent()) {
14638       Expr *SubExpr =
14639           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14640       if (SubExpr == GSE->getResultExpr())
14641         return GSE;
14642
14643       // Replace the resulting type information before rebuilding the generic
14644       // selection expression.
14645       ArrayRef<Expr *> A = GSE->getAssocExprs();
14646       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14647       unsigned ResultIdx = GSE->getResultIndex();
14648       AssocExprs[ResultIdx] = SubExpr;
14649
14650       return GenericSelectionExpr::Create(
14651           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14652           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14653           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14654           ResultIdx);
14655     }
14656     // Rather than fall through to the unreachable, return the original generic
14657     // selection expression.
14658     return GSE;
14659   }
14660
14661   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14662     assert(UnOp->getOpcode() == UO_AddrOf &&
14663            "Can only take the address of an overloaded function");
14664     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14665       if (Method->isStatic()) {
14666         // Do nothing: static member functions aren't any different
14667         // from non-member functions.
14668       } else {
14669         // Fix the subexpression, which really has to be an
14670         // UnresolvedLookupExpr holding an overloaded member function
14671         // or template.
14672         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14673                                                        Found, Fn);
14674         if (SubExpr == UnOp->getSubExpr())
14675           return UnOp;
14676
14677         assert(isa<DeclRefExpr>(SubExpr)
14678                && "fixed to something other than a decl ref");
14679         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14680                && "fixed to a member ref with no nested name qualifier");
14681
14682         // We have taken the address of a pointer to member
14683         // function. Perform the computation here so that we get the
14684         // appropriate pointer to member type.
14685         QualType ClassType
14686           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14687         QualType MemPtrType
14688           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14689         // Under the MS ABI, lock down the inheritance model now.
14690         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14691           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14692
14693         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14694                                            VK_RValue, OK_Ordinary,
14695                                            UnOp->getOperatorLoc(), false);
14696       }
14697     }
14698     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14699                                                    Found, Fn);
14700     if (SubExpr == UnOp->getSubExpr())
14701       return UnOp;
14702
14703     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14704                                      Context.getPointerType(SubExpr->getType()),
14705                                        VK_RValue, OK_Ordinary,
14706                                        UnOp->getOperatorLoc(), false);
14707   }
14708
14709   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14710     // FIXME: avoid copy.
14711     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14712     if (ULE->hasExplicitTemplateArgs()) {
14713       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14714       TemplateArgs = &TemplateArgsBuffer;
14715     }
14716
14717     DeclRefExpr *DRE =
14718         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14719                          ULE->getQualifierLoc(), Found.getDecl(),
14720                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14721     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14722     return DRE;
14723   }
14724
14725   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14726     // FIXME: avoid copy.
14727     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14728     if (MemExpr->hasExplicitTemplateArgs()) {
14729       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14730       TemplateArgs = &TemplateArgsBuffer;
14731     }
14732
14733     Expr *Base;
14734
14735     // If we're filling in a static method where we used to have an
14736     // implicit member access, rewrite to a simple decl ref.
14737     if (MemExpr->isImplicitAccess()) {
14738       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14739         DeclRefExpr *DRE = BuildDeclRefExpr(
14740             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14741             MemExpr->getQualifierLoc(), Found.getDecl(),
14742             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14743         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14744         return DRE;
14745       } else {
14746         SourceLocation Loc = MemExpr->getMemberLoc();
14747         if (MemExpr->getQualifier())
14748           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14749         Base =
14750             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14751       }
14752     } else
14753       Base = MemExpr->getBase();
14754
14755     ExprValueKind valueKind;
14756     QualType type;
14757     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14758       valueKind = VK_LValue;
14759       type = Fn->getType();
14760     } else {
14761       valueKind = VK_RValue;
14762       type = Context.BoundMemberTy;
14763     }
14764
14765     return BuildMemberExpr(
14766         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14767         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14768         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14769         type, valueKind, OK_Ordinary, TemplateArgs);
14770   }
14771
14772   llvm_unreachable("Invalid reference to overloaded function");
14773 }
14774
14775 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14776                                                 DeclAccessPair Found,
14777                                                 FunctionDecl *Fn) {
14778   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14779 }