]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaOverload.cpp
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38
39 using namespace clang;
40 using namespace sema;
41
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       const Expr *Base, bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70
71   S.MarkDeclRefReferenced(DRE, Base);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93
94
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isMemberPointerType() ||
227        getFromType()->isObjCObjectPointerType() ||
228        getFromType()->isBlockPointerType() ||
229        getFromType()->isNullPtrType() ||
230        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231     return true;
232
233   return false;
234 }
235
236 /// isPointerConversionToVoidPointer - Determines whether this
237 /// conversion is a conversion of a pointer to a void pointer. This is
238 /// used as part of the ranking of standard conversion sequences (C++
239 /// 13.3.3.2p4).
240 bool
241 StandardConversionSequence::
242 isPointerConversionToVoidPointer(ASTContext& Context) const {
243   QualType FromType = getFromType();
244   QualType ToType = getToType(1);
245
246   // Note that FromType has not necessarily been transformed by the
247   // array-to-pointer implicit conversion, so check for its presence
248   // and redo the conversion to get a pointer.
249   if (First == ICK_Array_To_Pointer)
250     FromType = Context.getArrayDecayedType(FromType);
251
252   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254       return ToPtrType->getPointeeType()->isVoidType();
255
256   return false;
257 }
258
259 /// Skip any implicit casts which could be either part of a narrowing conversion
260 /// or after one in an implicit conversion.
261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263     switch (ICE->getCastKind()) {
264     case CK_NoOp:
265     case CK_IntegralCast:
266     case CK_IntegralToBoolean:
267     case CK_IntegralToFloating:
268     case CK_BooleanToSignedIntegral:
269     case CK_FloatingToIntegral:
270     case CK_FloatingToBoolean:
271     case CK_FloatingCast:
272       Converted = ICE->getSubExpr();
273       continue;
274
275     default:
276       return Converted;
277     }
278   }
279
280   return Converted;
281 }
282
283 /// Check if this standard conversion sequence represents a narrowing
284 /// conversion, according to C++11 [dcl.init.list]p7.
285 ///
286 /// \param Ctx  The AST context.
287 /// \param Converted  The result of applying this standard conversion sequence.
288 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
289 ///        value of the expression prior to the narrowing conversion.
290 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
291 ///        type of the expression prior to the narrowing conversion.
292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293 ///        from floating point types to integral types should be ignored.
294 NarrowingKind StandardConversionSequence::getNarrowingKind(
295     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298
299   // C++11 [dcl.init.list]p7:
300   //   A narrowing conversion is an implicit conversion ...
301   QualType FromType = getToType(0);
302   QualType ToType = getToType(1);
303
304   // A conversion to an enumeration type is narrowing if the conversion to
305   // the underlying type is narrowing. This only arises for expressions of
306   // the form 'Enum{init}'.
307   if (auto *ET = ToType->getAs<EnumType>())
308     ToType = ET->getDecl()->getIntegerType();
309
310   switch (Second) {
311   // 'bool' is an integral type; dispatch to the right place to handle it.
312   case ICK_Boolean_Conversion:
313     if (FromType->isRealFloatingType())
314       goto FloatingIntegralConversion;
315     if (FromType->isIntegralOrUnscopedEnumerationType())
316       goto IntegralConversion;
317     // Boolean conversions can be from pointers and pointers to members
318     // [conv.bool], and those aren't considered narrowing conversions.
319     return NK_Not_Narrowing;
320
321   // -- from a floating-point type to an integer type, or
322   //
323   // -- from an integer type or unscoped enumeration type to a floating-point
324   //    type, except where the source is a constant expression and the actual
325   //    value after conversion will fit into the target type and will produce
326   //    the original value when converted back to the original type, or
327   case ICK_Floating_Integral:
328   FloatingIntegralConversion:
329     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330       return NK_Type_Narrowing;
331     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332                ToType->isRealFloatingType()) {
333       if (IgnoreFloatToIntegralConversion)
334         return NK_Not_Narrowing;
335       llvm::APSInt IntConstantValue;
336       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337       assert(Initializer && "Unknown conversion expression");
338
339       // If it's value-dependent, we can't tell whether it's narrowing.
340       if (Initializer->isValueDependent())
341         return NK_Dependent_Narrowing;
342
343       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344         // Convert the integer to the floating type.
345         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347                                 llvm::APFloat::rmNearestTiesToEven);
348         // And back.
349         llvm::APSInt ConvertedValue = IntConstantValue;
350         bool ignored;
351         Result.convertToInteger(ConvertedValue,
352                                 llvm::APFloat::rmTowardZero, &ignored);
353         // If the resulting value is different, this was a narrowing conversion.
354         if (IntConstantValue != ConvertedValue) {
355           ConstantValue = APValue(IntConstantValue);
356           ConstantType = Initializer->getType();
357           return NK_Constant_Narrowing;
358         }
359       } else {
360         // Variables are always narrowings.
361         return NK_Variable_Narrowing;
362       }
363     }
364     return NK_Not_Narrowing;
365
366   // -- from long double to double or float, or from double to float, except
367   //    where the source is a constant expression and the actual value after
368   //    conversion is within the range of values that can be represented (even
369   //    if it cannot be represented exactly), or
370   case ICK_Floating_Conversion:
371     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373       // FromType is larger than ToType.
374       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375
376       // If it's value-dependent, we can't tell whether it's narrowing.
377       if (Initializer->isValueDependent())
378         return NK_Dependent_Narrowing;
379
380       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381         // Constant!
382         assert(ConstantValue.isFloat());
383         llvm::APFloat FloatVal = ConstantValue.getFloat();
384         // Convert the source value into the target type.
385         bool ignored;
386         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387           Ctx.getFloatTypeSemantics(ToType),
388           llvm::APFloat::rmNearestTiesToEven, &ignored);
389         // If there was no overflow, the source value is within the range of
390         // values that can be represented.
391         if (ConvertStatus & llvm::APFloat::opOverflow) {
392           ConstantType = Initializer->getType();
393           return NK_Constant_Narrowing;
394         }
395       } else {
396         return NK_Variable_Narrowing;
397       }
398     }
399     return NK_Not_Narrowing;
400
401   // -- from an integer type or unscoped enumeration type to an integer type
402   //    that cannot represent all the values of the original type, except where
403   //    the source is a constant expression and the actual value after
404   //    conversion will fit into the target type and will produce the original
405   //    value when converted back to the original type.
406   case ICK_Integral_Conversion:
407   IntegralConversion: {
408     assert(FromType->isIntegralOrUnscopedEnumerationType());
409     assert(ToType->isIntegralOrUnscopedEnumerationType());
410     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411     const unsigned FromWidth = Ctx.getIntWidth(FromType);
412     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413     const unsigned ToWidth = Ctx.getIntWidth(ToType);
414
415     if (FromWidth > ToWidth ||
416         (FromWidth == ToWidth && FromSigned != ToSigned) ||
417         (FromSigned && !ToSigned)) {
418       // Not all values of FromType can be represented in ToType.
419       llvm::APSInt InitializerValue;
420       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421
422       // If it's value-dependent, we can't tell whether it's narrowing.
423       if (Initializer->isValueDependent())
424         return NK_Dependent_Narrowing;
425
426       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427         // Such conversions on variables are always narrowing.
428         return NK_Variable_Narrowing;
429       }
430       bool Narrowing = false;
431       if (FromWidth < ToWidth) {
432         // Negative -> unsigned is narrowing. Otherwise, more bits is never
433         // narrowing.
434         if (InitializerValue.isSigned() && InitializerValue.isNegative())
435           Narrowing = true;
436       } else {
437         // Add a bit to the InitializerValue so we don't have to worry about
438         // signed vs. unsigned comparisons.
439         InitializerValue = InitializerValue.extend(
440           InitializerValue.getBitWidth() + 1);
441         // Convert the initializer to and from the target width and signed-ness.
442         llvm::APSInt ConvertedValue = InitializerValue;
443         ConvertedValue = ConvertedValue.trunc(ToWidth);
444         ConvertedValue.setIsSigned(ToSigned);
445         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446         ConvertedValue.setIsSigned(InitializerValue.isSigned());
447         // If the result is different, this was a narrowing conversion.
448         if (ConvertedValue != InitializerValue)
449           Narrowing = true;
450       }
451       if (Narrowing) {
452         ConstantType = Initializer->getType();
453         ConstantValue = APValue(InitializerValue);
454         return NK_Constant_Narrowing;
455       }
456     }
457     return NK_Not_Narrowing;
458   }
459
460   default:
461     // Other kinds of conversions are not narrowings.
462     return NK_Not_Narrowing;
463   }
464 }
465
466 /// dump - Print this standard conversion sequence to standard
467 /// error. Useful for debugging overloading issues.
468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
469   raw_ostream &OS = llvm::errs();
470   bool PrintedSomething = false;
471   if (First != ICK_Identity) {
472     OS << GetImplicitConversionName(First);
473     PrintedSomething = true;
474   }
475
476   if (Second != ICK_Identity) {
477     if (PrintedSomething) {
478       OS << " -> ";
479     }
480     OS << GetImplicitConversionName(Second);
481
482     if (CopyConstructor) {
483       OS << " (by copy constructor)";
484     } else if (DirectBinding) {
485       OS << " (direct reference binding)";
486     } else if (ReferenceBinding) {
487       OS << " (reference binding)";
488     }
489     PrintedSomething = true;
490   }
491
492   if (Third != ICK_Identity) {
493     if (PrintedSomething) {
494       OS << " -> ";
495     }
496     OS << GetImplicitConversionName(Third);
497     PrintedSomething = true;
498   }
499
500   if (!PrintedSomething) {
501     OS << "No conversions required";
502   }
503 }
504
505 /// dump - Print this user-defined conversion sequence to standard
506 /// error. Useful for debugging overloading issues.
507 void UserDefinedConversionSequence::dump() const {
508   raw_ostream &OS = llvm::errs();
509   if (Before.First || Before.Second || Before.Third) {
510     Before.dump();
511     OS << " -> ";
512   }
513   if (ConversionFunction)
514     OS << '\'' << *ConversionFunction << '\'';
515   else
516     OS << "aggregate initialization";
517   if (After.First || After.Second || After.Third) {
518     OS << " -> ";
519     After.dump();
520   }
521 }
522
523 /// dump - Print this implicit conversion sequence to standard
524 /// error. Useful for debugging overloading issues.
525 void ImplicitConversionSequence::dump() const {
526   raw_ostream &OS = llvm::errs();
527   if (isStdInitializerListElement())
528     OS << "Worst std::initializer_list element conversion: ";
529   switch (ConversionKind) {
530   case StandardConversion:
531     OS << "Standard conversion: ";
532     Standard.dump();
533     break;
534   case UserDefinedConversion:
535     OS << "User-defined conversion: ";
536     UserDefined.dump();
537     break;
538   case EllipsisConversion:
539     OS << "Ellipsis conversion";
540     break;
541   case AmbiguousConversion:
542     OS << "Ambiguous conversion";
543     break;
544   case BadConversion:
545     OS << "Bad conversion";
546     break;
547   }
548
549   OS << "\n";
550 }
551
552 void AmbiguousConversionSequence::construct() {
553   new (&conversions()) ConversionSet();
554 }
555
556 void AmbiguousConversionSequence::destruct() {
557   conversions().~ConversionSet();
558 }
559
560 void
561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562   FromTypePtr = O.FromTypePtr;
563   ToTypePtr = O.ToTypePtr;
564   new (&conversions()) ConversionSet(O.conversions());
565 }
566
567 namespace {
568   // Structure used by DeductionFailureInfo to store
569   // template argument information.
570   struct DFIArguments {
571     TemplateArgument FirstArg;
572     TemplateArgument SecondArg;
573   };
574   // Structure used by DeductionFailureInfo to store
575   // template parameter and template argument information.
576   struct DFIParamWithArguments : DFIArguments {
577     TemplateParameter Param;
578   };
579   // Structure used by DeductionFailureInfo to store template argument
580   // information and the index of the problematic call argument.
581   struct DFIDeducedMismatchArgs : DFIArguments {
582     TemplateArgumentList *TemplateArgs;
583     unsigned CallArgIndex;
584   };
585 }
586
587 /// Convert from Sema's representation of template deduction information
588 /// to the form used in overload-candidate information.
589 DeductionFailureInfo
590 clang::MakeDeductionFailureInfo(ASTContext &Context,
591                                 Sema::TemplateDeductionResult TDK,
592                                 TemplateDeductionInfo &Info) {
593   DeductionFailureInfo Result;
594   Result.Result = static_cast<unsigned>(TDK);
595   Result.HasDiagnostic = false;
596   switch (TDK) {
597   case Sema::TDK_Invalid:
598   case Sema::TDK_InstantiationDepth:
599   case Sema::TDK_TooManyArguments:
600   case Sema::TDK_TooFewArguments:
601   case Sema::TDK_MiscellaneousDeductionFailure:
602   case Sema::TDK_CUDATargetMismatch:
603     Result.Data = nullptr;
604     break;
605
606   case Sema::TDK_Incomplete:
607   case Sema::TDK_InvalidExplicitArguments:
608     Result.Data = Info.Param.getOpaqueValue();
609     break;
610
611   case Sema::TDK_DeducedMismatch:
612   case Sema::TDK_DeducedMismatchNested: {
613     // FIXME: Should allocate from normal heap so that we can free this later.
614     auto *Saved = new (Context) DFIDeducedMismatchArgs;
615     Saved->FirstArg = Info.FirstArg;
616     Saved->SecondArg = Info.SecondArg;
617     Saved->TemplateArgs = Info.take();
618     Saved->CallArgIndex = Info.CallArgIndex;
619     Result.Data = Saved;
620     break;
621   }
622
623   case Sema::TDK_NonDeducedMismatch: {
624     // FIXME: Should allocate from normal heap so that we can free this later.
625     DFIArguments *Saved = new (Context) DFIArguments;
626     Saved->FirstArg = Info.FirstArg;
627     Saved->SecondArg = Info.SecondArg;
628     Result.Data = Saved;
629     break;
630   }
631
632   case Sema::TDK_IncompletePack:
633     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634   case Sema::TDK_Inconsistent:
635   case Sema::TDK_Underqualified: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
638     Saved->Param = Info.Param;
639     Saved->FirstArg = Info.FirstArg;
640     Saved->SecondArg = Info.SecondArg;
641     Result.Data = Saved;
642     break;
643   }
644
645   case Sema::TDK_SubstitutionFailure:
646     Result.Data = Info.take();
647     if (Info.hasSFINAEDiagnostic()) {
648       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649           SourceLocation(), PartialDiagnostic::NullDiagnostic());
650       Info.takeSFINAEDiagnostic(*Diag);
651       Result.HasDiagnostic = true;
652     }
653     break;
654
655   case Sema::TDK_Success:
656   case Sema::TDK_NonDependentConversionFailure:
657     llvm_unreachable("not a deduction failure");
658   }
659
660   return Result;
661 }
662
663 void DeductionFailureInfo::Destroy() {
664   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665   case Sema::TDK_Success:
666   case Sema::TDK_Invalid:
667   case Sema::TDK_InstantiationDepth:
668   case Sema::TDK_Incomplete:
669   case Sema::TDK_TooManyArguments:
670   case Sema::TDK_TooFewArguments:
671   case Sema::TDK_InvalidExplicitArguments:
672   case Sema::TDK_CUDATargetMismatch:
673   case Sema::TDK_NonDependentConversionFailure:
674     break;
675
676   case Sema::TDK_IncompletePack:
677   case Sema::TDK_Inconsistent:
678   case Sema::TDK_Underqualified:
679   case Sema::TDK_DeducedMismatch:
680   case Sema::TDK_DeducedMismatchNested:
681   case Sema::TDK_NonDeducedMismatch:
682     // FIXME: Destroy the data?
683     Data = nullptr;
684     break;
685
686   case Sema::TDK_SubstitutionFailure:
687     // FIXME: Destroy the template argument list?
688     Data = nullptr;
689     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690       Diag->~PartialDiagnosticAt();
691       HasDiagnostic = false;
692     }
693     break;
694
695   // Unhandled
696   case Sema::TDK_MiscellaneousDeductionFailure:
697     break;
698   }
699 }
700
701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702   if (HasDiagnostic)
703     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704   return nullptr;
705 }
706
707 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709   case Sema::TDK_Success:
710   case Sema::TDK_Invalid:
711   case Sema::TDK_InstantiationDepth:
712   case Sema::TDK_TooManyArguments:
713   case Sema::TDK_TooFewArguments:
714   case Sema::TDK_SubstitutionFailure:
715   case Sema::TDK_DeducedMismatch:
716   case Sema::TDK_DeducedMismatchNested:
717   case Sema::TDK_NonDeducedMismatch:
718   case Sema::TDK_CUDATargetMismatch:
719   case Sema::TDK_NonDependentConversionFailure:
720     return TemplateParameter();
721
722   case Sema::TDK_Incomplete:
723   case Sema::TDK_InvalidExplicitArguments:
724     return TemplateParameter::getFromOpaqueValue(Data);
725
726   case Sema::TDK_IncompletePack:
727   case Sema::TDK_Inconsistent:
728   case Sema::TDK_Underqualified:
729     return static_cast<DFIParamWithArguments*>(Data)->Param;
730
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735
736   return TemplateParameter();
737 }
738
739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
740   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741   case Sema::TDK_Success:
742   case Sema::TDK_Invalid:
743   case Sema::TDK_InstantiationDepth:
744   case Sema::TDK_TooManyArguments:
745   case Sema::TDK_TooFewArguments:
746   case Sema::TDK_Incomplete:
747   case Sema::TDK_IncompletePack:
748   case Sema::TDK_InvalidExplicitArguments:
749   case Sema::TDK_Inconsistent:
750   case Sema::TDK_Underqualified:
751   case Sema::TDK_NonDeducedMismatch:
752   case Sema::TDK_CUDATargetMismatch:
753   case Sema::TDK_NonDependentConversionFailure:
754     return nullptr;
755
756   case Sema::TDK_DeducedMismatch:
757   case Sema::TDK_DeducedMismatchNested:
758     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759
760   case Sema::TDK_SubstitutionFailure:
761     return static_cast<TemplateArgumentList*>(Data);
762
763   // Unhandled
764   case Sema::TDK_MiscellaneousDeductionFailure:
765     break;
766   }
767
768   return nullptr;
769 }
770
771 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773   case Sema::TDK_Success:
774   case Sema::TDK_Invalid:
775   case Sema::TDK_InstantiationDepth:
776   case Sema::TDK_Incomplete:
777   case Sema::TDK_TooManyArguments:
778   case Sema::TDK_TooFewArguments:
779   case Sema::TDK_InvalidExplicitArguments:
780   case Sema::TDK_SubstitutionFailure:
781   case Sema::TDK_CUDATargetMismatch:
782   case Sema::TDK_NonDependentConversionFailure:
783     return nullptr;
784
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_DeducedMismatch:
789   case Sema::TDK_DeducedMismatchNested:
790   case Sema::TDK_NonDeducedMismatch:
791     return &static_cast<DFIArguments*>(Data)->FirstArg;
792
793   // Unhandled
794   case Sema::TDK_MiscellaneousDeductionFailure:
795     break;
796   }
797
798   return nullptr;
799 }
800
801 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803   case Sema::TDK_Success:
804   case Sema::TDK_Invalid:
805   case Sema::TDK_InstantiationDepth:
806   case Sema::TDK_Incomplete:
807   case Sema::TDK_IncompletePack:
808   case Sema::TDK_TooManyArguments:
809   case Sema::TDK_TooFewArguments:
810   case Sema::TDK_InvalidExplicitArguments:
811   case Sema::TDK_SubstitutionFailure:
812   case Sema::TDK_CUDATargetMismatch:
813   case Sema::TDK_NonDependentConversionFailure:
814     return nullptr;
815
816   case Sema::TDK_Inconsistent:
817   case Sema::TDK_Underqualified:
818   case Sema::TDK_DeducedMismatch:
819   case Sema::TDK_DeducedMismatchNested:
820   case Sema::TDK_NonDeducedMismatch:
821     return &static_cast<DFIArguments*>(Data)->SecondArg;
822
823   // Unhandled
824   case Sema::TDK_MiscellaneousDeductionFailure:
825     break;
826   }
827
828   return nullptr;
829 }
830
831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836
837   default:
838     return llvm::None;
839   }
840 }
841
842 void OverloadCandidateSet::destroyCandidates() {
843   for (iterator i = begin(), e = end(); i != e; ++i) {
844     for (auto &C : i->Conversions)
845       C.~ImplicitConversionSequence();
846     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847       i->DeductionFailure.Destroy();
848   }
849 }
850
851 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852   destroyCandidates();
853   SlabAllocator.Reset();
854   NumInlineBytesUsed = 0;
855   Candidates.clear();
856   Functions.clear();
857   Kind = CSK;
858 }
859
860 namespace {
861   class UnbridgedCastsSet {
862     struct Entry {
863       Expr **Addr;
864       Expr *Saved;
865     };
866     SmallVector<Entry, 2> Entries;
867
868   public:
869     void save(Sema &S, Expr *&E) {
870       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871       Entry entry = { &E, E };
872       Entries.push_back(entry);
873       E = S.stripARCUnbridgedCast(E);
874     }
875
876     void restore() {
877       for (SmallVectorImpl<Entry>::iterator
878              i = Entries.begin(), e = Entries.end(); i != e; ++i)
879         *i->Addr = i->Saved;
880     }
881   };
882 }
883
884 /// checkPlaceholderForOverload - Do any interesting placeholder-like
885 /// preprocessing on the given expression.
886 ///
887 /// \param unbridgedCasts a collection to which to add unbridged casts;
888 ///   without this, they will be immediately diagnosed as errors
889 ///
890 /// Return true on unrecoverable error.
891 static bool
892 checkPlaceholderForOverload(Sema &S, Expr *&E,
893                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
894   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
895     // We can't handle overloaded expressions here because overload
896     // resolution might reasonably tweak them.
897     if (placeholder->getKind() == BuiltinType::Overload) return false;
898
899     // If the context potentially accepts unbridged ARC casts, strip
900     // the unbridged cast and add it to the collection for later restoration.
901     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902         unbridgedCasts) {
903       unbridgedCasts->save(S, E);
904       return false;
905     }
906
907     // Go ahead and check everything else.
908     ExprResult result = S.CheckPlaceholderExpr(E);
909     if (result.isInvalid())
910       return true;
911
912     E = result.get();
913     return false;
914   }
915
916   // Nothing to do.
917   return false;
918 }
919
920 /// checkArgPlaceholdersForOverload - Check a set of call operands for
921 /// placeholders.
922 static bool checkArgPlaceholdersForOverload(Sema &S,
923                                             MultiExprArg Args,
924                                             UnbridgedCastsSet &unbridged) {
925   for (unsigned i = 0, e = Args.size(); i != e; ++i)
926     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927       return true;
928
929   return false;
930 }
931
932 /// Determine whether the given New declaration is an overload of the
933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934 /// New and Old cannot be overloaded, e.g., if New has the same signature as
935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936 /// functions (or function templates) at all. When it does return Ovl_Match or
937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939 /// declaration.
940 ///
941 /// Example: Given the following input:
942 ///
943 ///   void f(int, float); // #1
944 ///   void f(int, int); // #2
945 ///   int f(int, int); // #3
946 ///
947 /// When we process #1, there is no previous declaration of "f", so IsOverload
948 /// will not be used.
949 ///
950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951 /// the parameter types, we see that #1 and #2 are overloaded (since they have
952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953 /// unchanged.
954 ///
955 /// When we process #3, Old is an overload set containing #1 and #2. We compare
956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958 /// functions are not part of the signature), IsOverload returns Ovl_Match and
959 /// MatchedDecl will be set to point to the FunctionDecl for #2.
960 ///
961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962 /// by a using declaration. The rules for whether to hide shadow declarations
963 /// ignore some properties which otherwise figure into a function template's
964 /// signature.
965 Sema::OverloadKind
966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967                     NamedDecl *&Match, bool NewIsUsingDecl) {
968   for (LookupResult::iterator I = Old.begin(), E = Old.end();
969          I != E; ++I) {
970     NamedDecl *OldD = *I;
971
972     bool OldIsUsingDecl = false;
973     if (isa<UsingShadowDecl>(OldD)) {
974       OldIsUsingDecl = true;
975
976       // We can always introduce two using declarations into the same
977       // context, even if they have identical signatures.
978       if (NewIsUsingDecl) continue;
979
980       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981     }
982
983     // A using-declaration does not conflict with another declaration
984     // if one of them is hidden.
985     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986       continue;
987
988     // If either declaration was introduced by a using declaration,
989     // we'll need to use slightly different rules for matching.
990     // Essentially, these rules are the normal rules, except that
991     // function templates hide function templates with different
992     // return types or template parameter lists.
993     bool UseMemberUsingDeclRules =
994       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995       !New->getFriendObjectKind();
996
997     if (FunctionDecl *OldF = OldD->getAsFunction()) {
998       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001           continue;
1002         }
1003
1004         if (!isa<FunctionTemplateDecl>(OldD) &&
1005             !shouldLinkPossiblyHiddenDecl(*I, New))
1006           continue;
1007
1008         Match = *I;
1009         return Ovl_Match;
1010       }
1011
1012       // Builtins that have custom typechecking or have a reference should
1013       // not be overloadable or redeclarable.
1014       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015         Match = *I;
1016         return Ovl_NonFunction;
1017       }
1018     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019       // We can overload with these, which can show up when doing
1020       // redeclaration checks for UsingDecls.
1021       assert(Old.getLookupKind() == LookupUsingDeclName);
1022     } else if (isa<TagDecl>(OldD)) {
1023       // We can always overload with tags by hiding them.
1024     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025       // Optimistically assume that an unresolved using decl will
1026       // overload; if it doesn't, we'll have to diagnose during
1027       // template instantiation.
1028       //
1029       // Exception: if the scope is dependent and this is not a class
1030       // member, the using declaration can only introduce an enumerator.
1031       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032         Match = *I;
1033         return Ovl_NonFunction;
1034       }
1035     } else {
1036       // (C++ 13p1):
1037       //   Only function declarations can be overloaded; object and type
1038       //   declarations cannot be overloaded.
1039       Match = *I;
1040       return Ovl_NonFunction;
1041     }
1042   }
1043
1044   return Ovl_Overload;
1045 }
1046
1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1048                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1049   // C++ [basic.start.main]p2: This function shall not be overloaded.
1050   if (New->isMain())
1051     return false;
1052
1053   // MSVCRT user defined entry points cannot be overloaded.
1054   if (New->isMSVCRTEntryPoint())
1055     return false;
1056
1057   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059
1060   // C++ [temp.fct]p2:
1061   //   A function template can be overloaded with other function templates
1062   //   and with normal (non-template) functions.
1063   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1064     return true;
1065
1066   // Is the function New an overload of the function Old?
1067   QualType OldQType = Context.getCanonicalType(Old->getType());
1068   QualType NewQType = Context.getCanonicalType(New->getType());
1069
1070   // Compare the signatures (C++ 1.3.10) of the two functions to
1071   // determine whether they are overloads. If we find any mismatch
1072   // in the signature, they are overloads.
1073
1074   // If either of these functions is a K&R-style function (no
1075   // prototype), then we consider them to have matching signatures.
1076   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078     return false;
1079
1080   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1082
1083   // The signature of a function includes the types of its
1084   // parameters (C++ 1.3.10), which includes the presence or absence
1085   // of the ellipsis; see C++ DR 357).
1086   if (OldQType != NewQType &&
1087       (OldType->getNumParams() != NewType->getNumParams() ||
1088        OldType->isVariadic() != NewType->isVariadic() ||
1089        !FunctionParamTypesAreEqual(OldType, NewType)))
1090     return true;
1091
1092   // C++ [temp.over.link]p4:
1093   //   The signature of a function template consists of its function
1094   //   signature, its return type and its template parameter list. The names
1095   //   of the template parameters are significant only for establishing the
1096   //   relationship between the template parameters and the rest of the
1097   //   signature.
1098   //
1099   // We check the return type and template parameter lists for function
1100   // templates first; the remaining checks follow.
1101   //
1102   // However, we don't consider either of these when deciding whether
1103   // a member introduced by a shadow declaration is hidden.
1104   if (!UseMemberUsingDeclRules && NewTemplate &&
1105       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106                                        OldTemplate->getTemplateParameters(),
1107                                        false, TPL_TemplateMatch) ||
1108        !Context.hasSameType(Old->getDeclaredReturnType(),
1109                             New->getDeclaredReturnType())))
1110     return true;
1111
1112   // If the function is a class member, its signature includes the
1113   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1114   //
1115   // As part of this, also check whether one of the member functions
1116   // is static, in which case they are not overloads (C++
1117   // 13.1p2). While not part of the definition of the signature,
1118   // this check is important to determine whether these functions
1119   // can be overloaded.
1120   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1121   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1122   if (OldMethod && NewMethod &&
1123       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1124     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1125       if (!UseMemberUsingDeclRules &&
1126           (OldMethod->getRefQualifier() == RQ_None ||
1127            NewMethod->getRefQualifier() == RQ_None)) {
1128         // C++0x [over.load]p2:
1129         //   - Member function declarations with the same name and the same
1130         //     parameter-type-list as well as member function template
1131         //     declarations with the same name, the same parameter-type-list, and
1132         //     the same template parameter lists cannot be overloaded if any of
1133         //     them, but not all, have a ref-qualifier (8.3.5).
1134         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1135           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1136         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1137       }
1138       return true;
1139     }
1140
1141     // We may not have applied the implicit const for a constexpr member
1142     // function yet (because we haven't yet resolved whether this is a static
1143     // or non-static member function). Add it now, on the assumption that this
1144     // is a redeclaration of OldMethod.
1145     unsigned OldQuals = OldMethod->getTypeQualifiers();
1146     unsigned NewQuals = NewMethod->getTypeQualifiers();
1147     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1148         !isa<CXXConstructorDecl>(NewMethod))
1149       NewQuals |= Qualifiers::Const;
1150
1151     // We do not allow overloading based off of '__restrict'.
1152     OldQuals &= ~Qualifiers::Restrict;
1153     NewQuals &= ~Qualifiers::Restrict;
1154     if (OldQuals != NewQuals)
1155       return true;
1156   }
1157
1158   // Though pass_object_size is placed on parameters and takes an argument, we
1159   // consider it to be a function-level modifier for the sake of function
1160   // identity. Either the function has one or more parameters with
1161   // pass_object_size or it doesn't.
1162   if (functionHasPassObjectSizeParams(New) !=
1163       functionHasPassObjectSizeParams(Old))
1164     return true;
1165
1166   // enable_if attributes are an order-sensitive part of the signature.
1167   for (specific_attr_iterator<EnableIfAttr>
1168          NewI = New->specific_attr_begin<EnableIfAttr>(),
1169          NewE = New->specific_attr_end<EnableIfAttr>(),
1170          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1171          OldE = Old->specific_attr_end<EnableIfAttr>();
1172        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1173     if (NewI == NewE || OldI == OldE)
1174       return true;
1175     llvm::FoldingSetNodeID NewID, OldID;
1176     NewI->getCond()->Profile(NewID, Context, true);
1177     OldI->getCond()->Profile(OldID, Context, true);
1178     if (NewID != OldID)
1179       return true;
1180   }
1181
1182   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1183     // Don't allow overloading of destructors.  (In theory we could, but it
1184     // would be a giant change to clang.)
1185     if (isa<CXXDestructorDecl>(New))
1186       return false;
1187
1188     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1189                        OldTarget = IdentifyCUDATarget(Old);
1190     if (NewTarget == CFT_InvalidTarget)
1191       return false;
1192
1193     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1194
1195     // Allow overloading of functions with same signature and different CUDA
1196     // target attributes.
1197     return NewTarget != OldTarget;
1198   }
1199
1200   // The signatures match; this is not an overload.
1201   return false;
1202 }
1203
1204 /// Checks availability of the function depending on the current
1205 /// function context. Inside an unavailable function, unavailability is ignored.
1206 ///
1207 /// \returns true if \arg FD is unavailable and current context is inside
1208 /// an available function, false otherwise.
1209 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1210   if (!FD->isUnavailable())
1211     return false;
1212
1213   // Walk up the context of the caller.
1214   Decl *C = cast<Decl>(CurContext);
1215   do {
1216     if (C->isUnavailable())
1217       return false;
1218   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1219   return true;
1220 }
1221
1222 /// Tries a user-defined conversion from From to ToType.
1223 ///
1224 /// Produces an implicit conversion sequence for when a standard conversion
1225 /// is not an option. See TryImplicitConversion for more information.
1226 static ImplicitConversionSequence
1227 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1228                          bool SuppressUserConversions,
1229                          bool AllowExplicit,
1230                          bool InOverloadResolution,
1231                          bool CStyle,
1232                          bool AllowObjCWritebackConversion,
1233                          bool AllowObjCConversionOnExplicit) {
1234   ImplicitConversionSequence ICS;
1235
1236   if (SuppressUserConversions) {
1237     // We're not in the case above, so there is no conversion that
1238     // we can perform.
1239     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1240     return ICS;
1241   }
1242
1243   // Attempt user-defined conversion.
1244   OverloadCandidateSet Conversions(From->getExprLoc(),
1245                                    OverloadCandidateSet::CSK_Normal);
1246   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1247                                   Conversions, AllowExplicit,
1248                                   AllowObjCConversionOnExplicit)) {
1249   case OR_Success:
1250   case OR_Deleted:
1251     ICS.setUserDefined();
1252     // C++ [over.ics.user]p4:
1253     //   A conversion of an expression of class type to the same class
1254     //   type is given Exact Match rank, and a conversion of an
1255     //   expression of class type to a base class of that type is
1256     //   given Conversion rank, in spite of the fact that a copy
1257     //   constructor (i.e., a user-defined conversion function) is
1258     //   called for those cases.
1259     if (CXXConstructorDecl *Constructor
1260           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1261       QualType FromCanon
1262         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1263       QualType ToCanon
1264         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1265       if (Constructor->isCopyConstructor() &&
1266           (FromCanon == ToCanon ||
1267            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1268         // Turn this into a "standard" conversion sequence, so that it
1269         // gets ranked with standard conversion sequences.
1270         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1271         ICS.setStandard();
1272         ICS.Standard.setAsIdentityConversion();
1273         ICS.Standard.setFromType(From->getType());
1274         ICS.Standard.setAllToTypes(ToType);
1275         ICS.Standard.CopyConstructor = Constructor;
1276         ICS.Standard.FoundCopyConstructor = Found;
1277         if (ToCanon != FromCanon)
1278           ICS.Standard.Second = ICK_Derived_To_Base;
1279       }
1280     }
1281     break;
1282
1283   case OR_Ambiguous:
1284     ICS.setAmbiguous();
1285     ICS.Ambiguous.setFromType(From->getType());
1286     ICS.Ambiguous.setToType(ToType);
1287     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1288          Cand != Conversions.end(); ++Cand)
1289       if (Cand->Viable)
1290         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1291     break;
1292
1293     // Fall through.
1294   case OR_No_Viable_Function:
1295     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1296     break;
1297   }
1298
1299   return ICS;
1300 }
1301
1302 /// TryImplicitConversion - Attempt to perform an implicit conversion
1303 /// from the given expression (Expr) to the given type (ToType). This
1304 /// function returns an implicit conversion sequence that can be used
1305 /// to perform the initialization. Given
1306 ///
1307 ///   void f(float f);
1308 ///   void g(int i) { f(i); }
1309 ///
1310 /// this routine would produce an implicit conversion sequence to
1311 /// describe the initialization of f from i, which will be a standard
1312 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1313 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1314 //
1315 /// Note that this routine only determines how the conversion can be
1316 /// performed; it does not actually perform the conversion. As such,
1317 /// it will not produce any diagnostics if no conversion is available,
1318 /// but will instead return an implicit conversion sequence of kind
1319 /// "BadConversion".
1320 ///
1321 /// If @p SuppressUserConversions, then user-defined conversions are
1322 /// not permitted.
1323 /// If @p AllowExplicit, then explicit user-defined conversions are
1324 /// permitted.
1325 ///
1326 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1327 /// writeback conversion, which allows __autoreleasing id* parameters to
1328 /// be initialized with __strong id* or __weak id* arguments.
1329 static ImplicitConversionSequence
1330 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1331                       bool SuppressUserConversions,
1332                       bool AllowExplicit,
1333                       bool InOverloadResolution,
1334                       bool CStyle,
1335                       bool AllowObjCWritebackConversion,
1336                       bool AllowObjCConversionOnExplicit) {
1337   ImplicitConversionSequence ICS;
1338   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1339                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1340     ICS.setStandard();
1341     return ICS;
1342   }
1343
1344   if (!S.getLangOpts().CPlusPlus) {
1345     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1346     return ICS;
1347   }
1348
1349   // C++ [over.ics.user]p4:
1350   //   A conversion of an expression of class type to the same class
1351   //   type is given Exact Match rank, and a conversion of an
1352   //   expression of class type to a base class of that type is
1353   //   given Conversion rank, in spite of the fact that a copy/move
1354   //   constructor (i.e., a user-defined conversion function) is
1355   //   called for those cases.
1356   QualType FromType = From->getType();
1357   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1358       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1359        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1360     ICS.setStandard();
1361     ICS.Standard.setAsIdentityConversion();
1362     ICS.Standard.setFromType(FromType);
1363     ICS.Standard.setAllToTypes(ToType);
1364
1365     // We don't actually check at this point whether there is a valid
1366     // copy/move constructor, since overloading just assumes that it
1367     // exists. When we actually perform initialization, we'll find the
1368     // appropriate constructor to copy the returned object, if needed.
1369     ICS.Standard.CopyConstructor = nullptr;
1370
1371     // Determine whether this is considered a derived-to-base conversion.
1372     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1373       ICS.Standard.Second = ICK_Derived_To_Base;
1374
1375     return ICS;
1376   }
1377
1378   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1379                                   AllowExplicit, InOverloadResolution, CStyle,
1380                                   AllowObjCWritebackConversion,
1381                                   AllowObjCConversionOnExplicit);
1382 }
1383
1384 ImplicitConversionSequence
1385 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1386                             bool SuppressUserConversions,
1387                             bool AllowExplicit,
1388                             bool InOverloadResolution,
1389                             bool CStyle,
1390                             bool AllowObjCWritebackConversion) {
1391   return ::TryImplicitConversion(*this, From, ToType,
1392                                  SuppressUserConversions, AllowExplicit,
1393                                  InOverloadResolution, CStyle,
1394                                  AllowObjCWritebackConversion,
1395                                  /*AllowObjCConversionOnExplicit=*/false);
1396 }
1397
1398 /// PerformImplicitConversion - Perform an implicit conversion of the
1399 /// expression From to the type ToType. Returns the
1400 /// converted expression. Flavor is the kind of conversion we're
1401 /// performing, used in the error message. If @p AllowExplicit,
1402 /// explicit user-defined conversions are permitted.
1403 ExprResult
1404 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1405                                 AssignmentAction Action, bool AllowExplicit) {
1406   ImplicitConversionSequence ICS;
1407   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1408 }
1409
1410 ExprResult
1411 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1412                                 AssignmentAction Action, bool AllowExplicit,
1413                                 ImplicitConversionSequence& ICS) {
1414   if (checkPlaceholderForOverload(*this, From))
1415     return ExprError();
1416
1417   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1418   bool AllowObjCWritebackConversion
1419     = getLangOpts().ObjCAutoRefCount &&
1420       (Action == AA_Passing || Action == AA_Sending);
1421   if (getLangOpts().ObjC1)
1422     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1423                                       ToType, From->getType(), From);
1424   ICS = ::TryImplicitConversion(*this, From, ToType,
1425                                 /*SuppressUserConversions=*/false,
1426                                 AllowExplicit,
1427                                 /*InOverloadResolution=*/false,
1428                                 /*CStyle=*/false,
1429                                 AllowObjCWritebackConversion,
1430                                 /*AllowObjCConversionOnExplicit=*/false);
1431   return PerformImplicitConversion(From, ToType, ICS, Action);
1432 }
1433
1434 /// Determine whether the conversion from FromType to ToType is a valid
1435 /// conversion that strips "noexcept" or "noreturn" off the nested function
1436 /// type.
1437 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1438                                 QualType &ResultTy) {
1439   if (Context.hasSameUnqualifiedType(FromType, ToType))
1440     return false;
1441
1442   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1443   //                    or F(t noexcept) -> F(t)
1444   // where F adds one of the following at most once:
1445   //   - a pointer
1446   //   - a member pointer
1447   //   - a block pointer
1448   // Changes here need matching changes in FindCompositePointerType.
1449   CanQualType CanTo = Context.getCanonicalType(ToType);
1450   CanQualType CanFrom = Context.getCanonicalType(FromType);
1451   Type::TypeClass TyClass = CanTo->getTypeClass();
1452   if (TyClass != CanFrom->getTypeClass()) return false;
1453   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1454     if (TyClass == Type::Pointer) {
1455       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1456       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1457     } else if (TyClass == Type::BlockPointer) {
1458       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1459       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1460     } else if (TyClass == Type::MemberPointer) {
1461       auto ToMPT = CanTo.getAs<MemberPointerType>();
1462       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1463       // A function pointer conversion cannot change the class of the function.
1464       if (ToMPT->getClass() != FromMPT->getClass())
1465         return false;
1466       CanTo = ToMPT->getPointeeType();
1467       CanFrom = FromMPT->getPointeeType();
1468     } else {
1469       return false;
1470     }
1471
1472     TyClass = CanTo->getTypeClass();
1473     if (TyClass != CanFrom->getTypeClass()) return false;
1474     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1475       return false;
1476   }
1477
1478   const auto *FromFn = cast<FunctionType>(CanFrom);
1479   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1480
1481   const auto *ToFn = cast<FunctionType>(CanTo);
1482   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1483
1484   bool Changed = false;
1485
1486   // Drop 'noreturn' if not present in target type.
1487   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1488     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1489     Changed = true;
1490   }
1491
1492   // Drop 'noexcept' if not present in target type.
1493   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1494     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1495     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1496       FromFn = cast<FunctionType>(
1497           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1498                                                    EST_None)
1499                  .getTypePtr());
1500       Changed = true;
1501     }
1502
1503     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1504     // only if the ExtParameterInfo lists of the two function prototypes can be
1505     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1506     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1507     bool CanUseToFPT, CanUseFromFPT;
1508     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1509                                       CanUseFromFPT, NewParamInfos) &&
1510         CanUseToFPT && !CanUseFromFPT) {
1511       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1512       ExtInfo.ExtParameterInfos =
1513           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1514       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1515                                             FromFPT->getParamTypes(), ExtInfo);
1516       FromFn = QT->getAs<FunctionType>();
1517       Changed = true;
1518     }
1519   }
1520
1521   if (!Changed)
1522     return false;
1523
1524   assert(QualType(FromFn, 0).isCanonical());
1525   if (QualType(FromFn, 0) != CanTo) return false;
1526
1527   ResultTy = ToType;
1528   return true;
1529 }
1530
1531 /// Determine whether the conversion from FromType to ToType is a valid
1532 /// vector conversion.
1533 ///
1534 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1535 /// conversion.
1536 static bool IsVectorConversion(Sema &S, QualType FromType,
1537                                QualType ToType, ImplicitConversionKind &ICK) {
1538   // We need at least one of these types to be a vector type to have a vector
1539   // conversion.
1540   if (!ToType->isVectorType() && !FromType->isVectorType())
1541     return false;
1542
1543   // Identical types require no conversions.
1544   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1545     return false;
1546
1547   // There are no conversions between extended vector types, only identity.
1548   if (ToType->isExtVectorType()) {
1549     // There are no conversions between extended vector types other than the
1550     // identity conversion.
1551     if (FromType->isExtVectorType())
1552       return false;
1553
1554     // Vector splat from any arithmetic type to a vector.
1555     if (FromType->isArithmeticType()) {
1556       ICK = ICK_Vector_Splat;
1557       return true;
1558     }
1559   }
1560
1561   // We can perform the conversion between vector types in the following cases:
1562   // 1)vector types are equivalent AltiVec and GCC vector types
1563   // 2)lax vector conversions are permitted and the vector types are of the
1564   //   same size
1565   if (ToType->isVectorType() && FromType->isVectorType()) {
1566     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1567         S.isLaxVectorConversion(FromType, ToType)) {
1568       ICK = ICK_Vector_Conversion;
1569       return true;
1570     }
1571   }
1572
1573   return false;
1574 }
1575
1576 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1577                                 bool InOverloadResolution,
1578                                 StandardConversionSequence &SCS,
1579                                 bool CStyle);
1580
1581 /// IsStandardConversion - Determines whether there is a standard
1582 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1583 /// expression From to the type ToType. Standard conversion sequences
1584 /// only consider non-class types; for conversions that involve class
1585 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1586 /// contain the standard conversion sequence required to perform this
1587 /// conversion and this routine will return true. Otherwise, this
1588 /// routine will return false and the value of SCS is unspecified.
1589 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1590                                  bool InOverloadResolution,
1591                                  StandardConversionSequence &SCS,
1592                                  bool CStyle,
1593                                  bool AllowObjCWritebackConversion) {
1594   QualType FromType = From->getType();
1595
1596   // Standard conversions (C++ [conv])
1597   SCS.setAsIdentityConversion();
1598   SCS.IncompatibleObjC = false;
1599   SCS.setFromType(FromType);
1600   SCS.CopyConstructor = nullptr;
1601
1602   // There are no standard conversions for class types in C++, so
1603   // abort early. When overloading in C, however, we do permit them.
1604   if (S.getLangOpts().CPlusPlus &&
1605       (FromType->isRecordType() || ToType->isRecordType()))
1606     return false;
1607
1608   // The first conversion can be an lvalue-to-rvalue conversion,
1609   // array-to-pointer conversion, or function-to-pointer conversion
1610   // (C++ 4p1).
1611
1612   if (FromType == S.Context.OverloadTy) {
1613     DeclAccessPair AccessPair;
1614     if (FunctionDecl *Fn
1615           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1616                                                  AccessPair)) {
1617       // We were able to resolve the address of the overloaded function,
1618       // so we can convert to the type of that function.
1619       FromType = Fn->getType();
1620       SCS.setFromType(FromType);
1621
1622       // we can sometimes resolve &foo<int> regardless of ToType, so check
1623       // if the type matches (identity) or we are converting to bool
1624       if (!S.Context.hasSameUnqualifiedType(
1625                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1626         QualType resultTy;
1627         // if the function type matches except for [[noreturn]], it's ok
1628         if (!S.IsFunctionConversion(FromType,
1629               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1630           // otherwise, only a boolean conversion is standard
1631           if (!ToType->isBooleanType())
1632             return false;
1633       }
1634
1635       // Check if the "from" expression is taking the address of an overloaded
1636       // function and recompute the FromType accordingly. Take advantage of the
1637       // fact that non-static member functions *must* have such an address-of
1638       // expression.
1639       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1640       if (Method && !Method->isStatic()) {
1641         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1642                "Non-unary operator on non-static member address");
1643         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1644                == UO_AddrOf &&
1645                "Non-address-of operator on non-static member address");
1646         const Type *ClassType
1647           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1648         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1649       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1650         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1651                UO_AddrOf &&
1652                "Non-address-of operator for overloaded function expression");
1653         FromType = S.Context.getPointerType(FromType);
1654       }
1655
1656       // Check that we've computed the proper type after overload resolution.
1657       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1658       // be calling it from within an NDEBUG block.
1659       assert(S.Context.hasSameType(
1660         FromType,
1661         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1662     } else {
1663       return false;
1664     }
1665   }
1666   // Lvalue-to-rvalue conversion (C++11 4.1):
1667   //   A glvalue (3.10) of a non-function, non-array type T can
1668   //   be converted to a prvalue.
1669   bool argIsLValue = From->isGLValue();
1670   if (argIsLValue &&
1671       !FromType->isFunctionType() && !FromType->isArrayType() &&
1672       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1673     SCS.First = ICK_Lvalue_To_Rvalue;
1674
1675     // C11 6.3.2.1p2:
1676     //   ... if the lvalue has atomic type, the value has the non-atomic version
1677     //   of the type of the lvalue ...
1678     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1679       FromType = Atomic->getValueType();
1680
1681     // If T is a non-class type, the type of the rvalue is the
1682     // cv-unqualified version of T. Otherwise, the type of the rvalue
1683     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1684     // just strip the qualifiers because they don't matter.
1685     FromType = FromType.getUnqualifiedType();
1686   } else if (FromType->isArrayType()) {
1687     // Array-to-pointer conversion (C++ 4.2)
1688     SCS.First = ICK_Array_To_Pointer;
1689
1690     // An lvalue or rvalue of type "array of N T" or "array of unknown
1691     // bound of T" can be converted to an rvalue of type "pointer to
1692     // T" (C++ 4.2p1).
1693     FromType = S.Context.getArrayDecayedType(FromType);
1694
1695     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1696       // This conversion is deprecated in C++03 (D.4)
1697       SCS.DeprecatedStringLiteralToCharPtr = true;
1698
1699       // For the purpose of ranking in overload resolution
1700       // (13.3.3.1.1), this conversion is considered an
1701       // array-to-pointer conversion followed by a qualification
1702       // conversion (4.4). (C++ 4.2p2)
1703       SCS.Second = ICK_Identity;
1704       SCS.Third = ICK_Qualification;
1705       SCS.QualificationIncludesObjCLifetime = false;
1706       SCS.setAllToTypes(FromType);
1707       return true;
1708     }
1709   } else if (FromType->isFunctionType() && argIsLValue) {
1710     // Function-to-pointer conversion (C++ 4.3).
1711     SCS.First = ICK_Function_To_Pointer;
1712
1713     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1714       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1715         if (!S.checkAddressOfFunctionIsAvailable(FD))
1716           return false;
1717
1718     // An lvalue of function type T can be converted to an rvalue of
1719     // type "pointer to T." The result is a pointer to the
1720     // function. (C++ 4.3p1).
1721     FromType = S.Context.getPointerType(FromType);
1722   } else {
1723     // We don't require any conversions for the first step.
1724     SCS.First = ICK_Identity;
1725   }
1726   SCS.setToType(0, FromType);
1727
1728   // The second conversion can be an integral promotion, floating
1729   // point promotion, integral conversion, floating point conversion,
1730   // floating-integral conversion, pointer conversion,
1731   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1732   // For overloading in C, this can also be a "compatible-type"
1733   // conversion.
1734   bool IncompatibleObjC = false;
1735   ImplicitConversionKind SecondICK = ICK_Identity;
1736   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1737     // The unqualified versions of the types are the same: there's no
1738     // conversion to do.
1739     SCS.Second = ICK_Identity;
1740   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1741     // Integral promotion (C++ 4.5).
1742     SCS.Second = ICK_Integral_Promotion;
1743     FromType = ToType.getUnqualifiedType();
1744   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1745     // Floating point promotion (C++ 4.6).
1746     SCS.Second = ICK_Floating_Promotion;
1747     FromType = ToType.getUnqualifiedType();
1748   } else if (S.IsComplexPromotion(FromType, ToType)) {
1749     // Complex promotion (Clang extension)
1750     SCS.Second = ICK_Complex_Promotion;
1751     FromType = ToType.getUnqualifiedType();
1752   } else if (ToType->isBooleanType() &&
1753              (FromType->isArithmeticType() ||
1754               FromType->isAnyPointerType() ||
1755               FromType->isBlockPointerType() ||
1756               FromType->isMemberPointerType() ||
1757               FromType->isNullPtrType())) {
1758     // Boolean conversions (C++ 4.12).
1759     SCS.Second = ICK_Boolean_Conversion;
1760     FromType = S.Context.BoolTy;
1761   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1762              ToType->isIntegralType(S.Context)) {
1763     // Integral conversions (C++ 4.7).
1764     SCS.Second = ICK_Integral_Conversion;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1767     // Complex conversions (C99 6.3.1.6)
1768     SCS.Second = ICK_Complex_Conversion;
1769     FromType = ToType.getUnqualifiedType();
1770   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1771              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1772     // Complex-real conversions (C99 6.3.1.7)
1773     SCS.Second = ICK_Complex_Real;
1774     FromType = ToType.getUnqualifiedType();
1775   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1776     // FIXME: disable conversions between long double and __float128 if
1777     // their representation is different until there is back end support
1778     // We of course allow this conversion if long double is really double.
1779     if (&S.Context.getFloatTypeSemantics(FromType) !=
1780         &S.Context.getFloatTypeSemantics(ToType)) {
1781       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1782                                     ToType == S.Context.LongDoubleTy) ||
1783                                    (FromType == S.Context.LongDoubleTy &&
1784                                     ToType == S.Context.Float128Ty));
1785       if (Float128AndLongDouble &&
1786           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1787            &llvm::APFloat::PPCDoubleDouble()))
1788         return false;
1789     }
1790     // Floating point conversions (C++ 4.8).
1791     SCS.Second = ICK_Floating_Conversion;
1792     FromType = ToType.getUnqualifiedType();
1793   } else if ((FromType->isRealFloatingType() &&
1794               ToType->isIntegralType(S.Context)) ||
1795              (FromType->isIntegralOrUnscopedEnumerationType() &&
1796               ToType->isRealFloatingType())) {
1797     // Floating-integral conversions (C++ 4.9).
1798     SCS.Second = ICK_Floating_Integral;
1799     FromType = ToType.getUnqualifiedType();
1800   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1801     SCS.Second = ICK_Block_Pointer_Conversion;
1802   } else if (AllowObjCWritebackConversion &&
1803              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1804     SCS.Second = ICK_Writeback_Conversion;
1805   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1806                                    FromType, IncompatibleObjC)) {
1807     // Pointer conversions (C++ 4.10).
1808     SCS.Second = ICK_Pointer_Conversion;
1809     SCS.IncompatibleObjC = IncompatibleObjC;
1810     FromType = FromType.getUnqualifiedType();
1811   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1812                                          InOverloadResolution, FromType)) {
1813     // Pointer to member conversions (4.11).
1814     SCS.Second = ICK_Pointer_Member;
1815   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1816     SCS.Second = SecondICK;
1817     FromType = ToType.getUnqualifiedType();
1818   } else if (!S.getLangOpts().CPlusPlus &&
1819              S.Context.typesAreCompatible(ToType, FromType)) {
1820     // Compatible conversions (Clang extension for C function overloading)
1821     SCS.Second = ICK_Compatible_Conversion;
1822     FromType = ToType.getUnqualifiedType();
1823   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1824                                              InOverloadResolution,
1825                                              SCS, CStyle)) {
1826     SCS.Second = ICK_TransparentUnionConversion;
1827     FromType = ToType;
1828   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1829                                  CStyle)) {
1830     // tryAtomicConversion has updated the standard conversion sequence
1831     // appropriately.
1832     return true;
1833   } else if (ToType->isEventT() &&
1834              From->isIntegerConstantExpr(S.getASTContext()) &&
1835              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1836     SCS.Second = ICK_Zero_Event_Conversion;
1837     FromType = ToType;
1838   } else if (ToType->isQueueT() &&
1839              From->isIntegerConstantExpr(S.getASTContext()) &&
1840              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1841     SCS.Second = ICK_Zero_Queue_Conversion;
1842     FromType = ToType;
1843   } else {
1844     // No second conversion required.
1845     SCS.Second = ICK_Identity;
1846   }
1847   SCS.setToType(1, FromType);
1848
1849   // The third conversion can be a function pointer conversion or a
1850   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1851   bool ObjCLifetimeConversion;
1852   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1853     // Function pointer conversions (removing 'noexcept') including removal of
1854     // 'noreturn' (Clang extension).
1855     SCS.Third = ICK_Function_Conversion;
1856   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1857                                          ObjCLifetimeConversion)) {
1858     SCS.Third = ICK_Qualification;
1859     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1860     FromType = ToType;
1861   } else {
1862     // No conversion required
1863     SCS.Third = ICK_Identity;
1864   }
1865
1866   // C++ [over.best.ics]p6:
1867   //   [...] Any difference in top-level cv-qualification is
1868   //   subsumed by the initialization itself and does not constitute
1869   //   a conversion. [...]
1870   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1871   QualType CanonTo = S.Context.getCanonicalType(ToType);
1872   if (CanonFrom.getLocalUnqualifiedType()
1873                                      == CanonTo.getLocalUnqualifiedType() &&
1874       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1875     FromType = ToType;
1876     CanonFrom = CanonTo;
1877   }
1878
1879   SCS.setToType(2, FromType);
1880
1881   if (CanonFrom == CanonTo)
1882     return true;
1883
1884   // If we have not converted the argument type to the parameter type,
1885   // this is a bad conversion sequence, unless we're resolving an overload in C.
1886   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1887     return false;
1888
1889   ExprResult ER = ExprResult{From};
1890   Sema::AssignConvertType Conv =
1891       S.CheckSingleAssignmentConstraints(ToType, ER,
1892                                          /*Diagnose=*/false,
1893                                          /*DiagnoseCFAudited=*/false,
1894                                          /*ConvertRHS=*/false);
1895   ImplicitConversionKind SecondConv;
1896   switch (Conv) {
1897   case Sema::Compatible:
1898     SecondConv = ICK_C_Only_Conversion;
1899     break;
1900   // For our purposes, discarding qualifiers is just as bad as using an
1901   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1902   // qualifiers, as well.
1903   case Sema::CompatiblePointerDiscardsQualifiers:
1904   case Sema::IncompatiblePointer:
1905   case Sema::IncompatiblePointerSign:
1906     SecondConv = ICK_Incompatible_Pointer_Conversion;
1907     break;
1908   default:
1909     return false;
1910   }
1911
1912   // First can only be an lvalue conversion, so we pretend that this was the
1913   // second conversion. First should already be valid from earlier in the
1914   // function.
1915   SCS.Second = SecondConv;
1916   SCS.setToType(1, ToType);
1917
1918   // Third is Identity, because Second should rank us worse than any other
1919   // conversion. This could also be ICK_Qualification, but it's simpler to just
1920   // lump everything in with the second conversion, and we don't gain anything
1921   // from making this ICK_Qualification.
1922   SCS.Third = ICK_Identity;
1923   SCS.setToType(2, ToType);
1924   return true;
1925 }
1926
1927 static bool
1928 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1929                                      QualType &ToType,
1930                                      bool InOverloadResolution,
1931                                      StandardConversionSequence &SCS,
1932                                      bool CStyle) {
1933
1934   const RecordType *UT = ToType->getAsUnionType();
1935   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1936     return false;
1937   // The field to initialize within the transparent union.
1938   RecordDecl *UD = UT->getDecl();
1939   // It's compatible if the expression matches any of the fields.
1940   for (const auto *it : UD->fields()) {
1941     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1942                              CStyle, /*ObjCWritebackConversion=*/false)) {
1943       ToType = it->getType();
1944       return true;
1945     }
1946   }
1947   return false;
1948 }
1949
1950 /// IsIntegralPromotion - Determines whether the conversion from the
1951 /// expression From (whose potentially-adjusted type is FromType) to
1952 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1953 /// sets PromotedType to the promoted type.
1954 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1955   const BuiltinType *To = ToType->getAs<BuiltinType>();
1956   // All integers are built-in.
1957   if (!To) {
1958     return false;
1959   }
1960
1961   // An rvalue of type char, signed char, unsigned char, short int, or
1962   // unsigned short int can be converted to an rvalue of type int if
1963   // int can represent all the values of the source type; otherwise,
1964   // the source rvalue can be converted to an rvalue of type unsigned
1965   // int (C++ 4.5p1).
1966   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1967       !FromType->isEnumeralType()) {
1968     if (// We can promote any signed, promotable integer type to an int
1969         (FromType->isSignedIntegerType() ||
1970          // We can promote any unsigned integer type whose size is
1971          // less than int to an int.
1972          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1973       return To->getKind() == BuiltinType::Int;
1974     }
1975
1976     return To->getKind() == BuiltinType::UInt;
1977   }
1978
1979   // C++11 [conv.prom]p3:
1980   //   A prvalue of an unscoped enumeration type whose underlying type is not
1981   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1982   //   following types that can represent all the values of the enumeration
1983   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1984   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1985   //   long long int. If none of the types in that list can represent all the
1986   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1987   //   type can be converted to an rvalue a prvalue of the extended integer type
1988   //   with lowest integer conversion rank (4.13) greater than the rank of long
1989   //   long in which all the values of the enumeration can be represented. If
1990   //   there are two such extended types, the signed one is chosen.
1991   // C++11 [conv.prom]p4:
1992   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1993   //   can be converted to a prvalue of its underlying type. Moreover, if
1994   //   integral promotion can be applied to its underlying type, a prvalue of an
1995   //   unscoped enumeration type whose underlying type is fixed can also be
1996   //   converted to a prvalue of the promoted underlying type.
1997   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1998     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1999     // provided for a scoped enumeration.
2000     if (FromEnumType->getDecl()->isScoped())
2001       return false;
2002
2003     // We can perform an integral promotion to the underlying type of the enum,
2004     // even if that's not the promoted type. Note that the check for promoting
2005     // the underlying type is based on the type alone, and does not consider
2006     // the bitfield-ness of the actual source expression.
2007     if (FromEnumType->getDecl()->isFixed()) {
2008       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2009       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2010              IsIntegralPromotion(nullptr, Underlying, ToType);
2011     }
2012
2013     // We have already pre-calculated the promotion type, so this is trivial.
2014     if (ToType->isIntegerType() &&
2015         isCompleteType(From->getLocStart(), FromType))
2016       return Context.hasSameUnqualifiedType(
2017           ToType, FromEnumType->getDecl()->getPromotionType());
2018
2019     // C++ [conv.prom]p5:
2020     //   If the bit-field has an enumerated type, it is treated as any other
2021     //   value of that type for promotion purposes.
2022     //
2023     // ... so do not fall through into the bit-field checks below in C++.
2024     if (getLangOpts().CPlusPlus)
2025       return false;
2026   }
2027
2028   // C++0x [conv.prom]p2:
2029   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2030   //   to an rvalue a prvalue of the first of the following types that can
2031   //   represent all the values of its underlying type: int, unsigned int,
2032   //   long int, unsigned long int, long long int, or unsigned long long int.
2033   //   If none of the types in that list can represent all the values of its
2034   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2035   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2036   //   type.
2037   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2038       ToType->isIntegerType()) {
2039     // Determine whether the type we're converting from is signed or
2040     // unsigned.
2041     bool FromIsSigned = FromType->isSignedIntegerType();
2042     uint64_t FromSize = Context.getTypeSize(FromType);
2043
2044     // The types we'll try to promote to, in the appropriate
2045     // order. Try each of these types.
2046     QualType PromoteTypes[6] = {
2047       Context.IntTy, Context.UnsignedIntTy,
2048       Context.LongTy, Context.UnsignedLongTy ,
2049       Context.LongLongTy, Context.UnsignedLongLongTy
2050     };
2051     for (int Idx = 0; Idx < 6; ++Idx) {
2052       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2053       if (FromSize < ToSize ||
2054           (FromSize == ToSize &&
2055            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2056         // We found the type that we can promote to. If this is the
2057         // type we wanted, we have a promotion. Otherwise, no
2058         // promotion.
2059         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2060       }
2061     }
2062   }
2063
2064   // An rvalue for an integral bit-field (9.6) can be converted to an
2065   // rvalue of type int if int can represent all the values of the
2066   // bit-field; otherwise, it can be converted to unsigned int if
2067   // unsigned int can represent all the values of the bit-field. If
2068   // the bit-field is larger yet, no integral promotion applies to
2069   // it. If the bit-field has an enumerated type, it is treated as any
2070   // other value of that type for promotion purposes (C++ 4.5p3).
2071   // FIXME: We should delay checking of bit-fields until we actually perform the
2072   // conversion.
2073   //
2074   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2075   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2076   // bit-fields and those whose underlying type is larger than int) for GCC
2077   // compatibility.
2078   if (From) {
2079     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2080       llvm::APSInt BitWidth;
2081       if (FromType->isIntegralType(Context) &&
2082           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2083         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2084         ToSize = Context.getTypeSize(ToType);
2085
2086         // Are we promoting to an int from a bitfield that fits in an int?
2087         if (BitWidth < ToSize ||
2088             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2089           return To->getKind() == BuiltinType::Int;
2090         }
2091
2092         // Are we promoting to an unsigned int from an unsigned bitfield
2093         // that fits into an unsigned int?
2094         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2095           return To->getKind() == BuiltinType::UInt;
2096         }
2097
2098         return false;
2099       }
2100     }
2101   }
2102
2103   // An rvalue of type bool can be converted to an rvalue of type int,
2104   // with false becoming zero and true becoming one (C++ 4.5p4).
2105   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2106     return true;
2107   }
2108
2109   return false;
2110 }
2111
2112 /// IsFloatingPointPromotion - Determines whether the conversion from
2113 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2114 /// returns true and sets PromotedType to the promoted type.
2115 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2116   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2117     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2118       /// An rvalue of type float can be converted to an rvalue of type
2119       /// double. (C++ 4.6p1).
2120       if (FromBuiltin->getKind() == BuiltinType::Float &&
2121           ToBuiltin->getKind() == BuiltinType::Double)
2122         return true;
2123
2124       // C99 6.3.1.5p1:
2125       //   When a float is promoted to double or long double, or a
2126       //   double is promoted to long double [...].
2127       if (!getLangOpts().CPlusPlus &&
2128           (FromBuiltin->getKind() == BuiltinType::Float ||
2129            FromBuiltin->getKind() == BuiltinType::Double) &&
2130           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2131            ToBuiltin->getKind() == BuiltinType::Float128))
2132         return true;
2133
2134       // Half can be promoted to float.
2135       if (!getLangOpts().NativeHalfType &&
2136            FromBuiltin->getKind() == BuiltinType::Half &&
2137           ToBuiltin->getKind() == BuiltinType::Float)
2138         return true;
2139     }
2140
2141   return false;
2142 }
2143
2144 /// Determine if a conversion is a complex promotion.
2145 ///
2146 /// A complex promotion is defined as a complex -> complex conversion
2147 /// where the conversion between the underlying real types is a
2148 /// floating-point or integral promotion.
2149 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2150   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2151   if (!FromComplex)
2152     return false;
2153
2154   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2155   if (!ToComplex)
2156     return false;
2157
2158   return IsFloatingPointPromotion(FromComplex->getElementType(),
2159                                   ToComplex->getElementType()) ||
2160     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2161                         ToComplex->getElementType());
2162 }
2163
2164 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2165 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2166 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2167 /// if non-empty, will be a pointer to ToType that may or may not have
2168 /// the right set of qualifiers on its pointee.
2169 ///
2170 static QualType
2171 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2172                                    QualType ToPointee, QualType ToType,
2173                                    ASTContext &Context,
2174                                    bool StripObjCLifetime = false) {
2175   assert((FromPtr->getTypeClass() == Type::Pointer ||
2176           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2177          "Invalid similarly-qualified pointer type");
2178
2179   /// Conversions to 'id' subsume cv-qualifier conversions.
2180   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2181     return ToType.getUnqualifiedType();
2182
2183   QualType CanonFromPointee
2184     = Context.getCanonicalType(FromPtr->getPointeeType());
2185   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2186   Qualifiers Quals = CanonFromPointee.getQualifiers();
2187
2188   if (StripObjCLifetime)
2189     Quals.removeObjCLifetime();
2190
2191   // Exact qualifier match -> return the pointer type we're converting to.
2192   if (CanonToPointee.getLocalQualifiers() == Quals) {
2193     // ToType is exactly what we need. Return it.
2194     if (!ToType.isNull())
2195       return ToType.getUnqualifiedType();
2196
2197     // Build a pointer to ToPointee. It has the right qualifiers
2198     // already.
2199     if (isa<ObjCObjectPointerType>(ToType))
2200       return Context.getObjCObjectPointerType(ToPointee);
2201     return Context.getPointerType(ToPointee);
2202   }
2203
2204   // Just build a canonical type that has the right qualifiers.
2205   QualType QualifiedCanonToPointee
2206     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2207
2208   if (isa<ObjCObjectPointerType>(ToType))
2209     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2210   return Context.getPointerType(QualifiedCanonToPointee);
2211 }
2212
2213 static bool isNullPointerConstantForConversion(Expr *Expr,
2214                                                bool InOverloadResolution,
2215                                                ASTContext &Context) {
2216   // Handle value-dependent integral null pointer constants correctly.
2217   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2218   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2219       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2220     return !InOverloadResolution;
2221
2222   return Expr->isNullPointerConstant(Context,
2223                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2224                                         : Expr::NPC_ValueDependentIsNull);
2225 }
2226
2227 /// IsPointerConversion - Determines whether the conversion of the
2228 /// expression From, which has the (possibly adjusted) type FromType,
2229 /// can be converted to the type ToType via a pointer conversion (C++
2230 /// 4.10). If so, returns true and places the converted type (that
2231 /// might differ from ToType in its cv-qualifiers at some level) into
2232 /// ConvertedType.
2233 ///
2234 /// This routine also supports conversions to and from block pointers
2235 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2236 /// pointers to interfaces. FIXME: Once we've determined the
2237 /// appropriate overloading rules for Objective-C, we may want to
2238 /// split the Objective-C checks into a different routine; however,
2239 /// GCC seems to consider all of these conversions to be pointer
2240 /// conversions, so for now they live here. IncompatibleObjC will be
2241 /// set if the conversion is an allowed Objective-C conversion that
2242 /// should result in a warning.
2243 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2244                                bool InOverloadResolution,
2245                                QualType& ConvertedType,
2246                                bool &IncompatibleObjC) {
2247   IncompatibleObjC = false;
2248   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2249                               IncompatibleObjC))
2250     return true;
2251
2252   // Conversion from a null pointer constant to any Objective-C pointer type.
2253   if (ToType->isObjCObjectPointerType() &&
2254       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2255     ConvertedType = ToType;
2256     return true;
2257   }
2258
2259   // Blocks: Block pointers can be converted to void*.
2260   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2261       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2262     ConvertedType = ToType;
2263     return true;
2264   }
2265   // Blocks: A null pointer constant can be converted to a block
2266   // pointer type.
2267   if (ToType->isBlockPointerType() &&
2268       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2269     ConvertedType = ToType;
2270     return true;
2271   }
2272
2273   // If the left-hand-side is nullptr_t, the right side can be a null
2274   // pointer constant.
2275   if (ToType->isNullPtrType() &&
2276       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2277     ConvertedType = ToType;
2278     return true;
2279   }
2280
2281   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2282   if (!ToTypePtr)
2283     return false;
2284
2285   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2286   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2287     ConvertedType = ToType;
2288     return true;
2289   }
2290
2291   // Beyond this point, both types need to be pointers
2292   // , including objective-c pointers.
2293   QualType ToPointeeType = ToTypePtr->getPointeeType();
2294   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2295       !getLangOpts().ObjCAutoRefCount) {
2296     ConvertedType = BuildSimilarlyQualifiedPointerType(
2297                                       FromType->getAs<ObjCObjectPointerType>(),
2298                                                        ToPointeeType,
2299                                                        ToType, Context);
2300     return true;
2301   }
2302   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2303   if (!FromTypePtr)
2304     return false;
2305
2306   QualType FromPointeeType = FromTypePtr->getPointeeType();
2307
2308   // If the unqualified pointee types are the same, this can't be a
2309   // pointer conversion, so don't do all of the work below.
2310   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2311     return false;
2312
2313   // An rvalue of type "pointer to cv T," where T is an object type,
2314   // can be converted to an rvalue of type "pointer to cv void" (C++
2315   // 4.10p2).
2316   if (FromPointeeType->isIncompleteOrObjectType() &&
2317       ToPointeeType->isVoidType()) {
2318     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2319                                                        ToPointeeType,
2320                                                        ToType, Context,
2321                                                    /*StripObjCLifetime=*/true);
2322     return true;
2323   }
2324
2325   // MSVC allows implicit function to void* type conversion.
2326   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2327       ToPointeeType->isVoidType()) {
2328     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2329                                                        ToPointeeType,
2330                                                        ToType, Context);
2331     return true;
2332   }
2333
2334   // When we're overloading in C, we allow a special kind of pointer
2335   // conversion for compatible-but-not-identical pointee types.
2336   if (!getLangOpts().CPlusPlus &&
2337       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2338     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                        ToPointeeType,
2340                                                        ToType, Context);
2341     return true;
2342   }
2343
2344   // C++ [conv.ptr]p3:
2345   //
2346   //   An rvalue of type "pointer to cv D," where D is a class type,
2347   //   can be converted to an rvalue of type "pointer to cv B," where
2348   //   B is a base class (clause 10) of D. If B is an inaccessible
2349   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2350   //   necessitates this conversion is ill-formed. The result of the
2351   //   conversion is a pointer to the base class sub-object of the
2352   //   derived class object. The null pointer value is converted to
2353   //   the null pointer value of the destination type.
2354   //
2355   // Note that we do not check for ambiguity or inaccessibility
2356   // here. That is handled by CheckPointerConversion.
2357   if (getLangOpts().CPlusPlus &&
2358       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2359       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2360       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2361     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2362                                                        ToPointeeType,
2363                                                        ToType, Context);
2364     return true;
2365   }
2366
2367   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2368       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2369     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2370                                                        ToPointeeType,
2371                                                        ToType, Context);
2372     return true;
2373   }
2374
2375   return false;
2376 }
2377
2378 /// Adopt the given qualifiers for the given type.
2379 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2380   Qualifiers TQs = T.getQualifiers();
2381
2382   // Check whether qualifiers already match.
2383   if (TQs == Qs)
2384     return T;
2385
2386   if (Qs.compatiblyIncludes(TQs))
2387     return Context.getQualifiedType(T, Qs);
2388
2389   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2390 }
2391
2392 /// isObjCPointerConversion - Determines whether this is an
2393 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2394 /// with the same arguments and return values.
2395 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2396                                    QualType& ConvertedType,
2397                                    bool &IncompatibleObjC) {
2398   if (!getLangOpts().ObjC1)
2399     return false;
2400
2401   // The set of qualifiers on the type we're converting from.
2402   Qualifiers FromQualifiers = FromType.getQualifiers();
2403
2404   // First, we handle all conversions on ObjC object pointer types.
2405   const ObjCObjectPointerType* ToObjCPtr =
2406     ToType->getAs<ObjCObjectPointerType>();
2407   const ObjCObjectPointerType *FromObjCPtr =
2408     FromType->getAs<ObjCObjectPointerType>();
2409
2410   if (ToObjCPtr && FromObjCPtr) {
2411     // If the pointee types are the same (ignoring qualifications),
2412     // then this is not a pointer conversion.
2413     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2414                                        FromObjCPtr->getPointeeType()))
2415       return false;
2416
2417     // Conversion between Objective-C pointers.
2418     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2419       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2420       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2421       if (getLangOpts().CPlusPlus && LHS && RHS &&
2422           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2423                                                 FromObjCPtr->getPointeeType()))
2424         return false;
2425       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2426                                                    ToObjCPtr->getPointeeType(),
2427                                                          ToType, Context);
2428       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2429       return true;
2430     }
2431
2432     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2433       // Okay: this is some kind of implicit downcast of Objective-C
2434       // interfaces, which is permitted. However, we're going to
2435       // complain about it.
2436       IncompatibleObjC = true;
2437       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2438                                                    ToObjCPtr->getPointeeType(),
2439                                                          ToType, Context);
2440       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2441       return true;
2442     }
2443   }
2444   // Beyond this point, both types need to be C pointers or block pointers.
2445   QualType ToPointeeType;
2446   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2447     ToPointeeType = ToCPtr->getPointeeType();
2448   else if (const BlockPointerType *ToBlockPtr =
2449             ToType->getAs<BlockPointerType>()) {
2450     // Objective C++: We're able to convert from a pointer to any object
2451     // to a block pointer type.
2452     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2453       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2454       return true;
2455     }
2456     ToPointeeType = ToBlockPtr->getPointeeType();
2457   }
2458   else if (FromType->getAs<BlockPointerType>() &&
2459            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2460     // Objective C++: We're able to convert from a block pointer type to a
2461     // pointer to any object.
2462     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2463     return true;
2464   }
2465   else
2466     return false;
2467
2468   QualType FromPointeeType;
2469   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2470     FromPointeeType = FromCPtr->getPointeeType();
2471   else if (const BlockPointerType *FromBlockPtr =
2472            FromType->getAs<BlockPointerType>())
2473     FromPointeeType = FromBlockPtr->getPointeeType();
2474   else
2475     return false;
2476
2477   // If we have pointers to pointers, recursively check whether this
2478   // is an Objective-C conversion.
2479   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2480       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2481                               IncompatibleObjC)) {
2482     // We always complain about this conversion.
2483     IncompatibleObjC = true;
2484     ConvertedType = Context.getPointerType(ConvertedType);
2485     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2486     return true;
2487   }
2488   // Allow conversion of pointee being objective-c pointer to another one;
2489   // as in I* to id.
2490   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2491       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2492       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2493                               IncompatibleObjC)) {
2494
2495     ConvertedType = Context.getPointerType(ConvertedType);
2496     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2497     return true;
2498   }
2499
2500   // If we have pointers to functions or blocks, check whether the only
2501   // differences in the argument and result types are in Objective-C
2502   // pointer conversions. If so, we permit the conversion (but
2503   // complain about it).
2504   const FunctionProtoType *FromFunctionType
2505     = FromPointeeType->getAs<FunctionProtoType>();
2506   const FunctionProtoType *ToFunctionType
2507     = ToPointeeType->getAs<FunctionProtoType>();
2508   if (FromFunctionType && ToFunctionType) {
2509     // If the function types are exactly the same, this isn't an
2510     // Objective-C pointer conversion.
2511     if (Context.getCanonicalType(FromPointeeType)
2512           == Context.getCanonicalType(ToPointeeType))
2513       return false;
2514
2515     // Perform the quick checks that will tell us whether these
2516     // function types are obviously different.
2517     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2518         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2519         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2520       return false;
2521
2522     bool HasObjCConversion = false;
2523     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2524         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2525       // Okay, the types match exactly. Nothing to do.
2526     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2527                                        ToFunctionType->getReturnType(),
2528                                        ConvertedType, IncompatibleObjC)) {
2529       // Okay, we have an Objective-C pointer conversion.
2530       HasObjCConversion = true;
2531     } else {
2532       // Function types are too different. Abort.
2533       return false;
2534     }
2535
2536     // Check argument types.
2537     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2538          ArgIdx != NumArgs; ++ArgIdx) {
2539       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2540       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2541       if (Context.getCanonicalType(FromArgType)
2542             == Context.getCanonicalType(ToArgType)) {
2543         // Okay, the types match exactly. Nothing to do.
2544       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2545                                          ConvertedType, IncompatibleObjC)) {
2546         // Okay, we have an Objective-C pointer conversion.
2547         HasObjCConversion = true;
2548       } else {
2549         // Argument types are too different. Abort.
2550         return false;
2551       }
2552     }
2553
2554     if (HasObjCConversion) {
2555       // We had an Objective-C conversion. Allow this pointer
2556       // conversion, but complain about it.
2557       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2558       IncompatibleObjC = true;
2559       return true;
2560     }
2561   }
2562
2563   return false;
2564 }
2565
2566 /// Determine whether this is an Objective-C writeback conversion,
2567 /// used for parameter passing when performing automatic reference counting.
2568 ///
2569 /// \param FromType The type we're converting form.
2570 ///
2571 /// \param ToType The type we're converting to.
2572 ///
2573 /// \param ConvertedType The type that will be produced after applying
2574 /// this conversion.
2575 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2576                                      QualType &ConvertedType) {
2577   if (!getLangOpts().ObjCAutoRefCount ||
2578       Context.hasSameUnqualifiedType(FromType, ToType))
2579     return false;
2580
2581   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2582   QualType ToPointee;
2583   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2584     ToPointee = ToPointer->getPointeeType();
2585   else
2586     return false;
2587
2588   Qualifiers ToQuals = ToPointee.getQualifiers();
2589   if (!ToPointee->isObjCLifetimeType() ||
2590       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2591       !ToQuals.withoutObjCLifetime().empty())
2592     return false;
2593
2594   // Argument must be a pointer to __strong to __weak.
2595   QualType FromPointee;
2596   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2597     FromPointee = FromPointer->getPointeeType();
2598   else
2599     return false;
2600
2601   Qualifiers FromQuals = FromPointee.getQualifiers();
2602   if (!FromPointee->isObjCLifetimeType() ||
2603       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2604        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2605     return false;
2606
2607   // Make sure that we have compatible qualifiers.
2608   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2609   if (!ToQuals.compatiblyIncludes(FromQuals))
2610     return false;
2611
2612   // Remove qualifiers from the pointee type we're converting from; they
2613   // aren't used in the compatibility check belong, and we'll be adding back
2614   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2615   FromPointee = FromPointee.getUnqualifiedType();
2616
2617   // The unqualified form of the pointee types must be compatible.
2618   ToPointee = ToPointee.getUnqualifiedType();
2619   bool IncompatibleObjC;
2620   if (Context.typesAreCompatible(FromPointee, ToPointee))
2621     FromPointee = ToPointee;
2622   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2623                                     IncompatibleObjC))
2624     return false;
2625
2626   /// Construct the type we're converting to, which is a pointer to
2627   /// __autoreleasing pointee.
2628   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2629   ConvertedType = Context.getPointerType(FromPointee);
2630   return true;
2631 }
2632
2633 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2634                                     QualType& ConvertedType) {
2635   QualType ToPointeeType;
2636   if (const BlockPointerType *ToBlockPtr =
2637         ToType->getAs<BlockPointerType>())
2638     ToPointeeType = ToBlockPtr->getPointeeType();
2639   else
2640     return false;
2641
2642   QualType FromPointeeType;
2643   if (const BlockPointerType *FromBlockPtr =
2644       FromType->getAs<BlockPointerType>())
2645     FromPointeeType = FromBlockPtr->getPointeeType();
2646   else
2647     return false;
2648   // We have pointer to blocks, check whether the only
2649   // differences in the argument and result types are in Objective-C
2650   // pointer conversions. If so, we permit the conversion.
2651
2652   const FunctionProtoType *FromFunctionType
2653     = FromPointeeType->getAs<FunctionProtoType>();
2654   const FunctionProtoType *ToFunctionType
2655     = ToPointeeType->getAs<FunctionProtoType>();
2656
2657   if (!FromFunctionType || !ToFunctionType)
2658     return false;
2659
2660   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2661     return true;
2662
2663   // Perform the quick checks that will tell us whether these
2664   // function types are obviously different.
2665   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2666       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2667     return false;
2668
2669   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2670   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2671   if (FromEInfo != ToEInfo)
2672     return false;
2673
2674   bool IncompatibleObjC = false;
2675   if (Context.hasSameType(FromFunctionType->getReturnType(),
2676                           ToFunctionType->getReturnType())) {
2677     // Okay, the types match exactly. Nothing to do.
2678   } else {
2679     QualType RHS = FromFunctionType->getReturnType();
2680     QualType LHS = ToFunctionType->getReturnType();
2681     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2682         !RHS.hasQualifiers() && LHS.hasQualifiers())
2683        LHS = LHS.getUnqualifiedType();
2684
2685      if (Context.hasSameType(RHS,LHS)) {
2686        // OK exact match.
2687      } else if (isObjCPointerConversion(RHS, LHS,
2688                                         ConvertedType, IncompatibleObjC)) {
2689      if (IncompatibleObjC)
2690        return false;
2691      // Okay, we have an Objective-C pointer conversion.
2692      }
2693      else
2694        return false;
2695    }
2696
2697    // Check argument types.
2698    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2699         ArgIdx != NumArgs; ++ArgIdx) {
2700      IncompatibleObjC = false;
2701      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2702      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2703      if (Context.hasSameType(FromArgType, ToArgType)) {
2704        // Okay, the types match exactly. Nothing to do.
2705      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2706                                         ConvertedType, IncompatibleObjC)) {
2707        if (IncompatibleObjC)
2708          return false;
2709        // Okay, we have an Objective-C pointer conversion.
2710      } else
2711        // Argument types are too different. Abort.
2712        return false;
2713    }
2714
2715    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2716    bool CanUseToFPT, CanUseFromFPT;
2717    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2718                                       CanUseToFPT, CanUseFromFPT,
2719                                       NewParamInfos))
2720      return false;
2721
2722    ConvertedType = ToType;
2723    return true;
2724 }
2725
2726 enum {
2727   ft_default,
2728   ft_different_class,
2729   ft_parameter_arity,
2730   ft_parameter_mismatch,
2731   ft_return_type,
2732   ft_qualifer_mismatch,
2733   ft_noexcept
2734 };
2735
2736 /// Attempts to get the FunctionProtoType from a Type. Handles
2737 /// MemberFunctionPointers properly.
2738 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2739   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2740     return FPT;
2741
2742   if (auto *MPT = FromType->getAs<MemberPointerType>())
2743     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2744
2745   return nullptr;
2746 }
2747
2748 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2749 /// function types.  Catches different number of parameter, mismatch in
2750 /// parameter types, and different return types.
2751 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2752                                       QualType FromType, QualType ToType) {
2753   // If either type is not valid, include no extra info.
2754   if (FromType.isNull() || ToType.isNull()) {
2755     PDiag << ft_default;
2756     return;
2757   }
2758
2759   // Get the function type from the pointers.
2760   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2761     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2762                             *ToMember = ToType->getAs<MemberPointerType>();
2763     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2764       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2765             << QualType(FromMember->getClass(), 0);
2766       return;
2767     }
2768     FromType = FromMember->getPointeeType();
2769     ToType = ToMember->getPointeeType();
2770   }
2771
2772   if (FromType->isPointerType())
2773     FromType = FromType->getPointeeType();
2774   if (ToType->isPointerType())
2775     ToType = ToType->getPointeeType();
2776
2777   // Remove references.
2778   FromType = FromType.getNonReferenceType();
2779   ToType = ToType.getNonReferenceType();
2780
2781   // Don't print extra info for non-specialized template functions.
2782   if (FromType->isInstantiationDependentType() &&
2783       !FromType->getAs<TemplateSpecializationType>()) {
2784     PDiag << ft_default;
2785     return;
2786   }
2787
2788   // No extra info for same types.
2789   if (Context.hasSameType(FromType, ToType)) {
2790     PDiag << ft_default;
2791     return;
2792   }
2793
2794   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2795                           *ToFunction = tryGetFunctionProtoType(ToType);
2796
2797   // Both types need to be function types.
2798   if (!FromFunction || !ToFunction) {
2799     PDiag << ft_default;
2800     return;
2801   }
2802
2803   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2804     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2805           << FromFunction->getNumParams();
2806     return;
2807   }
2808
2809   // Handle different parameter types.
2810   unsigned ArgPos;
2811   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2812     PDiag << ft_parameter_mismatch << ArgPos + 1
2813           << ToFunction->getParamType(ArgPos)
2814           << FromFunction->getParamType(ArgPos);
2815     return;
2816   }
2817
2818   // Handle different return type.
2819   if (!Context.hasSameType(FromFunction->getReturnType(),
2820                            ToFunction->getReturnType())) {
2821     PDiag << ft_return_type << ToFunction->getReturnType()
2822           << FromFunction->getReturnType();
2823     return;
2824   }
2825
2826   unsigned FromQuals = FromFunction->getTypeQuals(),
2827            ToQuals = ToFunction->getTypeQuals();
2828   if (FromQuals != ToQuals) {
2829     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2830     return;
2831   }
2832
2833   // Handle exception specification differences on canonical type (in C++17
2834   // onwards).
2835   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2836           ->isNothrow() !=
2837       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2838           ->isNothrow()) {
2839     PDiag << ft_noexcept;
2840     return;
2841   }
2842
2843   // Unable to find a difference, so add no extra info.
2844   PDiag << ft_default;
2845 }
2846
2847 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2848 /// for equality of their argument types. Caller has already checked that
2849 /// they have same number of arguments.  If the parameters are different,
2850 /// ArgPos will have the parameter index of the first different parameter.
2851 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2852                                       const FunctionProtoType *NewType,
2853                                       unsigned *ArgPos) {
2854   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2855                                               N = NewType->param_type_begin(),
2856                                               E = OldType->param_type_end();
2857        O && (O != E); ++O, ++N) {
2858     if (!Context.hasSameType(O->getUnqualifiedType(),
2859                              N->getUnqualifiedType())) {
2860       if (ArgPos)
2861         *ArgPos = O - OldType->param_type_begin();
2862       return false;
2863     }
2864   }
2865   return true;
2866 }
2867
2868 /// CheckPointerConversion - Check the pointer conversion from the
2869 /// expression From to the type ToType. This routine checks for
2870 /// ambiguous or inaccessible derived-to-base pointer
2871 /// conversions for which IsPointerConversion has already returned
2872 /// true. It returns true and produces a diagnostic if there was an
2873 /// error, or returns false otherwise.
2874 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2875                                   CastKind &Kind,
2876                                   CXXCastPath& BasePath,
2877                                   bool IgnoreBaseAccess,
2878                                   bool Diagnose) {
2879   QualType FromType = From->getType();
2880   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2881
2882   Kind = CK_BitCast;
2883
2884   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2885       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2886           Expr::NPCK_ZeroExpression) {
2887     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2888       DiagRuntimeBehavior(From->getExprLoc(), From,
2889                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2890                             << ToType << From->getSourceRange());
2891     else if (!isUnevaluatedContext())
2892       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2893         << ToType << From->getSourceRange();
2894   }
2895   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2896     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2897       QualType FromPointeeType = FromPtrType->getPointeeType(),
2898                ToPointeeType   = ToPtrType->getPointeeType();
2899
2900       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2901           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2902         // We must have a derived-to-base conversion. Check an
2903         // ambiguous or inaccessible conversion.
2904         unsigned InaccessibleID = 0;
2905         unsigned AmbigiousID = 0;
2906         if (Diagnose) {
2907           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2908           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2909         }
2910         if (CheckDerivedToBaseConversion(
2911                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2912                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2913                 &BasePath, IgnoreBaseAccess))
2914           return true;
2915
2916         // The conversion was successful.
2917         Kind = CK_DerivedToBase;
2918       }
2919
2920       if (Diagnose && !IsCStyleOrFunctionalCast &&
2921           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2922         assert(getLangOpts().MSVCCompat &&
2923                "this should only be possible with MSVCCompat!");
2924         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2925             << From->getSourceRange();
2926       }
2927     }
2928   } else if (const ObjCObjectPointerType *ToPtrType =
2929                ToType->getAs<ObjCObjectPointerType>()) {
2930     if (const ObjCObjectPointerType *FromPtrType =
2931           FromType->getAs<ObjCObjectPointerType>()) {
2932       // Objective-C++ conversions are always okay.
2933       // FIXME: We should have a different class of conversions for the
2934       // Objective-C++ implicit conversions.
2935       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2936         return false;
2937     } else if (FromType->isBlockPointerType()) {
2938       Kind = CK_BlockPointerToObjCPointerCast;
2939     } else {
2940       Kind = CK_CPointerToObjCPointerCast;
2941     }
2942   } else if (ToType->isBlockPointerType()) {
2943     if (!FromType->isBlockPointerType())
2944       Kind = CK_AnyPointerToBlockPointerCast;
2945   }
2946
2947   // We shouldn't fall into this case unless it's valid for other
2948   // reasons.
2949   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2950     Kind = CK_NullToPointer;
2951
2952   return false;
2953 }
2954
2955 /// IsMemberPointerConversion - Determines whether the conversion of the
2956 /// expression From, which has the (possibly adjusted) type FromType, can be
2957 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2958 /// If so, returns true and places the converted type (that might differ from
2959 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2960 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2961                                      QualType ToType,
2962                                      bool InOverloadResolution,
2963                                      QualType &ConvertedType) {
2964   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2965   if (!ToTypePtr)
2966     return false;
2967
2968   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2969   if (From->isNullPointerConstant(Context,
2970                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971                                         : Expr::NPC_ValueDependentIsNull)) {
2972     ConvertedType = ToType;
2973     return true;
2974   }
2975
2976   // Otherwise, both types have to be member pointers.
2977   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2978   if (!FromTypePtr)
2979     return false;
2980
2981   // A pointer to member of B can be converted to a pointer to member of D,
2982   // where D is derived from B (C++ 4.11p2).
2983   QualType FromClass(FromTypePtr->getClass(), 0);
2984   QualType ToClass(ToTypePtr->getClass(), 0);
2985
2986   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2987       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2988     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2989                                                  ToClass.getTypePtr());
2990     return true;
2991   }
2992
2993   return false;
2994 }
2995
2996 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2997 /// expression From to the type ToType. This routine checks for ambiguous or
2998 /// virtual or inaccessible base-to-derived member pointer conversions
2999 /// for which IsMemberPointerConversion has already returned true. It returns
3000 /// true and produces a diagnostic if there was an error, or returns false
3001 /// otherwise.
3002 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3003                                         CastKind &Kind,
3004                                         CXXCastPath &BasePath,
3005                                         bool IgnoreBaseAccess) {
3006   QualType FromType = From->getType();
3007   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3008   if (!FromPtrType) {
3009     // This must be a null pointer to member pointer conversion
3010     assert(From->isNullPointerConstant(Context,
3011                                        Expr::NPC_ValueDependentIsNull) &&
3012            "Expr must be null pointer constant!");
3013     Kind = CK_NullToMemberPointer;
3014     return false;
3015   }
3016
3017   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3018   assert(ToPtrType && "No member pointer cast has a target type "
3019                       "that is not a member pointer.");
3020
3021   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3022   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3023
3024   // FIXME: What about dependent types?
3025   assert(FromClass->isRecordType() && "Pointer into non-class.");
3026   assert(ToClass->isRecordType() && "Pointer into non-class.");
3027
3028   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3029                      /*DetectVirtual=*/true);
3030   bool DerivationOkay =
3031       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3032   assert(DerivationOkay &&
3033          "Should not have been called if derivation isn't OK.");
3034   (void)DerivationOkay;
3035
3036   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3037                                   getUnqualifiedType())) {
3038     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3039     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3040       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3041     return true;
3042   }
3043
3044   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3045     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3046       << FromClass << ToClass << QualType(VBase, 0)
3047       << From->getSourceRange();
3048     return true;
3049   }
3050
3051   if (!IgnoreBaseAccess)
3052     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3053                          Paths.front(),
3054                          diag::err_downcast_from_inaccessible_base);
3055
3056   // Must be a base to derived member conversion.
3057   BuildBasePathArray(Paths, BasePath);
3058   Kind = CK_BaseToDerivedMemberPointer;
3059   return false;
3060 }
3061
3062 /// Determine whether the lifetime conversion between the two given
3063 /// qualifiers sets is nontrivial.
3064 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3065                                                Qualifiers ToQuals) {
3066   // Converting anything to const __unsafe_unretained is trivial.
3067   if (ToQuals.hasConst() &&
3068       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3069     return false;
3070
3071   return true;
3072 }
3073
3074 /// IsQualificationConversion - Determines whether the conversion from
3075 /// an rvalue of type FromType to ToType is a qualification conversion
3076 /// (C++ 4.4).
3077 ///
3078 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3079 /// when the qualification conversion involves a change in the Objective-C
3080 /// object lifetime.
3081 bool
3082 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3083                                 bool CStyle, bool &ObjCLifetimeConversion) {
3084   FromType = Context.getCanonicalType(FromType);
3085   ToType = Context.getCanonicalType(ToType);
3086   ObjCLifetimeConversion = false;
3087
3088   // If FromType and ToType are the same type, this is not a
3089   // qualification conversion.
3090   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3091     return false;
3092
3093   // (C++ 4.4p4):
3094   //   A conversion can add cv-qualifiers at levels other than the first
3095   //   in multi-level pointers, subject to the following rules: [...]
3096   bool PreviousToQualsIncludeConst = true;
3097   bool UnwrappedAnyPointer = false;
3098   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3099     // Within each iteration of the loop, we check the qualifiers to
3100     // determine if this still looks like a qualification
3101     // conversion. Then, if all is well, we unwrap one more level of
3102     // pointers or pointers-to-members and do it all again
3103     // until there are no more pointers or pointers-to-members left to
3104     // unwrap.
3105     UnwrappedAnyPointer = true;
3106
3107     Qualifiers FromQuals = FromType.getQualifiers();
3108     Qualifiers ToQuals = ToType.getQualifiers();
3109
3110     // Ignore __unaligned qualifier if this type is void.
3111     if (ToType.getUnqualifiedType()->isVoidType())
3112       FromQuals.removeUnaligned();
3113
3114     // Objective-C ARC:
3115     //   Check Objective-C lifetime conversions.
3116     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3117         UnwrappedAnyPointer) {
3118       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3119         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3120           ObjCLifetimeConversion = true;
3121         FromQuals.removeObjCLifetime();
3122         ToQuals.removeObjCLifetime();
3123       } else {
3124         // Qualification conversions cannot cast between different
3125         // Objective-C lifetime qualifiers.
3126         return false;
3127       }
3128     }
3129
3130     // Allow addition/removal of GC attributes but not changing GC attributes.
3131     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3132         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3133       FromQuals.removeObjCGCAttr();
3134       ToQuals.removeObjCGCAttr();
3135     }
3136
3137     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3138     //      2,j, and similarly for volatile.
3139     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3140       return false;
3141
3142     //   -- if the cv 1,j and cv 2,j are different, then const is in
3143     //      every cv for 0 < k < j.
3144     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3145         && !PreviousToQualsIncludeConst)
3146       return false;
3147
3148     // Keep track of whether all prior cv-qualifiers in the "to" type
3149     // include const.
3150     PreviousToQualsIncludeConst
3151       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3152   }
3153
3154   // Allows address space promotion by language rules implemented in
3155   // Type::Qualifiers::isAddressSpaceSupersetOf.
3156   Qualifiers FromQuals = FromType.getQualifiers();
3157   Qualifiers ToQuals = ToType.getQualifiers();
3158   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3159       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3160     return false;
3161   }
3162
3163   // We are left with FromType and ToType being the pointee types
3164   // after unwrapping the original FromType and ToType the same number
3165   // of types. If we unwrapped any pointers, and if FromType and
3166   // ToType have the same unqualified type (since we checked
3167   // qualifiers above), then this is a qualification conversion.
3168   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3169 }
3170
3171 /// - Determine whether this is a conversion from a scalar type to an
3172 /// atomic type.
3173 ///
3174 /// If successful, updates \c SCS's second and third steps in the conversion
3175 /// sequence to finish the conversion.
3176 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3177                                 bool InOverloadResolution,
3178                                 StandardConversionSequence &SCS,
3179                                 bool CStyle) {
3180   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3181   if (!ToAtomic)
3182     return false;
3183
3184   StandardConversionSequence InnerSCS;
3185   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3186                             InOverloadResolution, InnerSCS,
3187                             CStyle, /*AllowObjCWritebackConversion=*/false))
3188     return false;
3189
3190   SCS.Second = InnerSCS.Second;
3191   SCS.setToType(1, InnerSCS.getToType(1));
3192   SCS.Third = InnerSCS.Third;
3193   SCS.QualificationIncludesObjCLifetime
3194     = InnerSCS.QualificationIncludesObjCLifetime;
3195   SCS.setToType(2, InnerSCS.getToType(2));
3196   return true;
3197 }
3198
3199 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3200                                               CXXConstructorDecl *Constructor,
3201                                               QualType Type) {
3202   const FunctionProtoType *CtorType =
3203       Constructor->getType()->getAs<FunctionProtoType>();
3204   if (CtorType->getNumParams() > 0) {
3205     QualType FirstArg = CtorType->getParamType(0);
3206     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3207       return true;
3208   }
3209   return false;
3210 }
3211
3212 static OverloadingResult
3213 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3214                                        CXXRecordDecl *To,
3215                                        UserDefinedConversionSequence &User,
3216                                        OverloadCandidateSet &CandidateSet,
3217                                        bool AllowExplicit) {
3218   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3219   for (auto *D : S.LookupConstructors(To)) {
3220     auto Info = getConstructorInfo(D);
3221     if (!Info)
3222       continue;
3223
3224     bool Usable = !Info.Constructor->isInvalidDecl() &&
3225                   S.isInitListConstructor(Info.Constructor) &&
3226                   (AllowExplicit || !Info.Constructor->isExplicit());
3227     if (Usable) {
3228       // If the first argument is (a reference to) the target type,
3229       // suppress conversions.
3230       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3231           S.Context, Info.Constructor, ToType);
3232       if (Info.ConstructorTmpl)
3233         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3234                                        /*ExplicitArgs*/ nullptr, From,
3235                                        CandidateSet, SuppressUserConversions);
3236       else
3237         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3238                                CandidateSet, SuppressUserConversions);
3239     }
3240   }
3241
3242   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3243
3244   OverloadCandidateSet::iterator Best;
3245   switch (auto Result =
3246             CandidateSet.BestViableFunction(S, From->getLocStart(),
3247                                             Best)) {
3248   case OR_Deleted:
3249   case OR_Success: {
3250     // Record the standard conversion we used and the conversion function.
3251     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3252     QualType ThisType = Constructor->getThisType(S.Context);
3253     // Initializer lists don't have conversions as such.
3254     User.Before.setAsIdentityConversion();
3255     User.HadMultipleCandidates = HadMultipleCandidates;
3256     User.ConversionFunction = Constructor;
3257     User.FoundConversionFunction = Best->FoundDecl;
3258     User.After.setAsIdentityConversion();
3259     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3260     User.After.setAllToTypes(ToType);
3261     return Result;
3262   }
3263
3264   case OR_No_Viable_Function:
3265     return OR_No_Viable_Function;
3266   case OR_Ambiguous:
3267     return OR_Ambiguous;
3268   }
3269
3270   llvm_unreachable("Invalid OverloadResult!");
3271 }
3272
3273 /// Determines whether there is a user-defined conversion sequence
3274 /// (C++ [over.ics.user]) that converts expression From to the type
3275 /// ToType. If such a conversion exists, User will contain the
3276 /// user-defined conversion sequence that performs such a conversion
3277 /// and this routine will return true. Otherwise, this routine returns
3278 /// false and User is unspecified.
3279 ///
3280 /// \param AllowExplicit  true if the conversion should consider C++0x
3281 /// "explicit" conversion functions as well as non-explicit conversion
3282 /// functions (C++0x [class.conv.fct]p2).
3283 ///
3284 /// \param AllowObjCConversionOnExplicit true if the conversion should
3285 /// allow an extra Objective-C pointer conversion on uses of explicit
3286 /// constructors. Requires \c AllowExplicit to also be set.
3287 static OverloadingResult
3288 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3289                         UserDefinedConversionSequence &User,
3290                         OverloadCandidateSet &CandidateSet,
3291                         bool AllowExplicit,
3292                         bool AllowObjCConversionOnExplicit) {
3293   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3294   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3295
3296   // Whether we will only visit constructors.
3297   bool ConstructorsOnly = false;
3298
3299   // If the type we are conversion to is a class type, enumerate its
3300   // constructors.
3301   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3302     // C++ [over.match.ctor]p1:
3303     //   When objects of class type are direct-initialized (8.5), or
3304     //   copy-initialized from an expression of the same or a
3305     //   derived class type (8.5), overload resolution selects the
3306     //   constructor. [...] For copy-initialization, the candidate
3307     //   functions are all the converting constructors (12.3.1) of
3308     //   that class. The argument list is the expression-list within
3309     //   the parentheses of the initializer.
3310     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3311         (From->getType()->getAs<RecordType>() &&
3312          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3313       ConstructorsOnly = true;
3314
3315     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3316       // We're not going to find any constructors.
3317     } else if (CXXRecordDecl *ToRecordDecl
3318                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3319
3320       Expr **Args = &From;
3321       unsigned NumArgs = 1;
3322       bool ListInitializing = false;
3323       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3324         // But first, see if there is an init-list-constructor that will work.
3325         OverloadingResult Result = IsInitializerListConstructorConversion(
3326             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3327         if (Result != OR_No_Viable_Function)
3328           return Result;
3329         // Never mind.
3330         CandidateSet.clear(
3331             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3332
3333         // If we're list-initializing, we pass the individual elements as
3334         // arguments, not the entire list.
3335         Args = InitList->getInits();
3336         NumArgs = InitList->getNumInits();
3337         ListInitializing = true;
3338       }
3339
3340       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3341         auto Info = getConstructorInfo(D);
3342         if (!Info)
3343           continue;
3344
3345         bool Usable = !Info.Constructor->isInvalidDecl();
3346         if (ListInitializing)
3347           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3348         else
3349           Usable = Usable &&
3350                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3351         if (Usable) {
3352           bool SuppressUserConversions = !ConstructorsOnly;
3353           if (SuppressUserConversions && ListInitializing) {
3354             SuppressUserConversions = false;
3355             if (NumArgs == 1) {
3356               // If the first argument is (a reference to) the target type,
3357               // suppress conversions.
3358               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3359                   S.Context, Info.Constructor, ToType);
3360             }
3361           }
3362           if (Info.ConstructorTmpl)
3363             S.AddTemplateOverloadCandidate(
3364                 Info.ConstructorTmpl, Info.FoundDecl,
3365                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3366                 CandidateSet, SuppressUserConversions);
3367           else
3368             // Allow one user-defined conversion when user specifies a
3369             // From->ToType conversion via an static cast (c-style, etc).
3370             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3371                                    llvm::makeArrayRef(Args, NumArgs),
3372                                    CandidateSet, SuppressUserConversions);
3373         }
3374       }
3375     }
3376   }
3377
3378   // Enumerate conversion functions, if we're allowed to.
3379   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3380   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3381     // No conversion functions from incomplete types.
3382   } else if (const RecordType *FromRecordType
3383                                    = From->getType()->getAs<RecordType>()) {
3384     if (CXXRecordDecl *FromRecordDecl
3385          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3386       // Add all of the conversion functions as candidates.
3387       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3388       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3389         DeclAccessPair FoundDecl = I.getPair();
3390         NamedDecl *D = FoundDecl.getDecl();
3391         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3392         if (isa<UsingShadowDecl>(D))
3393           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3394
3395         CXXConversionDecl *Conv;
3396         FunctionTemplateDecl *ConvTemplate;
3397         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3398           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3399         else
3400           Conv = cast<CXXConversionDecl>(D);
3401
3402         if (AllowExplicit || !Conv->isExplicit()) {
3403           if (ConvTemplate)
3404             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3405                                              ActingContext, From, ToType,
3406                                              CandidateSet,
3407                                              AllowObjCConversionOnExplicit);
3408           else
3409             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3410                                      From, ToType, CandidateSet,
3411                                      AllowObjCConversionOnExplicit);
3412         }
3413       }
3414     }
3415   }
3416
3417   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3418
3419   OverloadCandidateSet::iterator Best;
3420   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3421                                                         Best)) {
3422   case OR_Success:
3423   case OR_Deleted:
3424     // Record the standard conversion we used and the conversion function.
3425     if (CXXConstructorDecl *Constructor
3426           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3427       // C++ [over.ics.user]p1:
3428       //   If the user-defined conversion is specified by a
3429       //   constructor (12.3.1), the initial standard conversion
3430       //   sequence converts the source type to the type required by
3431       //   the argument of the constructor.
3432       //
3433       QualType ThisType = Constructor->getThisType(S.Context);
3434       if (isa<InitListExpr>(From)) {
3435         // Initializer lists don't have conversions as such.
3436         User.Before.setAsIdentityConversion();
3437       } else {
3438         if (Best->Conversions[0].isEllipsis())
3439           User.EllipsisConversion = true;
3440         else {
3441           User.Before = Best->Conversions[0].Standard;
3442           User.EllipsisConversion = false;
3443         }
3444       }
3445       User.HadMultipleCandidates = HadMultipleCandidates;
3446       User.ConversionFunction = Constructor;
3447       User.FoundConversionFunction = Best->FoundDecl;
3448       User.After.setAsIdentityConversion();
3449       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3450       User.After.setAllToTypes(ToType);
3451       return Result;
3452     }
3453     if (CXXConversionDecl *Conversion
3454                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3455       // C++ [over.ics.user]p1:
3456       //
3457       //   [...] If the user-defined conversion is specified by a
3458       //   conversion function (12.3.2), the initial standard
3459       //   conversion sequence converts the source type to the
3460       //   implicit object parameter of the conversion function.
3461       User.Before = Best->Conversions[0].Standard;
3462       User.HadMultipleCandidates = HadMultipleCandidates;
3463       User.ConversionFunction = Conversion;
3464       User.FoundConversionFunction = Best->FoundDecl;
3465       User.EllipsisConversion = false;
3466
3467       // C++ [over.ics.user]p2:
3468       //   The second standard conversion sequence converts the
3469       //   result of the user-defined conversion to the target type
3470       //   for the sequence. Since an implicit conversion sequence
3471       //   is an initialization, the special rules for
3472       //   initialization by user-defined conversion apply when
3473       //   selecting the best user-defined conversion for a
3474       //   user-defined conversion sequence (see 13.3.3 and
3475       //   13.3.3.1).
3476       User.After = Best->FinalConversion;
3477       return Result;
3478     }
3479     llvm_unreachable("Not a constructor or conversion function?");
3480
3481   case OR_No_Viable_Function:
3482     return OR_No_Viable_Function;
3483
3484   case OR_Ambiguous:
3485     return OR_Ambiguous;
3486   }
3487
3488   llvm_unreachable("Invalid OverloadResult!");
3489 }
3490
3491 bool
3492 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3493   ImplicitConversionSequence ICS;
3494   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3495                                     OverloadCandidateSet::CSK_Normal);
3496   OverloadingResult OvResult =
3497     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3498                             CandidateSet, false, false);
3499   if (OvResult == OR_Ambiguous)
3500     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3501         << From->getType() << ToType << From->getSourceRange();
3502   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3503     if (!RequireCompleteType(From->getLocStart(), ToType,
3504                              diag::err_typecheck_nonviable_condition_incomplete,
3505                              From->getType(), From->getSourceRange()))
3506       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3507           << false << From->getType() << From->getSourceRange() << ToType;
3508   } else
3509     return false;
3510   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3511   return true;
3512 }
3513
3514 /// Compare the user-defined conversion functions or constructors
3515 /// of two user-defined conversion sequences to determine whether any ordering
3516 /// is possible.
3517 static ImplicitConversionSequence::CompareKind
3518 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3519                            FunctionDecl *Function2) {
3520   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3521     return ImplicitConversionSequence::Indistinguishable;
3522
3523   // Objective-C++:
3524   //   If both conversion functions are implicitly-declared conversions from
3525   //   a lambda closure type to a function pointer and a block pointer,
3526   //   respectively, always prefer the conversion to a function pointer,
3527   //   because the function pointer is more lightweight and is more likely
3528   //   to keep code working.
3529   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3530   if (!Conv1)
3531     return ImplicitConversionSequence::Indistinguishable;
3532
3533   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3534   if (!Conv2)
3535     return ImplicitConversionSequence::Indistinguishable;
3536
3537   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3538     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3539     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3540     if (Block1 != Block2)
3541       return Block1 ? ImplicitConversionSequence::Worse
3542                     : ImplicitConversionSequence::Better;
3543   }
3544
3545   return ImplicitConversionSequence::Indistinguishable;
3546 }
3547
3548 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3549     const ImplicitConversionSequence &ICS) {
3550   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3551          (ICS.isUserDefined() &&
3552           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3553 }
3554
3555 /// CompareImplicitConversionSequences - Compare two implicit
3556 /// conversion sequences to determine whether one is better than the
3557 /// other or if they are indistinguishable (C++ 13.3.3.2).
3558 static ImplicitConversionSequence::CompareKind
3559 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3560                                    const ImplicitConversionSequence& ICS1,
3561                                    const ImplicitConversionSequence& ICS2)
3562 {
3563   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3564   // conversion sequences (as defined in 13.3.3.1)
3565   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3566   //      conversion sequence than a user-defined conversion sequence or
3567   //      an ellipsis conversion sequence, and
3568   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3569   //      conversion sequence than an ellipsis conversion sequence
3570   //      (13.3.3.1.3).
3571   //
3572   // C++0x [over.best.ics]p10:
3573   //   For the purpose of ranking implicit conversion sequences as
3574   //   described in 13.3.3.2, the ambiguous conversion sequence is
3575   //   treated as a user-defined sequence that is indistinguishable
3576   //   from any other user-defined conversion sequence.
3577
3578   // String literal to 'char *' conversion has been deprecated in C++03. It has
3579   // been removed from C++11. We still accept this conversion, if it happens at
3580   // the best viable function. Otherwise, this conversion is considered worse
3581   // than ellipsis conversion. Consider this as an extension; this is not in the
3582   // standard. For example:
3583   //
3584   // int &f(...);    // #1
3585   // void f(char*);  // #2
3586   // void g() { int &r = f("foo"); }
3587   //
3588   // In C++03, we pick #2 as the best viable function.
3589   // In C++11, we pick #1 as the best viable function, because ellipsis
3590   // conversion is better than string-literal to char* conversion (since there
3591   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3592   // convert arguments, #2 would be the best viable function in C++11.
3593   // If the best viable function has this conversion, a warning will be issued
3594   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3595
3596   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3597       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3598       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3599     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3600                ? ImplicitConversionSequence::Worse
3601                : ImplicitConversionSequence::Better;
3602
3603   if (ICS1.getKindRank() < ICS2.getKindRank())
3604     return ImplicitConversionSequence::Better;
3605   if (ICS2.getKindRank() < ICS1.getKindRank())
3606     return ImplicitConversionSequence::Worse;
3607
3608   // The following checks require both conversion sequences to be of
3609   // the same kind.
3610   if (ICS1.getKind() != ICS2.getKind())
3611     return ImplicitConversionSequence::Indistinguishable;
3612
3613   ImplicitConversionSequence::CompareKind Result =
3614       ImplicitConversionSequence::Indistinguishable;
3615
3616   // Two implicit conversion sequences of the same form are
3617   // indistinguishable conversion sequences unless one of the
3618   // following rules apply: (C++ 13.3.3.2p3):
3619
3620   // List-initialization sequence L1 is a better conversion sequence than
3621   // list-initialization sequence L2 if:
3622   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3623   //   if not that,
3624   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3625   //   and N1 is smaller than N2.,
3626   // even if one of the other rules in this paragraph would otherwise apply.
3627   if (!ICS1.isBad()) {
3628     if (ICS1.isStdInitializerListElement() &&
3629         !ICS2.isStdInitializerListElement())
3630       return ImplicitConversionSequence::Better;
3631     if (!ICS1.isStdInitializerListElement() &&
3632         ICS2.isStdInitializerListElement())
3633       return ImplicitConversionSequence::Worse;
3634   }
3635
3636   if (ICS1.isStandard())
3637     // Standard conversion sequence S1 is a better conversion sequence than
3638     // standard conversion sequence S2 if [...]
3639     Result = CompareStandardConversionSequences(S, Loc,
3640                                                 ICS1.Standard, ICS2.Standard);
3641   else if (ICS1.isUserDefined()) {
3642     // User-defined conversion sequence U1 is a better conversion
3643     // sequence than another user-defined conversion sequence U2 if
3644     // they contain the same user-defined conversion function or
3645     // constructor and if the second standard conversion sequence of
3646     // U1 is better than the second standard conversion sequence of
3647     // U2 (C++ 13.3.3.2p3).
3648     if (ICS1.UserDefined.ConversionFunction ==
3649           ICS2.UserDefined.ConversionFunction)
3650       Result = CompareStandardConversionSequences(S, Loc,
3651                                                   ICS1.UserDefined.After,
3652                                                   ICS2.UserDefined.After);
3653     else
3654       Result = compareConversionFunctions(S,
3655                                           ICS1.UserDefined.ConversionFunction,
3656                                           ICS2.UserDefined.ConversionFunction);
3657   }
3658
3659   return Result;
3660 }
3661
3662 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3663 // determine if one is a proper subset of the other.
3664 static ImplicitConversionSequence::CompareKind
3665 compareStandardConversionSubsets(ASTContext &Context,
3666                                  const StandardConversionSequence& SCS1,
3667                                  const StandardConversionSequence& SCS2) {
3668   ImplicitConversionSequence::CompareKind Result
3669     = ImplicitConversionSequence::Indistinguishable;
3670
3671   // the identity conversion sequence is considered to be a subsequence of
3672   // any non-identity conversion sequence
3673   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3674     return ImplicitConversionSequence::Better;
3675   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3676     return ImplicitConversionSequence::Worse;
3677
3678   if (SCS1.Second != SCS2.Second) {
3679     if (SCS1.Second == ICK_Identity)
3680       Result = ImplicitConversionSequence::Better;
3681     else if (SCS2.Second == ICK_Identity)
3682       Result = ImplicitConversionSequence::Worse;
3683     else
3684       return ImplicitConversionSequence::Indistinguishable;
3685   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3686     return ImplicitConversionSequence::Indistinguishable;
3687
3688   if (SCS1.Third == SCS2.Third) {
3689     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3690                              : ImplicitConversionSequence::Indistinguishable;
3691   }
3692
3693   if (SCS1.Third == ICK_Identity)
3694     return Result == ImplicitConversionSequence::Worse
3695              ? ImplicitConversionSequence::Indistinguishable
3696              : ImplicitConversionSequence::Better;
3697
3698   if (SCS2.Third == ICK_Identity)
3699     return Result == ImplicitConversionSequence::Better
3700              ? ImplicitConversionSequence::Indistinguishable
3701              : ImplicitConversionSequence::Worse;
3702
3703   return ImplicitConversionSequence::Indistinguishable;
3704 }
3705
3706 /// Determine whether one of the given reference bindings is better
3707 /// than the other based on what kind of bindings they are.
3708 static bool
3709 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3710                              const StandardConversionSequence &SCS2) {
3711   // C++0x [over.ics.rank]p3b4:
3712   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3713   //      implicit object parameter of a non-static member function declared
3714   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3715   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3716   //      lvalue reference to a function lvalue and S2 binds an rvalue
3717   //      reference*.
3718   //
3719   // FIXME: Rvalue references. We're going rogue with the above edits,
3720   // because the semantics in the current C++0x working paper (N3225 at the
3721   // time of this writing) break the standard definition of std::forward
3722   // and std::reference_wrapper when dealing with references to functions.
3723   // Proposed wording changes submitted to CWG for consideration.
3724   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3725       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3726     return false;
3727
3728   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3729           SCS2.IsLvalueReference) ||
3730          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3731           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3732 }
3733
3734 /// CompareStandardConversionSequences - Compare two standard
3735 /// conversion sequences to determine whether one is better than the
3736 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3737 static ImplicitConversionSequence::CompareKind
3738 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3739                                    const StandardConversionSequence& SCS1,
3740                                    const StandardConversionSequence& SCS2)
3741 {
3742   // Standard conversion sequence S1 is a better conversion sequence
3743   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3744
3745   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3746   //     sequences in the canonical form defined by 13.3.3.1.1,
3747   //     excluding any Lvalue Transformation; the identity conversion
3748   //     sequence is considered to be a subsequence of any
3749   //     non-identity conversion sequence) or, if not that,
3750   if (ImplicitConversionSequence::CompareKind CK
3751         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3752     return CK;
3753
3754   //  -- the rank of S1 is better than the rank of S2 (by the rules
3755   //     defined below), or, if not that,
3756   ImplicitConversionRank Rank1 = SCS1.getRank();
3757   ImplicitConversionRank Rank2 = SCS2.getRank();
3758   if (Rank1 < Rank2)
3759     return ImplicitConversionSequence::Better;
3760   else if (Rank2 < Rank1)
3761     return ImplicitConversionSequence::Worse;
3762
3763   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3764   // are indistinguishable unless one of the following rules
3765   // applies:
3766
3767   //   A conversion that is not a conversion of a pointer, or
3768   //   pointer to member, to bool is better than another conversion
3769   //   that is such a conversion.
3770   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3771     return SCS2.isPointerConversionToBool()
3772              ? ImplicitConversionSequence::Better
3773              : ImplicitConversionSequence::Worse;
3774
3775   // C++ [over.ics.rank]p4b2:
3776   //
3777   //   If class B is derived directly or indirectly from class A,
3778   //   conversion of B* to A* is better than conversion of B* to
3779   //   void*, and conversion of A* to void* is better than conversion
3780   //   of B* to void*.
3781   bool SCS1ConvertsToVoid
3782     = SCS1.isPointerConversionToVoidPointer(S.Context);
3783   bool SCS2ConvertsToVoid
3784     = SCS2.isPointerConversionToVoidPointer(S.Context);
3785   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3786     // Exactly one of the conversion sequences is a conversion to
3787     // a void pointer; it's the worse conversion.
3788     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3789                               : ImplicitConversionSequence::Worse;
3790   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3791     // Neither conversion sequence converts to a void pointer; compare
3792     // their derived-to-base conversions.
3793     if (ImplicitConversionSequence::CompareKind DerivedCK
3794           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3795       return DerivedCK;
3796   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3797              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3798     // Both conversion sequences are conversions to void
3799     // pointers. Compare the source types to determine if there's an
3800     // inheritance relationship in their sources.
3801     QualType FromType1 = SCS1.getFromType();
3802     QualType FromType2 = SCS2.getFromType();
3803
3804     // Adjust the types we're converting from via the array-to-pointer
3805     // conversion, if we need to.
3806     if (SCS1.First == ICK_Array_To_Pointer)
3807       FromType1 = S.Context.getArrayDecayedType(FromType1);
3808     if (SCS2.First == ICK_Array_To_Pointer)
3809       FromType2 = S.Context.getArrayDecayedType(FromType2);
3810
3811     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3812     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3813
3814     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3815       return ImplicitConversionSequence::Better;
3816     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3817       return ImplicitConversionSequence::Worse;
3818
3819     // Objective-C++: If one interface is more specific than the
3820     // other, it is the better one.
3821     const ObjCObjectPointerType* FromObjCPtr1
3822       = FromType1->getAs<ObjCObjectPointerType>();
3823     const ObjCObjectPointerType* FromObjCPtr2
3824       = FromType2->getAs<ObjCObjectPointerType>();
3825     if (FromObjCPtr1 && FromObjCPtr2) {
3826       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3827                                                           FromObjCPtr2);
3828       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3829                                                            FromObjCPtr1);
3830       if (AssignLeft != AssignRight) {
3831         return AssignLeft? ImplicitConversionSequence::Better
3832                          : ImplicitConversionSequence::Worse;
3833       }
3834     }
3835   }
3836
3837   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3838   // bullet 3).
3839   if (ImplicitConversionSequence::CompareKind QualCK
3840         = CompareQualificationConversions(S, SCS1, SCS2))
3841     return QualCK;
3842
3843   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3844     // Check for a better reference binding based on the kind of bindings.
3845     if (isBetterReferenceBindingKind(SCS1, SCS2))
3846       return ImplicitConversionSequence::Better;
3847     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3848       return ImplicitConversionSequence::Worse;
3849
3850     // C++ [over.ics.rank]p3b4:
3851     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3852     //      which the references refer are the same type except for
3853     //      top-level cv-qualifiers, and the type to which the reference
3854     //      initialized by S2 refers is more cv-qualified than the type
3855     //      to which the reference initialized by S1 refers.
3856     QualType T1 = SCS1.getToType(2);
3857     QualType T2 = SCS2.getToType(2);
3858     T1 = S.Context.getCanonicalType(T1);
3859     T2 = S.Context.getCanonicalType(T2);
3860     Qualifiers T1Quals, T2Quals;
3861     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3862     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3863     if (UnqualT1 == UnqualT2) {
3864       // Objective-C++ ARC: If the references refer to objects with different
3865       // lifetimes, prefer bindings that don't change lifetime.
3866       if (SCS1.ObjCLifetimeConversionBinding !=
3867                                           SCS2.ObjCLifetimeConversionBinding) {
3868         return SCS1.ObjCLifetimeConversionBinding
3869                                            ? ImplicitConversionSequence::Worse
3870                                            : ImplicitConversionSequence::Better;
3871       }
3872
3873       // If the type is an array type, promote the element qualifiers to the
3874       // type for comparison.
3875       if (isa<ArrayType>(T1) && T1Quals)
3876         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3877       if (isa<ArrayType>(T2) && T2Quals)
3878         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3879       if (T2.isMoreQualifiedThan(T1))
3880         return ImplicitConversionSequence::Better;
3881       else if (T1.isMoreQualifiedThan(T2))
3882         return ImplicitConversionSequence::Worse;
3883     }
3884   }
3885
3886   // In Microsoft mode, prefer an integral conversion to a
3887   // floating-to-integral conversion if the integral conversion
3888   // is between types of the same size.
3889   // For example:
3890   // void f(float);
3891   // void f(int);
3892   // int main {
3893   //    long a;
3894   //    f(a);
3895   // }
3896   // Here, MSVC will call f(int) instead of generating a compile error
3897   // as clang will do in standard mode.
3898   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3899       SCS2.Second == ICK_Floating_Integral &&
3900       S.Context.getTypeSize(SCS1.getFromType()) ==
3901           S.Context.getTypeSize(SCS1.getToType(2)))
3902     return ImplicitConversionSequence::Better;
3903
3904   return ImplicitConversionSequence::Indistinguishable;
3905 }
3906
3907 /// CompareQualificationConversions - Compares two standard conversion
3908 /// sequences to determine whether they can be ranked based on their
3909 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3910 static ImplicitConversionSequence::CompareKind
3911 CompareQualificationConversions(Sema &S,
3912                                 const StandardConversionSequence& SCS1,
3913                                 const StandardConversionSequence& SCS2) {
3914   // C++ 13.3.3.2p3:
3915   //  -- S1 and S2 differ only in their qualification conversion and
3916   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3917   //     cv-qualification signature of type T1 is a proper subset of
3918   //     the cv-qualification signature of type T2, and S1 is not the
3919   //     deprecated string literal array-to-pointer conversion (4.2).
3920   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3921       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3922     return ImplicitConversionSequence::Indistinguishable;
3923
3924   // FIXME: the example in the standard doesn't use a qualification
3925   // conversion (!)
3926   QualType T1 = SCS1.getToType(2);
3927   QualType T2 = SCS2.getToType(2);
3928   T1 = S.Context.getCanonicalType(T1);
3929   T2 = S.Context.getCanonicalType(T2);
3930   Qualifiers T1Quals, T2Quals;
3931   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3932   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3933
3934   // If the types are the same, we won't learn anything by unwrapped
3935   // them.
3936   if (UnqualT1 == UnqualT2)
3937     return ImplicitConversionSequence::Indistinguishable;
3938
3939   // If the type is an array type, promote the element qualifiers to the type
3940   // for comparison.
3941   if (isa<ArrayType>(T1) && T1Quals)
3942     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3943   if (isa<ArrayType>(T2) && T2Quals)
3944     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3945
3946   ImplicitConversionSequence::CompareKind Result
3947     = ImplicitConversionSequence::Indistinguishable;
3948
3949   // Objective-C++ ARC:
3950   //   Prefer qualification conversions not involving a change in lifetime
3951   //   to qualification conversions that do not change lifetime.
3952   if (SCS1.QualificationIncludesObjCLifetime !=
3953                                       SCS2.QualificationIncludesObjCLifetime) {
3954     Result = SCS1.QualificationIncludesObjCLifetime
3955                ? ImplicitConversionSequence::Worse
3956                : ImplicitConversionSequence::Better;
3957   }
3958
3959   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3960     // Within each iteration of the loop, we check the qualifiers to
3961     // determine if this still looks like a qualification
3962     // conversion. Then, if all is well, we unwrap one more level of
3963     // pointers or pointers-to-members and do it all again
3964     // until there are no more pointers or pointers-to-members left
3965     // to unwrap. This essentially mimics what
3966     // IsQualificationConversion does, but here we're checking for a
3967     // strict subset of qualifiers.
3968     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3969       // The qualifiers are the same, so this doesn't tell us anything
3970       // about how the sequences rank.
3971       ;
3972     else if (T2.isMoreQualifiedThan(T1)) {
3973       // T1 has fewer qualifiers, so it could be the better sequence.
3974       if (Result == ImplicitConversionSequence::Worse)
3975         // Neither has qualifiers that are a subset of the other's
3976         // qualifiers.
3977         return ImplicitConversionSequence::Indistinguishable;
3978
3979       Result = ImplicitConversionSequence::Better;
3980     } else if (T1.isMoreQualifiedThan(T2)) {
3981       // T2 has fewer qualifiers, so it could be the better sequence.
3982       if (Result == ImplicitConversionSequence::Better)
3983         // Neither has qualifiers that are a subset of the other's
3984         // qualifiers.
3985         return ImplicitConversionSequence::Indistinguishable;
3986
3987       Result = ImplicitConversionSequence::Worse;
3988     } else {
3989       // Qualifiers are disjoint.
3990       return ImplicitConversionSequence::Indistinguishable;
3991     }
3992
3993     // If the types after this point are equivalent, we're done.
3994     if (S.Context.hasSameUnqualifiedType(T1, T2))
3995       break;
3996   }
3997
3998   // Check that the winning standard conversion sequence isn't using
3999   // the deprecated string literal array to pointer conversion.
4000   switch (Result) {
4001   case ImplicitConversionSequence::Better:
4002     if (SCS1.DeprecatedStringLiteralToCharPtr)
4003       Result = ImplicitConversionSequence::Indistinguishable;
4004     break;
4005
4006   case ImplicitConversionSequence::Indistinguishable:
4007     break;
4008
4009   case ImplicitConversionSequence::Worse:
4010     if (SCS2.DeprecatedStringLiteralToCharPtr)
4011       Result = ImplicitConversionSequence::Indistinguishable;
4012     break;
4013   }
4014
4015   return Result;
4016 }
4017
4018 /// CompareDerivedToBaseConversions - Compares two standard conversion
4019 /// sequences to determine whether they can be ranked based on their
4020 /// various kinds of derived-to-base conversions (C++
4021 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4022 /// conversions between Objective-C interface types.
4023 static ImplicitConversionSequence::CompareKind
4024 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4025                                 const StandardConversionSequence& SCS1,
4026                                 const StandardConversionSequence& SCS2) {
4027   QualType FromType1 = SCS1.getFromType();
4028   QualType ToType1 = SCS1.getToType(1);
4029   QualType FromType2 = SCS2.getFromType();
4030   QualType ToType2 = SCS2.getToType(1);
4031
4032   // Adjust the types we're converting from via the array-to-pointer
4033   // conversion, if we need to.
4034   if (SCS1.First == ICK_Array_To_Pointer)
4035     FromType1 = S.Context.getArrayDecayedType(FromType1);
4036   if (SCS2.First == ICK_Array_To_Pointer)
4037     FromType2 = S.Context.getArrayDecayedType(FromType2);
4038
4039   // Canonicalize all of the types.
4040   FromType1 = S.Context.getCanonicalType(FromType1);
4041   ToType1 = S.Context.getCanonicalType(ToType1);
4042   FromType2 = S.Context.getCanonicalType(FromType2);
4043   ToType2 = S.Context.getCanonicalType(ToType2);
4044
4045   // C++ [over.ics.rank]p4b3:
4046   //
4047   //   If class B is derived directly or indirectly from class A and
4048   //   class C is derived directly or indirectly from B,
4049   //
4050   // Compare based on pointer conversions.
4051   if (SCS1.Second == ICK_Pointer_Conversion &&
4052       SCS2.Second == ICK_Pointer_Conversion &&
4053       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4054       FromType1->isPointerType() && FromType2->isPointerType() &&
4055       ToType1->isPointerType() && ToType2->isPointerType()) {
4056     QualType FromPointee1
4057       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4058     QualType ToPointee1
4059       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4060     QualType FromPointee2
4061       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4062     QualType ToPointee2
4063       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4064
4065     //   -- conversion of C* to B* is better than conversion of C* to A*,
4066     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4067       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4068         return ImplicitConversionSequence::Better;
4069       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4070         return ImplicitConversionSequence::Worse;
4071     }
4072
4073     //   -- conversion of B* to A* is better than conversion of C* to A*,
4074     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4075       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4076         return ImplicitConversionSequence::Better;
4077       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4078         return ImplicitConversionSequence::Worse;
4079     }
4080   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4081              SCS2.Second == ICK_Pointer_Conversion) {
4082     const ObjCObjectPointerType *FromPtr1
4083       = FromType1->getAs<ObjCObjectPointerType>();
4084     const ObjCObjectPointerType *FromPtr2
4085       = FromType2->getAs<ObjCObjectPointerType>();
4086     const ObjCObjectPointerType *ToPtr1
4087       = ToType1->getAs<ObjCObjectPointerType>();
4088     const ObjCObjectPointerType *ToPtr2
4089       = ToType2->getAs<ObjCObjectPointerType>();
4090
4091     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4092       // Apply the same conversion ranking rules for Objective-C pointer types
4093       // that we do for C++ pointers to class types. However, we employ the
4094       // Objective-C pseudo-subtyping relationship used for assignment of
4095       // Objective-C pointer types.
4096       bool FromAssignLeft
4097         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4098       bool FromAssignRight
4099         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4100       bool ToAssignLeft
4101         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4102       bool ToAssignRight
4103         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4104
4105       // A conversion to an a non-id object pointer type or qualified 'id'
4106       // type is better than a conversion to 'id'.
4107       if (ToPtr1->isObjCIdType() &&
4108           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4109         return ImplicitConversionSequence::Worse;
4110       if (ToPtr2->isObjCIdType() &&
4111           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4112         return ImplicitConversionSequence::Better;
4113
4114       // A conversion to a non-id object pointer type is better than a
4115       // conversion to a qualified 'id' type
4116       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4117         return ImplicitConversionSequence::Worse;
4118       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4119         return ImplicitConversionSequence::Better;
4120
4121       // A conversion to an a non-Class object pointer type or qualified 'Class'
4122       // type is better than a conversion to 'Class'.
4123       if (ToPtr1->isObjCClassType() &&
4124           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4125         return ImplicitConversionSequence::Worse;
4126       if (ToPtr2->isObjCClassType() &&
4127           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4128         return ImplicitConversionSequence::Better;
4129
4130       // A conversion to a non-Class object pointer type is better than a
4131       // conversion to a qualified 'Class' type.
4132       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4133         return ImplicitConversionSequence::Worse;
4134       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4135         return ImplicitConversionSequence::Better;
4136
4137       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4138       if (S.Context.hasSameType(FromType1, FromType2) &&
4139           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4140           (ToAssignLeft != ToAssignRight)) {
4141         if (FromPtr1->isSpecialized()) {
4142           // "conversion of B<A> * to B * is better than conversion of B * to
4143           // C *.
4144           bool IsFirstSame =
4145               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4146           bool IsSecondSame =
4147               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4148           if (IsFirstSame) {
4149             if (!IsSecondSame)
4150               return ImplicitConversionSequence::Better;
4151           } else if (IsSecondSame)
4152             return ImplicitConversionSequence::Worse;
4153         }
4154         return ToAssignLeft? ImplicitConversionSequence::Worse
4155                            : ImplicitConversionSequence::Better;
4156       }
4157
4158       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4159       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4160           (FromAssignLeft != FromAssignRight))
4161         return FromAssignLeft? ImplicitConversionSequence::Better
4162         : ImplicitConversionSequence::Worse;
4163     }
4164   }
4165
4166   // Ranking of member-pointer types.
4167   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4168       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4169       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4170     const MemberPointerType * FromMemPointer1 =
4171                                         FromType1->getAs<MemberPointerType>();
4172     const MemberPointerType * ToMemPointer1 =
4173                                           ToType1->getAs<MemberPointerType>();
4174     const MemberPointerType * FromMemPointer2 =
4175                                           FromType2->getAs<MemberPointerType>();
4176     const MemberPointerType * ToMemPointer2 =
4177                                           ToType2->getAs<MemberPointerType>();
4178     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4179     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4180     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4181     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4182     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4183     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4184     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4185     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4186     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4187     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4188       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4189         return ImplicitConversionSequence::Worse;
4190       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4191         return ImplicitConversionSequence::Better;
4192     }
4193     // conversion of B::* to C::* is better than conversion of A::* to C::*
4194     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4195       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4196         return ImplicitConversionSequence::Better;
4197       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4198         return ImplicitConversionSequence::Worse;
4199     }
4200   }
4201
4202   if (SCS1.Second == ICK_Derived_To_Base) {
4203     //   -- conversion of C to B is better than conversion of C to A,
4204     //   -- binding of an expression of type C to a reference of type
4205     //      B& is better than binding an expression of type C to a
4206     //      reference of type A&,
4207     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4208         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4209       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4210         return ImplicitConversionSequence::Better;
4211       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4212         return ImplicitConversionSequence::Worse;
4213     }
4214
4215     //   -- conversion of B to A is better than conversion of C to A.
4216     //   -- binding of an expression of type B to a reference of type
4217     //      A& is better than binding an expression of type C to a
4218     //      reference of type A&,
4219     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4220         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4221       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4222         return ImplicitConversionSequence::Better;
4223       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4224         return ImplicitConversionSequence::Worse;
4225     }
4226   }
4227
4228   return ImplicitConversionSequence::Indistinguishable;
4229 }
4230
4231 /// Determine whether the given type is valid, e.g., it is not an invalid
4232 /// C++ class.
4233 static bool isTypeValid(QualType T) {
4234   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4235     return !Record->isInvalidDecl();
4236
4237   return true;
4238 }
4239
4240 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4241 /// determine whether they are reference-related,
4242 /// reference-compatible, reference-compatible with added
4243 /// qualification, or incompatible, for use in C++ initialization by
4244 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4245 /// type, and the first type (T1) is the pointee type of the reference
4246 /// type being initialized.
4247 Sema::ReferenceCompareResult
4248 Sema::CompareReferenceRelationship(SourceLocation Loc,
4249                                    QualType OrigT1, QualType OrigT2,
4250                                    bool &DerivedToBase,
4251                                    bool &ObjCConversion,
4252                                    bool &ObjCLifetimeConversion) {
4253   assert(!OrigT1->isReferenceType() &&
4254     "T1 must be the pointee type of the reference type");
4255   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4256
4257   QualType T1 = Context.getCanonicalType(OrigT1);
4258   QualType T2 = Context.getCanonicalType(OrigT2);
4259   Qualifiers T1Quals, T2Quals;
4260   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4261   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4262
4263   // C++ [dcl.init.ref]p4:
4264   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4265   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4266   //   T1 is a base class of T2.
4267   DerivedToBase = false;
4268   ObjCConversion = false;
4269   ObjCLifetimeConversion = false;
4270   QualType ConvertedT2;
4271   if (UnqualT1 == UnqualT2) {
4272     // Nothing to do.
4273   } else if (isCompleteType(Loc, OrigT2) &&
4274              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4275              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4276     DerivedToBase = true;
4277   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4278            UnqualT2->isObjCObjectOrInterfaceType() &&
4279            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4280     ObjCConversion = true;
4281   else if (UnqualT2->isFunctionType() &&
4282            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4283     // C++1z [dcl.init.ref]p4:
4284     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4285     //   function" and T1 is "function"
4286     //
4287     // We extend this to also apply to 'noreturn', so allow any function
4288     // conversion between function types.
4289     return Ref_Compatible;
4290   else
4291     return Ref_Incompatible;
4292
4293   // At this point, we know that T1 and T2 are reference-related (at
4294   // least).
4295
4296   // If the type is an array type, promote the element qualifiers to the type
4297   // for comparison.
4298   if (isa<ArrayType>(T1) && T1Quals)
4299     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4300   if (isa<ArrayType>(T2) && T2Quals)
4301     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4302
4303   // C++ [dcl.init.ref]p4:
4304   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4305   //   reference-related to T2 and cv1 is the same cv-qualification
4306   //   as, or greater cv-qualification than, cv2. For purposes of
4307   //   overload resolution, cases for which cv1 is greater
4308   //   cv-qualification than cv2 are identified as
4309   //   reference-compatible with added qualification (see 13.3.3.2).
4310   //
4311   // Note that we also require equivalence of Objective-C GC and address-space
4312   // qualifiers when performing these computations, so that e.g., an int in
4313   // address space 1 is not reference-compatible with an int in address
4314   // space 2.
4315   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4316       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4317     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4318       ObjCLifetimeConversion = true;
4319
4320     T1Quals.removeObjCLifetime();
4321     T2Quals.removeObjCLifetime();
4322   }
4323
4324   // MS compiler ignores __unaligned qualifier for references; do the same.
4325   T1Quals.removeUnaligned();
4326   T2Quals.removeUnaligned();
4327
4328   if (T1Quals.compatiblyIncludes(T2Quals))
4329     return Ref_Compatible;
4330   else
4331     return Ref_Related;
4332 }
4333
4334 /// Look for a user-defined conversion to a value reference-compatible
4335 ///        with DeclType. Return true if something definite is found.
4336 static bool
4337 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4338                          QualType DeclType, SourceLocation DeclLoc,
4339                          Expr *Init, QualType T2, bool AllowRvalues,
4340                          bool AllowExplicit) {
4341   assert(T2->isRecordType() && "Can only find conversions of record types.");
4342   CXXRecordDecl *T2RecordDecl
4343     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4344
4345   OverloadCandidateSet CandidateSet(
4346       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4347   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4348   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4349     NamedDecl *D = *I;
4350     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4351     if (isa<UsingShadowDecl>(D))
4352       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4353
4354     FunctionTemplateDecl *ConvTemplate
4355       = dyn_cast<FunctionTemplateDecl>(D);
4356     CXXConversionDecl *Conv;
4357     if (ConvTemplate)
4358       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4359     else
4360       Conv = cast<CXXConversionDecl>(D);
4361
4362     // If this is an explicit conversion, and we're not allowed to consider
4363     // explicit conversions, skip it.
4364     if (!AllowExplicit && Conv->isExplicit())
4365       continue;
4366
4367     if (AllowRvalues) {
4368       bool DerivedToBase = false;
4369       bool ObjCConversion = false;
4370       bool ObjCLifetimeConversion = false;
4371
4372       // If we are initializing an rvalue reference, don't permit conversion
4373       // functions that return lvalues.
4374       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4375         const ReferenceType *RefType
4376           = Conv->getConversionType()->getAs<LValueReferenceType>();
4377         if (RefType && !RefType->getPointeeType()->isFunctionType())
4378           continue;
4379       }
4380
4381       if (!ConvTemplate &&
4382           S.CompareReferenceRelationship(
4383             DeclLoc,
4384             Conv->getConversionType().getNonReferenceType()
4385               .getUnqualifiedType(),
4386             DeclType.getNonReferenceType().getUnqualifiedType(),
4387             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4388           Sema::Ref_Incompatible)
4389         continue;
4390     } else {
4391       // If the conversion function doesn't return a reference type,
4392       // it can't be considered for this conversion. An rvalue reference
4393       // is only acceptable if its referencee is a function type.
4394
4395       const ReferenceType *RefType =
4396         Conv->getConversionType()->getAs<ReferenceType>();
4397       if (!RefType ||
4398           (!RefType->isLValueReferenceType() &&
4399            !RefType->getPointeeType()->isFunctionType()))
4400         continue;
4401     }
4402
4403     if (ConvTemplate)
4404       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4405                                        Init, DeclType, CandidateSet,
4406                                        /*AllowObjCConversionOnExplicit=*/false);
4407     else
4408       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4409                                DeclType, CandidateSet,
4410                                /*AllowObjCConversionOnExplicit=*/false);
4411   }
4412
4413   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4414
4415   OverloadCandidateSet::iterator Best;
4416   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4417   case OR_Success:
4418     // C++ [over.ics.ref]p1:
4419     //
4420     //   [...] If the parameter binds directly to the result of
4421     //   applying a conversion function to the argument
4422     //   expression, the implicit conversion sequence is a
4423     //   user-defined conversion sequence (13.3.3.1.2), with the
4424     //   second standard conversion sequence either an identity
4425     //   conversion or, if the conversion function returns an
4426     //   entity of a type that is a derived class of the parameter
4427     //   type, a derived-to-base Conversion.
4428     if (!Best->FinalConversion.DirectBinding)
4429       return false;
4430
4431     ICS.setUserDefined();
4432     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4433     ICS.UserDefined.After = Best->FinalConversion;
4434     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4435     ICS.UserDefined.ConversionFunction = Best->Function;
4436     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4437     ICS.UserDefined.EllipsisConversion = false;
4438     assert(ICS.UserDefined.After.ReferenceBinding &&
4439            ICS.UserDefined.After.DirectBinding &&
4440            "Expected a direct reference binding!");
4441     return true;
4442
4443   case OR_Ambiguous:
4444     ICS.setAmbiguous();
4445     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4446          Cand != CandidateSet.end(); ++Cand)
4447       if (Cand->Viable)
4448         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4449     return true;
4450
4451   case OR_No_Viable_Function:
4452   case OR_Deleted:
4453     // There was no suitable conversion, or we found a deleted
4454     // conversion; continue with other checks.
4455     return false;
4456   }
4457
4458   llvm_unreachable("Invalid OverloadResult!");
4459 }
4460
4461 /// Compute an implicit conversion sequence for reference
4462 /// initialization.
4463 static ImplicitConversionSequence
4464 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4465                  SourceLocation DeclLoc,
4466                  bool SuppressUserConversions,
4467                  bool AllowExplicit) {
4468   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4469
4470   // Most paths end in a failed conversion.
4471   ImplicitConversionSequence ICS;
4472   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4473
4474   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4475   QualType T2 = Init->getType();
4476
4477   // If the initializer is the address of an overloaded function, try
4478   // to resolve the overloaded function. If all goes well, T2 is the
4479   // type of the resulting function.
4480   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4481     DeclAccessPair Found;
4482     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4483                                                                 false, Found))
4484       T2 = Fn->getType();
4485   }
4486
4487   // Compute some basic properties of the types and the initializer.
4488   bool isRValRef = DeclType->isRValueReferenceType();
4489   bool DerivedToBase = false;
4490   bool ObjCConversion = false;
4491   bool ObjCLifetimeConversion = false;
4492   Expr::Classification InitCategory = Init->Classify(S.Context);
4493   Sema::ReferenceCompareResult RefRelationship
4494     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4495                                      ObjCConversion, ObjCLifetimeConversion);
4496
4497
4498   // C++0x [dcl.init.ref]p5:
4499   //   A reference to type "cv1 T1" is initialized by an expression
4500   //   of type "cv2 T2" as follows:
4501
4502   //     -- If reference is an lvalue reference and the initializer expression
4503   if (!isRValRef) {
4504     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4505     //        reference-compatible with "cv2 T2," or
4506     //
4507     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4508     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4509       // C++ [over.ics.ref]p1:
4510       //   When a parameter of reference type binds directly (8.5.3)
4511       //   to an argument expression, the implicit conversion sequence
4512       //   is the identity conversion, unless the argument expression
4513       //   has a type that is a derived class of the parameter type,
4514       //   in which case the implicit conversion sequence is a
4515       //   derived-to-base Conversion (13.3.3.1).
4516       ICS.setStandard();
4517       ICS.Standard.First = ICK_Identity;
4518       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4519                          : ObjCConversion? ICK_Compatible_Conversion
4520                          : ICK_Identity;
4521       ICS.Standard.Third = ICK_Identity;
4522       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4523       ICS.Standard.setToType(0, T2);
4524       ICS.Standard.setToType(1, T1);
4525       ICS.Standard.setToType(2, T1);
4526       ICS.Standard.ReferenceBinding = true;
4527       ICS.Standard.DirectBinding = true;
4528       ICS.Standard.IsLvalueReference = !isRValRef;
4529       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4530       ICS.Standard.BindsToRvalue = false;
4531       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4532       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4533       ICS.Standard.CopyConstructor = nullptr;
4534       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4535
4536       // Nothing more to do: the inaccessibility/ambiguity check for
4537       // derived-to-base conversions is suppressed when we're
4538       // computing the implicit conversion sequence (C++
4539       // [over.best.ics]p2).
4540       return ICS;
4541     }
4542
4543     //       -- has a class type (i.e., T2 is a class type), where T1 is
4544     //          not reference-related to T2, and can be implicitly
4545     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4546     //          is reference-compatible with "cv3 T3" 92) (this
4547     //          conversion is selected by enumerating the applicable
4548     //          conversion functions (13.3.1.6) and choosing the best
4549     //          one through overload resolution (13.3)),
4550     if (!SuppressUserConversions && T2->isRecordType() &&
4551         S.isCompleteType(DeclLoc, T2) &&
4552         RefRelationship == Sema::Ref_Incompatible) {
4553       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4554                                    Init, T2, /*AllowRvalues=*/false,
4555                                    AllowExplicit))
4556         return ICS;
4557     }
4558   }
4559
4560   //     -- Otherwise, the reference shall be an lvalue reference to a
4561   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4562   //        shall be an rvalue reference.
4563   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4564     return ICS;
4565
4566   //       -- If the initializer expression
4567   //
4568   //            -- is an xvalue, class prvalue, array prvalue or function
4569   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4570   if (RefRelationship == Sema::Ref_Compatible &&
4571       (InitCategory.isXValue() ||
4572        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4573        (InitCategory.isLValue() && T2->isFunctionType()))) {
4574     ICS.setStandard();
4575     ICS.Standard.First = ICK_Identity;
4576     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4577                       : ObjCConversion? ICK_Compatible_Conversion
4578                       : ICK_Identity;
4579     ICS.Standard.Third = ICK_Identity;
4580     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4581     ICS.Standard.setToType(0, T2);
4582     ICS.Standard.setToType(1, T1);
4583     ICS.Standard.setToType(2, T1);
4584     ICS.Standard.ReferenceBinding = true;
4585     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4586     // binding unless we're binding to a class prvalue.
4587     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4588     // allow the use of rvalue references in C++98/03 for the benefit of
4589     // standard library implementors; therefore, we need the xvalue check here.
4590     ICS.Standard.DirectBinding =
4591       S.getLangOpts().CPlusPlus11 ||
4592       !(InitCategory.isPRValue() || T2->isRecordType());
4593     ICS.Standard.IsLvalueReference = !isRValRef;
4594     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4595     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4596     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4597     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4598     ICS.Standard.CopyConstructor = nullptr;
4599     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4600     return ICS;
4601   }
4602
4603   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4604   //               reference-related to T2, and can be implicitly converted to
4605   //               an xvalue, class prvalue, or function lvalue of type
4606   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4607   //               "cv3 T3",
4608   //
4609   //          then the reference is bound to the value of the initializer
4610   //          expression in the first case and to the result of the conversion
4611   //          in the second case (or, in either case, to an appropriate base
4612   //          class subobject).
4613   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4614       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4615       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4616                                Init, T2, /*AllowRvalues=*/true,
4617                                AllowExplicit)) {
4618     // In the second case, if the reference is an rvalue reference
4619     // and the second standard conversion sequence of the
4620     // user-defined conversion sequence includes an lvalue-to-rvalue
4621     // conversion, the program is ill-formed.
4622     if (ICS.isUserDefined() && isRValRef &&
4623         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4624       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4625
4626     return ICS;
4627   }
4628
4629   // A temporary of function type cannot be created; don't even try.
4630   if (T1->isFunctionType())
4631     return ICS;
4632
4633   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4634   //          initialized from the initializer expression using the
4635   //          rules for a non-reference copy initialization (8.5). The
4636   //          reference is then bound to the temporary. If T1 is
4637   //          reference-related to T2, cv1 must be the same
4638   //          cv-qualification as, or greater cv-qualification than,
4639   //          cv2; otherwise, the program is ill-formed.
4640   if (RefRelationship == Sema::Ref_Related) {
4641     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4642     // we would be reference-compatible or reference-compatible with
4643     // added qualification. But that wasn't the case, so the reference
4644     // initialization fails.
4645     //
4646     // Note that we only want to check address spaces and cvr-qualifiers here.
4647     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4648     Qualifiers T1Quals = T1.getQualifiers();
4649     Qualifiers T2Quals = T2.getQualifiers();
4650     T1Quals.removeObjCGCAttr();
4651     T1Quals.removeObjCLifetime();
4652     T2Quals.removeObjCGCAttr();
4653     T2Quals.removeObjCLifetime();
4654     // MS compiler ignores __unaligned qualifier for references; do the same.
4655     T1Quals.removeUnaligned();
4656     T2Quals.removeUnaligned();
4657     if (!T1Quals.compatiblyIncludes(T2Quals))
4658       return ICS;
4659   }
4660
4661   // If at least one of the types is a class type, the types are not
4662   // related, and we aren't allowed any user conversions, the
4663   // reference binding fails. This case is important for breaking
4664   // recursion, since TryImplicitConversion below will attempt to
4665   // create a temporary through the use of a copy constructor.
4666   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4667       (T1->isRecordType() || T2->isRecordType()))
4668     return ICS;
4669
4670   // If T1 is reference-related to T2 and the reference is an rvalue
4671   // reference, the initializer expression shall not be an lvalue.
4672   if (RefRelationship >= Sema::Ref_Related &&
4673       isRValRef && Init->Classify(S.Context).isLValue())
4674     return ICS;
4675
4676   // C++ [over.ics.ref]p2:
4677   //   When a parameter of reference type is not bound directly to
4678   //   an argument expression, the conversion sequence is the one
4679   //   required to convert the argument expression to the
4680   //   underlying type of the reference according to
4681   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4682   //   to copy-initializing a temporary of the underlying type with
4683   //   the argument expression. Any difference in top-level
4684   //   cv-qualification is subsumed by the initialization itself
4685   //   and does not constitute a conversion.
4686   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4687                               /*AllowExplicit=*/false,
4688                               /*InOverloadResolution=*/false,
4689                               /*CStyle=*/false,
4690                               /*AllowObjCWritebackConversion=*/false,
4691                               /*AllowObjCConversionOnExplicit=*/false);
4692
4693   // Of course, that's still a reference binding.
4694   if (ICS.isStandard()) {
4695     ICS.Standard.ReferenceBinding = true;
4696     ICS.Standard.IsLvalueReference = !isRValRef;
4697     ICS.Standard.BindsToFunctionLvalue = false;
4698     ICS.Standard.BindsToRvalue = true;
4699     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4700     ICS.Standard.ObjCLifetimeConversionBinding = false;
4701   } else if (ICS.isUserDefined()) {
4702     const ReferenceType *LValRefType =
4703         ICS.UserDefined.ConversionFunction->getReturnType()
4704             ->getAs<LValueReferenceType>();
4705
4706     // C++ [over.ics.ref]p3:
4707     //   Except for an implicit object parameter, for which see 13.3.1, a
4708     //   standard conversion sequence cannot be formed if it requires [...]
4709     //   binding an rvalue reference to an lvalue other than a function
4710     //   lvalue.
4711     // Note that the function case is not possible here.
4712     if (DeclType->isRValueReferenceType() && LValRefType) {
4713       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4714       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4715       // reference to an rvalue!
4716       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4717       return ICS;
4718     }
4719
4720     ICS.UserDefined.After.ReferenceBinding = true;
4721     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4722     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4723     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4724     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4725     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4726   }
4727
4728   return ICS;
4729 }
4730
4731 static ImplicitConversionSequence
4732 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4733                       bool SuppressUserConversions,
4734                       bool InOverloadResolution,
4735                       bool AllowObjCWritebackConversion,
4736                       bool AllowExplicit = false);
4737
4738 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4739 /// initializer list From.
4740 static ImplicitConversionSequence
4741 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4742                   bool SuppressUserConversions,
4743                   bool InOverloadResolution,
4744                   bool AllowObjCWritebackConversion) {
4745   // C++11 [over.ics.list]p1:
4746   //   When an argument is an initializer list, it is not an expression and
4747   //   special rules apply for converting it to a parameter type.
4748
4749   ImplicitConversionSequence Result;
4750   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4751
4752   // We need a complete type for what follows. Incomplete types can never be
4753   // initialized from init lists.
4754   if (!S.isCompleteType(From->getLocStart(), ToType))
4755     return Result;
4756
4757   // Per DR1467:
4758   //   If the parameter type is a class X and the initializer list has a single
4759   //   element of type cv U, where U is X or a class derived from X, the
4760   //   implicit conversion sequence is the one required to convert the element
4761   //   to the parameter type.
4762   //
4763   //   Otherwise, if the parameter type is a character array [... ]
4764   //   and the initializer list has a single element that is an
4765   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4766   //   implicit conversion sequence is the identity conversion.
4767   if (From->getNumInits() == 1) {
4768     if (ToType->isRecordType()) {
4769       QualType InitType = From->getInit(0)->getType();
4770       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4771           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4772         return TryCopyInitialization(S, From->getInit(0), ToType,
4773                                      SuppressUserConversions,
4774                                      InOverloadResolution,
4775                                      AllowObjCWritebackConversion);
4776     }
4777     // FIXME: Check the other conditions here: array of character type,
4778     // initializer is a string literal.
4779     if (ToType->isArrayType()) {
4780       InitializedEntity Entity =
4781         InitializedEntity::InitializeParameter(S.Context, ToType,
4782                                                /*Consumed=*/false);
4783       if (S.CanPerformCopyInitialization(Entity, From)) {
4784         Result.setStandard();
4785         Result.Standard.setAsIdentityConversion();
4786         Result.Standard.setFromType(ToType);
4787         Result.Standard.setAllToTypes(ToType);
4788         return Result;
4789       }
4790     }
4791   }
4792
4793   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4794   // C++11 [over.ics.list]p2:
4795   //   If the parameter type is std::initializer_list<X> or "array of X" and
4796   //   all the elements can be implicitly converted to X, the implicit
4797   //   conversion sequence is the worst conversion necessary to convert an
4798   //   element of the list to X.
4799   //
4800   // C++14 [over.ics.list]p3:
4801   //   Otherwise, if the parameter type is "array of N X", if the initializer
4802   //   list has exactly N elements or if it has fewer than N elements and X is
4803   //   default-constructible, and if all the elements of the initializer list
4804   //   can be implicitly converted to X, the implicit conversion sequence is
4805   //   the worst conversion necessary to convert an element of the list to X.
4806   //
4807   // FIXME: We're missing a lot of these checks.
4808   bool toStdInitializerList = false;
4809   QualType X;
4810   if (ToType->isArrayType())
4811     X = S.Context.getAsArrayType(ToType)->getElementType();
4812   else
4813     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4814   if (!X.isNull()) {
4815     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4816       Expr *Init = From->getInit(i);
4817       ImplicitConversionSequence ICS =
4818           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4819                                 InOverloadResolution,
4820                                 AllowObjCWritebackConversion);
4821       // If a single element isn't convertible, fail.
4822       if (ICS.isBad()) {
4823         Result = ICS;
4824         break;
4825       }
4826       // Otherwise, look for the worst conversion.
4827       if (Result.isBad() ||
4828           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4829                                              Result) ==
4830               ImplicitConversionSequence::Worse)
4831         Result = ICS;
4832     }
4833
4834     // For an empty list, we won't have computed any conversion sequence.
4835     // Introduce the identity conversion sequence.
4836     if (From->getNumInits() == 0) {
4837       Result.setStandard();
4838       Result.Standard.setAsIdentityConversion();
4839       Result.Standard.setFromType(ToType);
4840       Result.Standard.setAllToTypes(ToType);
4841     }
4842
4843     Result.setStdInitializerListElement(toStdInitializerList);
4844     return Result;
4845   }
4846
4847   // C++14 [over.ics.list]p4:
4848   // C++11 [over.ics.list]p3:
4849   //   Otherwise, if the parameter is a non-aggregate class X and overload
4850   //   resolution chooses a single best constructor [...] the implicit
4851   //   conversion sequence is a user-defined conversion sequence. If multiple
4852   //   constructors are viable but none is better than the others, the
4853   //   implicit conversion sequence is a user-defined conversion sequence.
4854   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4855     // This function can deal with initializer lists.
4856     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4857                                     /*AllowExplicit=*/false,
4858                                     InOverloadResolution, /*CStyle=*/false,
4859                                     AllowObjCWritebackConversion,
4860                                     /*AllowObjCConversionOnExplicit=*/false);
4861   }
4862
4863   // C++14 [over.ics.list]p5:
4864   // C++11 [over.ics.list]p4:
4865   //   Otherwise, if the parameter has an aggregate type which can be
4866   //   initialized from the initializer list [...] the implicit conversion
4867   //   sequence is a user-defined conversion sequence.
4868   if (ToType->isAggregateType()) {
4869     // Type is an aggregate, argument is an init list. At this point it comes
4870     // down to checking whether the initialization works.
4871     // FIXME: Find out whether this parameter is consumed or not.
4872     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4873     // need to call into the initialization code here; overload resolution
4874     // should not be doing that.
4875     InitializedEntity Entity =
4876         InitializedEntity::InitializeParameter(S.Context, ToType,
4877                                                /*Consumed=*/false);
4878     if (S.CanPerformCopyInitialization(Entity, From)) {
4879       Result.setUserDefined();
4880       Result.UserDefined.Before.setAsIdentityConversion();
4881       // Initializer lists don't have a type.
4882       Result.UserDefined.Before.setFromType(QualType());
4883       Result.UserDefined.Before.setAllToTypes(QualType());
4884
4885       Result.UserDefined.After.setAsIdentityConversion();
4886       Result.UserDefined.After.setFromType(ToType);
4887       Result.UserDefined.After.setAllToTypes(ToType);
4888       Result.UserDefined.ConversionFunction = nullptr;
4889     }
4890     return Result;
4891   }
4892
4893   // C++14 [over.ics.list]p6:
4894   // C++11 [over.ics.list]p5:
4895   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4896   if (ToType->isReferenceType()) {
4897     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4898     // mention initializer lists in any way. So we go by what list-
4899     // initialization would do and try to extrapolate from that.
4900
4901     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4902
4903     // If the initializer list has a single element that is reference-related
4904     // to the parameter type, we initialize the reference from that.
4905     if (From->getNumInits() == 1) {
4906       Expr *Init = From->getInit(0);
4907
4908       QualType T2 = Init->getType();
4909
4910       // If the initializer is the address of an overloaded function, try
4911       // to resolve the overloaded function. If all goes well, T2 is the
4912       // type of the resulting function.
4913       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4914         DeclAccessPair Found;
4915         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4916                                    Init, ToType, false, Found))
4917           T2 = Fn->getType();
4918       }
4919
4920       // Compute some basic properties of the types and the initializer.
4921       bool dummy1 = false;
4922       bool dummy2 = false;
4923       bool dummy3 = false;
4924       Sema::ReferenceCompareResult RefRelationship
4925         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4926                                          dummy2, dummy3);
4927
4928       if (RefRelationship >= Sema::Ref_Related) {
4929         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4930                                 SuppressUserConversions,
4931                                 /*AllowExplicit=*/false);
4932       }
4933     }
4934
4935     // Otherwise, we bind the reference to a temporary created from the
4936     // initializer list.
4937     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4938                                InOverloadResolution,
4939                                AllowObjCWritebackConversion);
4940     if (Result.isFailure())
4941       return Result;
4942     assert(!Result.isEllipsis() &&
4943            "Sub-initialization cannot result in ellipsis conversion.");
4944
4945     // Can we even bind to a temporary?
4946     if (ToType->isRValueReferenceType() ||
4947         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4948       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4949                                             Result.UserDefined.After;
4950       SCS.ReferenceBinding = true;
4951       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4952       SCS.BindsToRvalue = true;
4953       SCS.BindsToFunctionLvalue = false;
4954       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4955       SCS.ObjCLifetimeConversionBinding = false;
4956     } else
4957       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4958                     From, ToType);
4959     return Result;
4960   }
4961
4962   // C++14 [over.ics.list]p7:
4963   // C++11 [over.ics.list]p6:
4964   //   Otherwise, if the parameter type is not a class:
4965   if (!ToType->isRecordType()) {
4966     //    - if the initializer list has one element that is not itself an
4967     //      initializer list, the implicit conversion sequence is the one
4968     //      required to convert the element to the parameter type.
4969     unsigned NumInits = From->getNumInits();
4970     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4971       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4972                                      SuppressUserConversions,
4973                                      InOverloadResolution,
4974                                      AllowObjCWritebackConversion);
4975     //    - if the initializer list has no elements, the implicit conversion
4976     //      sequence is the identity conversion.
4977     else if (NumInits == 0) {
4978       Result.setStandard();
4979       Result.Standard.setAsIdentityConversion();
4980       Result.Standard.setFromType(ToType);
4981       Result.Standard.setAllToTypes(ToType);
4982     }
4983     return Result;
4984   }
4985
4986   // C++14 [over.ics.list]p8:
4987   // C++11 [over.ics.list]p7:
4988   //   In all cases other than those enumerated above, no conversion is possible
4989   return Result;
4990 }
4991
4992 /// TryCopyInitialization - Try to copy-initialize a value of type
4993 /// ToType from the expression From. Return the implicit conversion
4994 /// sequence required to pass this argument, which may be a bad
4995 /// conversion sequence (meaning that the argument cannot be passed to
4996 /// a parameter of this type). If @p SuppressUserConversions, then we
4997 /// do not permit any user-defined conversion sequences.
4998 static ImplicitConversionSequence
4999 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5000                       bool SuppressUserConversions,
5001                       bool InOverloadResolution,
5002                       bool AllowObjCWritebackConversion,
5003                       bool AllowExplicit) {
5004   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5005     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5006                              InOverloadResolution,AllowObjCWritebackConversion);
5007
5008   if (ToType->isReferenceType())
5009     return TryReferenceInit(S, From, ToType,
5010                             /*FIXME:*/From->getLocStart(),
5011                             SuppressUserConversions,
5012                             AllowExplicit);
5013
5014   return TryImplicitConversion(S, From, ToType,
5015                                SuppressUserConversions,
5016                                /*AllowExplicit=*/false,
5017                                InOverloadResolution,
5018                                /*CStyle=*/false,
5019                                AllowObjCWritebackConversion,
5020                                /*AllowObjCConversionOnExplicit=*/false);
5021 }
5022
5023 static bool TryCopyInitialization(const CanQualType FromQTy,
5024                                   const CanQualType ToQTy,
5025                                   Sema &S,
5026                                   SourceLocation Loc,
5027                                   ExprValueKind FromVK) {
5028   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5029   ImplicitConversionSequence ICS =
5030     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5031
5032   return !ICS.isBad();
5033 }
5034
5035 /// TryObjectArgumentInitialization - Try to initialize the object
5036 /// parameter of the given member function (@c Method) from the
5037 /// expression @p From.
5038 static ImplicitConversionSequence
5039 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5040                                 Expr::Classification FromClassification,
5041                                 CXXMethodDecl *Method,
5042                                 CXXRecordDecl *ActingContext) {
5043   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5044   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5045   //                 const volatile object.
5046   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5047     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5048   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5049
5050   // Set up the conversion sequence as a "bad" conversion, to allow us
5051   // to exit early.
5052   ImplicitConversionSequence ICS;
5053
5054   // We need to have an object of class type.
5055   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5056     FromType = PT->getPointeeType();
5057
5058     // When we had a pointer, it's implicitly dereferenced, so we
5059     // better have an lvalue.
5060     assert(FromClassification.isLValue());
5061   }
5062
5063   assert(FromType->isRecordType());
5064
5065   // C++0x [over.match.funcs]p4:
5066   //   For non-static member functions, the type of the implicit object
5067   //   parameter is
5068   //
5069   //     - "lvalue reference to cv X" for functions declared without a
5070   //        ref-qualifier or with the & ref-qualifier
5071   //     - "rvalue reference to cv X" for functions declared with the &&
5072   //        ref-qualifier
5073   //
5074   // where X is the class of which the function is a member and cv is the
5075   // cv-qualification on the member function declaration.
5076   //
5077   // However, when finding an implicit conversion sequence for the argument, we
5078   // are not allowed to perform user-defined conversions
5079   // (C++ [over.match.funcs]p5). We perform a simplified version of
5080   // reference binding here, that allows class rvalues to bind to
5081   // non-constant references.
5082
5083   // First check the qualifiers.
5084   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5085   if (ImplicitParamType.getCVRQualifiers()
5086                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5087       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5088     ICS.setBad(BadConversionSequence::bad_qualifiers,
5089                FromType, ImplicitParamType);
5090     return ICS;
5091   }
5092
5093   // Check that we have either the same type or a derived type. It
5094   // affects the conversion rank.
5095   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5096   ImplicitConversionKind SecondKind;
5097   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5098     SecondKind = ICK_Identity;
5099   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5100     SecondKind = ICK_Derived_To_Base;
5101   else {
5102     ICS.setBad(BadConversionSequence::unrelated_class,
5103                FromType, ImplicitParamType);
5104     return ICS;
5105   }
5106
5107   // Check the ref-qualifier.
5108   switch (Method->getRefQualifier()) {
5109   case RQ_None:
5110     // Do nothing; we don't care about lvalueness or rvalueness.
5111     break;
5112
5113   case RQ_LValue:
5114     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5115       // non-const lvalue reference cannot bind to an rvalue
5116       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5117                  ImplicitParamType);
5118       return ICS;
5119     }
5120     break;
5121
5122   case RQ_RValue:
5123     if (!FromClassification.isRValue()) {
5124       // rvalue reference cannot bind to an lvalue
5125       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5126                  ImplicitParamType);
5127       return ICS;
5128     }
5129     break;
5130   }
5131
5132   // Success. Mark this as a reference binding.
5133   ICS.setStandard();
5134   ICS.Standard.setAsIdentityConversion();
5135   ICS.Standard.Second = SecondKind;
5136   ICS.Standard.setFromType(FromType);
5137   ICS.Standard.setAllToTypes(ImplicitParamType);
5138   ICS.Standard.ReferenceBinding = true;
5139   ICS.Standard.DirectBinding = true;
5140   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5141   ICS.Standard.BindsToFunctionLvalue = false;
5142   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5143   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5144     = (Method->getRefQualifier() == RQ_None);
5145   return ICS;
5146 }
5147
5148 /// PerformObjectArgumentInitialization - Perform initialization of
5149 /// the implicit object parameter for the given Method with the given
5150 /// expression.
5151 ExprResult
5152 Sema::PerformObjectArgumentInitialization(Expr *From,
5153                                           NestedNameSpecifier *Qualifier,
5154                                           NamedDecl *FoundDecl,
5155                                           CXXMethodDecl *Method) {
5156   QualType FromRecordType, DestType;
5157   QualType ImplicitParamRecordType  =
5158     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5159
5160   Expr::Classification FromClassification;
5161   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5162     FromRecordType = PT->getPointeeType();
5163     DestType = Method->getThisType(Context);
5164     FromClassification = Expr::Classification::makeSimpleLValue();
5165   } else {
5166     FromRecordType = From->getType();
5167     DestType = ImplicitParamRecordType;
5168     FromClassification = From->Classify(Context);
5169
5170     // When performing member access on an rvalue, materialize a temporary.
5171     if (From->isRValue()) {
5172       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5173                                             Method->getRefQualifier() !=
5174                                                 RefQualifierKind::RQ_RValue);
5175     }
5176   }
5177
5178   // Note that we always use the true parent context when performing
5179   // the actual argument initialization.
5180   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5181       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5182       Method->getParent());
5183   if (ICS.isBad()) {
5184     switch (ICS.Bad.Kind) {
5185     case BadConversionSequence::bad_qualifiers: {
5186       Qualifiers FromQs = FromRecordType.getQualifiers();
5187       Qualifiers ToQs = DestType.getQualifiers();
5188       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5189       if (CVR) {
5190         Diag(From->getLocStart(),
5191              diag::err_member_function_call_bad_cvr)
5192           << Method->getDeclName() << FromRecordType << (CVR - 1)
5193           << From->getSourceRange();
5194         Diag(Method->getLocation(), diag::note_previous_decl)
5195           << Method->getDeclName();
5196         return ExprError();
5197       }
5198       break;
5199     }
5200
5201     case BadConversionSequence::lvalue_ref_to_rvalue:
5202     case BadConversionSequence::rvalue_ref_to_lvalue: {
5203       bool IsRValueQualified =
5204         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5205       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5206         << Method->getDeclName() << FromClassification.isRValue()
5207         << IsRValueQualified;
5208       Diag(Method->getLocation(), diag::note_previous_decl)
5209         << Method->getDeclName();
5210       return ExprError();
5211     }
5212
5213     case BadConversionSequence::no_conversion:
5214     case BadConversionSequence::unrelated_class:
5215       break;
5216     }
5217
5218     return Diag(From->getLocStart(),
5219                 diag::err_member_function_call_bad_type)
5220        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5221   }
5222
5223   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5224     ExprResult FromRes =
5225       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5226     if (FromRes.isInvalid())
5227       return ExprError();
5228     From = FromRes.get();
5229   }
5230
5231   if (!Context.hasSameType(From->getType(), DestType))
5232     From = ImpCastExprToType(From, DestType, CK_NoOp,
5233                              From->getValueKind()).get();
5234   return From;
5235 }
5236
5237 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5238 /// expression From to bool (C++0x [conv]p3).
5239 static ImplicitConversionSequence
5240 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5241   return TryImplicitConversion(S, From, S.Context.BoolTy,
5242                                /*SuppressUserConversions=*/false,
5243                                /*AllowExplicit=*/true,
5244                                /*InOverloadResolution=*/false,
5245                                /*CStyle=*/false,
5246                                /*AllowObjCWritebackConversion=*/false,
5247                                /*AllowObjCConversionOnExplicit=*/false);
5248 }
5249
5250 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5251 /// of the expression From to bool (C++0x [conv]p3).
5252 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5253   if (checkPlaceholderForOverload(*this, From))
5254     return ExprError();
5255
5256   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5257   if (!ICS.isBad())
5258     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5259
5260   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5261     return Diag(From->getLocStart(),
5262                 diag::err_typecheck_bool_condition)
5263                   << From->getType() << From->getSourceRange();
5264   return ExprError();
5265 }
5266
5267 /// Check that the specified conversion is permitted in a converted constant
5268 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5269 /// is acceptable.
5270 static bool CheckConvertedConstantConversions(Sema &S,
5271                                               StandardConversionSequence &SCS) {
5272   // Since we know that the target type is an integral or unscoped enumeration
5273   // type, most conversion kinds are impossible. All possible First and Third
5274   // conversions are fine.
5275   switch (SCS.Second) {
5276   case ICK_Identity:
5277   case ICK_Function_Conversion:
5278   case ICK_Integral_Promotion:
5279   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5280   case ICK_Zero_Queue_Conversion:
5281     return true;
5282
5283   case ICK_Boolean_Conversion:
5284     // Conversion from an integral or unscoped enumeration type to bool is
5285     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5286     // conversion, so we allow it in a converted constant expression.
5287     //
5288     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5289     // a lot of popular code. We should at least add a warning for this
5290     // (non-conforming) extension.
5291     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5292            SCS.getToType(2)->isBooleanType();
5293
5294   case ICK_Pointer_Conversion:
5295   case ICK_Pointer_Member:
5296     // C++1z: null pointer conversions and null member pointer conversions are
5297     // only permitted if the source type is std::nullptr_t.
5298     return SCS.getFromType()->isNullPtrType();
5299
5300   case ICK_Floating_Promotion:
5301   case ICK_Complex_Promotion:
5302   case ICK_Floating_Conversion:
5303   case ICK_Complex_Conversion:
5304   case ICK_Floating_Integral:
5305   case ICK_Compatible_Conversion:
5306   case ICK_Derived_To_Base:
5307   case ICK_Vector_Conversion:
5308   case ICK_Vector_Splat:
5309   case ICK_Complex_Real:
5310   case ICK_Block_Pointer_Conversion:
5311   case ICK_TransparentUnionConversion:
5312   case ICK_Writeback_Conversion:
5313   case ICK_Zero_Event_Conversion:
5314   case ICK_C_Only_Conversion:
5315   case ICK_Incompatible_Pointer_Conversion:
5316     return false;
5317
5318   case ICK_Lvalue_To_Rvalue:
5319   case ICK_Array_To_Pointer:
5320   case ICK_Function_To_Pointer:
5321     llvm_unreachable("found a first conversion kind in Second");
5322
5323   case ICK_Qualification:
5324     llvm_unreachable("found a third conversion kind in Second");
5325
5326   case ICK_Num_Conversion_Kinds:
5327     break;
5328   }
5329
5330   llvm_unreachable("unknown conversion kind");
5331 }
5332
5333 /// CheckConvertedConstantExpression - Check that the expression From is a
5334 /// converted constant expression of type T, perform the conversion and produce
5335 /// the converted expression, per C++11 [expr.const]p3.
5336 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5337                                                    QualType T, APValue &Value,
5338                                                    Sema::CCEKind CCE,
5339                                                    bool RequireInt) {
5340   assert(S.getLangOpts().CPlusPlus11 &&
5341          "converted constant expression outside C++11");
5342
5343   if (checkPlaceholderForOverload(S, From))
5344     return ExprError();
5345
5346   // C++1z [expr.const]p3:
5347   //  A converted constant expression of type T is an expression,
5348   //  implicitly converted to type T, where the converted
5349   //  expression is a constant expression and the implicit conversion
5350   //  sequence contains only [... list of conversions ...].
5351   // C++1z [stmt.if]p2:
5352   //  If the if statement is of the form if constexpr, the value of the
5353   //  condition shall be a contextually converted constant expression of type
5354   //  bool.
5355   ImplicitConversionSequence ICS =
5356       CCE == Sema::CCEK_ConstexprIf
5357           ? TryContextuallyConvertToBool(S, From)
5358           : TryCopyInitialization(S, From, T,
5359                                   /*SuppressUserConversions=*/false,
5360                                   /*InOverloadResolution=*/false,
5361                                   /*AllowObjcWritebackConversion=*/false,
5362                                   /*AllowExplicit=*/false);
5363   StandardConversionSequence *SCS = nullptr;
5364   switch (ICS.getKind()) {
5365   case ImplicitConversionSequence::StandardConversion:
5366     SCS = &ICS.Standard;
5367     break;
5368   case ImplicitConversionSequence::UserDefinedConversion:
5369     // We are converting to a non-class type, so the Before sequence
5370     // must be trivial.
5371     SCS = &ICS.UserDefined.After;
5372     break;
5373   case ImplicitConversionSequence::AmbiguousConversion:
5374   case ImplicitConversionSequence::BadConversion:
5375     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5376       return S.Diag(From->getLocStart(),
5377                     diag::err_typecheck_converted_constant_expression)
5378                 << From->getType() << From->getSourceRange() << T;
5379     return ExprError();
5380
5381   case ImplicitConversionSequence::EllipsisConversion:
5382     llvm_unreachable("ellipsis conversion in converted constant expression");
5383   }
5384
5385   // Check that we would only use permitted conversions.
5386   if (!CheckConvertedConstantConversions(S, *SCS)) {
5387     return S.Diag(From->getLocStart(),
5388                   diag::err_typecheck_converted_constant_expression_disallowed)
5389              << From->getType() << From->getSourceRange() << T;
5390   }
5391   // [...] and where the reference binding (if any) binds directly.
5392   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5393     return S.Diag(From->getLocStart(),
5394                   diag::err_typecheck_converted_constant_expression_indirect)
5395              << From->getType() << From->getSourceRange() << T;
5396   }
5397
5398   ExprResult Result =
5399       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5400   if (Result.isInvalid())
5401     return Result;
5402
5403   // Check for a narrowing implicit conversion.
5404   APValue PreNarrowingValue;
5405   QualType PreNarrowingType;
5406   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5407                                 PreNarrowingType)) {
5408   case NK_Dependent_Narrowing:
5409     // Implicit conversion to a narrower type, but the expression is
5410     // value-dependent so we can't tell whether it's actually narrowing.
5411   case NK_Variable_Narrowing:
5412     // Implicit conversion to a narrower type, and the value is not a constant
5413     // expression. We'll diagnose this in a moment.
5414   case NK_Not_Narrowing:
5415     break;
5416
5417   case NK_Constant_Narrowing:
5418     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5419       << CCE << /*Constant*/1
5420       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5421     break;
5422
5423   case NK_Type_Narrowing:
5424     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5425       << CCE << /*Constant*/0 << From->getType() << T;
5426     break;
5427   }
5428
5429   if (Result.get()->isValueDependent()) {
5430     Value = APValue();
5431     return Result;
5432   }
5433
5434   // Check the expression is a constant expression.
5435   SmallVector<PartialDiagnosticAt, 8> Notes;
5436   Expr::EvalResult Eval;
5437   Eval.Diag = &Notes;
5438   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5439                                    ? Expr::EvaluateForMangling
5440                                    : Expr::EvaluateForCodeGen;
5441
5442   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5443       (RequireInt && !Eval.Val.isInt())) {
5444     // The expression can't be folded, so we can't keep it at this position in
5445     // the AST.
5446     Result = ExprError();
5447   } else {
5448     Value = Eval.Val;
5449
5450     if (Notes.empty()) {
5451       // It's a constant expression.
5452       return Result;
5453     }
5454   }
5455
5456   // It's not a constant expression. Produce an appropriate diagnostic.
5457   if (Notes.size() == 1 &&
5458       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5459     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5460   else {
5461     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5462       << CCE << From->getSourceRange();
5463     for (unsigned I = 0; I < Notes.size(); ++I)
5464       S.Diag(Notes[I].first, Notes[I].second);
5465   }
5466   return ExprError();
5467 }
5468
5469 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5470                                                   APValue &Value, CCEKind CCE) {
5471   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5472 }
5473
5474 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5475                                                   llvm::APSInt &Value,
5476                                                   CCEKind CCE) {
5477   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5478
5479   APValue V;
5480   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5481   if (!R.isInvalid() && !R.get()->isValueDependent())
5482     Value = V.getInt();
5483   return R;
5484 }
5485
5486
5487 /// dropPointerConversions - If the given standard conversion sequence
5488 /// involves any pointer conversions, remove them.  This may change
5489 /// the result type of the conversion sequence.
5490 static void dropPointerConversion(StandardConversionSequence &SCS) {
5491   if (SCS.Second == ICK_Pointer_Conversion) {
5492     SCS.Second = ICK_Identity;
5493     SCS.Third = ICK_Identity;
5494     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5495   }
5496 }
5497
5498 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5499 /// convert the expression From to an Objective-C pointer type.
5500 static ImplicitConversionSequence
5501 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5502   // Do an implicit conversion to 'id'.
5503   QualType Ty = S.Context.getObjCIdType();
5504   ImplicitConversionSequence ICS
5505     = TryImplicitConversion(S, From, Ty,
5506                             // FIXME: Are these flags correct?
5507                             /*SuppressUserConversions=*/false,
5508                             /*AllowExplicit=*/true,
5509                             /*InOverloadResolution=*/false,
5510                             /*CStyle=*/false,
5511                             /*AllowObjCWritebackConversion=*/false,
5512                             /*AllowObjCConversionOnExplicit=*/true);
5513
5514   // Strip off any final conversions to 'id'.
5515   switch (ICS.getKind()) {
5516   case ImplicitConversionSequence::BadConversion:
5517   case ImplicitConversionSequence::AmbiguousConversion:
5518   case ImplicitConversionSequence::EllipsisConversion:
5519     break;
5520
5521   case ImplicitConversionSequence::UserDefinedConversion:
5522     dropPointerConversion(ICS.UserDefined.After);
5523     break;
5524
5525   case ImplicitConversionSequence::StandardConversion:
5526     dropPointerConversion(ICS.Standard);
5527     break;
5528   }
5529
5530   return ICS;
5531 }
5532
5533 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5534 /// conversion of the expression From to an Objective-C pointer type.
5535 /// Returns a valid but null ExprResult if no conversion sequence exists.
5536 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5537   if (checkPlaceholderForOverload(*this, From))
5538     return ExprError();
5539
5540   QualType Ty = Context.getObjCIdType();
5541   ImplicitConversionSequence ICS =
5542     TryContextuallyConvertToObjCPointer(*this, From);
5543   if (!ICS.isBad())
5544     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5545   return ExprResult();
5546 }
5547
5548 /// Determine whether the provided type is an integral type, or an enumeration
5549 /// type of a permitted flavor.
5550 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5551   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5552                                  : T->isIntegralOrUnscopedEnumerationType();
5553 }
5554
5555 static ExprResult
5556 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5557                             Sema::ContextualImplicitConverter &Converter,
5558                             QualType T, UnresolvedSetImpl &ViableConversions) {
5559
5560   if (Converter.Suppress)
5561     return ExprError();
5562
5563   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5564   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5565     CXXConversionDecl *Conv =
5566         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5567     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5568     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5569   }
5570   return From;
5571 }
5572
5573 static bool
5574 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5575                            Sema::ContextualImplicitConverter &Converter,
5576                            QualType T, bool HadMultipleCandidates,
5577                            UnresolvedSetImpl &ExplicitConversions) {
5578   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5579     DeclAccessPair Found = ExplicitConversions[0];
5580     CXXConversionDecl *Conversion =
5581         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5582
5583     // The user probably meant to invoke the given explicit
5584     // conversion; use it.
5585     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5586     std::string TypeStr;
5587     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5588
5589     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5590         << FixItHint::CreateInsertion(From->getLocStart(),
5591                                       "static_cast<" + TypeStr + ">(")
5592         << FixItHint::CreateInsertion(
5593                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5594     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5595
5596     // If we aren't in a SFINAE context, build a call to the
5597     // explicit conversion function.
5598     if (SemaRef.isSFINAEContext())
5599       return true;
5600
5601     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5602     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5603                                                        HadMultipleCandidates);
5604     if (Result.isInvalid())
5605       return true;
5606     // Record usage of conversion in an implicit cast.
5607     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5608                                     CK_UserDefinedConversion, Result.get(),
5609                                     nullptr, Result.get()->getValueKind());
5610   }
5611   return false;
5612 }
5613
5614 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5615                              Sema::ContextualImplicitConverter &Converter,
5616                              QualType T, bool HadMultipleCandidates,
5617                              DeclAccessPair &Found) {
5618   CXXConversionDecl *Conversion =
5619       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5620   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5621
5622   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5623   if (!Converter.SuppressConversion) {
5624     if (SemaRef.isSFINAEContext())
5625       return true;
5626
5627     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5628         << From->getSourceRange();
5629   }
5630
5631   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5632                                                      HadMultipleCandidates);
5633   if (Result.isInvalid())
5634     return true;
5635   // Record usage of conversion in an implicit cast.
5636   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5637                                   CK_UserDefinedConversion, Result.get(),
5638                                   nullptr, Result.get()->getValueKind());
5639   return false;
5640 }
5641
5642 static ExprResult finishContextualImplicitConversion(
5643     Sema &SemaRef, SourceLocation Loc, Expr *From,
5644     Sema::ContextualImplicitConverter &Converter) {
5645   if (!Converter.match(From->getType()) && !Converter.Suppress)
5646     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5647         << From->getSourceRange();
5648
5649   return SemaRef.DefaultLvalueConversion(From);
5650 }
5651
5652 static void
5653 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5654                                   UnresolvedSetImpl &ViableConversions,
5655                                   OverloadCandidateSet &CandidateSet) {
5656   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5657     DeclAccessPair FoundDecl = ViableConversions[I];
5658     NamedDecl *D = FoundDecl.getDecl();
5659     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5660     if (isa<UsingShadowDecl>(D))
5661       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5662
5663     CXXConversionDecl *Conv;
5664     FunctionTemplateDecl *ConvTemplate;
5665     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5666       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5667     else
5668       Conv = cast<CXXConversionDecl>(D);
5669
5670     if (ConvTemplate)
5671       SemaRef.AddTemplateConversionCandidate(
5672         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5673         /*AllowObjCConversionOnExplicit=*/false);
5674     else
5675       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5676                                      ToType, CandidateSet,
5677                                      /*AllowObjCConversionOnExplicit=*/false);
5678   }
5679 }
5680
5681 /// Attempt to convert the given expression to a type which is accepted
5682 /// by the given converter.
5683 ///
5684 /// This routine will attempt to convert an expression of class type to a
5685 /// type accepted by the specified converter. In C++11 and before, the class
5686 /// must have a single non-explicit conversion function converting to a matching
5687 /// type. In C++1y, there can be multiple such conversion functions, but only
5688 /// one target type.
5689 ///
5690 /// \param Loc The source location of the construct that requires the
5691 /// conversion.
5692 ///
5693 /// \param From The expression we're converting from.
5694 ///
5695 /// \param Converter Used to control and diagnose the conversion process.
5696 ///
5697 /// \returns The expression, converted to an integral or enumeration type if
5698 /// successful.
5699 ExprResult Sema::PerformContextualImplicitConversion(
5700     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5701   // We can't perform any more checking for type-dependent expressions.
5702   if (From->isTypeDependent())
5703     return From;
5704
5705   // Process placeholders immediately.
5706   if (From->hasPlaceholderType()) {
5707     ExprResult result = CheckPlaceholderExpr(From);
5708     if (result.isInvalid())
5709       return result;
5710     From = result.get();
5711   }
5712
5713   // If the expression already has a matching type, we're golden.
5714   QualType T = From->getType();
5715   if (Converter.match(T))
5716     return DefaultLvalueConversion(From);
5717
5718   // FIXME: Check for missing '()' if T is a function type?
5719
5720   // We can only perform contextual implicit conversions on objects of class
5721   // type.
5722   const RecordType *RecordTy = T->getAs<RecordType>();
5723   if (!RecordTy || !getLangOpts().CPlusPlus) {
5724     if (!Converter.Suppress)
5725       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5726     return From;
5727   }
5728
5729   // We must have a complete class type.
5730   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5731     ContextualImplicitConverter &Converter;
5732     Expr *From;
5733
5734     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5735         : Converter(Converter), From(From) {}
5736
5737     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5738       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5739     }
5740   } IncompleteDiagnoser(Converter, From);
5741
5742   if (Converter.Suppress ? !isCompleteType(Loc, T)
5743                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5744     return From;
5745
5746   // Look for a conversion to an integral or enumeration type.
5747   UnresolvedSet<4>
5748       ViableConversions; // These are *potentially* viable in C++1y.
5749   UnresolvedSet<4> ExplicitConversions;
5750   const auto &Conversions =
5751       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5752
5753   bool HadMultipleCandidates =
5754       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5755
5756   // To check that there is only one target type, in C++1y:
5757   QualType ToType;
5758   bool HasUniqueTargetType = true;
5759
5760   // Collect explicit or viable (potentially in C++1y) conversions.
5761   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5762     NamedDecl *D = (*I)->getUnderlyingDecl();
5763     CXXConversionDecl *Conversion;
5764     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5765     if (ConvTemplate) {
5766       if (getLangOpts().CPlusPlus14)
5767         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5768       else
5769         continue; // C++11 does not consider conversion operator templates(?).
5770     } else
5771       Conversion = cast<CXXConversionDecl>(D);
5772
5773     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5774            "Conversion operator templates are considered potentially "
5775            "viable in C++1y");
5776
5777     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5778     if (Converter.match(CurToType) || ConvTemplate) {
5779
5780       if (Conversion->isExplicit()) {
5781         // FIXME: For C++1y, do we need this restriction?
5782         // cf. diagnoseNoViableConversion()
5783         if (!ConvTemplate)
5784           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5785       } else {
5786         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5787           if (ToType.isNull())
5788             ToType = CurToType.getUnqualifiedType();
5789           else if (HasUniqueTargetType &&
5790                    (CurToType.getUnqualifiedType() != ToType))
5791             HasUniqueTargetType = false;
5792         }
5793         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5794       }
5795     }
5796   }
5797
5798   if (getLangOpts().CPlusPlus14) {
5799     // C++1y [conv]p6:
5800     // ... An expression e of class type E appearing in such a context
5801     // is said to be contextually implicitly converted to a specified
5802     // type T and is well-formed if and only if e can be implicitly
5803     // converted to a type T that is determined as follows: E is searched
5804     // for conversion functions whose return type is cv T or reference to
5805     // cv T such that T is allowed by the context. There shall be
5806     // exactly one such T.
5807
5808     // If no unique T is found:
5809     if (ToType.isNull()) {
5810       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5811                                      HadMultipleCandidates,
5812                                      ExplicitConversions))
5813         return ExprError();
5814       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5815     }
5816
5817     // If more than one unique Ts are found:
5818     if (!HasUniqueTargetType)
5819       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5820                                          ViableConversions);
5821
5822     // If one unique T is found:
5823     // First, build a candidate set from the previously recorded
5824     // potentially viable conversions.
5825     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5826     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5827                                       CandidateSet);
5828
5829     // Then, perform overload resolution over the candidate set.
5830     OverloadCandidateSet::iterator Best;
5831     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5832     case OR_Success: {
5833       // Apply this conversion.
5834       DeclAccessPair Found =
5835           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5836       if (recordConversion(*this, Loc, From, Converter, T,
5837                            HadMultipleCandidates, Found))
5838         return ExprError();
5839       break;
5840     }
5841     case OR_Ambiguous:
5842       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5843                                          ViableConversions);
5844     case OR_No_Viable_Function:
5845       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5846                                      HadMultipleCandidates,
5847                                      ExplicitConversions))
5848         return ExprError();
5849       LLVM_FALLTHROUGH;
5850     case OR_Deleted:
5851       // We'll complain below about a non-integral condition type.
5852       break;
5853     }
5854   } else {
5855     switch (ViableConversions.size()) {
5856     case 0: {
5857       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5858                                      HadMultipleCandidates,
5859                                      ExplicitConversions))
5860         return ExprError();
5861
5862       // We'll complain below about a non-integral condition type.
5863       break;
5864     }
5865     case 1: {
5866       // Apply this conversion.
5867       DeclAccessPair Found = ViableConversions[0];
5868       if (recordConversion(*this, Loc, From, Converter, T,
5869                            HadMultipleCandidates, Found))
5870         return ExprError();
5871       break;
5872     }
5873     default:
5874       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5875                                          ViableConversions);
5876     }
5877   }
5878
5879   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5880 }
5881
5882 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5883 /// an acceptable non-member overloaded operator for a call whose
5884 /// arguments have types T1 (and, if non-empty, T2). This routine
5885 /// implements the check in C++ [over.match.oper]p3b2 concerning
5886 /// enumeration types.
5887 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5888                                                    FunctionDecl *Fn,
5889                                                    ArrayRef<Expr *> Args) {
5890   QualType T1 = Args[0]->getType();
5891   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5892
5893   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5894     return true;
5895
5896   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5897     return true;
5898
5899   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5900   if (Proto->getNumParams() < 1)
5901     return false;
5902
5903   if (T1->isEnumeralType()) {
5904     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5905     if (Context.hasSameUnqualifiedType(T1, ArgType))
5906       return true;
5907   }
5908
5909   if (Proto->getNumParams() < 2)
5910     return false;
5911
5912   if (!T2.isNull() && T2->isEnumeralType()) {
5913     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5914     if (Context.hasSameUnqualifiedType(T2, ArgType))
5915       return true;
5916   }
5917
5918   return false;
5919 }
5920
5921 /// AddOverloadCandidate - Adds the given function to the set of
5922 /// candidate functions, using the given function call arguments.  If
5923 /// @p SuppressUserConversions, then don't allow user-defined
5924 /// conversions via constructors or conversion operators.
5925 ///
5926 /// \param PartialOverloading true if we are performing "partial" overloading
5927 /// based on an incomplete set of function arguments. This feature is used by
5928 /// code completion.
5929 void
5930 Sema::AddOverloadCandidate(FunctionDecl *Function,
5931                            DeclAccessPair FoundDecl,
5932                            ArrayRef<Expr *> Args,
5933                            OverloadCandidateSet &CandidateSet,
5934                            bool SuppressUserConversions,
5935                            bool PartialOverloading,
5936                            bool AllowExplicit,
5937                            ConversionSequenceList EarlyConversions) {
5938   const FunctionProtoType *Proto
5939     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5940   assert(Proto && "Functions without a prototype cannot be overloaded");
5941   assert(!Function->getDescribedFunctionTemplate() &&
5942          "Use AddTemplateOverloadCandidate for function templates");
5943
5944   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5945     if (!isa<CXXConstructorDecl>(Method)) {
5946       // If we get here, it's because we're calling a member function
5947       // that is named without a member access expression (e.g.,
5948       // "this->f") that was either written explicitly or created
5949       // implicitly. This can happen with a qualified call to a member
5950       // function, e.g., X::f(). We use an empty type for the implied
5951       // object argument (C++ [over.call.func]p3), and the acting context
5952       // is irrelevant.
5953       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5954                          Expr::Classification::makeSimpleLValue(), Args,
5955                          CandidateSet, SuppressUserConversions,
5956                          PartialOverloading, EarlyConversions);
5957       return;
5958     }
5959     // We treat a constructor like a non-member function, since its object
5960     // argument doesn't participate in overload resolution.
5961   }
5962
5963   if (!CandidateSet.isNewCandidate(Function))
5964     return;
5965
5966   // C++ [over.match.oper]p3:
5967   //   if no operand has a class type, only those non-member functions in the
5968   //   lookup set that have a first parameter of type T1 or "reference to
5969   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5970   //   is a right operand) a second parameter of type T2 or "reference to
5971   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5972   //   candidate functions.
5973   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5974       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5975     return;
5976
5977   // C++11 [class.copy]p11: [DR1402]
5978   //   A defaulted move constructor that is defined as deleted is ignored by
5979   //   overload resolution.
5980   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5981   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5982       Constructor->isMoveConstructor())
5983     return;
5984
5985   // Overload resolution is always an unevaluated context.
5986   EnterExpressionEvaluationContext Unevaluated(
5987       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5988
5989   // Add this candidate
5990   OverloadCandidate &Candidate =
5991       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5992   Candidate.FoundDecl = FoundDecl;
5993   Candidate.Function = Function;
5994   Candidate.Viable = true;
5995   Candidate.IsSurrogate = false;
5996   Candidate.IgnoreObjectArgument = false;
5997   Candidate.ExplicitCallArguments = Args.size();
5998
5999   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6000       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6001     Candidate.Viable = false;
6002     Candidate.FailureKind = ovl_non_default_multiversion_function;
6003     return;
6004   }
6005
6006   if (Constructor) {
6007     // C++ [class.copy]p3:
6008     //   A member function template is never instantiated to perform the copy
6009     //   of a class object to an object of its class type.
6010     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6011     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6012         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6013          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
6014                        ClassType))) {
6015       Candidate.Viable = false;
6016       Candidate.FailureKind = ovl_fail_illegal_constructor;
6017       return;
6018     }
6019
6020     // C++ [over.match.funcs]p8: (proposed DR resolution)
6021     //   A constructor inherited from class type C that has a first parameter
6022     //   of type "reference to P" (including such a constructor instantiated
6023     //   from a template) is excluded from the set of candidate functions when
6024     //   constructing an object of type cv D if the argument list has exactly
6025     //   one argument and D is reference-related to P and P is reference-related
6026     //   to C.
6027     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6028     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6029         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6030       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6031       QualType C = Context.getRecordType(Constructor->getParent());
6032       QualType D = Context.getRecordType(Shadow->getParent());
6033       SourceLocation Loc = Args.front()->getExprLoc();
6034       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6035           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6036         Candidate.Viable = false;
6037         Candidate.FailureKind = ovl_fail_inhctor_slice;
6038         return;
6039       }
6040     }
6041   }
6042
6043   unsigned NumParams = Proto->getNumParams();
6044
6045   // (C++ 13.3.2p2): A candidate function having fewer than m
6046   // parameters is viable only if it has an ellipsis in its parameter
6047   // list (8.3.5).
6048   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6049       !Proto->isVariadic()) {
6050     Candidate.Viable = false;
6051     Candidate.FailureKind = ovl_fail_too_many_arguments;
6052     return;
6053   }
6054
6055   // (C++ 13.3.2p2): A candidate function having more than m parameters
6056   // is viable only if the (m+1)st parameter has a default argument
6057   // (8.3.6). For the purposes of overload resolution, the
6058   // parameter list is truncated on the right, so that there are
6059   // exactly m parameters.
6060   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6061   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6062     // Not enough arguments.
6063     Candidate.Viable = false;
6064     Candidate.FailureKind = ovl_fail_too_few_arguments;
6065     return;
6066   }
6067
6068   // (CUDA B.1): Check for invalid calls between targets.
6069   if (getLangOpts().CUDA)
6070     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6071       // Skip the check for callers that are implicit members, because in this
6072       // case we may not yet know what the member's target is; the target is
6073       // inferred for the member automatically, based on the bases and fields of
6074       // the class.
6075       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6076         Candidate.Viable = false;
6077         Candidate.FailureKind = ovl_fail_bad_target;
6078         return;
6079       }
6080
6081   // Determine the implicit conversion sequences for each of the
6082   // arguments.
6083   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6084     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6085       // We already formed a conversion sequence for this parameter during
6086       // template argument deduction.
6087     } else if (ArgIdx < NumParams) {
6088       // (C++ 13.3.2p3): for F to be a viable function, there shall
6089       // exist for each argument an implicit conversion sequence
6090       // (13.3.3.1) that converts that argument to the corresponding
6091       // parameter of F.
6092       QualType ParamType = Proto->getParamType(ArgIdx);
6093       Candidate.Conversions[ArgIdx]
6094         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6095                                 SuppressUserConversions,
6096                                 /*InOverloadResolution=*/true,
6097                                 /*AllowObjCWritebackConversion=*/
6098                                   getLangOpts().ObjCAutoRefCount,
6099                                 AllowExplicit);
6100       if (Candidate.Conversions[ArgIdx].isBad()) {
6101         Candidate.Viable = false;
6102         Candidate.FailureKind = ovl_fail_bad_conversion;
6103         return;
6104       }
6105     } else {
6106       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6107       // argument for which there is no corresponding parameter is
6108       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6109       Candidate.Conversions[ArgIdx].setEllipsis();
6110     }
6111   }
6112
6113   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6114     Candidate.Viable = false;
6115     Candidate.FailureKind = ovl_fail_enable_if;
6116     Candidate.DeductionFailure.Data = FailedAttr;
6117     return;
6118   }
6119
6120   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6121     Candidate.Viable = false;
6122     Candidate.FailureKind = ovl_fail_ext_disabled;
6123     return;
6124   }
6125 }
6126
6127 ObjCMethodDecl *
6128 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6129                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6130   if (Methods.size() <= 1)
6131     return nullptr;
6132
6133   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6134     bool Match = true;
6135     ObjCMethodDecl *Method = Methods[b];
6136     unsigned NumNamedArgs = Sel.getNumArgs();
6137     // Method might have more arguments than selector indicates. This is due
6138     // to addition of c-style arguments in method.
6139     if (Method->param_size() > NumNamedArgs)
6140       NumNamedArgs = Method->param_size();
6141     if (Args.size() < NumNamedArgs)
6142       continue;
6143
6144     for (unsigned i = 0; i < NumNamedArgs; i++) {
6145       // We can't do any type-checking on a type-dependent argument.
6146       if (Args[i]->isTypeDependent()) {
6147         Match = false;
6148         break;
6149       }
6150
6151       ParmVarDecl *param = Method->parameters()[i];
6152       Expr *argExpr = Args[i];
6153       assert(argExpr && "SelectBestMethod(): missing expression");
6154
6155       // Strip the unbridged-cast placeholder expression off unless it's
6156       // a consumed argument.
6157       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6158           !param->hasAttr<CFConsumedAttr>())
6159         argExpr = stripARCUnbridgedCast(argExpr);
6160
6161       // If the parameter is __unknown_anytype, move on to the next method.
6162       if (param->getType() == Context.UnknownAnyTy) {
6163         Match = false;
6164         break;
6165       }
6166
6167       ImplicitConversionSequence ConversionState
6168         = TryCopyInitialization(*this, argExpr, param->getType(),
6169                                 /*SuppressUserConversions*/false,
6170                                 /*InOverloadResolution=*/true,
6171                                 /*AllowObjCWritebackConversion=*/
6172                                 getLangOpts().ObjCAutoRefCount,
6173                                 /*AllowExplicit*/false);
6174       // This function looks for a reasonably-exact match, so we consider
6175       // incompatible pointer conversions to be a failure here.
6176       if (ConversionState.isBad() ||
6177           (ConversionState.isStandard() &&
6178            ConversionState.Standard.Second ==
6179                ICK_Incompatible_Pointer_Conversion)) {
6180         Match = false;
6181         break;
6182       }
6183     }
6184     // Promote additional arguments to variadic methods.
6185     if (Match && Method->isVariadic()) {
6186       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6187         if (Args[i]->isTypeDependent()) {
6188           Match = false;
6189           break;
6190         }
6191         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6192                                                           nullptr);
6193         if (Arg.isInvalid()) {
6194           Match = false;
6195           break;
6196         }
6197       }
6198     } else {
6199       // Check for extra arguments to non-variadic methods.
6200       if (Args.size() != NumNamedArgs)
6201         Match = false;
6202       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6203         // Special case when selectors have no argument. In this case, select
6204         // one with the most general result type of 'id'.
6205         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6206           QualType ReturnT = Methods[b]->getReturnType();
6207           if (ReturnT->isObjCIdType())
6208             return Methods[b];
6209         }
6210       }
6211     }
6212
6213     if (Match)
6214       return Method;
6215   }
6216   return nullptr;
6217 }
6218
6219 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6220 // enable_if is order-sensitive. As a result, we need to reverse things
6221 // sometimes. Size of 4 elements is arbitrary.
6222 static SmallVector<EnableIfAttr *, 4>
6223 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6224   SmallVector<EnableIfAttr *, 4> Result;
6225   if (!Function->hasAttrs())
6226     return Result;
6227
6228   const auto &FuncAttrs = Function->getAttrs();
6229   for (Attr *Attr : FuncAttrs)
6230     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6231       Result.push_back(EnableIf);
6232
6233   std::reverse(Result.begin(), Result.end());
6234   return Result;
6235 }
6236
6237 static bool
6238 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6239                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6240                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6241                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6242   if (ThisArg) {
6243     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6244     assert(!isa<CXXConstructorDecl>(Method) &&
6245            "Shouldn't have `this` for ctors!");
6246     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6247     ExprResult R = S.PerformObjectArgumentInitialization(
6248         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6249     if (R.isInvalid())
6250       return false;
6251     ConvertedThis = R.get();
6252   } else {
6253     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6254       (void)MD;
6255       assert((MissingImplicitThis || MD->isStatic() ||
6256               isa<CXXConstructorDecl>(MD)) &&
6257              "Expected `this` for non-ctor instance methods");
6258     }
6259     ConvertedThis = nullptr;
6260   }
6261
6262   // Ignore any variadic arguments. Converting them is pointless, since the
6263   // user can't refer to them in the function condition.
6264   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6265
6266   // Convert the arguments.
6267   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6268     ExprResult R;
6269     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6270                                         S.Context, Function->getParamDecl(I)),
6271                                     SourceLocation(), Args[I]);
6272
6273     if (R.isInvalid())
6274       return false;
6275
6276     ConvertedArgs.push_back(R.get());
6277   }
6278
6279   if (Trap.hasErrorOccurred())
6280     return false;
6281
6282   // Push default arguments if needed.
6283   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6284     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6285       ParmVarDecl *P = Function->getParamDecl(i);
6286       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6287                          ? P->getUninstantiatedDefaultArg()
6288                          : P->getDefaultArg();
6289       // This can only happen in code completion, i.e. when PartialOverloading
6290       // is true.
6291       if (!DefArg)
6292         return false;
6293       ExprResult R =
6294           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6295                                           S.Context, Function->getParamDecl(i)),
6296                                       SourceLocation(), DefArg);
6297       if (R.isInvalid())
6298         return false;
6299       ConvertedArgs.push_back(R.get());
6300     }
6301
6302     if (Trap.hasErrorOccurred())
6303       return false;
6304   }
6305   return true;
6306 }
6307
6308 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6309                                   bool MissingImplicitThis) {
6310   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6311       getOrderedEnableIfAttrs(Function);
6312   if (EnableIfAttrs.empty())
6313     return nullptr;
6314
6315   SFINAETrap Trap(*this);
6316   SmallVector<Expr *, 16> ConvertedArgs;
6317   // FIXME: We should look into making enable_if late-parsed.
6318   Expr *DiscardedThis;
6319   if (!convertArgsForAvailabilityChecks(
6320           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6321           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6322     return EnableIfAttrs[0];
6323
6324   for (auto *EIA : EnableIfAttrs) {
6325     APValue Result;
6326     // FIXME: This doesn't consider value-dependent cases, because doing so is
6327     // very difficult. Ideally, we should handle them more gracefully.
6328     if (!EIA->getCond()->EvaluateWithSubstitution(
6329             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6330       return EIA;
6331
6332     if (!Result.isInt() || !Result.getInt().getBoolValue())
6333       return EIA;
6334   }
6335   return nullptr;
6336 }
6337
6338 template <typename CheckFn>
6339 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6340                                         bool ArgDependent, SourceLocation Loc,
6341                                         CheckFn &&IsSuccessful) {
6342   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6343   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6344     if (ArgDependent == DIA->getArgDependent())
6345       Attrs.push_back(DIA);
6346   }
6347
6348   // Common case: No diagnose_if attributes, so we can quit early.
6349   if (Attrs.empty())
6350     return false;
6351
6352   auto WarningBegin = std::stable_partition(
6353       Attrs.begin(), Attrs.end(),
6354       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6355
6356   // Note that diagnose_if attributes are late-parsed, so they appear in the
6357   // correct order (unlike enable_if attributes).
6358   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6359                                IsSuccessful);
6360   if (ErrAttr != WarningBegin) {
6361     const DiagnoseIfAttr *DIA = *ErrAttr;
6362     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6363     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6364         << DIA->getParent() << DIA->getCond()->getSourceRange();
6365     return true;
6366   }
6367
6368   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6369     if (IsSuccessful(DIA)) {
6370       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6371       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6372           << DIA->getParent() << DIA->getCond()->getSourceRange();
6373     }
6374
6375   return false;
6376 }
6377
6378 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6379                                                const Expr *ThisArg,
6380                                                ArrayRef<const Expr *> Args,
6381                                                SourceLocation Loc) {
6382   return diagnoseDiagnoseIfAttrsWith(
6383       *this, Function, /*ArgDependent=*/true, Loc,
6384       [&](const DiagnoseIfAttr *DIA) {
6385         APValue Result;
6386         // It's sane to use the same Args for any redecl of this function, since
6387         // EvaluateWithSubstitution only cares about the position of each
6388         // argument in the arg list, not the ParmVarDecl* it maps to.
6389         if (!DIA->getCond()->EvaluateWithSubstitution(
6390                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6391           return false;
6392         return Result.isInt() && Result.getInt().getBoolValue();
6393       });
6394 }
6395
6396 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6397                                                  SourceLocation Loc) {
6398   return diagnoseDiagnoseIfAttrsWith(
6399       *this, ND, /*ArgDependent=*/false, Loc,
6400       [&](const DiagnoseIfAttr *DIA) {
6401         bool Result;
6402         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6403                Result;
6404       });
6405 }
6406
6407 /// Add all of the function declarations in the given function set to
6408 /// the overload candidate set.
6409 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6410                                  ArrayRef<Expr *> Args,
6411                                  OverloadCandidateSet &CandidateSet,
6412                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6413                                  bool SuppressUserConversions,
6414                                  bool PartialOverloading,
6415                                  bool FirstArgumentIsBase) {
6416   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6417     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6418     ArrayRef<Expr *> FunctionArgs = Args;
6419
6420     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6421     FunctionDecl *FD =
6422         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6423
6424     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6425       QualType ObjectType;
6426       Expr::Classification ObjectClassification;
6427       if (Args.size() > 0) {
6428         if (Expr *E = Args[0]) {
6429           // Use the explicit base to restrict the lookup:
6430           ObjectType = E->getType();
6431           ObjectClassification = E->Classify(Context);
6432         } // .. else there is an implicit base.
6433         FunctionArgs = Args.slice(1);
6434       }
6435       if (FunTmpl) {
6436         AddMethodTemplateCandidate(
6437             FunTmpl, F.getPair(),
6438             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6439             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6440             FunctionArgs, CandidateSet, SuppressUserConversions,
6441             PartialOverloading);
6442       } else {
6443         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6444                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6445                            ObjectClassification, FunctionArgs, CandidateSet,
6446                            SuppressUserConversions, PartialOverloading);
6447       }
6448     } else {
6449       // This branch handles both standalone functions and static methods.
6450
6451       // Slice the first argument (which is the base) when we access
6452       // static method as non-static.
6453       if (Args.size() > 0 &&
6454           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6455                         !isa<CXXConstructorDecl>(FD)))) {
6456         assert(cast<CXXMethodDecl>(FD)->isStatic());
6457         FunctionArgs = Args.slice(1);
6458       }
6459       if (FunTmpl) {
6460         AddTemplateOverloadCandidate(
6461             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6462             CandidateSet, SuppressUserConversions, PartialOverloading);
6463       } else {
6464         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6465                              SuppressUserConversions, PartialOverloading);
6466       }
6467     }
6468   }
6469 }
6470
6471 /// AddMethodCandidate - Adds a named decl (which is some kind of
6472 /// method) as a method candidate to the given overload set.
6473 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6474                               QualType ObjectType,
6475                               Expr::Classification ObjectClassification,
6476                               ArrayRef<Expr *> Args,
6477                               OverloadCandidateSet& CandidateSet,
6478                               bool SuppressUserConversions) {
6479   NamedDecl *Decl = FoundDecl.getDecl();
6480   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6481
6482   if (isa<UsingShadowDecl>(Decl))
6483     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6484
6485   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6486     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6487            "Expected a member function template");
6488     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6489                                /*ExplicitArgs*/ nullptr, ObjectType,
6490                                ObjectClassification, Args, CandidateSet,
6491                                SuppressUserConversions);
6492   } else {
6493     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6494                        ObjectType, ObjectClassification, Args, CandidateSet,
6495                        SuppressUserConversions);
6496   }
6497 }
6498
6499 /// AddMethodCandidate - Adds the given C++ member function to the set
6500 /// of candidate functions, using the given function call arguments
6501 /// and the object argument (@c Object). For example, in a call
6502 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6503 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6504 /// allow user-defined conversions via constructors or conversion
6505 /// operators.
6506 void
6507 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6508                          CXXRecordDecl *ActingContext, QualType ObjectType,
6509                          Expr::Classification ObjectClassification,
6510                          ArrayRef<Expr *> Args,
6511                          OverloadCandidateSet &CandidateSet,
6512                          bool SuppressUserConversions,
6513                          bool PartialOverloading,
6514                          ConversionSequenceList EarlyConversions) {
6515   const FunctionProtoType *Proto
6516     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6517   assert(Proto && "Methods without a prototype cannot be overloaded");
6518   assert(!isa<CXXConstructorDecl>(Method) &&
6519          "Use AddOverloadCandidate for constructors");
6520
6521   if (!CandidateSet.isNewCandidate(Method))
6522     return;
6523
6524   // C++11 [class.copy]p23: [DR1402]
6525   //   A defaulted move assignment operator that is defined as deleted is
6526   //   ignored by overload resolution.
6527   if (Method->isDefaulted() && Method->isDeleted() &&
6528       Method->isMoveAssignmentOperator())
6529     return;
6530
6531   // Overload resolution is always an unevaluated context.
6532   EnterExpressionEvaluationContext Unevaluated(
6533       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6534
6535   // Add this candidate
6536   OverloadCandidate &Candidate =
6537       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6538   Candidate.FoundDecl = FoundDecl;
6539   Candidate.Function = Method;
6540   Candidate.IsSurrogate = false;
6541   Candidate.IgnoreObjectArgument = false;
6542   Candidate.ExplicitCallArguments = Args.size();
6543
6544   unsigned NumParams = Proto->getNumParams();
6545
6546   // (C++ 13.3.2p2): A candidate function having fewer than m
6547   // parameters is viable only if it has an ellipsis in its parameter
6548   // list (8.3.5).
6549   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6550       !Proto->isVariadic()) {
6551     Candidate.Viable = false;
6552     Candidate.FailureKind = ovl_fail_too_many_arguments;
6553     return;
6554   }
6555
6556   // (C++ 13.3.2p2): A candidate function having more than m parameters
6557   // is viable only if the (m+1)st parameter has a default argument
6558   // (8.3.6). For the purposes of overload resolution, the
6559   // parameter list is truncated on the right, so that there are
6560   // exactly m parameters.
6561   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6562   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6563     // Not enough arguments.
6564     Candidate.Viable = false;
6565     Candidate.FailureKind = ovl_fail_too_few_arguments;
6566     return;
6567   }
6568
6569   Candidate.Viable = true;
6570
6571   if (Method->isStatic() || ObjectType.isNull())
6572     // The implicit object argument is ignored.
6573     Candidate.IgnoreObjectArgument = true;
6574   else {
6575     // Determine the implicit conversion sequence for the object
6576     // parameter.
6577     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6578         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6579         Method, ActingContext);
6580     if (Candidate.Conversions[0].isBad()) {
6581       Candidate.Viable = false;
6582       Candidate.FailureKind = ovl_fail_bad_conversion;
6583       return;
6584     }
6585   }
6586
6587   // (CUDA B.1): Check for invalid calls between targets.
6588   if (getLangOpts().CUDA)
6589     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6590       if (!IsAllowedCUDACall(Caller, Method)) {
6591         Candidate.Viable = false;
6592         Candidate.FailureKind = ovl_fail_bad_target;
6593         return;
6594       }
6595
6596   // Determine the implicit conversion sequences for each of the
6597   // arguments.
6598   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6599     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6600       // We already formed a conversion sequence for this parameter during
6601       // template argument deduction.
6602     } else if (ArgIdx < NumParams) {
6603       // (C++ 13.3.2p3): for F to be a viable function, there shall
6604       // exist for each argument an implicit conversion sequence
6605       // (13.3.3.1) that converts that argument to the corresponding
6606       // parameter of F.
6607       QualType ParamType = Proto->getParamType(ArgIdx);
6608       Candidate.Conversions[ArgIdx + 1]
6609         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6610                                 SuppressUserConversions,
6611                                 /*InOverloadResolution=*/true,
6612                                 /*AllowObjCWritebackConversion=*/
6613                                   getLangOpts().ObjCAutoRefCount);
6614       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6615         Candidate.Viable = false;
6616         Candidate.FailureKind = ovl_fail_bad_conversion;
6617         return;
6618       }
6619     } else {
6620       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6621       // argument for which there is no corresponding parameter is
6622       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6623       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6624     }
6625   }
6626
6627   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6628     Candidate.Viable = false;
6629     Candidate.FailureKind = ovl_fail_enable_if;
6630     Candidate.DeductionFailure.Data = FailedAttr;
6631     return;
6632   }
6633
6634   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6635       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6636     Candidate.Viable = false;
6637     Candidate.FailureKind = ovl_non_default_multiversion_function;
6638   }
6639 }
6640
6641 /// Add a C++ member function template as a candidate to the candidate
6642 /// set, using template argument deduction to produce an appropriate member
6643 /// function template specialization.
6644 void
6645 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6646                                  DeclAccessPair FoundDecl,
6647                                  CXXRecordDecl *ActingContext,
6648                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6649                                  QualType ObjectType,
6650                                  Expr::Classification ObjectClassification,
6651                                  ArrayRef<Expr *> Args,
6652                                  OverloadCandidateSet& CandidateSet,
6653                                  bool SuppressUserConversions,
6654                                  bool PartialOverloading) {
6655   if (!CandidateSet.isNewCandidate(MethodTmpl))
6656     return;
6657
6658   // C++ [over.match.funcs]p7:
6659   //   In each case where a candidate is a function template, candidate
6660   //   function template specializations are generated using template argument
6661   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6662   //   candidate functions in the usual way.113) A given name can refer to one
6663   //   or more function templates and also to a set of overloaded non-template
6664   //   functions. In such a case, the candidate functions generated from each
6665   //   function template are combined with the set of non-template candidate
6666   //   functions.
6667   TemplateDeductionInfo Info(CandidateSet.getLocation());
6668   FunctionDecl *Specialization = nullptr;
6669   ConversionSequenceList Conversions;
6670   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6671           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6672           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6673             return CheckNonDependentConversions(
6674                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6675                 SuppressUserConversions, ActingContext, ObjectType,
6676                 ObjectClassification);
6677           })) {
6678     OverloadCandidate &Candidate =
6679         CandidateSet.addCandidate(Conversions.size(), Conversions);
6680     Candidate.FoundDecl = FoundDecl;
6681     Candidate.Function = MethodTmpl->getTemplatedDecl();
6682     Candidate.Viable = false;
6683     Candidate.IsSurrogate = false;
6684     Candidate.IgnoreObjectArgument =
6685         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6686         ObjectType.isNull();
6687     Candidate.ExplicitCallArguments = Args.size();
6688     if (Result == TDK_NonDependentConversionFailure)
6689       Candidate.FailureKind = ovl_fail_bad_conversion;
6690     else {
6691       Candidate.FailureKind = ovl_fail_bad_deduction;
6692       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6693                                                             Info);
6694     }
6695     return;
6696   }
6697
6698   // Add the function template specialization produced by template argument
6699   // deduction as a candidate.
6700   assert(Specialization && "Missing member function template specialization?");
6701   assert(isa<CXXMethodDecl>(Specialization) &&
6702          "Specialization is not a member function?");
6703   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6704                      ActingContext, ObjectType, ObjectClassification, Args,
6705                      CandidateSet, SuppressUserConversions, PartialOverloading,
6706                      Conversions);
6707 }
6708
6709 /// Add a C++ function template specialization as a candidate
6710 /// in the candidate set, using template argument deduction to produce
6711 /// an appropriate function template specialization.
6712 void
6713 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6714                                    DeclAccessPair FoundDecl,
6715                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6716                                    ArrayRef<Expr *> Args,
6717                                    OverloadCandidateSet& CandidateSet,
6718                                    bool SuppressUserConversions,
6719                                    bool PartialOverloading) {
6720   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6721     return;
6722
6723   // C++ [over.match.funcs]p7:
6724   //   In each case where a candidate is a function template, candidate
6725   //   function template specializations are generated using template argument
6726   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6727   //   candidate functions in the usual way.113) A given name can refer to one
6728   //   or more function templates and also to a set of overloaded non-template
6729   //   functions. In such a case, the candidate functions generated from each
6730   //   function template are combined with the set of non-template candidate
6731   //   functions.
6732   TemplateDeductionInfo Info(CandidateSet.getLocation());
6733   FunctionDecl *Specialization = nullptr;
6734   ConversionSequenceList Conversions;
6735   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6736           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6737           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6738             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6739                                                 Args, CandidateSet, Conversions,
6740                                                 SuppressUserConversions);
6741           })) {
6742     OverloadCandidate &Candidate =
6743         CandidateSet.addCandidate(Conversions.size(), Conversions);
6744     Candidate.FoundDecl = FoundDecl;
6745     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6746     Candidate.Viable = false;
6747     Candidate.IsSurrogate = false;
6748     // Ignore the object argument if there is one, since we don't have an object
6749     // type.
6750     Candidate.IgnoreObjectArgument =
6751         isa<CXXMethodDecl>(Candidate.Function) &&
6752         !isa<CXXConstructorDecl>(Candidate.Function);
6753     Candidate.ExplicitCallArguments = Args.size();
6754     if (Result == TDK_NonDependentConversionFailure)
6755       Candidate.FailureKind = ovl_fail_bad_conversion;
6756     else {
6757       Candidate.FailureKind = ovl_fail_bad_deduction;
6758       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6759                                                             Info);
6760     }
6761     return;
6762   }
6763
6764   // Add the function template specialization produced by template argument
6765   // deduction as a candidate.
6766   assert(Specialization && "Missing function template specialization?");
6767   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6768                        SuppressUserConversions, PartialOverloading,
6769                        /*AllowExplicit*/false, Conversions);
6770 }
6771
6772 /// Check that implicit conversion sequences can be formed for each argument
6773 /// whose corresponding parameter has a non-dependent type, per DR1391's
6774 /// [temp.deduct.call]p10.
6775 bool Sema::CheckNonDependentConversions(
6776     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6777     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6778     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6779     CXXRecordDecl *ActingContext, QualType ObjectType,
6780     Expr::Classification ObjectClassification) {
6781   // FIXME: The cases in which we allow explicit conversions for constructor
6782   // arguments never consider calling a constructor template. It's not clear
6783   // that is correct.
6784   const bool AllowExplicit = false;
6785
6786   auto *FD = FunctionTemplate->getTemplatedDecl();
6787   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6788   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6789   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6790
6791   Conversions =
6792       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6793
6794   // Overload resolution is always an unevaluated context.
6795   EnterExpressionEvaluationContext Unevaluated(
6796       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6797
6798   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6799   // require that, but this check should never result in a hard error, and
6800   // overload resolution is permitted to sidestep instantiations.
6801   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6802       !ObjectType.isNull()) {
6803     Conversions[0] = TryObjectArgumentInitialization(
6804         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6805         Method, ActingContext);
6806     if (Conversions[0].isBad())
6807       return true;
6808   }
6809
6810   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6811        ++I) {
6812     QualType ParamType = ParamTypes[I];
6813     if (!ParamType->isDependentType()) {
6814       Conversions[ThisConversions + I]
6815         = TryCopyInitialization(*this, Args[I], ParamType,
6816                                 SuppressUserConversions,
6817                                 /*InOverloadResolution=*/true,
6818                                 /*AllowObjCWritebackConversion=*/
6819                                   getLangOpts().ObjCAutoRefCount,
6820                                 AllowExplicit);
6821       if (Conversions[ThisConversions + I].isBad())
6822         return true;
6823     }
6824   }
6825
6826   return false;
6827 }
6828
6829 /// Determine whether this is an allowable conversion from the result
6830 /// of an explicit conversion operator to the expected type, per C++
6831 /// [over.match.conv]p1 and [over.match.ref]p1.
6832 ///
6833 /// \param ConvType The return type of the conversion function.
6834 ///
6835 /// \param ToType The type we are converting to.
6836 ///
6837 /// \param AllowObjCPointerConversion Allow a conversion from one
6838 /// Objective-C pointer to another.
6839 ///
6840 /// \returns true if the conversion is allowable, false otherwise.
6841 static bool isAllowableExplicitConversion(Sema &S,
6842                                           QualType ConvType, QualType ToType,
6843                                           bool AllowObjCPointerConversion) {
6844   QualType ToNonRefType = ToType.getNonReferenceType();
6845
6846   // Easy case: the types are the same.
6847   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6848     return true;
6849
6850   // Allow qualification conversions.
6851   bool ObjCLifetimeConversion;
6852   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6853                                   ObjCLifetimeConversion))
6854     return true;
6855
6856   // If we're not allowed to consider Objective-C pointer conversions,
6857   // we're done.
6858   if (!AllowObjCPointerConversion)
6859     return false;
6860
6861   // Is this an Objective-C pointer conversion?
6862   bool IncompatibleObjC = false;
6863   QualType ConvertedType;
6864   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6865                                    IncompatibleObjC);
6866 }
6867
6868 /// AddConversionCandidate - Add a C++ conversion function as a
6869 /// candidate in the candidate set (C++ [over.match.conv],
6870 /// C++ [over.match.copy]). From is the expression we're converting from,
6871 /// and ToType is the type that we're eventually trying to convert to
6872 /// (which may or may not be the same type as the type that the
6873 /// conversion function produces).
6874 void
6875 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6876                              DeclAccessPair FoundDecl,
6877                              CXXRecordDecl *ActingContext,
6878                              Expr *From, QualType ToType,
6879                              OverloadCandidateSet& CandidateSet,
6880                              bool AllowObjCConversionOnExplicit,
6881                              bool AllowResultConversion) {
6882   assert(!Conversion->getDescribedFunctionTemplate() &&
6883          "Conversion function templates use AddTemplateConversionCandidate");
6884   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6885   if (!CandidateSet.isNewCandidate(Conversion))
6886     return;
6887
6888   // If the conversion function has an undeduced return type, trigger its
6889   // deduction now.
6890   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6891     if (DeduceReturnType(Conversion, From->getExprLoc()))
6892       return;
6893     ConvType = Conversion->getConversionType().getNonReferenceType();
6894   }
6895
6896   // If we don't allow any conversion of the result type, ignore conversion
6897   // functions that don't convert to exactly (possibly cv-qualified) T.
6898   if (!AllowResultConversion &&
6899       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6900     return;
6901
6902   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6903   // operator is only a candidate if its return type is the target type or
6904   // can be converted to the target type with a qualification conversion.
6905   if (Conversion->isExplicit() &&
6906       !isAllowableExplicitConversion(*this, ConvType, ToType,
6907                                      AllowObjCConversionOnExplicit))
6908     return;
6909
6910   // Overload resolution is always an unevaluated context.
6911   EnterExpressionEvaluationContext Unevaluated(
6912       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6913
6914   // Add this candidate
6915   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6916   Candidate.FoundDecl = FoundDecl;
6917   Candidate.Function = Conversion;
6918   Candidate.IsSurrogate = false;
6919   Candidate.IgnoreObjectArgument = false;
6920   Candidate.FinalConversion.setAsIdentityConversion();
6921   Candidate.FinalConversion.setFromType(ConvType);
6922   Candidate.FinalConversion.setAllToTypes(ToType);
6923   Candidate.Viable = true;
6924   Candidate.ExplicitCallArguments = 1;
6925
6926   // C++ [over.match.funcs]p4:
6927   //   For conversion functions, the function is considered to be a member of
6928   //   the class of the implicit implied object argument for the purpose of
6929   //   defining the type of the implicit object parameter.
6930   //
6931   // Determine the implicit conversion sequence for the implicit
6932   // object parameter.
6933   QualType ImplicitParamType = From->getType();
6934   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6935     ImplicitParamType = FromPtrType->getPointeeType();
6936   CXXRecordDecl *ConversionContext
6937     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6938
6939   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6940       *this, CandidateSet.getLocation(), From->getType(),
6941       From->Classify(Context), Conversion, ConversionContext);
6942
6943   if (Candidate.Conversions[0].isBad()) {
6944     Candidate.Viable = false;
6945     Candidate.FailureKind = ovl_fail_bad_conversion;
6946     return;
6947   }
6948
6949   // We won't go through a user-defined type conversion function to convert a
6950   // derived to base as such conversions are given Conversion Rank. They only
6951   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6952   QualType FromCanon
6953     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6954   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6955   if (FromCanon == ToCanon ||
6956       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6957     Candidate.Viable = false;
6958     Candidate.FailureKind = ovl_fail_trivial_conversion;
6959     return;
6960   }
6961
6962   // To determine what the conversion from the result of calling the
6963   // conversion function to the type we're eventually trying to
6964   // convert to (ToType), we need to synthesize a call to the
6965   // conversion function and attempt copy initialization from it. This
6966   // makes sure that we get the right semantics with respect to
6967   // lvalues/rvalues and the type. Fortunately, we can allocate this
6968   // call on the stack and we don't need its arguments to be
6969   // well-formed.
6970   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6971                             VK_LValue, From->getLocStart());
6972   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6973                                 Context.getPointerType(Conversion->getType()),
6974                                 CK_FunctionToPointerDecay,
6975                                 &ConversionRef, VK_RValue);
6976
6977   QualType ConversionType = Conversion->getConversionType();
6978   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6979     Candidate.Viable = false;
6980     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6981     return;
6982   }
6983
6984   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6985
6986   // Note that it is safe to allocate CallExpr on the stack here because
6987   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6988   // allocator).
6989   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6990   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6991                 From->getLocStart());
6992   ImplicitConversionSequence ICS =
6993     TryCopyInitialization(*this, &Call, ToType,
6994                           /*SuppressUserConversions=*/true,
6995                           /*InOverloadResolution=*/false,
6996                           /*AllowObjCWritebackConversion=*/false);
6997
6998   switch (ICS.getKind()) {
6999   case ImplicitConversionSequence::StandardConversion:
7000     Candidate.FinalConversion = ICS.Standard;
7001
7002     // C++ [over.ics.user]p3:
7003     //   If the user-defined conversion is specified by a specialization of a
7004     //   conversion function template, the second standard conversion sequence
7005     //   shall have exact match rank.
7006     if (Conversion->getPrimaryTemplate() &&
7007         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7008       Candidate.Viable = false;
7009       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7010       return;
7011     }
7012
7013     // C++0x [dcl.init.ref]p5:
7014     //    In the second case, if the reference is an rvalue reference and
7015     //    the second standard conversion sequence of the user-defined
7016     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7017     //    program is ill-formed.
7018     if (ToType->isRValueReferenceType() &&
7019         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7020       Candidate.Viable = false;
7021       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7022       return;
7023     }
7024     break;
7025
7026   case ImplicitConversionSequence::BadConversion:
7027     Candidate.Viable = false;
7028     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7029     return;
7030
7031   default:
7032     llvm_unreachable(
7033            "Can only end up with a standard conversion sequence or failure");
7034   }
7035
7036   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7037     Candidate.Viable = false;
7038     Candidate.FailureKind = ovl_fail_enable_if;
7039     Candidate.DeductionFailure.Data = FailedAttr;
7040     return;
7041   }
7042
7043   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7044       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7045     Candidate.Viable = false;
7046     Candidate.FailureKind = ovl_non_default_multiversion_function;
7047   }
7048 }
7049
7050 /// Adds a conversion function template specialization
7051 /// candidate to the overload set, using template argument deduction
7052 /// to deduce the template arguments of the conversion function
7053 /// template from the type that we are converting to (C++
7054 /// [temp.deduct.conv]).
7055 void
7056 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7057                                      DeclAccessPair FoundDecl,
7058                                      CXXRecordDecl *ActingDC,
7059                                      Expr *From, QualType ToType,
7060                                      OverloadCandidateSet &CandidateSet,
7061                                      bool AllowObjCConversionOnExplicit,
7062                                      bool AllowResultConversion) {
7063   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7064          "Only conversion function templates permitted here");
7065
7066   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7067     return;
7068
7069   TemplateDeductionInfo Info(CandidateSet.getLocation());
7070   CXXConversionDecl *Specialization = nullptr;
7071   if (TemplateDeductionResult Result
7072         = DeduceTemplateArguments(FunctionTemplate, ToType,
7073                                   Specialization, Info)) {
7074     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7075     Candidate.FoundDecl = FoundDecl;
7076     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7077     Candidate.Viable = false;
7078     Candidate.FailureKind = ovl_fail_bad_deduction;
7079     Candidate.IsSurrogate = false;
7080     Candidate.IgnoreObjectArgument = false;
7081     Candidate.ExplicitCallArguments = 1;
7082     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7083                                                           Info);
7084     return;
7085   }
7086
7087   // Add the conversion function template specialization produced by
7088   // template argument deduction as a candidate.
7089   assert(Specialization && "Missing function template specialization?");
7090   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7091                          CandidateSet, AllowObjCConversionOnExplicit,
7092                          AllowResultConversion);
7093 }
7094
7095 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7096 /// converts the given @c Object to a function pointer via the
7097 /// conversion function @c Conversion, and then attempts to call it
7098 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7099 /// the type of function that we'll eventually be calling.
7100 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7101                                  DeclAccessPair FoundDecl,
7102                                  CXXRecordDecl *ActingContext,
7103                                  const FunctionProtoType *Proto,
7104                                  Expr *Object,
7105                                  ArrayRef<Expr *> Args,
7106                                  OverloadCandidateSet& CandidateSet) {
7107   if (!CandidateSet.isNewCandidate(Conversion))
7108     return;
7109
7110   // Overload resolution is always an unevaluated context.
7111   EnterExpressionEvaluationContext Unevaluated(
7112       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7113
7114   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7115   Candidate.FoundDecl = FoundDecl;
7116   Candidate.Function = nullptr;
7117   Candidate.Surrogate = Conversion;
7118   Candidate.Viable = true;
7119   Candidate.IsSurrogate = true;
7120   Candidate.IgnoreObjectArgument = false;
7121   Candidate.ExplicitCallArguments = Args.size();
7122
7123   // Determine the implicit conversion sequence for the implicit
7124   // object parameter.
7125   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7126       *this, CandidateSet.getLocation(), Object->getType(),
7127       Object->Classify(Context), Conversion, ActingContext);
7128   if (ObjectInit.isBad()) {
7129     Candidate.Viable = false;
7130     Candidate.FailureKind = ovl_fail_bad_conversion;
7131     Candidate.Conversions[0] = ObjectInit;
7132     return;
7133   }
7134
7135   // The first conversion is actually a user-defined conversion whose
7136   // first conversion is ObjectInit's standard conversion (which is
7137   // effectively a reference binding). Record it as such.
7138   Candidate.Conversions[0].setUserDefined();
7139   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7140   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7141   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7142   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7143   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7144   Candidate.Conversions[0].UserDefined.After
7145     = Candidate.Conversions[0].UserDefined.Before;
7146   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7147
7148   // Find the
7149   unsigned NumParams = Proto->getNumParams();
7150
7151   // (C++ 13.3.2p2): A candidate function having fewer than m
7152   // parameters is viable only if it has an ellipsis in its parameter
7153   // list (8.3.5).
7154   if (Args.size() > NumParams && !Proto->isVariadic()) {
7155     Candidate.Viable = false;
7156     Candidate.FailureKind = ovl_fail_too_many_arguments;
7157     return;
7158   }
7159
7160   // Function types don't have any default arguments, so just check if
7161   // we have enough arguments.
7162   if (Args.size() < NumParams) {
7163     // Not enough arguments.
7164     Candidate.Viable = false;
7165     Candidate.FailureKind = ovl_fail_too_few_arguments;
7166     return;
7167   }
7168
7169   // Determine the implicit conversion sequences for each of the
7170   // arguments.
7171   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7172     if (ArgIdx < NumParams) {
7173       // (C++ 13.3.2p3): for F to be a viable function, there shall
7174       // exist for each argument an implicit conversion sequence
7175       // (13.3.3.1) that converts that argument to the corresponding
7176       // parameter of F.
7177       QualType ParamType = Proto->getParamType(ArgIdx);
7178       Candidate.Conversions[ArgIdx + 1]
7179         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7180                                 /*SuppressUserConversions=*/false,
7181                                 /*InOverloadResolution=*/false,
7182                                 /*AllowObjCWritebackConversion=*/
7183                                   getLangOpts().ObjCAutoRefCount);
7184       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7185         Candidate.Viable = false;
7186         Candidate.FailureKind = ovl_fail_bad_conversion;
7187         return;
7188       }
7189     } else {
7190       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7191       // argument for which there is no corresponding parameter is
7192       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7193       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7194     }
7195   }
7196
7197   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7198     Candidate.Viable = false;
7199     Candidate.FailureKind = ovl_fail_enable_if;
7200     Candidate.DeductionFailure.Data = FailedAttr;
7201     return;
7202   }
7203 }
7204
7205 /// Add overload candidates for overloaded operators that are
7206 /// member functions.
7207 ///
7208 /// Add the overloaded operator candidates that are member functions
7209 /// for the operator Op that was used in an operator expression such
7210 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7211 /// CandidateSet will store the added overload candidates. (C++
7212 /// [over.match.oper]).
7213 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7214                                        SourceLocation OpLoc,
7215                                        ArrayRef<Expr *> Args,
7216                                        OverloadCandidateSet& CandidateSet,
7217                                        SourceRange OpRange) {
7218   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7219
7220   // C++ [over.match.oper]p3:
7221   //   For a unary operator @ with an operand of a type whose
7222   //   cv-unqualified version is T1, and for a binary operator @ with
7223   //   a left operand of a type whose cv-unqualified version is T1 and
7224   //   a right operand of a type whose cv-unqualified version is T2,
7225   //   three sets of candidate functions, designated member
7226   //   candidates, non-member candidates and built-in candidates, are
7227   //   constructed as follows:
7228   QualType T1 = Args[0]->getType();
7229
7230   //     -- If T1 is a complete class type or a class currently being
7231   //        defined, the set of member candidates is the result of the
7232   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7233   //        the set of member candidates is empty.
7234   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7235     // Complete the type if it can be completed.
7236     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7237       return;
7238     // If the type is neither complete nor being defined, bail out now.
7239     if (!T1Rec->getDecl()->getDefinition())
7240       return;
7241
7242     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7243     LookupQualifiedName(Operators, T1Rec->getDecl());
7244     Operators.suppressDiagnostics();
7245
7246     for (LookupResult::iterator Oper = Operators.begin(),
7247                              OperEnd = Operators.end();
7248          Oper != OperEnd;
7249          ++Oper)
7250       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7251                          Args[0]->Classify(Context), Args.slice(1),
7252                          CandidateSet, /*SuppressUserConversions=*/false);
7253   }
7254 }
7255
7256 /// AddBuiltinCandidate - Add a candidate for a built-in
7257 /// operator. ResultTy and ParamTys are the result and parameter types
7258 /// of the built-in candidate, respectively. Args and NumArgs are the
7259 /// arguments being passed to the candidate. IsAssignmentOperator
7260 /// should be true when this built-in candidate is an assignment
7261 /// operator. NumContextualBoolArguments is the number of arguments
7262 /// (at the beginning of the argument list) that will be contextually
7263 /// converted to bool.
7264 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7265                                OverloadCandidateSet& CandidateSet,
7266                                bool IsAssignmentOperator,
7267                                unsigned NumContextualBoolArguments) {
7268   // Overload resolution is always an unevaluated context.
7269   EnterExpressionEvaluationContext Unevaluated(
7270       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7271
7272   // Add this candidate
7273   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7274   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7275   Candidate.Function = nullptr;
7276   Candidate.IsSurrogate = false;
7277   Candidate.IgnoreObjectArgument = false;
7278   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7279
7280   // Determine the implicit conversion sequences for each of the
7281   // arguments.
7282   Candidate.Viable = true;
7283   Candidate.ExplicitCallArguments = Args.size();
7284   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7285     // C++ [over.match.oper]p4:
7286     //   For the built-in assignment operators, conversions of the
7287     //   left operand are restricted as follows:
7288     //     -- no temporaries are introduced to hold the left operand, and
7289     //     -- no user-defined conversions are applied to the left
7290     //        operand to achieve a type match with the left-most
7291     //        parameter of a built-in candidate.
7292     //
7293     // We block these conversions by turning off user-defined
7294     // conversions, since that is the only way that initialization of
7295     // a reference to a non-class type can occur from something that
7296     // is not of the same type.
7297     if (ArgIdx < NumContextualBoolArguments) {
7298       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7299              "Contextual conversion to bool requires bool type");
7300       Candidate.Conversions[ArgIdx]
7301         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7302     } else {
7303       Candidate.Conversions[ArgIdx]
7304         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7305                                 ArgIdx == 0 && IsAssignmentOperator,
7306                                 /*InOverloadResolution=*/false,
7307                                 /*AllowObjCWritebackConversion=*/
7308                                   getLangOpts().ObjCAutoRefCount);
7309     }
7310     if (Candidate.Conversions[ArgIdx].isBad()) {
7311       Candidate.Viable = false;
7312       Candidate.FailureKind = ovl_fail_bad_conversion;
7313       break;
7314     }
7315   }
7316 }
7317
7318 namespace {
7319
7320 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7321 /// candidate operator functions for built-in operators (C++
7322 /// [over.built]). The types are separated into pointer types and
7323 /// enumeration types.
7324 class BuiltinCandidateTypeSet  {
7325   /// TypeSet - A set of types.
7326   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7327                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7328
7329   /// PointerTypes - The set of pointer types that will be used in the
7330   /// built-in candidates.
7331   TypeSet PointerTypes;
7332
7333   /// MemberPointerTypes - The set of member pointer types that will be
7334   /// used in the built-in candidates.
7335   TypeSet MemberPointerTypes;
7336
7337   /// EnumerationTypes - The set of enumeration types that will be
7338   /// used in the built-in candidates.
7339   TypeSet EnumerationTypes;
7340
7341   /// The set of vector types that will be used in the built-in
7342   /// candidates.
7343   TypeSet VectorTypes;
7344
7345   /// A flag indicating non-record types are viable candidates
7346   bool HasNonRecordTypes;
7347
7348   /// A flag indicating whether either arithmetic or enumeration types
7349   /// were present in the candidate set.
7350   bool HasArithmeticOrEnumeralTypes;
7351
7352   /// A flag indicating whether the nullptr type was present in the
7353   /// candidate set.
7354   bool HasNullPtrType;
7355
7356   /// Sema - The semantic analysis instance where we are building the
7357   /// candidate type set.
7358   Sema &SemaRef;
7359
7360   /// Context - The AST context in which we will build the type sets.
7361   ASTContext &Context;
7362
7363   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7364                                                const Qualifiers &VisibleQuals);
7365   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7366
7367 public:
7368   /// iterator - Iterates through the types that are part of the set.
7369   typedef TypeSet::iterator iterator;
7370
7371   BuiltinCandidateTypeSet(Sema &SemaRef)
7372     : HasNonRecordTypes(false),
7373       HasArithmeticOrEnumeralTypes(false),
7374       HasNullPtrType(false),
7375       SemaRef(SemaRef),
7376       Context(SemaRef.Context) { }
7377
7378   void AddTypesConvertedFrom(QualType Ty,
7379                              SourceLocation Loc,
7380                              bool AllowUserConversions,
7381                              bool AllowExplicitConversions,
7382                              const Qualifiers &VisibleTypeConversionsQuals);
7383
7384   /// pointer_begin - First pointer type found;
7385   iterator pointer_begin() { return PointerTypes.begin(); }
7386
7387   /// pointer_end - Past the last pointer type found;
7388   iterator pointer_end() { return PointerTypes.end(); }
7389
7390   /// member_pointer_begin - First member pointer type found;
7391   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7392
7393   /// member_pointer_end - Past the last member pointer type found;
7394   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7395
7396   /// enumeration_begin - First enumeration type found;
7397   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7398
7399   /// enumeration_end - Past the last enumeration type found;
7400   iterator enumeration_end() { return EnumerationTypes.end(); }
7401
7402   iterator vector_begin() { return VectorTypes.begin(); }
7403   iterator vector_end() { return VectorTypes.end(); }
7404
7405   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7406   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7407   bool hasNullPtrType() const { return HasNullPtrType; }
7408 };
7409
7410 } // end anonymous namespace
7411
7412 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7413 /// the set of pointer types along with any more-qualified variants of
7414 /// that type. For example, if @p Ty is "int const *", this routine
7415 /// will add "int const *", "int const volatile *", "int const
7416 /// restrict *", and "int const volatile restrict *" to the set of
7417 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7418 /// false otherwise.
7419 ///
7420 /// FIXME: what to do about extended qualifiers?
7421 bool
7422 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7423                                              const Qualifiers &VisibleQuals) {
7424
7425   // Insert this type.
7426   if (!PointerTypes.insert(Ty))
7427     return false;
7428
7429   QualType PointeeTy;
7430   const PointerType *PointerTy = Ty->getAs<PointerType>();
7431   bool buildObjCPtr = false;
7432   if (!PointerTy) {
7433     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7434     PointeeTy = PTy->getPointeeType();
7435     buildObjCPtr = true;
7436   } else {
7437     PointeeTy = PointerTy->getPointeeType();
7438   }
7439
7440   // Don't add qualified variants of arrays. For one, they're not allowed
7441   // (the qualifier would sink to the element type), and for another, the
7442   // only overload situation where it matters is subscript or pointer +- int,
7443   // and those shouldn't have qualifier variants anyway.
7444   if (PointeeTy->isArrayType())
7445     return true;
7446
7447   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7448   bool hasVolatile = VisibleQuals.hasVolatile();
7449   bool hasRestrict = VisibleQuals.hasRestrict();
7450
7451   // Iterate through all strict supersets of BaseCVR.
7452   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7453     if ((CVR | BaseCVR) != CVR) continue;
7454     // Skip over volatile if no volatile found anywhere in the types.
7455     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7456
7457     // Skip over restrict if no restrict found anywhere in the types, or if
7458     // the type cannot be restrict-qualified.
7459     if ((CVR & Qualifiers::Restrict) &&
7460         (!hasRestrict ||
7461          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7462       continue;
7463
7464     // Build qualified pointee type.
7465     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7466
7467     // Build qualified pointer type.
7468     QualType QPointerTy;
7469     if (!buildObjCPtr)
7470       QPointerTy = Context.getPointerType(QPointeeTy);
7471     else
7472       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7473
7474     // Insert qualified pointer type.
7475     PointerTypes.insert(QPointerTy);
7476   }
7477
7478   return true;
7479 }
7480
7481 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7482 /// to the set of pointer types along with any more-qualified variants of
7483 /// that type. For example, if @p Ty is "int const *", this routine
7484 /// will add "int const *", "int const volatile *", "int const
7485 /// restrict *", and "int const volatile restrict *" to the set of
7486 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7487 /// false otherwise.
7488 ///
7489 /// FIXME: what to do about extended qualifiers?
7490 bool
7491 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7492     QualType Ty) {
7493   // Insert this type.
7494   if (!MemberPointerTypes.insert(Ty))
7495     return false;
7496
7497   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7498   assert(PointerTy && "type was not a member pointer type!");
7499
7500   QualType PointeeTy = PointerTy->getPointeeType();
7501   // Don't add qualified variants of arrays. For one, they're not allowed
7502   // (the qualifier would sink to the element type), and for another, the
7503   // only overload situation where it matters is subscript or pointer +- int,
7504   // and those shouldn't have qualifier variants anyway.
7505   if (PointeeTy->isArrayType())
7506     return true;
7507   const Type *ClassTy = PointerTy->getClass();
7508
7509   // Iterate through all strict supersets of the pointee type's CVR
7510   // qualifiers.
7511   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7512   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7513     if ((CVR | BaseCVR) != CVR) continue;
7514
7515     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7516     MemberPointerTypes.insert(
7517       Context.getMemberPointerType(QPointeeTy, ClassTy));
7518   }
7519
7520   return true;
7521 }
7522
7523 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7524 /// Ty can be implicit converted to the given set of @p Types. We're
7525 /// primarily interested in pointer types and enumeration types. We also
7526 /// take member pointer types, for the conditional operator.
7527 /// AllowUserConversions is true if we should look at the conversion
7528 /// functions of a class type, and AllowExplicitConversions if we
7529 /// should also include the explicit conversion functions of a class
7530 /// type.
7531 void
7532 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7533                                                SourceLocation Loc,
7534                                                bool AllowUserConversions,
7535                                                bool AllowExplicitConversions,
7536                                                const Qualifiers &VisibleQuals) {
7537   // Only deal with canonical types.
7538   Ty = Context.getCanonicalType(Ty);
7539
7540   // Look through reference types; they aren't part of the type of an
7541   // expression for the purposes of conversions.
7542   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7543     Ty = RefTy->getPointeeType();
7544
7545   // If we're dealing with an array type, decay to the pointer.
7546   if (Ty->isArrayType())
7547     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7548
7549   // Otherwise, we don't care about qualifiers on the type.
7550   Ty = Ty.getLocalUnqualifiedType();
7551
7552   // Flag if we ever add a non-record type.
7553   const RecordType *TyRec = Ty->getAs<RecordType>();
7554   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7555
7556   // Flag if we encounter an arithmetic type.
7557   HasArithmeticOrEnumeralTypes =
7558     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7559
7560   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7561     PointerTypes.insert(Ty);
7562   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7563     // Insert our type, and its more-qualified variants, into the set
7564     // of types.
7565     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7566       return;
7567   } else if (Ty->isMemberPointerType()) {
7568     // Member pointers are far easier, since the pointee can't be converted.
7569     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7570       return;
7571   } else if (Ty->isEnumeralType()) {
7572     HasArithmeticOrEnumeralTypes = true;
7573     EnumerationTypes.insert(Ty);
7574   } else if (Ty->isVectorType()) {
7575     // We treat vector types as arithmetic types in many contexts as an
7576     // extension.
7577     HasArithmeticOrEnumeralTypes = true;
7578     VectorTypes.insert(Ty);
7579   } else if (Ty->isNullPtrType()) {
7580     HasNullPtrType = true;
7581   } else if (AllowUserConversions && TyRec) {
7582     // No conversion functions in incomplete types.
7583     if (!SemaRef.isCompleteType(Loc, Ty))
7584       return;
7585
7586     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7587     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7588       if (isa<UsingShadowDecl>(D))
7589         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7590
7591       // Skip conversion function templates; they don't tell us anything
7592       // about which builtin types we can convert to.
7593       if (isa<FunctionTemplateDecl>(D))
7594         continue;
7595
7596       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7597       if (AllowExplicitConversions || !Conv->isExplicit()) {
7598         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7599                               VisibleQuals);
7600       }
7601     }
7602   }
7603 }
7604
7605 /// Helper function for AddBuiltinOperatorCandidates() that adds
7606 /// the volatile- and non-volatile-qualified assignment operators for the
7607 /// given type to the candidate set.
7608 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7609                                                    QualType T,
7610                                                    ArrayRef<Expr *> Args,
7611                                     OverloadCandidateSet &CandidateSet) {
7612   QualType ParamTypes[2];
7613
7614   // T& operator=(T&, T)
7615   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7616   ParamTypes[1] = T;
7617   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7618                         /*IsAssignmentOperator=*/true);
7619
7620   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7621     // volatile T& operator=(volatile T&, T)
7622     ParamTypes[0]
7623       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7624     ParamTypes[1] = T;
7625     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7626                           /*IsAssignmentOperator=*/true);
7627   }
7628 }
7629
7630 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7631 /// if any, found in visible type conversion functions found in ArgExpr's type.
7632 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7633     Qualifiers VRQuals;
7634     const RecordType *TyRec;
7635     if (const MemberPointerType *RHSMPType =
7636         ArgExpr->getType()->getAs<MemberPointerType>())
7637       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7638     else
7639       TyRec = ArgExpr->getType()->getAs<RecordType>();
7640     if (!TyRec) {
7641       // Just to be safe, assume the worst case.
7642       VRQuals.addVolatile();
7643       VRQuals.addRestrict();
7644       return VRQuals;
7645     }
7646
7647     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7648     if (!ClassDecl->hasDefinition())
7649       return VRQuals;
7650
7651     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7652       if (isa<UsingShadowDecl>(D))
7653         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7654       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7655         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7656         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7657           CanTy = ResTypeRef->getPointeeType();
7658         // Need to go down the pointer/mempointer chain and add qualifiers
7659         // as see them.
7660         bool done = false;
7661         while (!done) {
7662           if (CanTy.isRestrictQualified())
7663             VRQuals.addRestrict();
7664           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7665             CanTy = ResTypePtr->getPointeeType();
7666           else if (const MemberPointerType *ResTypeMPtr =
7667                 CanTy->getAs<MemberPointerType>())
7668             CanTy = ResTypeMPtr->getPointeeType();
7669           else
7670             done = true;
7671           if (CanTy.isVolatileQualified())
7672             VRQuals.addVolatile();
7673           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7674             return VRQuals;
7675         }
7676       }
7677     }
7678     return VRQuals;
7679 }
7680
7681 namespace {
7682
7683 /// Helper class to manage the addition of builtin operator overload
7684 /// candidates. It provides shared state and utility methods used throughout
7685 /// the process, as well as a helper method to add each group of builtin
7686 /// operator overloads from the standard to a candidate set.
7687 class BuiltinOperatorOverloadBuilder {
7688   // Common instance state available to all overload candidate addition methods.
7689   Sema &S;
7690   ArrayRef<Expr *> Args;
7691   Qualifiers VisibleTypeConversionsQuals;
7692   bool HasArithmeticOrEnumeralCandidateType;
7693   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7694   OverloadCandidateSet &CandidateSet;
7695
7696   static constexpr int ArithmeticTypesCap = 24;
7697   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7698
7699   // Define some indices used to iterate over the arithemetic types in
7700   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7701   // types are that preserved by promotion (C++ [over.built]p2).
7702   unsigned FirstIntegralType,
7703            LastIntegralType;
7704   unsigned FirstPromotedIntegralType,
7705            LastPromotedIntegralType;
7706   unsigned FirstPromotedArithmeticType,
7707            LastPromotedArithmeticType;
7708   unsigned NumArithmeticTypes;
7709
7710   void InitArithmeticTypes() {
7711     // Start of promoted types.
7712     FirstPromotedArithmeticType = 0;
7713     ArithmeticTypes.push_back(S.Context.FloatTy);
7714     ArithmeticTypes.push_back(S.Context.DoubleTy);
7715     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7716     if (S.Context.getTargetInfo().hasFloat128Type())
7717       ArithmeticTypes.push_back(S.Context.Float128Ty);
7718
7719     // Start of integral types.
7720     FirstIntegralType = ArithmeticTypes.size();
7721     FirstPromotedIntegralType = ArithmeticTypes.size();
7722     ArithmeticTypes.push_back(S.Context.IntTy);
7723     ArithmeticTypes.push_back(S.Context.LongTy);
7724     ArithmeticTypes.push_back(S.Context.LongLongTy);
7725     if (S.Context.getTargetInfo().hasInt128Type())
7726       ArithmeticTypes.push_back(S.Context.Int128Ty);
7727     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7728     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7729     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7730     if (S.Context.getTargetInfo().hasInt128Type())
7731       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7732     LastPromotedIntegralType = ArithmeticTypes.size();
7733     LastPromotedArithmeticType = ArithmeticTypes.size();
7734     // End of promoted types.
7735
7736     ArithmeticTypes.push_back(S.Context.BoolTy);
7737     ArithmeticTypes.push_back(S.Context.CharTy);
7738     ArithmeticTypes.push_back(S.Context.WCharTy);
7739     if (S.Context.getLangOpts().Char8)
7740       ArithmeticTypes.push_back(S.Context.Char8Ty);
7741     ArithmeticTypes.push_back(S.Context.Char16Ty);
7742     ArithmeticTypes.push_back(S.Context.Char32Ty);
7743     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7744     ArithmeticTypes.push_back(S.Context.ShortTy);
7745     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7746     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7747     LastIntegralType = ArithmeticTypes.size();
7748     NumArithmeticTypes = ArithmeticTypes.size();
7749     // End of integral types.
7750     // FIXME: What about complex? What about half?
7751
7752     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7753            "Enough inline storage for all arithmetic types.");
7754   }
7755
7756   /// Helper method to factor out the common pattern of adding overloads
7757   /// for '++' and '--' builtin operators.
7758   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7759                                            bool HasVolatile,
7760                                            bool HasRestrict) {
7761     QualType ParamTypes[2] = {
7762       S.Context.getLValueReferenceType(CandidateTy),
7763       S.Context.IntTy
7764     };
7765
7766     // Non-volatile version.
7767     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7768
7769     // Use a heuristic to reduce number of builtin candidates in the set:
7770     // add volatile version only if there are conversions to a volatile type.
7771     if (HasVolatile) {
7772       ParamTypes[0] =
7773         S.Context.getLValueReferenceType(
7774           S.Context.getVolatileType(CandidateTy));
7775       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7776     }
7777
7778     // Add restrict version only if there are conversions to a restrict type
7779     // and our candidate type is a non-restrict-qualified pointer.
7780     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7781         !CandidateTy.isRestrictQualified()) {
7782       ParamTypes[0]
7783         = S.Context.getLValueReferenceType(
7784             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7785       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7786
7787       if (HasVolatile) {
7788         ParamTypes[0]
7789           = S.Context.getLValueReferenceType(
7790               S.Context.getCVRQualifiedType(CandidateTy,
7791                                             (Qualifiers::Volatile |
7792                                              Qualifiers::Restrict)));
7793         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7794       }
7795     }
7796
7797   }
7798
7799 public:
7800   BuiltinOperatorOverloadBuilder(
7801     Sema &S, ArrayRef<Expr *> Args,
7802     Qualifiers VisibleTypeConversionsQuals,
7803     bool HasArithmeticOrEnumeralCandidateType,
7804     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7805     OverloadCandidateSet &CandidateSet)
7806     : S(S), Args(Args),
7807       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7808       HasArithmeticOrEnumeralCandidateType(
7809         HasArithmeticOrEnumeralCandidateType),
7810       CandidateTypes(CandidateTypes),
7811       CandidateSet(CandidateSet) {
7812
7813     InitArithmeticTypes();
7814   }
7815
7816   // Increment is deprecated for bool since C++17.
7817   //
7818   // C++ [over.built]p3:
7819   //
7820   //   For every pair (T, VQ), where T is an arithmetic type other
7821   //   than bool, and VQ is either volatile or empty, there exist
7822   //   candidate operator functions of the form
7823   //
7824   //       VQ T&      operator++(VQ T&);
7825   //       T          operator++(VQ T&, int);
7826   //
7827   // C++ [over.built]p4:
7828   //
7829   //   For every pair (T, VQ), where T is an arithmetic type other
7830   //   than bool, and VQ is either volatile or empty, there exist
7831   //   candidate operator functions of the form
7832   //
7833   //       VQ T&      operator--(VQ T&);
7834   //       T          operator--(VQ T&, int);
7835   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7836     if (!HasArithmeticOrEnumeralCandidateType)
7837       return;
7838
7839     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7840       const auto TypeOfT = ArithmeticTypes[Arith];
7841       if (TypeOfT == S.Context.BoolTy) {
7842         if (Op == OO_MinusMinus)
7843           continue;
7844         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7845           continue;
7846       }
7847       addPlusPlusMinusMinusStyleOverloads(
7848         TypeOfT,
7849         VisibleTypeConversionsQuals.hasVolatile(),
7850         VisibleTypeConversionsQuals.hasRestrict());
7851     }
7852   }
7853
7854   // C++ [over.built]p5:
7855   //
7856   //   For every pair (T, VQ), where T is a cv-qualified or
7857   //   cv-unqualified object type, and VQ is either volatile or
7858   //   empty, there exist candidate operator functions of the form
7859   //
7860   //       T*VQ&      operator++(T*VQ&);
7861   //       T*VQ&      operator--(T*VQ&);
7862   //       T*         operator++(T*VQ&, int);
7863   //       T*         operator--(T*VQ&, int);
7864   void addPlusPlusMinusMinusPointerOverloads() {
7865     for (BuiltinCandidateTypeSet::iterator
7866               Ptr = CandidateTypes[0].pointer_begin(),
7867            PtrEnd = CandidateTypes[0].pointer_end();
7868          Ptr != PtrEnd; ++Ptr) {
7869       // Skip pointer types that aren't pointers to object types.
7870       if (!(*Ptr)->getPointeeType()->isObjectType())
7871         continue;
7872
7873       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7874         (!(*Ptr).isVolatileQualified() &&
7875          VisibleTypeConversionsQuals.hasVolatile()),
7876         (!(*Ptr).isRestrictQualified() &&
7877          VisibleTypeConversionsQuals.hasRestrict()));
7878     }
7879   }
7880
7881   // C++ [over.built]p6:
7882   //   For every cv-qualified or cv-unqualified object type T, there
7883   //   exist candidate operator functions of the form
7884   //
7885   //       T&         operator*(T*);
7886   //
7887   // C++ [over.built]p7:
7888   //   For every function type T that does not have cv-qualifiers or a
7889   //   ref-qualifier, there exist candidate operator functions of the form
7890   //       T&         operator*(T*);
7891   void addUnaryStarPointerOverloads() {
7892     for (BuiltinCandidateTypeSet::iterator
7893               Ptr = CandidateTypes[0].pointer_begin(),
7894            PtrEnd = CandidateTypes[0].pointer_end();
7895          Ptr != PtrEnd; ++Ptr) {
7896       QualType ParamTy = *Ptr;
7897       QualType PointeeTy = ParamTy->getPointeeType();
7898       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7899         continue;
7900
7901       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7902         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7903           continue;
7904
7905       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7906     }
7907   }
7908
7909   // C++ [over.built]p9:
7910   //  For every promoted arithmetic type T, there exist candidate
7911   //  operator functions of the form
7912   //
7913   //       T         operator+(T);
7914   //       T         operator-(T);
7915   void addUnaryPlusOrMinusArithmeticOverloads() {
7916     if (!HasArithmeticOrEnumeralCandidateType)
7917       return;
7918
7919     for (unsigned Arith = FirstPromotedArithmeticType;
7920          Arith < LastPromotedArithmeticType; ++Arith) {
7921       QualType ArithTy = ArithmeticTypes[Arith];
7922       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7923     }
7924
7925     // Extension: We also add these operators for vector types.
7926     for (BuiltinCandidateTypeSet::iterator
7927               Vec = CandidateTypes[0].vector_begin(),
7928            VecEnd = CandidateTypes[0].vector_end();
7929          Vec != VecEnd; ++Vec) {
7930       QualType VecTy = *Vec;
7931       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7932     }
7933   }
7934
7935   // C++ [over.built]p8:
7936   //   For every type T, there exist candidate operator functions of
7937   //   the form
7938   //
7939   //       T*         operator+(T*);
7940   void addUnaryPlusPointerOverloads() {
7941     for (BuiltinCandidateTypeSet::iterator
7942               Ptr = CandidateTypes[0].pointer_begin(),
7943            PtrEnd = CandidateTypes[0].pointer_end();
7944          Ptr != PtrEnd; ++Ptr) {
7945       QualType ParamTy = *Ptr;
7946       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7947     }
7948   }
7949
7950   // C++ [over.built]p10:
7951   //   For every promoted integral type T, there exist candidate
7952   //   operator functions of the form
7953   //
7954   //        T         operator~(T);
7955   void addUnaryTildePromotedIntegralOverloads() {
7956     if (!HasArithmeticOrEnumeralCandidateType)
7957       return;
7958
7959     for (unsigned Int = FirstPromotedIntegralType;
7960          Int < LastPromotedIntegralType; ++Int) {
7961       QualType IntTy = ArithmeticTypes[Int];
7962       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7963     }
7964
7965     // Extension: We also add this operator for vector types.
7966     for (BuiltinCandidateTypeSet::iterator
7967               Vec = CandidateTypes[0].vector_begin(),
7968            VecEnd = CandidateTypes[0].vector_end();
7969          Vec != VecEnd; ++Vec) {
7970       QualType VecTy = *Vec;
7971       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7972     }
7973   }
7974
7975   // C++ [over.match.oper]p16:
7976   //   For every pointer to member type T or type std::nullptr_t, there
7977   //   exist candidate operator functions of the form
7978   //
7979   //        bool operator==(T,T);
7980   //        bool operator!=(T,T);
7981   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7982     /// Set of (canonical) types that we've already handled.
7983     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7984
7985     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7986       for (BuiltinCandidateTypeSet::iterator
7987                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7988              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7989            MemPtr != MemPtrEnd;
7990            ++MemPtr) {
7991         // Don't add the same builtin candidate twice.
7992         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7993           continue;
7994
7995         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7996         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7997       }
7998
7999       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8000         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8001         if (AddedTypes.insert(NullPtrTy).second) {
8002           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8003           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8004         }
8005       }
8006     }
8007   }
8008
8009   // C++ [over.built]p15:
8010   //
8011   //   For every T, where T is an enumeration type or a pointer type,
8012   //   there exist candidate operator functions of the form
8013   //
8014   //        bool       operator<(T, T);
8015   //        bool       operator>(T, T);
8016   //        bool       operator<=(T, T);
8017   //        bool       operator>=(T, T);
8018   //        bool       operator==(T, T);
8019   //        bool       operator!=(T, T);
8020   //           R       operator<=>(T, T)
8021   void addGenericBinaryPointerOrEnumeralOverloads() {
8022     // C++ [over.match.oper]p3:
8023     //   [...]the built-in candidates include all of the candidate operator
8024     //   functions defined in 13.6 that, compared to the given operator, [...]
8025     //   do not have the same parameter-type-list as any non-template non-member
8026     //   candidate.
8027     //
8028     // Note that in practice, this only affects enumeration types because there
8029     // aren't any built-in candidates of record type, and a user-defined operator
8030     // must have an operand of record or enumeration type. Also, the only other
8031     // overloaded operator with enumeration arguments, operator=,
8032     // cannot be overloaded for enumeration types, so this is the only place
8033     // where we must suppress candidates like this.
8034     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8035       UserDefinedBinaryOperators;
8036
8037     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8038       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8039           CandidateTypes[ArgIdx].enumeration_end()) {
8040         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8041                                          CEnd = CandidateSet.end();
8042              C != CEnd; ++C) {
8043           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8044             continue;
8045
8046           if (C->Function->isFunctionTemplateSpecialization())
8047             continue;
8048
8049           QualType FirstParamType =
8050             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8051           QualType SecondParamType =
8052             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8053
8054           // Skip if either parameter isn't of enumeral type.
8055           if (!FirstParamType->isEnumeralType() ||
8056               !SecondParamType->isEnumeralType())
8057             continue;
8058
8059           // Add this operator to the set of known user-defined operators.
8060           UserDefinedBinaryOperators.insert(
8061             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8062                            S.Context.getCanonicalType(SecondParamType)));
8063         }
8064       }
8065     }
8066
8067     /// Set of (canonical) types that we've already handled.
8068     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8069
8070     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8071       for (BuiltinCandidateTypeSet::iterator
8072                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8073              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8074            Ptr != PtrEnd; ++Ptr) {
8075         // Don't add the same builtin candidate twice.
8076         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8077           continue;
8078
8079         QualType ParamTypes[2] = { *Ptr, *Ptr };
8080         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8081       }
8082       for (BuiltinCandidateTypeSet::iterator
8083                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8084              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8085            Enum != EnumEnd; ++Enum) {
8086         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8087
8088         // Don't add the same builtin candidate twice, or if a user defined
8089         // candidate exists.
8090         if (!AddedTypes.insert(CanonType).second ||
8091             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8092                                                             CanonType)))
8093           continue;
8094         QualType ParamTypes[2] = { *Enum, *Enum };
8095         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8096       }
8097     }
8098   }
8099
8100   // C++ [over.built]p13:
8101   //
8102   //   For every cv-qualified or cv-unqualified object type T
8103   //   there exist candidate operator functions of the form
8104   //
8105   //      T*         operator+(T*, ptrdiff_t);
8106   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8107   //      T*         operator-(T*, ptrdiff_t);
8108   //      T*         operator+(ptrdiff_t, T*);
8109   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8110   //
8111   // C++ [over.built]p14:
8112   //
8113   //   For every T, where T is a pointer to object type, there
8114   //   exist candidate operator functions of the form
8115   //
8116   //      ptrdiff_t  operator-(T, T);
8117   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8118     /// Set of (canonical) types that we've already handled.
8119     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8120
8121     for (int Arg = 0; Arg < 2; ++Arg) {
8122       QualType AsymmetricParamTypes[2] = {
8123         S.Context.getPointerDiffType(),
8124         S.Context.getPointerDiffType(),
8125       };
8126       for (BuiltinCandidateTypeSet::iterator
8127                 Ptr = CandidateTypes[Arg].pointer_begin(),
8128              PtrEnd = CandidateTypes[Arg].pointer_end();
8129            Ptr != PtrEnd; ++Ptr) {
8130         QualType PointeeTy = (*Ptr)->getPointeeType();
8131         if (!PointeeTy->isObjectType())
8132           continue;
8133
8134         AsymmetricParamTypes[Arg] = *Ptr;
8135         if (Arg == 0 || Op == OO_Plus) {
8136           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8137           // T* operator+(ptrdiff_t, T*);
8138           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8139         }
8140         if (Op == OO_Minus) {
8141           // ptrdiff_t operator-(T, T);
8142           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8143             continue;
8144
8145           QualType ParamTypes[2] = { *Ptr, *Ptr };
8146           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8147         }
8148       }
8149     }
8150   }
8151
8152   // C++ [over.built]p12:
8153   //
8154   //   For every pair of promoted arithmetic types L and R, there
8155   //   exist candidate operator functions of the form
8156   //
8157   //        LR         operator*(L, R);
8158   //        LR         operator/(L, R);
8159   //        LR         operator+(L, R);
8160   //        LR         operator-(L, R);
8161   //        bool       operator<(L, R);
8162   //        bool       operator>(L, R);
8163   //        bool       operator<=(L, R);
8164   //        bool       operator>=(L, R);
8165   //        bool       operator==(L, R);
8166   //        bool       operator!=(L, R);
8167   //
8168   //   where LR is the result of the usual arithmetic conversions
8169   //   between types L and R.
8170   //
8171   // C++ [over.built]p24:
8172   //
8173   //   For every pair of promoted arithmetic types L and R, there exist
8174   //   candidate operator functions of the form
8175   //
8176   //        LR       operator?(bool, L, R);
8177   //
8178   //   where LR is the result of the usual arithmetic conversions
8179   //   between types L and R.
8180   // Our candidates ignore the first parameter.
8181   void addGenericBinaryArithmeticOverloads() {
8182     if (!HasArithmeticOrEnumeralCandidateType)
8183       return;
8184
8185     for (unsigned Left = FirstPromotedArithmeticType;
8186          Left < LastPromotedArithmeticType; ++Left) {
8187       for (unsigned Right = FirstPromotedArithmeticType;
8188            Right < LastPromotedArithmeticType; ++Right) {
8189         QualType LandR[2] = { ArithmeticTypes[Left],
8190                               ArithmeticTypes[Right] };
8191         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8192       }
8193     }
8194
8195     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8196     // conditional operator for vector types.
8197     for (BuiltinCandidateTypeSet::iterator
8198               Vec1 = CandidateTypes[0].vector_begin(),
8199            Vec1End = CandidateTypes[0].vector_end();
8200          Vec1 != Vec1End; ++Vec1) {
8201       for (BuiltinCandidateTypeSet::iterator
8202                 Vec2 = CandidateTypes[1].vector_begin(),
8203              Vec2End = CandidateTypes[1].vector_end();
8204            Vec2 != Vec2End; ++Vec2) {
8205         QualType LandR[2] = { *Vec1, *Vec2 };
8206         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8207       }
8208     }
8209   }
8210
8211   // C++2a [over.built]p14:
8212   //
8213   //   For every integral type T there exists a candidate operator function
8214   //   of the form
8215   //
8216   //        std::strong_ordering operator<=>(T, T)
8217   //
8218   // C++2a [over.built]p15:
8219   //
8220   //   For every pair of floating-point types L and R, there exists a candidate
8221   //   operator function of the form
8222   //
8223   //       std::partial_ordering operator<=>(L, R);
8224   //
8225   // FIXME: The current specification for integral types doesn't play nice with
8226   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8227   // comparisons. Under the current spec this can lead to ambiguity during
8228   // overload resolution. For example:
8229   //
8230   //   enum A : int {a};
8231   //   auto x = (a <=> (long)42);
8232   //
8233   //   error: call is ambiguous for arguments 'A' and 'long'.
8234   //   note: candidate operator<=>(int, int)
8235   //   note: candidate operator<=>(long, long)
8236   //
8237   // To avoid this error, this function deviates from the specification and adds
8238   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8239   // arithmetic types (the same as the generic relational overloads).
8240   //
8241   // For now this function acts as a placeholder.
8242   void addThreeWayArithmeticOverloads() {
8243     addGenericBinaryArithmeticOverloads();
8244   }
8245
8246   // C++ [over.built]p17:
8247   //
8248   //   For every pair of promoted integral types L and R, there
8249   //   exist candidate operator functions of the form
8250   //
8251   //      LR         operator%(L, R);
8252   //      LR         operator&(L, R);
8253   //      LR         operator^(L, R);
8254   //      LR         operator|(L, R);
8255   //      L          operator<<(L, R);
8256   //      L          operator>>(L, R);
8257   //
8258   //   where LR is the result of the usual arithmetic conversions
8259   //   between types L and R.
8260   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8261     if (!HasArithmeticOrEnumeralCandidateType)
8262       return;
8263
8264     for (unsigned Left = FirstPromotedIntegralType;
8265          Left < LastPromotedIntegralType; ++Left) {
8266       for (unsigned Right = FirstPromotedIntegralType;
8267            Right < LastPromotedIntegralType; ++Right) {
8268         QualType LandR[2] = { ArithmeticTypes[Left],
8269                               ArithmeticTypes[Right] };
8270         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8271       }
8272     }
8273   }
8274
8275   // C++ [over.built]p20:
8276   //
8277   //   For every pair (T, VQ), where T is an enumeration or
8278   //   pointer to member type and VQ is either volatile or
8279   //   empty, there exist candidate operator functions of the form
8280   //
8281   //        VQ T&      operator=(VQ T&, T);
8282   void addAssignmentMemberPointerOrEnumeralOverloads() {
8283     /// Set of (canonical) types that we've already handled.
8284     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8285
8286     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8287       for (BuiltinCandidateTypeSet::iterator
8288                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8289              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8290            Enum != EnumEnd; ++Enum) {
8291         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8292           continue;
8293
8294         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8295       }
8296
8297       for (BuiltinCandidateTypeSet::iterator
8298                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8299              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8300            MemPtr != MemPtrEnd; ++MemPtr) {
8301         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8302           continue;
8303
8304         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8305       }
8306     }
8307   }
8308
8309   // C++ [over.built]p19:
8310   //
8311   //   For every pair (T, VQ), where T is any type and VQ is either
8312   //   volatile or empty, there exist candidate operator functions
8313   //   of the form
8314   //
8315   //        T*VQ&      operator=(T*VQ&, T*);
8316   //
8317   // C++ [over.built]p21:
8318   //
8319   //   For every pair (T, VQ), where T is a cv-qualified or
8320   //   cv-unqualified object type and VQ is either volatile or
8321   //   empty, there exist candidate operator functions of the form
8322   //
8323   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8324   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8325   void addAssignmentPointerOverloads(bool isEqualOp) {
8326     /// Set of (canonical) types that we've already handled.
8327     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8328
8329     for (BuiltinCandidateTypeSet::iterator
8330               Ptr = CandidateTypes[0].pointer_begin(),
8331            PtrEnd = CandidateTypes[0].pointer_end();
8332          Ptr != PtrEnd; ++Ptr) {
8333       // If this is operator=, keep track of the builtin candidates we added.
8334       if (isEqualOp)
8335         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8336       else if (!(*Ptr)->getPointeeType()->isObjectType())
8337         continue;
8338
8339       // non-volatile version
8340       QualType ParamTypes[2] = {
8341         S.Context.getLValueReferenceType(*Ptr),
8342         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8343       };
8344       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8345                             /*IsAssigmentOperator=*/ isEqualOp);
8346
8347       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8348                           VisibleTypeConversionsQuals.hasVolatile();
8349       if (NeedVolatile) {
8350         // volatile version
8351         ParamTypes[0] =
8352           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8353         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8354                               /*IsAssigmentOperator=*/isEqualOp);
8355       }
8356
8357       if (!(*Ptr).isRestrictQualified() &&
8358           VisibleTypeConversionsQuals.hasRestrict()) {
8359         // restrict version
8360         ParamTypes[0]
8361           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8362         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8363                               /*IsAssigmentOperator=*/isEqualOp);
8364
8365         if (NeedVolatile) {
8366           // volatile restrict version
8367           ParamTypes[0]
8368             = S.Context.getLValueReferenceType(
8369                 S.Context.getCVRQualifiedType(*Ptr,
8370                                               (Qualifiers::Volatile |
8371                                                Qualifiers::Restrict)));
8372           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8373                                 /*IsAssigmentOperator=*/isEqualOp);
8374         }
8375       }
8376     }
8377
8378     if (isEqualOp) {
8379       for (BuiltinCandidateTypeSet::iterator
8380                 Ptr = CandidateTypes[1].pointer_begin(),
8381              PtrEnd = CandidateTypes[1].pointer_end();
8382            Ptr != PtrEnd; ++Ptr) {
8383         // Make sure we don't add the same candidate twice.
8384         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8385           continue;
8386
8387         QualType ParamTypes[2] = {
8388           S.Context.getLValueReferenceType(*Ptr),
8389           *Ptr,
8390         };
8391
8392         // non-volatile version
8393         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8394                               /*IsAssigmentOperator=*/true);
8395
8396         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8397                            VisibleTypeConversionsQuals.hasVolatile();
8398         if (NeedVolatile) {
8399           // volatile version
8400           ParamTypes[0] =
8401             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8402           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8403                                 /*IsAssigmentOperator=*/true);
8404         }
8405
8406         if (!(*Ptr).isRestrictQualified() &&
8407             VisibleTypeConversionsQuals.hasRestrict()) {
8408           // restrict version
8409           ParamTypes[0]
8410             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8411           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8412                                 /*IsAssigmentOperator=*/true);
8413
8414           if (NeedVolatile) {
8415             // volatile restrict version
8416             ParamTypes[0]
8417               = S.Context.getLValueReferenceType(
8418                   S.Context.getCVRQualifiedType(*Ptr,
8419                                                 (Qualifiers::Volatile |
8420                                                  Qualifiers::Restrict)));
8421             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8422                                   /*IsAssigmentOperator=*/true);
8423           }
8424         }
8425       }
8426     }
8427   }
8428
8429   // C++ [over.built]p18:
8430   //
8431   //   For every triple (L, VQ, R), where L is an arithmetic type,
8432   //   VQ is either volatile or empty, and R is a promoted
8433   //   arithmetic type, there exist candidate operator functions of
8434   //   the form
8435   //
8436   //        VQ L&      operator=(VQ L&, R);
8437   //        VQ L&      operator*=(VQ L&, R);
8438   //        VQ L&      operator/=(VQ L&, R);
8439   //        VQ L&      operator+=(VQ L&, R);
8440   //        VQ L&      operator-=(VQ L&, R);
8441   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8442     if (!HasArithmeticOrEnumeralCandidateType)
8443       return;
8444
8445     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8446       for (unsigned Right = FirstPromotedArithmeticType;
8447            Right < LastPromotedArithmeticType; ++Right) {
8448         QualType ParamTypes[2];
8449         ParamTypes[1] = ArithmeticTypes[Right];
8450
8451         // Add this built-in operator as a candidate (VQ is empty).
8452         ParamTypes[0] =
8453           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8454         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8455                               /*IsAssigmentOperator=*/isEqualOp);
8456
8457         // Add this built-in operator as a candidate (VQ is 'volatile').
8458         if (VisibleTypeConversionsQuals.hasVolatile()) {
8459           ParamTypes[0] =
8460             S.Context.getVolatileType(ArithmeticTypes[Left]);
8461           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8462           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8463                                 /*IsAssigmentOperator=*/isEqualOp);
8464         }
8465       }
8466     }
8467
8468     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8469     for (BuiltinCandidateTypeSet::iterator
8470               Vec1 = CandidateTypes[0].vector_begin(),
8471            Vec1End = CandidateTypes[0].vector_end();
8472          Vec1 != Vec1End; ++Vec1) {
8473       for (BuiltinCandidateTypeSet::iterator
8474                 Vec2 = CandidateTypes[1].vector_begin(),
8475              Vec2End = CandidateTypes[1].vector_end();
8476            Vec2 != Vec2End; ++Vec2) {
8477         QualType ParamTypes[2];
8478         ParamTypes[1] = *Vec2;
8479         // Add this built-in operator as a candidate (VQ is empty).
8480         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8481         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8482                               /*IsAssigmentOperator=*/isEqualOp);
8483
8484         // Add this built-in operator as a candidate (VQ is 'volatile').
8485         if (VisibleTypeConversionsQuals.hasVolatile()) {
8486           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8487           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8488           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8489                                 /*IsAssigmentOperator=*/isEqualOp);
8490         }
8491       }
8492     }
8493   }
8494
8495   // C++ [over.built]p22:
8496   //
8497   //   For every triple (L, VQ, R), where L is an integral type, VQ
8498   //   is either volatile or empty, and R is a promoted integral
8499   //   type, there exist candidate operator functions of the form
8500   //
8501   //        VQ L&       operator%=(VQ L&, R);
8502   //        VQ L&       operator<<=(VQ L&, R);
8503   //        VQ L&       operator>>=(VQ L&, R);
8504   //        VQ L&       operator&=(VQ L&, R);
8505   //        VQ L&       operator^=(VQ L&, R);
8506   //        VQ L&       operator|=(VQ L&, R);
8507   void addAssignmentIntegralOverloads() {
8508     if (!HasArithmeticOrEnumeralCandidateType)
8509       return;
8510
8511     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8512       for (unsigned Right = FirstPromotedIntegralType;
8513            Right < LastPromotedIntegralType; ++Right) {
8514         QualType ParamTypes[2];
8515         ParamTypes[1] = ArithmeticTypes[Right];
8516
8517         // Add this built-in operator as a candidate (VQ is empty).
8518         ParamTypes[0] =
8519           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8520         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8521         if (VisibleTypeConversionsQuals.hasVolatile()) {
8522           // Add this built-in operator as a candidate (VQ is 'volatile').
8523           ParamTypes[0] = ArithmeticTypes[Left];
8524           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8525           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8526           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8527         }
8528       }
8529     }
8530   }
8531
8532   // C++ [over.operator]p23:
8533   //
8534   //   There also exist candidate operator functions of the form
8535   //
8536   //        bool        operator!(bool);
8537   //        bool        operator&&(bool, bool);
8538   //        bool        operator||(bool, bool);
8539   void addExclaimOverload() {
8540     QualType ParamTy = S.Context.BoolTy;
8541     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8542                           /*IsAssignmentOperator=*/false,
8543                           /*NumContextualBoolArguments=*/1);
8544   }
8545   void addAmpAmpOrPipePipeOverload() {
8546     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8547     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8548                           /*IsAssignmentOperator=*/false,
8549                           /*NumContextualBoolArguments=*/2);
8550   }
8551
8552   // C++ [over.built]p13:
8553   //
8554   //   For every cv-qualified or cv-unqualified object type T there
8555   //   exist candidate operator functions of the form
8556   //
8557   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8558   //        T&         operator[](T*, ptrdiff_t);
8559   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8560   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8561   //        T&         operator[](ptrdiff_t, T*);
8562   void addSubscriptOverloads() {
8563     for (BuiltinCandidateTypeSet::iterator
8564               Ptr = CandidateTypes[0].pointer_begin(),
8565            PtrEnd = CandidateTypes[0].pointer_end();
8566          Ptr != PtrEnd; ++Ptr) {
8567       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8568       QualType PointeeType = (*Ptr)->getPointeeType();
8569       if (!PointeeType->isObjectType())
8570         continue;
8571
8572       // T& operator[](T*, ptrdiff_t)
8573       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8574     }
8575
8576     for (BuiltinCandidateTypeSet::iterator
8577               Ptr = CandidateTypes[1].pointer_begin(),
8578            PtrEnd = CandidateTypes[1].pointer_end();
8579          Ptr != PtrEnd; ++Ptr) {
8580       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8581       QualType PointeeType = (*Ptr)->getPointeeType();
8582       if (!PointeeType->isObjectType())
8583         continue;
8584
8585       // T& operator[](ptrdiff_t, T*)
8586       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8587     }
8588   }
8589
8590   // C++ [over.built]p11:
8591   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8592   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8593   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8594   //    there exist candidate operator functions of the form
8595   //
8596   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8597   //
8598   //    where CV12 is the union of CV1 and CV2.
8599   void addArrowStarOverloads() {
8600     for (BuiltinCandidateTypeSet::iterator
8601              Ptr = CandidateTypes[0].pointer_begin(),
8602            PtrEnd = CandidateTypes[0].pointer_end();
8603          Ptr != PtrEnd; ++Ptr) {
8604       QualType C1Ty = (*Ptr);
8605       QualType C1;
8606       QualifierCollector Q1;
8607       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8608       if (!isa<RecordType>(C1))
8609         continue;
8610       // heuristic to reduce number of builtin candidates in the set.
8611       // Add volatile/restrict version only if there are conversions to a
8612       // volatile/restrict type.
8613       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8614         continue;
8615       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8616         continue;
8617       for (BuiltinCandidateTypeSet::iterator
8618                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8619              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8620            MemPtr != MemPtrEnd; ++MemPtr) {
8621         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8622         QualType C2 = QualType(mptr->getClass(), 0);
8623         C2 = C2.getUnqualifiedType();
8624         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8625           break;
8626         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8627         // build CV12 T&
8628         QualType T = mptr->getPointeeType();
8629         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8630             T.isVolatileQualified())
8631           continue;
8632         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8633             T.isRestrictQualified())
8634           continue;
8635         T = Q1.apply(S.Context, T);
8636         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8637       }
8638     }
8639   }
8640
8641   // Note that we don't consider the first argument, since it has been
8642   // contextually converted to bool long ago. The candidates below are
8643   // therefore added as binary.
8644   //
8645   // C++ [over.built]p25:
8646   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8647   //   enumeration type, there exist candidate operator functions of the form
8648   //
8649   //        T        operator?(bool, T, T);
8650   //
8651   void addConditionalOperatorOverloads() {
8652     /// Set of (canonical) types that we've already handled.
8653     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8654
8655     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8656       for (BuiltinCandidateTypeSet::iterator
8657                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8658              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8659            Ptr != PtrEnd; ++Ptr) {
8660         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8661           continue;
8662
8663         QualType ParamTypes[2] = { *Ptr, *Ptr };
8664         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8665       }
8666
8667       for (BuiltinCandidateTypeSet::iterator
8668                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8669              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8670            MemPtr != MemPtrEnd; ++MemPtr) {
8671         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8672           continue;
8673
8674         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8675         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8676       }
8677
8678       if (S.getLangOpts().CPlusPlus11) {
8679         for (BuiltinCandidateTypeSet::iterator
8680                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8681                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8682              Enum != EnumEnd; ++Enum) {
8683           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8684             continue;
8685
8686           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8687             continue;
8688
8689           QualType ParamTypes[2] = { *Enum, *Enum };
8690           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8691         }
8692       }
8693     }
8694   }
8695 };
8696
8697 } // end anonymous namespace
8698
8699 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8700 /// operator overloads to the candidate set (C++ [over.built]), based
8701 /// on the operator @p Op and the arguments given. For example, if the
8702 /// operator is a binary '+', this routine might add "int
8703 /// operator+(int, int)" to cover integer addition.
8704 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8705                                         SourceLocation OpLoc,
8706                                         ArrayRef<Expr *> Args,
8707                                         OverloadCandidateSet &CandidateSet) {
8708   // Find all of the types that the arguments can convert to, but only
8709   // if the operator we're looking at has built-in operator candidates
8710   // that make use of these types. Also record whether we encounter non-record
8711   // candidate types or either arithmetic or enumeral candidate types.
8712   Qualifiers VisibleTypeConversionsQuals;
8713   VisibleTypeConversionsQuals.addConst();
8714   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8715     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8716
8717   bool HasNonRecordCandidateType = false;
8718   bool HasArithmeticOrEnumeralCandidateType = false;
8719   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8720   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8721     CandidateTypes.emplace_back(*this);
8722     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8723                                                  OpLoc,
8724                                                  true,
8725                                                  (Op == OO_Exclaim ||
8726                                                   Op == OO_AmpAmp ||
8727                                                   Op == OO_PipePipe),
8728                                                  VisibleTypeConversionsQuals);
8729     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8730         CandidateTypes[ArgIdx].hasNonRecordTypes();
8731     HasArithmeticOrEnumeralCandidateType =
8732         HasArithmeticOrEnumeralCandidateType ||
8733         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8734   }
8735
8736   // Exit early when no non-record types have been added to the candidate set
8737   // for any of the arguments to the operator.
8738   //
8739   // We can't exit early for !, ||, or &&, since there we have always have
8740   // 'bool' overloads.
8741   if (!HasNonRecordCandidateType &&
8742       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8743     return;
8744
8745   // Setup an object to manage the common state for building overloads.
8746   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8747                                            VisibleTypeConversionsQuals,
8748                                            HasArithmeticOrEnumeralCandidateType,
8749                                            CandidateTypes, CandidateSet);
8750
8751   // Dispatch over the operation to add in only those overloads which apply.
8752   switch (Op) {
8753   case OO_None:
8754   case NUM_OVERLOADED_OPERATORS:
8755     llvm_unreachable("Expected an overloaded operator");
8756
8757   case OO_New:
8758   case OO_Delete:
8759   case OO_Array_New:
8760   case OO_Array_Delete:
8761   case OO_Call:
8762     llvm_unreachable(
8763                     "Special operators don't use AddBuiltinOperatorCandidates");
8764
8765   case OO_Comma:
8766   case OO_Arrow:
8767   case OO_Coawait:
8768     // C++ [over.match.oper]p3:
8769     //   -- For the operator ',', the unary operator '&', the
8770     //      operator '->', or the operator 'co_await', the
8771     //      built-in candidates set is empty.
8772     break;
8773
8774   case OO_Plus: // '+' is either unary or binary
8775     if (Args.size() == 1)
8776       OpBuilder.addUnaryPlusPointerOverloads();
8777     LLVM_FALLTHROUGH;
8778
8779   case OO_Minus: // '-' is either unary or binary
8780     if (Args.size() == 1) {
8781       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8782     } else {
8783       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8784       OpBuilder.addGenericBinaryArithmeticOverloads();
8785     }
8786     break;
8787
8788   case OO_Star: // '*' is either unary or binary
8789     if (Args.size() == 1)
8790       OpBuilder.addUnaryStarPointerOverloads();
8791     else
8792       OpBuilder.addGenericBinaryArithmeticOverloads();
8793     break;
8794
8795   case OO_Slash:
8796     OpBuilder.addGenericBinaryArithmeticOverloads();
8797     break;
8798
8799   case OO_PlusPlus:
8800   case OO_MinusMinus:
8801     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8802     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8803     break;
8804
8805   case OO_EqualEqual:
8806   case OO_ExclaimEqual:
8807     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8808     LLVM_FALLTHROUGH;
8809
8810   case OO_Less:
8811   case OO_Greater:
8812   case OO_LessEqual:
8813   case OO_GreaterEqual:
8814     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8815     OpBuilder.addGenericBinaryArithmeticOverloads();
8816     break;
8817
8818   case OO_Spaceship:
8819     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8820     OpBuilder.addThreeWayArithmeticOverloads();
8821     break;
8822
8823   case OO_Percent:
8824   case OO_Caret:
8825   case OO_Pipe:
8826   case OO_LessLess:
8827   case OO_GreaterGreater:
8828     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8829     break;
8830
8831   case OO_Amp: // '&' is either unary or binary
8832     if (Args.size() == 1)
8833       // C++ [over.match.oper]p3:
8834       //   -- For the operator ',', the unary operator '&', or the
8835       //      operator '->', the built-in candidates set is empty.
8836       break;
8837
8838     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8839     break;
8840
8841   case OO_Tilde:
8842     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8843     break;
8844
8845   case OO_Equal:
8846     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8847     LLVM_FALLTHROUGH;
8848
8849   case OO_PlusEqual:
8850   case OO_MinusEqual:
8851     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8852     LLVM_FALLTHROUGH;
8853
8854   case OO_StarEqual:
8855   case OO_SlashEqual:
8856     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8857     break;
8858
8859   case OO_PercentEqual:
8860   case OO_LessLessEqual:
8861   case OO_GreaterGreaterEqual:
8862   case OO_AmpEqual:
8863   case OO_CaretEqual:
8864   case OO_PipeEqual:
8865     OpBuilder.addAssignmentIntegralOverloads();
8866     break;
8867
8868   case OO_Exclaim:
8869     OpBuilder.addExclaimOverload();
8870     break;
8871
8872   case OO_AmpAmp:
8873   case OO_PipePipe:
8874     OpBuilder.addAmpAmpOrPipePipeOverload();
8875     break;
8876
8877   case OO_Subscript:
8878     OpBuilder.addSubscriptOverloads();
8879     break;
8880
8881   case OO_ArrowStar:
8882     OpBuilder.addArrowStarOverloads();
8883     break;
8884
8885   case OO_Conditional:
8886     OpBuilder.addConditionalOperatorOverloads();
8887     OpBuilder.addGenericBinaryArithmeticOverloads();
8888     break;
8889   }
8890 }
8891
8892 /// Add function candidates found via argument-dependent lookup
8893 /// to the set of overloading candidates.
8894 ///
8895 /// This routine performs argument-dependent name lookup based on the
8896 /// given function name (which may also be an operator name) and adds
8897 /// all of the overload candidates found by ADL to the overload
8898 /// candidate set (C++ [basic.lookup.argdep]).
8899 void
8900 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8901                                            SourceLocation Loc,
8902                                            ArrayRef<Expr *> Args,
8903                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8904                                            OverloadCandidateSet& CandidateSet,
8905                                            bool PartialOverloading) {
8906   ADLResult Fns;
8907
8908   // FIXME: This approach for uniquing ADL results (and removing
8909   // redundant candidates from the set) relies on pointer-equality,
8910   // which means we need to key off the canonical decl.  However,
8911   // always going back to the canonical decl might not get us the
8912   // right set of default arguments.  What default arguments are
8913   // we supposed to consider on ADL candidates, anyway?
8914
8915   // FIXME: Pass in the explicit template arguments?
8916   ArgumentDependentLookup(Name, Loc, Args, Fns);
8917
8918   // Erase all of the candidates we already knew about.
8919   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8920                                    CandEnd = CandidateSet.end();
8921        Cand != CandEnd; ++Cand)
8922     if (Cand->Function) {
8923       Fns.erase(Cand->Function);
8924       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8925         Fns.erase(FunTmpl);
8926     }
8927
8928   // For each of the ADL candidates we found, add it to the overload
8929   // set.
8930   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8931     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8932     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8933       if (ExplicitTemplateArgs)
8934         continue;
8935
8936       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8937                            PartialOverloading);
8938     } else
8939       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8940                                    FoundDecl, ExplicitTemplateArgs,
8941                                    Args, CandidateSet, PartialOverloading);
8942   }
8943 }
8944
8945 namespace {
8946 enum class Comparison { Equal, Better, Worse };
8947 }
8948
8949 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8950 /// overload resolution.
8951 ///
8952 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8953 /// Cand1's first N enable_if attributes have precisely the same conditions as
8954 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8955 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8956 ///
8957 /// Note that you can have a pair of candidates such that Cand1's enable_if
8958 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8959 /// worse than Cand1's.
8960 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8961                                        const FunctionDecl *Cand2) {
8962   // Common case: One (or both) decls don't have enable_if attrs.
8963   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8964   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8965   if (!Cand1Attr || !Cand2Attr) {
8966     if (Cand1Attr == Cand2Attr)
8967       return Comparison::Equal;
8968     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8969   }
8970
8971   // FIXME: The next several lines are just
8972   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8973   // instead of reverse order which is how they're stored in the AST.
8974   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8975   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8976
8977   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8978   // has fewer enable_if attributes than Cand2.
8979   if (Cand1Attrs.size() < Cand2Attrs.size())
8980     return Comparison::Worse;
8981
8982   auto Cand1I = Cand1Attrs.begin();
8983   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8984   for (auto &Cand2A : Cand2Attrs) {
8985     Cand1ID.clear();
8986     Cand2ID.clear();
8987
8988     auto &Cand1A = *Cand1I++;
8989     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8990     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8991     if (Cand1ID != Cand2ID)
8992       return Comparison::Worse;
8993   }
8994
8995   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8996 }
8997
8998 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
8999                                           const OverloadCandidate &Cand2) {
9000   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9001       !Cand2.Function->isMultiVersion())
9002     return false;
9003
9004   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9005   // cpu_dispatch, else arbitrarily based on the identifiers.
9006   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9007   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9008   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9009   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9010
9011   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9012     return false;
9013
9014   if (Cand1CPUDisp && !Cand2CPUDisp)
9015     return true;
9016   if (Cand2CPUDisp && !Cand1CPUDisp)
9017     return false;
9018
9019   if (Cand1CPUSpec && Cand2CPUSpec) {
9020     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9021       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9022
9023     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9024         FirstDiff = std::mismatch(
9025             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9026             Cand2CPUSpec->cpus_begin(),
9027             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9028               return LHS->getName() == RHS->getName();
9029             });
9030
9031     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9032            "Two different cpu-specific versions should not have the same "
9033            "identifier list, otherwise they'd be the same decl!");
9034     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9035   }
9036   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9037 }
9038
9039 /// isBetterOverloadCandidate - Determines whether the first overload
9040 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9041 bool clang::isBetterOverloadCandidate(
9042     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9043     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9044   // Define viable functions to be better candidates than non-viable
9045   // functions.
9046   if (!Cand2.Viable)
9047     return Cand1.Viable;
9048   else if (!Cand1.Viable)
9049     return false;
9050
9051   // C++ [over.match.best]p1:
9052   //
9053   //   -- if F is a static member function, ICS1(F) is defined such
9054   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9055   //      any function G, and, symmetrically, ICS1(G) is neither
9056   //      better nor worse than ICS1(F).
9057   unsigned StartArg = 0;
9058   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9059     StartArg = 1;
9060
9061   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9062     // We don't allow incompatible pointer conversions in C++.
9063     if (!S.getLangOpts().CPlusPlus)
9064       return ICS.isStandard() &&
9065              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9066
9067     // The only ill-formed conversion we allow in C++ is the string literal to
9068     // char* conversion, which is only considered ill-formed after C++11.
9069     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9070            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9071   };
9072
9073   // Define functions that don't require ill-formed conversions for a given
9074   // argument to be better candidates than functions that do.
9075   unsigned NumArgs = Cand1.Conversions.size();
9076   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9077   bool HasBetterConversion = false;
9078   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9079     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9080     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9081     if (Cand1Bad != Cand2Bad) {
9082       if (Cand1Bad)
9083         return false;
9084       HasBetterConversion = true;
9085     }
9086   }
9087
9088   if (HasBetterConversion)
9089     return true;
9090
9091   // C++ [over.match.best]p1:
9092   //   A viable function F1 is defined to be a better function than another
9093   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9094   //   conversion sequence than ICSi(F2), and then...
9095   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9096     switch (CompareImplicitConversionSequences(S, Loc,
9097                                                Cand1.Conversions[ArgIdx],
9098                                                Cand2.Conversions[ArgIdx])) {
9099     case ImplicitConversionSequence::Better:
9100       // Cand1 has a better conversion sequence.
9101       HasBetterConversion = true;
9102       break;
9103
9104     case ImplicitConversionSequence::Worse:
9105       // Cand1 can't be better than Cand2.
9106       return false;
9107
9108     case ImplicitConversionSequence::Indistinguishable:
9109       // Do nothing.
9110       break;
9111     }
9112   }
9113
9114   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9115   //       ICSj(F2), or, if not that,
9116   if (HasBetterConversion)
9117     return true;
9118
9119   //   -- the context is an initialization by user-defined conversion
9120   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9121   //      from the return type of F1 to the destination type (i.e.,
9122   //      the type of the entity being initialized) is a better
9123   //      conversion sequence than the standard conversion sequence
9124   //      from the return type of F2 to the destination type.
9125   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9126       Cand1.Function && Cand2.Function &&
9127       isa<CXXConversionDecl>(Cand1.Function) &&
9128       isa<CXXConversionDecl>(Cand2.Function)) {
9129     // First check whether we prefer one of the conversion functions over the
9130     // other. This only distinguishes the results in non-standard, extension
9131     // cases such as the conversion from a lambda closure type to a function
9132     // pointer or block.
9133     ImplicitConversionSequence::CompareKind Result =
9134         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9135     if (Result == ImplicitConversionSequence::Indistinguishable)
9136       Result = CompareStandardConversionSequences(S, Loc,
9137                                                   Cand1.FinalConversion,
9138                                                   Cand2.FinalConversion);
9139
9140     if (Result != ImplicitConversionSequence::Indistinguishable)
9141       return Result == ImplicitConversionSequence::Better;
9142
9143     // FIXME: Compare kind of reference binding if conversion functions
9144     // convert to a reference type used in direct reference binding, per
9145     // C++14 [over.match.best]p1 section 2 bullet 3.
9146   }
9147
9148   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9149   // as combined with the resolution to CWG issue 243.
9150   //
9151   // When the context is initialization by constructor ([over.match.ctor] or
9152   // either phase of [over.match.list]), a constructor is preferred over
9153   // a conversion function.
9154   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9155       Cand1.Function && Cand2.Function &&
9156       isa<CXXConstructorDecl>(Cand1.Function) !=
9157           isa<CXXConstructorDecl>(Cand2.Function))
9158     return isa<CXXConstructorDecl>(Cand1.Function);
9159
9160   //    -- F1 is a non-template function and F2 is a function template
9161   //       specialization, or, if not that,
9162   bool Cand1IsSpecialization = Cand1.Function &&
9163                                Cand1.Function->getPrimaryTemplate();
9164   bool Cand2IsSpecialization = Cand2.Function &&
9165                                Cand2.Function->getPrimaryTemplate();
9166   if (Cand1IsSpecialization != Cand2IsSpecialization)
9167     return Cand2IsSpecialization;
9168
9169   //   -- F1 and F2 are function template specializations, and the function
9170   //      template for F1 is more specialized than the template for F2
9171   //      according to the partial ordering rules described in 14.5.5.2, or,
9172   //      if not that,
9173   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9174     if (FunctionTemplateDecl *BetterTemplate
9175           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9176                                          Cand2.Function->getPrimaryTemplate(),
9177                                          Loc,
9178                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9179                                                              : TPOC_Call,
9180                                          Cand1.ExplicitCallArguments,
9181                                          Cand2.ExplicitCallArguments))
9182       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9183   }
9184
9185   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9186   // A derived-class constructor beats an (inherited) base class constructor.
9187   bool Cand1IsInherited =
9188       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9189   bool Cand2IsInherited =
9190       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9191   if (Cand1IsInherited != Cand2IsInherited)
9192     return Cand2IsInherited;
9193   else if (Cand1IsInherited) {
9194     assert(Cand2IsInherited);
9195     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9196     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9197     if (Cand1Class->isDerivedFrom(Cand2Class))
9198       return true;
9199     if (Cand2Class->isDerivedFrom(Cand1Class))
9200       return false;
9201     // Inherited from sibling base classes: still ambiguous.
9202   }
9203
9204   // Check C++17 tie-breakers for deduction guides.
9205   {
9206     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9207     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9208     if (Guide1 && Guide2) {
9209       //  -- F1 is generated from a deduction-guide and F2 is not
9210       if (Guide1->isImplicit() != Guide2->isImplicit())
9211         return Guide2->isImplicit();
9212
9213       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9214       if (Guide1->isCopyDeductionCandidate())
9215         return true;
9216     }
9217   }
9218
9219   // Check for enable_if value-based overload resolution.
9220   if (Cand1.Function && Cand2.Function) {
9221     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9222     if (Cmp != Comparison::Equal)
9223       return Cmp == Comparison::Better;
9224   }
9225
9226   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9227     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9228     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9229            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9230   }
9231
9232   bool HasPS1 = Cand1.Function != nullptr &&
9233                 functionHasPassObjectSizeParams(Cand1.Function);
9234   bool HasPS2 = Cand2.Function != nullptr &&
9235                 functionHasPassObjectSizeParams(Cand2.Function);
9236   if (HasPS1 != HasPS2 && HasPS1)
9237     return true;
9238
9239   return isBetterMultiversionCandidate(Cand1, Cand2);
9240 }
9241
9242 /// Determine whether two declarations are "equivalent" for the purposes of
9243 /// name lookup and overload resolution. This applies when the same internal/no
9244 /// linkage entity is defined by two modules (probably by textually including
9245 /// the same header). In such a case, we don't consider the declarations to
9246 /// declare the same entity, but we also don't want lookups with both
9247 /// declarations visible to be ambiguous in some cases (this happens when using
9248 /// a modularized libstdc++).
9249 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9250                                                   const NamedDecl *B) {
9251   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9252   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9253   if (!VA || !VB)
9254     return false;
9255
9256   // The declarations must be declaring the same name as an internal linkage
9257   // entity in different modules.
9258   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9259           VB->getDeclContext()->getRedeclContext()) ||
9260       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9261           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9262       VA->isExternallyVisible() || VB->isExternallyVisible())
9263     return false;
9264
9265   // Check that the declarations appear to be equivalent.
9266   //
9267   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9268   // For constants and functions, we should check the initializer or body is
9269   // the same. For non-constant variables, we shouldn't allow it at all.
9270   if (Context.hasSameType(VA->getType(), VB->getType()))
9271     return true;
9272
9273   // Enum constants within unnamed enumerations will have different types, but
9274   // may still be similar enough to be interchangeable for our purposes.
9275   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9276     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9277       // Only handle anonymous enums. If the enumerations were named and
9278       // equivalent, they would have been merged to the same type.
9279       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9280       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9281       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9282           !Context.hasSameType(EnumA->getIntegerType(),
9283                                EnumB->getIntegerType()))
9284         return false;
9285       // Allow this only if the value is the same for both enumerators.
9286       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9287     }
9288   }
9289
9290   // Nothing else is sufficiently similar.
9291   return false;
9292 }
9293
9294 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9295     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9296   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9297
9298   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9299   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9300       << !M << (M ? M->getFullModuleName() : "");
9301
9302   for (auto *E : Equiv) {
9303     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9304     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9305         << !M << (M ? M->getFullModuleName() : "");
9306   }
9307 }
9308
9309 /// Computes the best viable function (C++ 13.3.3)
9310 /// within an overload candidate set.
9311 ///
9312 /// \param Loc The location of the function name (or operator symbol) for
9313 /// which overload resolution occurs.
9314 ///
9315 /// \param Best If overload resolution was successful or found a deleted
9316 /// function, \p Best points to the candidate function found.
9317 ///
9318 /// \returns The result of overload resolution.
9319 OverloadingResult
9320 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9321                                          iterator &Best) {
9322   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9323   std::transform(begin(), end(), std::back_inserter(Candidates),
9324                  [](OverloadCandidate &Cand) { return &Cand; });
9325
9326   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9327   // are accepted by both clang and NVCC. However, during a particular
9328   // compilation mode only one call variant is viable. We need to
9329   // exclude non-viable overload candidates from consideration based
9330   // only on their host/device attributes. Specifically, if one
9331   // candidate call is WrongSide and the other is SameSide, we ignore
9332   // the WrongSide candidate.
9333   if (S.getLangOpts().CUDA) {
9334     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9335     bool ContainsSameSideCandidate =
9336         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9337           return Cand->Function &&
9338                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9339                      Sema::CFP_SameSide;
9340         });
9341     if (ContainsSameSideCandidate) {
9342       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9343         return Cand->Function &&
9344                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9345                    Sema::CFP_WrongSide;
9346       };
9347       llvm::erase_if(Candidates, IsWrongSideCandidate);
9348     }
9349   }
9350
9351   // Find the best viable function.
9352   Best = end();
9353   for (auto *Cand : Candidates)
9354     if (Cand->Viable)
9355       if (Best == end() ||
9356           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9357         Best = Cand;
9358
9359   // If we didn't find any viable functions, abort.
9360   if (Best == end())
9361     return OR_No_Viable_Function;
9362
9363   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9364
9365   // Make sure that this function is better than every other viable
9366   // function. If not, we have an ambiguity.
9367   for (auto *Cand : Candidates) {
9368     if (Cand->Viable && Cand != Best &&
9369         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9370       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9371                                                    Cand->Function)) {
9372         EquivalentCands.push_back(Cand->Function);
9373         continue;
9374       }
9375
9376       Best = end();
9377       return OR_Ambiguous;
9378     }
9379   }
9380
9381   // Best is the best viable function.
9382   if (Best->Function &&
9383       (Best->Function->isDeleted() ||
9384        S.isFunctionConsideredUnavailable(Best->Function)))
9385     return OR_Deleted;
9386
9387   if (!EquivalentCands.empty())
9388     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9389                                                     EquivalentCands);
9390
9391   return OR_Success;
9392 }
9393
9394 namespace {
9395
9396 enum OverloadCandidateKind {
9397   oc_function,
9398   oc_method,
9399   oc_constructor,
9400   oc_implicit_default_constructor,
9401   oc_implicit_copy_constructor,
9402   oc_implicit_move_constructor,
9403   oc_implicit_copy_assignment,
9404   oc_implicit_move_assignment,
9405   oc_inherited_constructor
9406 };
9407
9408 enum OverloadCandidateSelect {
9409   ocs_non_template,
9410   ocs_template,
9411   ocs_described_template,
9412 };
9413
9414 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9415 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9416                           std::string &Description) {
9417
9418   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9419   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9420     isTemplate = true;
9421     Description = S.getTemplateArgumentBindingsText(
9422         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9423   }
9424
9425   OverloadCandidateSelect Select = [&]() {
9426     if (!Description.empty())
9427       return ocs_described_template;
9428     return isTemplate ? ocs_template : ocs_non_template;
9429   }();
9430
9431   OverloadCandidateKind Kind = [&]() {
9432     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9433       if (!Ctor->isImplicit()) {
9434         if (isa<ConstructorUsingShadowDecl>(Found))
9435           return oc_inherited_constructor;
9436         else
9437           return oc_constructor;
9438       }
9439
9440       if (Ctor->isDefaultConstructor())
9441         return oc_implicit_default_constructor;
9442
9443       if (Ctor->isMoveConstructor())
9444         return oc_implicit_move_constructor;
9445
9446       assert(Ctor->isCopyConstructor() &&
9447              "unexpected sort of implicit constructor");
9448       return oc_implicit_copy_constructor;
9449     }
9450
9451     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9452       // This actually gets spelled 'candidate function' for now, but
9453       // it doesn't hurt to split it out.
9454       if (!Meth->isImplicit())
9455         return oc_method;
9456
9457       if (Meth->isMoveAssignmentOperator())
9458         return oc_implicit_move_assignment;
9459
9460       if (Meth->isCopyAssignmentOperator())
9461         return oc_implicit_copy_assignment;
9462
9463       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9464       return oc_method;
9465     }
9466
9467     return oc_function;
9468   }();
9469
9470   return std::make_pair(Kind, Select);
9471 }
9472
9473 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9474   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9475   // set.
9476   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9477     S.Diag(FoundDecl->getLocation(),
9478            diag::note_ovl_candidate_inherited_constructor)
9479       << Shadow->getNominatedBaseClass();
9480 }
9481
9482 } // end anonymous namespace
9483
9484 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9485                                     const FunctionDecl *FD) {
9486   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9487     bool AlwaysTrue;
9488     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9489       return false;
9490     if (!AlwaysTrue)
9491       return false;
9492   }
9493   return true;
9494 }
9495
9496 /// Returns true if we can take the address of the function.
9497 ///
9498 /// \param Complain - If true, we'll emit a diagnostic
9499 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9500 ///   we in overload resolution?
9501 /// \param Loc - The location of the statement we're complaining about. Ignored
9502 ///   if we're not complaining, or if we're in overload resolution.
9503 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9504                                               bool Complain,
9505                                               bool InOverloadResolution,
9506                                               SourceLocation Loc) {
9507   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9508     if (Complain) {
9509       if (InOverloadResolution)
9510         S.Diag(FD->getLocStart(),
9511                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9512       else
9513         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9514     }
9515     return false;
9516   }
9517
9518   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9519     return P->hasAttr<PassObjectSizeAttr>();
9520   });
9521   if (I == FD->param_end())
9522     return true;
9523
9524   if (Complain) {
9525     // Add one to ParamNo because it's user-facing
9526     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9527     if (InOverloadResolution)
9528       S.Diag(FD->getLocation(),
9529              diag::note_ovl_candidate_has_pass_object_size_params)
9530           << ParamNo;
9531     else
9532       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9533           << FD << ParamNo;
9534   }
9535   return false;
9536 }
9537
9538 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9539                                                const FunctionDecl *FD) {
9540   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9541                                            /*InOverloadResolution=*/true,
9542                                            /*Loc=*/SourceLocation());
9543 }
9544
9545 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9546                                              bool Complain,
9547                                              SourceLocation Loc) {
9548   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9549                                              /*InOverloadResolution=*/false,
9550                                              Loc);
9551 }
9552
9553 // Notes the location of an overload candidate.
9554 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9555                                  QualType DestType, bool TakingAddress) {
9556   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9557     return;
9558   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9559       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9560     return;
9561
9562   std::string FnDesc;
9563   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9564       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9565   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9566                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9567                          << Fn << FnDesc;
9568
9569   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9570   Diag(Fn->getLocation(), PD);
9571   MaybeEmitInheritedConstructorNote(*this, Found);
9572 }
9573
9574 // Notes the location of all overload candidates designated through
9575 // OverloadedExpr
9576 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9577                                      bool TakingAddress) {
9578   assert(OverloadedExpr->getType() == Context.OverloadTy);
9579
9580   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9581   OverloadExpr *OvlExpr = Ovl.Expression;
9582
9583   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9584                             IEnd = OvlExpr->decls_end();
9585        I != IEnd; ++I) {
9586     if (FunctionTemplateDecl *FunTmpl =
9587                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9588       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9589                             TakingAddress);
9590     } else if (FunctionDecl *Fun
9591                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9592       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9593     }
9594   }
9595 }
9596
9597 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9598 /// "lead" diagnostic; it will be given two arguments, the source and
9599 /// target types of the conversion.
9600 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9601                                  Sema &S,
9602                                  SourceLocation CaretLoc,
9603                                  const PartialDiagnostic &PDiag) const {
9604   S.Diag(CaretLoc, PDiag)
9605     << Ambiguous.getFromType() << Ambiguous.getToType();
9606   // FIXME: The note limiting machinery is borrowed from
9607   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9608   // refactoring here.
9609   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9610   unsigned CandsShown = 0;
9611   AmbiguousConversionSequence::const_iterator I, E;
9612   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9613     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9614       break;
9615     ++CandsShown;
9616     S.NoteOverloadCandidate(I->first, I->second);
9617   }
9618   if (I != E)
9619     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9620 }
9621
9622 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9623                                   unsigned I, bool TakingCandidateAddress) {
9624   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9625   assert(Conv.isBad());
9626   assert(Cand->Function && "for now, candidate must be a function");
9627   FunctionDecl *Fn = Cand->Function;
9628
9629   // There's a conversion slot for the object argument if this is a
9630   // non-constructor method.  Note that 'I' corresponds the
9631   // conversion-slot index.
9632   bool isObjectArgument = false;
9633   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9634     if (I == 0)
9635       isObjectArgument = true;
9636     else
9637       I--;
9638   }
9639
9640   std::string FnDesc;
9641   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9642       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9643
9644   Expr *FromExpr = Conv.Bad.FromExpr;
9645   QualType FromTy = Conv.Bad.getFromType();
9646   QualType ToTy = Conv.Bad.getToType();
9647
9648   if (FromTy == S.Context.OverloadTy) {
9649     assert(FromExpr && "overload set argument came from implicit argument?");
9650     Expr *E = FromExpr->IgnoreParens();
9651     if (isa<UnaryOperator>(E))
9652       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9653     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9654
9655     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9656         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9657         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9658         << Name << I + 1;
9659     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9660     return;
9661   }
9662
9663   // Do some hand-waving analysis to see if the non-viability is due
9664   // to a qualifier mismatch.
9665   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9666   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9667   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9668     CToTy = RT->getPointeeType();
9669   else {
9670     // TODO: detect and diagnose the full richness of const mismatches.
9671     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9672       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9673         CFromTy = FromPT->getPointeeType();
9674         CToTy = ToPT->getPointeeType();
9675       }
9676   }
9677
9678   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9679       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9680     Qualifiers FromQs = CFromTy.getQualifiers();
9681     Qualifiers ToQs = CToTy.getQualifiers();
9682
9683     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9684       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9685           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9686           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9687           << ToTy << (unsigned)isObjectArgument << I + 1;
9688       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9689       return;
9690     }
9691
9692     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9693       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9694           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9695           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9696           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9697           << (unsigned)isObjectArgument << I + 1;
9698       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9699       return;
9700     }
9701
9702     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9703       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9704           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9705           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9706           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9707           << (unsigned)isObjectArgument << I + 1;
9708       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9709       return;
9710     }
9711
9712     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9713       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9714           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9715           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9716           << FromQs.hasUnaligned() << I + 1;
9717       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9718       return;
9719     }
9720
9721     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9722     assert(CVR && "unexpected qualifiers mismatch");
9723
9724     if (isObjectArgument) {
9725       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9726           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9727           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9728           << (CVR - 1);
9729     } else {
9730       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9731           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9732           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9733           << (CVR - 1) << I + 1;
9734     }
9735     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9736     return;
9737   }
9738
9739   // Special diagnostic for failure to convert an initializer list, since
9740   // telling the user that it has type void is not useful.
9741   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9742     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9743         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9744         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9745         << ToTy << (unsigned)isObjectArgument << I + 1;
9746     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9747     return;
9748   }
9749
9750   // Diagnose references or pointers to incomplete types differently,
9751   // since it's far from impossible that the incompleteness triggered
9752   // the failure.
9753   QualType TempFromTy = FromTy.getNonReferenceType();
9754   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9755     TempFromTy = PTy->getPointeeType();
9756   if (TempFromTy->isIncompleteType()) {
9757     // Emit the generic diagnostic and, optionally, add the hints to it.
9758     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9759         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9760         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9761         << ToTy << (unsigned)isObjectArgument << I + 1
9762         << (unsigned)(Cand->Fix.Kind);
9763
9764     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9765     return;
9766   }
9767
9768   // Diagnose base -> derived pointer conversions.
9769   unsigned BaseToDerivedConversion = 0;
9770   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9771     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9772       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9773                                                FromPtrTy->getPointeeType()) &&
9774           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9775           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9776           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9777                           FromPtrTy->getPointeeType()))
9778         BaseToDerivedConversion = 1;
9779     }
9780   } else if (const ObjCObjectPointerType *FromPtrTy
9781                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9782     if (const ObjCObjectPointerType *ToPtrTy
9783                                         = ToTy->getAs<ObjCObjectPointerType>())
9784       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9785         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9786           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9787                                                 FromPtrTy->getPointeeType()) &&
9788               FromIface->isSuperClassOf(ToIface))
9789             BaseToDerivedConversion = 2;
9790   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9791     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9792         !FromTy->isIncompleteType() &&
9793         !ToRefTy->getPointeeType()->isIncompleteType() &&
9794         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9795       BaseToDerivedConversion = 3;
9796     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9797                ToTy.getNonReferenceType().getCanonicalType() ==
9798                FromTy.getNonReferenceType().getCanonicalType()) {
9799       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9800           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9801           << (unsigned)isObjectArgument << I + 1
9802           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9803       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9804       return;
9805     }
9806   }
9807
9808   if (BaseToDerivedConversion) {
9809     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9810         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9811         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9812         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9813     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9814     return;
9815   }
9816
9817   if (isa<ObjCObjectPointerType>(CFromTy) &&
9818       isa<PointerType>(CToTy)) {
9819       Qualifiers FromQs = CFromTy.getQualifiers();
9820       Qualifiers ToQs = CToTy.getQualifiers();
9821       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9822         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9823             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9824             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9825             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9826         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9827         return;
9828       }
9829   }
9830
9831   if (TakingCandidateAddress &&
9832       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9833     return;
9834
9835   // Emit the generic diagnostic and, optionally, add the hints to it.
9836   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9837   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9838         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9839         << ToTy << (unsigned)isObjectArgument << I + 1
9840         << (unsigned)(Cand->Fix.Kind);
9841
9842   // If we can fix the conversion, suggest the FixIts.
9843   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9844        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9845     FDiag << *HI;
9846   S.Diag(Fn->getLocation(), FDiag);
9847
9848   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9849 }
9850
9851 /// Additional arity mismatch diagnosis specific to a function overload
9852 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9853 /// over a candidate in any candidate set.
9854 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9855                                unsigned NumArgs) {
9856   FunctionDecl *Fn = Cand->Function;
9857   unsigned MinParams = Fn->getMinRequiredArguments();
9858
9859   // With invalid overloaded operators, it's possible that we think we
9860   // have an arity mismatch when in fact it looks like we have the
9861   // right number of arguments, because only overloaded operators have
9862   // the weird behavior of overloading member and non-member functions.
9863   // Just don't report anything.
9864   if (Fn->isInvalidDecl() &&
9865       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9866     return true;
9867
9868   if (NumArgs < MinParams) {
9869     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9870            (Cand->FailureKind == ovl_fail_bad_deduction &&
9871             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9872   } else {
9873     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9874            (Cand->FailureKind == ovl_fail_bad_deduction &&
9875             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9876   }
9877
9878   return false;
9879 }
9880
9881 /// General arity mismatch diagnosis over a candidate in a candidate set.
9882 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9883                                   unsigned NumFormalArgs) {
9884   assert(isa<FunctionDecl>(D) &&
9885       "The templated declaration should at least be a function"
9886       " when diagnosing bad template argument deduction due to too many"
9887       " or too few arguments");
9888
9889   FunctionDecl *Fn = cast<FunctionDecl>(D);
9890
9891   // TODO: treat calls to a missing default constructor as a special case
9892   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9893   unsigned MinParams = Fn->getMinRequiredArguments();
9894
9895   // at least / at most / exactly
9896   unsigned mode, modeCount;
9897   if (NumFormalArgs < MinParams) {
9898     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9899         FnTy->isTemplateVariadic())
9900       mode = 0; // "at least"
9901     else
9902       mode = 2; // "exactly"
9903     modeCount = MinParams;
9904   } else {
9905     if (MinParams != FnTy->getNumParams())
9906       mode = 1; // "at most"
9907     else
9908       mode = 2; // "exactly"
9909     modeCount = FnTy->getNumParams();
9910   }
9911
9912   std::string Description;
9913   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9914       ClassifyOverloadCandidate(S, Found, Fn, Description);
9915
9916   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9917     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9918         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9919         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9920   else
9921     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9922         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9923         << Description << mode << modeCount << NumFormalArgs;
9924
9925   MaybeEmitInheritedConstructorNote(S, Found);
9926 }
9927
9928 /// Arity mismatch diagnosis specific to a function overload candidate.
9929 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9930                                   unsigned NumFormalArgs) {
9931   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9932     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9933 }
9934
9935 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9936   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9937     return TD;
9938   llvm_unreachable("Unsupported: Getting the described template declaration"
9939                    " for bad deduction diagnosis");
9940 }
9941
9942 /// Diagnose a failed template-argument deduction.
9943 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9944                                  DeductionFailureInfo &DeductionFailure,
9945                                  unsigned NumArgs,
9946                                  bool TakingCandidateAddress) {
9947   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9948   NamedDecl *ParamD;
9949   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9950   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9951   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9952   switch (DeductionFailure.Result) {
9953   case Sema::TDK_Success:
9954     llvm_unreachable("TDK_success while diagnosing bad deduction");
9955
9956   case Sema::TDK_Incomplete: {
9957     assert(ParamD && "no parameter found for incomplete deduction result");
9958     S.Diag(Templated->getLocation(),
9959            diag::note_ovl_candidate_incomplete_deduction)
9960         << ParamD->getDeclName();
9961     MaybeEmitInheritedConstructorNote(S, Found);
9962     return;
9963   }
9964
9965   case Sema::TDK_IncompletePack: {
9966     assert(ParamD && "no parameter found for incomplete deduction result");
9967     S.Diag(Templated->getLocation(),
9968            diag::note_ovl_candidate_incomplete_deduction_pack)
9969         << ParamD->getDeclName()
9970         << (DeductionFailure.getFirstArg()->pack_size() + 1)
9971         << *DeductionFailure.getFirstArg();
9972     MaybeEmitInheritedConstructorNote(S, Found);
9973     return;
9974   }
9975
9976   case Sema::TDK_Underqualified: {
9977     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9978     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9979
9980     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9981
9982     // Param will have been canonicalized, but it should just be a
9983     // qualified version of ParamD, so move the qualifiers to that.
9984     QualifierCollector Qs;
9985     Qs.strip(Param);
9986     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9987     assert(S.Context.hasSameType(Param, NonCanonParam));
9988
9989     // Arg has also been canonicalized, but there's nothing we can do
9990     // about that.  It also doesn't matter as much, because it won't
9991     // have any template parameters in it (because deduction isn't
9992     // done on dependent types).
9993     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9994
9995     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9996         << ParamD->getDeclName() << Arg << NonCanonParam;
9997     MaybeEmitInheritedConstructorNote(S, Found);
9998     return;
9999   }
10000
10001   case Sema::TDK_Inconsistent: {
10002     assert(ParamD && "no parameter found for inconsistent deduction result");
10003     int which = 0;
10004     if (isa<TemplateTypeParmDecl>(ParamD))
10005       which = 0;
10006     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10007       // Deduction might have failed because we deduced arguments of two
10008       // different types for a non-type template parameter.
10009       // FIXME: Use a different TDK value for this.
10010       QualType T1 =
10011           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10012       QualType T2 =
10013           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10014       if (!S.Context.hasSameType(T1, T2)) {
10015         S.Diag(Templated->getLocation(),
10016                diag::note_ovl_candidate_inconsistent_deduction_types)
10017           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10018           << *DeductionFailure.getSecondArg() << T2;
10019         MaybeEmitInheritedConstructorNote(S, Found);
10020         return;
10021       }
10022
10023       which = 1;
10024     } else {
10025       which = 2;
10026     }
10027
10028     S.Diag(Templated->getLocation(),
10029            diag::note_ovl_candidate_inconsistent_deduction)
10030         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10031         << *DeductionFailure.getSecondArg();
10032     MaybeEmitInheritedConstructorNote(S, Found);
10033     return;
10034   }
10035
10036   case Sema::TDK_InvalidExplicitArguments:
10037     assert(ParamD && "no parameter found for invalid explicit arguments");
10038     if (ParamD->getDeclName())
10039       S.Diag(Templated->getLocation(),
10040              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10041           << ParamD->getDeclName();
10042     else {
10043       int index = 0;
10044       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10045         index = TTP->getIndex();
10046       else if (NonTypeTemplateParmDecl *NTTP
10047                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10048         index = NTTP->getIndex();
10049       else
10050         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10051       S.Diag(Templated->getLocation(),
10052              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10053           << (index + 1);
10054     }
10055     MaybeEmitInheritedConstructorNote(S, Found);
10056     return;
10057
10058   case Sema::TDK_TooManyArguments:
10059   case Sema::TDK_TooFewArguments:
10060     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10061     return;
10062
10063   case Sema::TDK_InstantiationDepth:
10064     S.Diag(Templated->getLocation(),
10065            diag::note_ovl_candidate_instantiation_depth);
10066     MaybeEmitInheritedConstructorNote(S, Found);
10067     return;
10068
10069   case Sema::TDK_SubstitutionFailure: {
10070     // Format the template argument list into the argument string.
10071     SmallString<128> TemplateArgString;
10072     if (TemplateArgumentList *Args =
10073             DeductionFailure.getTemplateArgumentList()) {
10074       TemplateArgString = " ";
10075       TemplateArgString += S.getTemplateArgumentBindingsText(
10076           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10077     }
10078
10079     // If this candidate was disabled by enable_if, say so.
10080     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10081     if (PDiag && PDiag->second.getDiagID() ==
10082           diag::err_typename_nested_not_found_enable_if) {
10083       // FIXME: Use the source range of the condition, and the fully-qualified
10084       //        name of the enable_if template. These are both present in PDiag.
10085       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10086         << "'enable_if'" << TemplateArgString;
10087       return;
10088     }
10089
10090     // We found a specific requirement that disabled the enable_if.
10091     if (PDiag && PDiag->second.getDiagID() ==
10092         diag::err_typename_nested_not_found_requirement) {
10093       S.Diag(Templated->getLocation(),
10094              diag::note_ovl_candidate_disabled_by_requirement)
10095         << PDiag->second.getStringArg(0) << TemplateArgString;
10096       return;
10097     }
10098
10099     // Format the SFINAE diagnostic into the argument string.
10100     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10101     //        formatted message in another diagnostic.
10102     SmallString<128> SFINAEArgString;
10103     SourceRange R;
10104     if (PDiag) {
10105       SFINAEArgString = ": ";
10106       R = SourceRange(PDiag->first, PDiag->first);
10107       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10108     }
10109
10110     S.Diag(Templated->getLocation(),
10111            diag::note_ovl_candidate_substitution_failure)
10112         << TemplateArgString << SFINAEArgString << R;
10113     MaybeEmitInheritedConstructorNote(S, Found);
10114     return;
10115   }
10116
10117   case Sema::TDK_DeducedMismatch:
10118   case Sema::TDK_DeducedMismatchNested: {
10119     // Format the template argument list into the argument string.
10120     SmallString<128> TemplateArgString;
10121     if (TemplateArgumentList *Args =
10122             DeductionFailure.getTemplateArgumentList()) {
10123       TemplateArgString = " ";
10124       TemplateArgString += S.getTemplateArgumentBindingsText(
10125           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10126     }
10127
10128     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10129         << (*DeductionFailure.getCallArgIndex() + 1)
10130         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10131         << TemplateArgString
10132         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10133     break;
10134   }
10135
10136   case Sema::TDK_NonDeducedMismatch: {
10137     // FIXME: Provide a source location to indicate what we couldn't match.
10138     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10139     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10140     if (FirstTA.getKind() == TemplateArgument::Template &&
10141         SecondTA.getKind() == TemplateArgument::Template) {
10142       TemplateName FirstTN = FirstTA.getAsTemplate();
10143       TemplateName SecondTN = SecondTA.getAsTemplate();
10144       if (FirstTN.getKind() == TemplateName::Template &&
10145           SecondTN.getKind() == TemplateName::Template) {
10146         if (FirstTN.getAsTemplateDecl()->getName() ==
10147             SecondTN.getAsTemplateDecl()->getName()) {
10148           // FIXME: This fixes a bad diagnostic where both templates are named
10149           // the same.  This particular case is a bit difficult since:
10150           // 1) It is passed as a string to the diagnostic printer.
10151           // 2) The diagnostic printer only attempts to find a better
10152           //    name for types, not decls.
10153           // Ideally, this should folded into the diagnostic printer.
10154           S.Diag(Templated->getLocation(),
10155                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10156               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10157           return;
10158         }
10159       }
10160     }
10161
10162     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10163         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10164       return;
10165
10166     // FIXME: For generic lambda parameters, check if the function is a lambda
10167     // call operator, and if so, emit a prettier and more informative
10168     // diagnostic that mentions 'auto' and lambda in addition to
10169     // (or instead of?) the canonical template type parameters.
10170     S.Diag(Templated->getLocation(),
10171            diag::note_ovl_candidate_non_deduced_mismatch)
10172         << FirstTA << SecondTA;
10173     return;
10174   }
10175   // TODO: diagnose these individually, then kill off
10176   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10177   case Sema::TDK_MiscellaneousDeductionFailure:
10178     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10179     MaybeEmitInheritedConstructorNote(S, Found);
10180     return;
10181   case Sema::TDK_CUDATargetMismatch:
10182     S.Diag(Templated->getLocation(),
10183            diag::note_cuda_ovl_candidate_target_mismatch);
10184     return;
10185   }
10186 }
10187
10188 /// Diagnose a failed template-argument deduction, for function calls.
10189 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10190                                  unsigned NumArgs,
10191                                  bool TakingCandidateAddress) {
10192   unsigned TDK = Cand->DeductionFailure.Result;
10193   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10194     if (CheckArityMismatch(S, Cand, NumArgs))
10195       return;
10196   }
10197   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10198                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10199 }
10200
10201 /// CUDA: diagnose an invalid call across targets.
10202 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10203   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10204   FunctionDecl *Callee = Cand->Function;
10205
10206   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10207                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10208
10209   std::string FnDesc;
10210   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10211       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10212
10213   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10214       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10215       << FnDesc /* Ignored */
10216       << CalleeTarget << CallerTarget;
10217
10218   // This could be an implicit constructor for which we could not infer the
10219   // target due to a collsion. Diagnose that case.
10220   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10221   if (Meth != nullptr && Meth->isImplicit()) {
10222     CXXRecordDecl *ParentClass = Meth->getParent();
10223     Sema::CXXSpecialMember CSM;
10224
10225     switch (FnKindPair.first) {
10226     default:
10227       return;
10228     case oc_implicit_default_constructor:
10229       CSM = Sema::CXXDefaultConstructor;
10230       break;
10231     case oc_implicit_copy_constructor:
10232       CSM = Sema::CXXCopyConstructor;
10233       break;
10234     case oc_implicit_move_constructor:
10235       CSM = Sema::CXXMoveConstructor;
10236       break;
10237     case oc_implicit_copy_assignment:
10238       CSM = Sema::CXXCopyAssignment;
10239       break;
10240     case oc_implicit_move_assignment:
10241       CSM = Sema::CXXMoveAssignment;
10242       break;
10243     };
10244
10245     bool ConstRHS = false;
10246     if (Meth->getNumParams()) {
10247       if (const ReferenceType *RT =
10248               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10249         ConstRHS = RT->getPointeeType().isConstQualified();
10250       }
10251     }
10252
10253     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10254                                               /* ConstRHS */ ConstRHS,
10255                                               /* Diagnose */ true);
10256   }
10257 }
10258
10259 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10260   FunctionDecl *Callee = Cand->Function;
10261   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10262
10263   S.Diag(Callee->getLocation(),
10264          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10265       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10266 }
10267
10268 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10269   FunctionDecl *Callee = Cand->Function;
10270
10271   S.Diag(Callee->getLocation(),
10272          diag::note_ovl_candidate_disabled_by_extension);
10273 }
10274
10275 /// Generates a 'note' diagnostic for an overload candidate.  We've
10276 /// already generated a primary error at the call site.
10277 ///
10278 /// It really does need to be a single diagnostic with its caret
10279 /// pointed at the candidate declaration.  Yes, this creates some
10280 /// major challenges of technical writing.  Yes, this makes pointing
10281 /// out problems with specific arguments quite awkward.  It's still
10282 /// better than generating twenty screens of text for every failed
10283 /// overload.
10284 ///
10285 /// It would be great to be able to express per-candidate problems
10286 /// more richly for those diagnostic clients that cared, but we'd
10287 /// still have to be just as careful with the default diagnostics.
10288 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10289                                   unsigned NumArgs,
10290                                   bool TakingCandidateAddress) {
10291   FunctionDecl *Fn = Cand->Function;
10292
10293   // Note deleted candidates, but only if they're viable.
10294   if (Cand->Viable) {
10295     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10296       std::string FnDesc;
10297       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10298           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10299
10300       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10301           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10302           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10303       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10304       return;
10305     }
10306
10307     // We don't really have anything else to say about viable candidates.
10308     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10309     return;
10310   }
10311
10312   switch (Cand->FailureKind) {
10313   case ovl_fail_too_many_arguments:
10314   case ovl_fail_too_few_arguments:
10315     return DiagnoseArityMismatch(S, Cand, NumArgs);
10316
10317   case ovl_fail_bad_deduction:
10318     return DiagnoseBadDeduction(S, Cand, NumArgs,
10319                                 TakingCandidateAddress);
10320
10321   case ovl_fail_illegal_constructor: {
10322     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10323       << (Fn->getPrimaryTemplate() ? 1 : 0);
10324     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10325     return;
10326   }
10327
10328   case ovl_fail_trivial_conversion:
10329   case ovl_fail_bad_final_conversion:
10330   case ovl_fail_final_conversion_not_exact:
10331     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10332
10333   case ovl_fail_bad_conversion: {
10334     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10335     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10336       if (Cand->Conversions[I].isBad())
10337         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10338
10339     // FIXME: this currently happens when we're called from SemaInit
10340     // when user-conversion overload fails.  Figure out how to handle
10341     // those conditions and diagnose them well.
10342     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10343   }
10344
10345   case ovl_fail_bad_target:
10346     return DiagnoseBadTarget(S, Cand);
10347
10348   case ovl_fail_enable_if:
10349     return DiagnoseFailedEnableIfAttr(S, Cand);
10350
10351   case ovl_fail_ext_disabled:
10352     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10353
10354   case ovl_fail_inhctor_slice:
10355     // It's generally not interesting to note copy/move constructors here.
10356     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10357       return;
10358     S.Diag(Fn->getLocation(),
10359            diag::note_ovl_candidate_inherited_constructor_slice)
10360       << (Fn->getPrimaryTemplate() ? 1 : 0)
10361       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10362     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10363     return;
10364
10365   case ovl_fail_addr_not_available: {
10366     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10367     (void)Available;
10368     assert(!Available);
10369     break;
10370   }
10371   case ovl_non_default_multiversion_function:
10372     // Do nothing, these should simply be ignored.
10373     break;
10374   }
10375 }
10376
10377 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10378   // Desugar the type of the surrogate down to a function type,
10379   // retaining as many typedefs as possible while still showing
10380   // the function type (and, therefore, its parameter types).
10381   QualType FnType = Cand->Surrogate->getConversionType();
10382   bool isLValueReference = false;
10383   bool isRValueReference = false;
10384   bool isPointer = false;
10385   if (const LValueReferenceType *FnTypeRef =
10386         FnType->getAs<LValueReferenceType>()) {
10387     FnType = FnTypeRef->getPointeeType();
10388     isLValueReference = true;
10389   } else if (const RValueReferenceType *FnTypeRef =
10390                FnType->getAs<RValueReferenceType>()) {
10391     FnType = FnTypeRef->getPointeeType();
10392     isRValueReference = true;
10393   }
10394   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10395     FnType = FnTypePtr->getPointeeType();
10396     isPointer = true;
10397   }
10398   // Desugar down to a function type.
10399   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10400   // Reconstruct the pointer/reference as appropriate.
10401   if (isPointer) FnType = S.Context.getPointerType(FnType);
10402   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10403   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10404
10405   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10406     << FnType;
10407 }
10408
10409 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10410                                          SourceLocation OpLoc,
10411                                          OverloadCandidate *Cand) {
10412   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10413   std::string TypeStr("operator");
10414   TypeStr += Opc;
10415   TypeStr += "(";
10416   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10417   if (Cand->Conversions.size() == 1) {
10418     TypeStr += ")";
10419     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10420   } else {
10421     TypeStr += ", ";
10422     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10423     TypeStr += ")";
10424     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10425   }
10426 }
10427
10428 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10429                                          OverloadCandidate *Cand) {
10430   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10431     if (ICS.isBad()) break; // all meaningless after first invalid
10432     if (!ICS.isAmbiguous()) continue;
10433
10434     ICS.DiagnoseAmbiguousConversion(
10435         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10436   }
10437 }
10438
10439 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10440   if (Cand->Function)
10441     return Cand->Function->getLocation();
10442   if (Cand->IsSurrogate)
10443     return Cand->Surrogate->getLocation();
10444   return SourceLocation();
10445 }
10446
10447 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10448   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10449   case Sema::TDK_Success:
10450   case Sema::TDK_NonDependentConversionFailure:
10451     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10452
10453   case Sema::TDK_Invalid:
10454   case Sema::TDK_Incomplete:
10455   case Sema::TDK_IncompletePack:
10456     return 1;
10457
10458   case Sema::TDK_Underqualified:
10459   case Sema::TDK_Inconsistent:
10460     return 2;
10461
10462   case Sema::TDK_SubstitutionFailure:
10463   case Sema::TDK_DeducedMismatch:
10464   case Sema::TDK_DeducedMismatchNested:
10465   case Sema::TDK_NonDeducedMismatch:
10466   case Sema::TDK_MiscellaneousDeductionFailure:
10467   case Sema::TDK_CUDATargetMismatch:
10468     return 3;
10469
10470   case Sema::TDK_InstantiationDepth:
10471     return 4;
10472
10473   case Sema::TDK_InvalidExplicitArguments:
10474     return 5;
10475
10476   case Sema::TDK_TooManyArguments:
10477   case Sema::TDK_TooFewArguments:
10478     return 6;
10479   }
10480   llvm_unreachable("Unhandled deduction result");
10481 }
10482
10483 namespace {
10484 struct CompareOverloadCandidatesForDisplay {
10485   Sema &S;
10486   SourceLocation Loc;
10487   size_t NumArgs;
10488   OverloadCandidateSet::CandidateSetKind CSK;
10489
10490   CompareOverloadCandidatesForDisplay(
10491       Sema &S, SourceLocation Loc, size_t NArgs,
10492       OverloadCandidateSet::CandidateSetKind CSK)
10493       : S(S), NumArgs(NArgs), CSK(CSK) {}
10494
10495   bool operator()(const OverloadCandidate *L,
10496                   const OverloadCandidate *R) {
10497     // Fast-path this check.
10498     if (L == R) return false;
10499
10500     // Order first by viability.
10501     if (L->Viable) {
10502       if (!R->Viable) return true;
10503
10504       // TODO: introduce a tri-valued comparison for overload
10505       // candidates.  Would be more worthwhile if we had a sort
10506       // that could exploit it.
10507       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10508         return true;
10509       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10510         return false;
10511     } else if (R->Viable)
10512       return false;
10513
10514     assert(L->Viable == R->Viable);
10515
10516     // Criteria by which we can sort non-viable candidates:
10517     if (!L->Viable) {
10518       // 1. Arity mismatches come after other candidates.
10519       if (L->FailureKind == ovl_fail_too_many_arguments ||
10520           L->FailureKind == ovl_fail_too_few_arguments) {
10521         if (R->FailureKind == ovl_fail_too_many_arguments ||
10522             R->FailureKind == ovl_fail_too_few_arguments) {
10523           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10524           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10525           if (LDist == RDist) {
10526             if (L->FailureKind == R->FailureKind)
10527               // Sort non-surrogates before surrogates.
10528               return !L->IsSurrogate && R->IsSurrogate;
10529             // Sort candidates requiring fewer parameters than there were
10530             // arguments given after candidates requiring more parameters
10531             // than there were arguments given.
10532             return L->FailureKind == ovl_fail_too_many_arguments;
10533           }
10534           return LDist < RDist;
10535         }
10536         return false;
10537       }
10538       if (R->FailureKind == ovl_fail_too_many_arguments ||
10539           R->FailureKind == ovl_fail_too_few_arguments)
10540         return true;
10541
10542       // 2. Bad conversions come first and are ordered by the number
10543       // of bad conversions and quality of good conversions.
10544       if (L->FailureKind == ovl_fail_bad_conversion) {
10545         if (R->FailureKind != ovl_fail_bad_conversion)
10546           return true;
10547
10548         // The conversion that can be fixed with a smaller number of changes,
10549         // comes first.
10550         unsigned numLFixes = L->Fix.NumConversionsFixed;
10551         unsigned numRFixes = R->Fix.NumConversionsFixed;
10552         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10553         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10554         if (numLFixes != numRFixes) {
10555           return numLFixes < numRFixes;
10556         }
10557
10558         // If there's any ordering between the defined conversions...
10559         // FIXME: this might not be transitive.
10560         assert(L->Conversions.size() == R->Conversions.size());
10561
10562         int leftBetter = 0;
10563         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10564         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10565           switch (CompareImplicitConversionSequences(S, Loc,
10566                                                      L->Conversions[I],
10567                                                      R->Conversions[I])) {
10568           case ImplicitConversionSequence::Better:
10569             leftBetter++;
10570             break;
10571
10572           case ImplicitConversionSequence::Worse:
10573             leftBetter--;
10574             break;
10575
10576           case ImplicitConversionSequence::Indistinguishable:
10577             break;
10578           }
10579         }
10580         if (leftBetter > 0) return true;
10581         if (leftBetter < 0) return false;
10582
10583       } else if (R->FailureKind == ovl_fail_bad_conversion)
10584         return false;
10585
10586       if (L->FailureKind == ovl_fail_bad_deduction) {
10587         if (R->FailureKind != ovl_fail_bad_deduction)
10588           return true;
10589
10590         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10591           return RankDeductionFailure(L->DeductionFailure)
10592                < RankDeductionFailure(R->DeductionFailure);
10593       } else if (R->FailureKind == ovl_fail_bad_deduction)
10594         return false;
10595
10596       // TODO: others?
10597     }
10598
10599     // Sort everything else by location.
10600     SourceLocation LLoc = GetLocationForCandidate(L);
10601     SourceLocation RLoc = GetLocationForCandidate(R);
10602
10603     // Put candidates without locations (e.g. builtins) at the end.
10604     if (LLoc.isInvalid()) return false;
10605     if (RLoc.isInvalid()) return true;
10606
10607     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10608   }
10609 };
10610 }
10611
10612 /// CompleteNonViableCandidate - Normally, overload resolution only
10613 /// computes up to the first bad conversion. Produces the FixIt set if
10614 /// possible.
10615 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10616                                        ArrayRef<Expr *> Args) {
10617   assert(!Cand->Viable);
10618
10619   // Don't do anything on failures other than bad conversion.
10620   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10621
10622   // We only want the FixIts if all the arguments can be corrected.
10623   bool Unfixable = false;
10624   // Use a implicit copy initialization to check conversion fixes.
10625   Cand->Fix.setConversionChecker(TryCopyInitialization);
10626
10627   // Attempt to fix the bad conversion.
10628   unsigned ConvCount = Cand->Conversions.size();
10629   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10630        ++ConvIdx) {
10631     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10632     if (Cand->Conversions[ConvIdx].isInitialized() &&
10633         Cand->Conversions[ConvIdx].isBad()) {
10634       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10635       break;
10636     }
10637   }
10638
10639   // FIXME: this should probably be preserved from the overload
10640   // operation somehow.
10641   bool SuppressUserConversions = false;
10642
10643   unsigned ConvIdx = 0;
10644   ArrayRef<QualType> ParamTypes;
10645
10646   if (Cand->IsSurrogate) {
10647     QualType ConvType
10648       = Cand->Surrogate->getConversionType().getNonReferenceType();
10649     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10650       ConvType = ConvPtrType->getPointeeType();
10651     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10652     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10653     ConvIdx = 1;
10654   } else if (Cand->Function) {
10655     ParamTypes =
10656         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10657     if (isa<CXXMethodDecl>(Cand->Function) &&
10658         !isa<CXXConstructorDecl>(Cand->Function)) {
10659       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10660       ConvIdx = 1;
10661     }
10662   } else {
10663     // Builtin operator.
10664     assert(ConvCount <= 3);
10665     ParamTypes = Cand->BuiltinParamTypes;
10666   }
10667
10668   // Fill in the rest of the conversions.
10669   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10670     if (Cand->Conversions[ConvIdx].isInitialized()) {
10671       // We've already checked this conversion.
10672     } else if (ArgIdx < ParamTypes.size()) {
10673       if (ParamTypes[ArgIdx]->isDependentType())
10674         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10675             Args[ArgIdx]->getType());
10676       else {
10677         Cand->Conversions[ConvIdx] =
10678             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10679                                   SuppressUserConversions,
10680                                   /*InOverloadResolution=*/true,
10681                                   /*AllowObjCWritebackConversion=*/
10682                                   S.getLangOpts().ObjCAutoRefCount);
10683         // Store the FixIt in the candidate if it exists.
10684         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10685           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10686       }
10687     } else
10688       Cand->Conversions[ConvIdx].setEllipsis();
10689   }
10690 }
10691
10692 /// When overload resolution fails, prints diagnostic messages containing the
10693 /// candidates in the candidate set.
10694 void OverloadCandidateSet::NoteCandidates(
10695     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10696     StringRef Opc, SourceLocation OpLoc,
10697     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10698   // Sort the candidates by viability and position.  Sorting directly would
10699   // be prohibitive, so we make a set of pointers and sort those.
10700   SmallVector<OverloadCandidate*, 32> Cands;
10701   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10702   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10703     if (!Filter(*Cand))
10704       continue;
10705     if (Cand->Viable)
10706       Cands.push_back(Cand);
10707     else if (OCD == OCD_AllCandidates) {
10708       CompleteNonViableCandidate(S, Cand, Args);
10709       if (Cand->Function || Cand->IsSurrogate)
10710         Cands.push_back(Cand);
10711       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10712       // want to list every possible builtin candidate.
10713     }
10714   }
10715
10716   std::stable_sort(Cands.begin(), Cands.end(),
10717             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10718
10719   bool ReportedAmbiguousConversions = false;
10720
10721   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10722   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10723   unsigned CandsShown = 0;
10724   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10725     OverloadCandidate *Cand = *I;
10726
10727     // Set an arbitrary limit on the number of candidate functions we'll spam
10728     // the user with.  FIXME: This limit should depend on details of the
10729     // candidate list.
10730     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10731       break;
10732     }
10733     ++CandsShown;
10734
10735     if (Cand->Function)
10736       NoteFunctionCandidate(S, Cand, Args.size(),
10737                             /*TakingCandidateAddress=*/false);
10738     else if (Cand->IsSurrogate)
10739       NoteSurrogateCandidate(S, Cand);
10740     else {
10741       assert(Cand->Viable &&
10742              "Non-viable built-in candidates are not added to Cands.");
10743       // Generally we only see ambiguities including viable builtin
10744       // operators if overload resolution got screwed up by an
10745       // ambiguous user-defined conversion.
10746       //
10747       // FIXME: It's quite possible for different conversions to see
10748       // different ambiguities, though.
10749       if (!ReportedAmbiguousConversions) {
10750         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10751         ReportedAmbiguousConversions = true;
10752       }
10753
10754       // If this is a viable builtin, print it.
10755       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10756     }
10757   }
10758
10759   if (I != E)
10760     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10761 }
10762
10763 static SourceLocation
10764 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10765   return Cand->Specialization ? Cand->Specialization->getLocation()
10766                               : SourceLocation();
10767 }
10768
10769 namespace {
10770 struct CompareTemplateSpecCandidatesForDisplay {
10771   Sema &S;
10772   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10773
10774   bool operator()(const TemplateSpecCandidate *L,
10775                   const TemplateSpecCandidate *R) {
10776     // Fast-path this check.
10777     if (L == R)
10778       return false;
10779
10780     // Assuming that both candidates are not matches...
10781
10782     // Sort by the ranking of deduction failures.
10783     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10784       return RankDeductionFailure(L->DeductionFailure) <
10785              RankDeductionFailure(R->DeductionFailure);
10786
10787     // Sort everything else by location.
10788     SourceLocation LLoc = GetLocationForCandidate(L);
10789     SourceLocation RLoc = GetLocationForCandidate(R);
10790
10791     // Put candidates without locations (e.g. builtins) at the end.
10792     if (LLoc.isInvalid())
10793       return false;
10794     if (RLoc.isInvalid())
10795       return true;
10796
10797     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10798   }
10799 };
10800 }
10801
10802 /// Diagnose a template argument deduction failure.
10803 /// We are treating these failures as overload failures due to bad
10804 /// deductions.
10805 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10806                                                  bool ForTakingAddress) {
10807   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10808                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10809 }
10810
10811 void TemplateSpecCandidateSet::destroyCandidates() {
10812   for (iterator i = begin(), e = end(); i != e; ++i) {
10813     i->DeductionFailure.Destroy();
10814   }
10815 }
10816
10817 void TemplateSpecCandidateSet::clear() {
10818   destroyCandidates();
10819   Candidates.clear();
10820 }
10821
10822 /// NoteCandidates - When no template specialization match is found, prints
10823 /// diagnostic messages containing the non-matching specializations that form
10824 /// the candidate set.
10825 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10826 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10827 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10828   // Sort the candidates by position (assuming no candidate is a match).
10829   // Sorting directly would be prohibitive, so we make a set of pointers
10830   // and sort those.
10831   SmallVector<TemplateSpecCandidate *, 32> Cands;
10832   Cands.reserve(size());
10833   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10834     if (Cand->Specialization)
10835       Cands.push_back(Cand);
10836     // Otherwise, this is a non-matching builtin candidate.  We do not,
10837     // in general, want to list every possible builtin candidate.
10838   }
10839
10840   llvm::sort(Cands.begin(), Cands.end(),
10841              CompareTemplateSpecCandidatesForDisplay(S));
10842
10843   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10844   // for generalization purposes (?).
10845   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10846
10847   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10848   unsigned CandsShown = 0;
10849   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10850     TemplateSpecCandidate *Cand = *I;
10851
10852     // Set an arbitrary limit on the number of candidates we'll spam
10853     // the user with.  FIXME: This limit should depend on details of the
10854     // candidate list.
10855     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10856       break;
10857     ++CandsShown;
10858
10859     assert(Cand->Specialization &&
10860            "Non-matching built-in candidates are not added to Cands.");
10861     Cand->NoteDeductionFailure(S, ForTakingAddress);
10862   }
10863
10864   if (I != E)
10865     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10866 }
10867
10868 // [PossiblyAFunctionType]  -->   [Return]
10869 // NonFunctionType --> NonFunctionType
10870 // R (A) --> R(A)
10871 // R (*)(A) --> R (A)
10872 // R (&)(A) --> R (A)
10873 // R (S::*)(A) --> R (A)
10874 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10875   QualType Ret = PossiblyAFunctionType;
10876   if (const PointerType *ToTypePtr =
10877     PossiblyAFunctionType->getAs<PointerType>())
10878     Ret = ToTypePtr->getPointeeType();
10879   else if (const ReferenceType *ToTypeRef =
10880     PossiblyAFunctionType->getAs<ReferenceType>())
10881     Ret = ToTypeRef->getPointeeType();
10882   else if (const MemberPointerType *MemTypePtr =
10883     PossiblyAFunctionType->getAs<MemberPointerType>())
10884     Ret = MemTypePtr->getPointeeType();
10885   Ret =
10886     Context.getCanonicalType(Ret).getUnqualifiedType();
10887   return Ret;
10888 }
10889
10890 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10891                                  bool Complain = true) {
10892   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10893       S.DeduceReturnType(FD, Loc, Complain))
10894     return true;
10895
10896   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10897   if (S.getLangOpts().CPlusPlus17 &&
10898       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10899       !S.ResolveExceptionSpec(Loc, FPT))
10900     return true;
10901
10902   return false;
10903 }
10904
10905 namespace {
10906 // A helper class to help with address of function resolution
10907 // - allows us to avoid passing around all those ugly parameters
10908 class AddressOfFunctionResolver {
10909   Sema& S;
10910   Expr* SourceExpr;
10911   const QualType& TargetType;
10912   QualType TargetFunctionType; // Extracted function type from target type
10913
10914   bool Complain;
10915   //DeclAccessPair& ResultFunctionAccessPair;
10916   ASTContext& Context;
10917
10918   bool TargetTypeIsNonStaticMemberFunction;
10919   bool FoundNonTemplateFunction;
10920   bool StaticMemberFunctionFromBoundPointer;
10921   bool HasComplained;
10922
10923   OverloadExpr::FindResult OvlExprInfo;
10924   OverloadExpr *OvlExpr;
10925   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10926   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10927   TemplateSpecCandidateSet FailedCandidates;
10928
10929 public:
10930   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10931                             const QualType &TargetType, bool Complain)
10932       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10933         Complain(Complain), Context(S.getASTContext()),
10934         TargetTypeIsNonStaticMemberFunction(
10935             !!TargetType->getAs<MemberPointerType>()),
10936         FoundNonTemplateFunction(false),
10937         StaticMemberFunctionFromBoundPointer(false),
10938         HasComplained(false),
10939         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10940         OvlExpr(OvlExprInfo.Expression),
10941         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10942     ExtractUnqualifiedFunctionTypeFromTargetType();
10943
10944     if (TargetFunctionType->isFunctionType()) {
10945       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10946         if (!UME->isImplicitAccess() &&
10947             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10948           StaticMemberFunctionFromBoundPointer = true;
10949     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10950       DeclAccessPair dap;
10951       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10952               OvlExpr, false, &dap)) {
10953         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10954           if (!Method->isStatic()) {
10955             // If the target type is a non-function type and the function found
10956             // is a non-static member function, pretend as if that was the
10957             // target, it's the only possible type to end up with.
10958             TargetTypeIsNonStaticMemberFunction = true;
10959
10960             // And skip adding the function if its not in the proper form.
10961             // We'll diagnose this due to an empty set of functions.
10962             if (!OvlExprInfo.HasFormOfMemberPointer)
10963               return;
10964           }
10965
10966         Matches.push_back(std::make_pair(dap, Fn));
10967       }
10968       return;
10969     }
10970
10971     if (OvlExpr->hasExplicitTemplateArgs())
10972       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10973
10974     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10975       // C++ [over.over]p4:
10976       //   If more than one function is selected, [...]
10977       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10978         if (FoundNonTemplateFunction)
10979           EliminateAllTemplateMatches();
10980         else
10981           EliminateAllExceptMostSpecializedTemplate();
10982       }
10983     }
10984
10985     if (S.getLangOpts().CUDA && Matches.size() > 1)
10986       EliminateSuboptimalCudaMatches();
10987   }
10988
10989   bool hasComplained() const { return HasComplained; }
10990
10991 private:
10992   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10993     QualType Discard;
10994     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10995            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10996   }
10997
10998   /// \return true if A is considered a better overload candidate for the
10999   /// desired type than B.
11000   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11001     // If A doesn't have exactly the correct type, we don't want to classify it
11002     // as "better" than anything else. This way, the user is required to
11003     // disambiguate for us if there are multiple candidates and no exact match.
11004     return candidateHasExactlyCorrectType(A) &&
11005            (!candidateHasExactlyCorrectType(B) ||
11006             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11007   }
11008
11009   /// \return true if we were able to eliminate all but one overload candidate,
11010   /// false otherwise.
11011   bool eliminiateSuboptimalOverloadCandidates() {
11012     // Same algorithm as overload resolution -- one pass to pick the "best",
11013     // another pass to be sure that nothing is better than the best.
11014     auto Best = Matches.begin();
11015     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11016       if (isBetterCandidate(I->second, Best->second))
11017         Best = I;
11018
11019     const FunctionDecl *BestFn = Best->second;
11020     auto IsBestOrInferiorToBest = [this, BestFn](
11021         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11022       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11023     };
11024
11025     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11026     // option, so we can potentially give the user a better error
11027     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
11028       return false;
11029     Matches[0] = *Best;
11030     Matches.resize(1);
11031     return true;
11032   }
11033
11034   bool isTargetTypeAFunction() const {
11035     return TargetFunctionType->isFunctionType();
11036   }
11037
11038   // [ToType]     [Return]
11039
11040   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11041   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11042   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11043   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11044     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11045   }
11046
11047   // return true if any matching specializations were found
11048   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11049                                    const DeclAccessPair& CurAccessFunPair) {
11050     if (CXXMethodDecl *Method
11051               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11052       // Skip non-static function templates when converting to pointer, and
11053       // static when converting to member pointer.
11054       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11055         return false;
11056     }
11057     else if (TargetTypeIsNonStaticMemberFunction)
11058       return false;
11059
11060     // C++ [over.over]p2:
11061     //   If the name is a function template, template argument deduction is
11062     //   done (14.8.2.2), and if the argument deduction succeeds, the
11063     //   resulting template argument list is used to generate a single
11064     //   function template specialization, which is added to the set of
11065     //   overloaded functions considered.
11066     FunctionDecl *Specialization = nullptr;
11067     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11068     if (Sema::TemplateDeductionResult Result
11069           = S.DeduceTemplateArguments(FunctionTemplate,
11070                                       &OvlExplicitTemplateArgs,
11071                                       TargetFunctionType, Specialization,
11072                                       Info, /*IsAddressOfFunction*/true)) {
11073       // Make a note of the failed deduction for diagnostics.
11074       FailedCandidates.addCandidate()
11075           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11076                MakeDeductionFailureInfo(Context, Result, Info));
11077       return false;
11078     }
11079
11080     // Template argument deduction ensures that we have an exact match or
11081     // compatible pointer-to-function arguments that would be adjusted by ICS.
11082     // This function template specicalization works.
11083     assert(S.isSameOrCompatibleFunctionType(
11084               Context.getCanonicalType(Specialization->getType()),
11085               Context.getCanonicalType(TargetFunctionType)));
11086
11087     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11088       return false;
11089
11090     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11091     return true;
11092   }
11093
11094   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11095                                       const DeclAccessPair& CurAccessFunPair) {
11096     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11097       // Skip non-static functions when converting to pointer, and static
11098       // when converting to member pointer.
11099       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11100         return false;
11101     }
11102     else if (TargetTypeIsNonStaticMemberFunction)
11103       return false;
11104
11105     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11106       if (S.getLangOpts().CUDA)
11107         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11108           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11109             return false;
11110       if (FunDecl->isMultiVersion()) {
11111         const auto *TA = FunDecl->getAttr<TargetAttr>();
11112         if (TA && !TA->isDefaultVersion())
11113           return false;
11114       }
11115
11116       // If any candidate has a placeholder return type, trigger its deduction
11117       // now.
11118       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11119                                Complain)) {
11120         HasComplained |= Complain;
11121         return false;
11122       }
11123
11124       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11125         return false;
11126
11127       // If we're in C, we need to support types that aren't exactly identical.
11128       if (!S.getLangOpts().CPlusPlus ||
11129           candidateHasExactlyCorrectType(FunDecl)) {
11130         Matches.push_back(std::make_pair(
11131             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11132         FoundNonTemplateFunction = true;
11133         return true;
11134       }
11135     }
11136
11137     return false;
11138   }
11139
11140   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11141     bool Ret = false;
11142
11143     // If the overload expression doesn't have the form of a pointer to
11144     // member, don't try to convert it to a pointer-to-member type.
11145     if (IsInvalidFormOfPointerToMemberFunction())
11146       return false;
11147
11148     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11149                                E = OvlExpr->decls_end();
11150          I != E; ++I) {
11151       // Look through any using declarations to find the underlying function.
11152       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11153
11154       // C++ [over.over]p3:
11155       //   Non-member functions and static member functions match
11156       //   targets of type "pointer-to-function" or "reference-to-function."
11157       //   Nonstatic member functions match targets of
11158       //   type "pointer-to-member-function."
11159       // Note that according to DR 247, the containing class does not matter.
11160       if (FunctionTemplateDecl *FunctionTemplate
11161                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11162         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11163           Ret = true;
11164       }
11165       // If we have explicit template arguments supplied, skip non-templates.
11166       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11167                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11168         Ret = true;
11169     }
11170     assert(Ret || Matches.empty());
11171     return Ret;
11172   }
11173
11174   void EliminateAllExceptMostSpecializedTemplate() {
11175     //   [...] and any given function template specialization F1 is
11176     //   eliminated if the set contains a second function template
11177     //   specialization whose function template is more specialized
11178     //   than the function template of F1 according to the partial
11179     //   ordering rules of 14.5.5.2.
11180
11181     // The algorithm specified above is quadratic. We instead use a
11182     // two-pass algorithm (similar to the one used to identify the
11183     // best viable function in an overload set) that identifies the
11184     // best function template (if it exists).
11185
11186     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11187     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11188       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11189
11190     // TODO: It looks like FailedCandidates does not serve much purpose
11191     // here, since the no_viable diagnostic has index 0.
11192     UnresolvedSetIterator Result = S.getMostSpecialized(
11193         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11194         SourceExpr->getLocStart(), S.PDiag(),
11195         S.PDiag(diag::err_addr_ovl_ambiguous)
11196             << Matches[0].second->getDeclName(),
11197         S.PDiag(diag::note_ovl_candidate)
11198             << (unsigned)oc_function << (unsigned)ocs_described_template,
11199         Complain, TargetFunctionType);
11200
11201     if (Result != MatchesCopy.end()) {
11202       // Make it the first and only element
11203       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11204       Matches[0].second = cast<FunctionDecl>(*Result);
11205       Matches.resize(1);
11206     } else
11207       HasComplained |= Complain;
11208   }
11209
11210   void EliminateAllTemplateMatches() {
11211     //   [...] any function template specializations in the set are
11212     //   eliminated if the set also contains a non-template function, [...]
11213     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11214       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11215         ++I;
11216       else {
11217         Matches[I] = Matches[--N];
11218         Matches.resize(N);
11219       }
11220     }
11221   }
11222
11223   void EliminateSuboptimalCudaMatches() {
11224     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11225   }
11226
11227 public:
11228   void ComplainNoMatchesFound() const {
11229     assert(Matches.empty());
11230     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11231         << OvlExpr->getName() << TargetFunctionType
11232         << OvlExpr->getSourceRange();
11233     if (FailedCandidates.empty())
11234       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11235                                   /*TakingAddress=*/true);
11236     else {
11237       // We have some deduction failure messages. Use them to diagnose
11238       // the function templates, and diagnose the non-template candidates
11239       // normally.
11240       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11241                                  IEnd = OvlExpr->decls_end();
11242            I != IEnd; ++I)
11243         if (FunctionDecl *Fun =
11244                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11245           if (!functionHasPassObjectSizeParams(Fun))
11246             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11247                                     /*TakingAddress=*/true);
11248       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11249     }
11250   }
11251
11252   bool IsInvalidFormOfPointerToMemberFunction() const {
11253     return TargetTypeIsNonStaticMemberFunction &&
11254       !OvlExprInfo.HasFormOfMemberPointer;
11255   }
11256
11257   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11258       // TODO: Should we condition this on whether any functions might
11259       // have matched, or is it more appropriate to do that in callers?
11260       // TODO: a fixit wouldn't hurt.
11261       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11262         << TargetType << OvlExpr->getSourceRange();
11263   }
11264
11265   bool IsStaticMemberFunctionFromBoundPointer() const {
11266     return StaticMemberFunctionFromBoundPointer;
11267   }
11268
11269   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11270     S.Diag(OvlExpr->getLocStart(),
11271            diag::err_invalid_form_pointer_member_function)
11272       << OvlExpr->getSourceRange();
11273   }
11274
11275   void ComplainOfInvalidConversion() const {
11276     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11277       << OvlExpr->getName() << TargetType;
11278   }
11279
11280   void ComplainMultipleMatchesFound() const {
11281     assert(Matches.size() > 1);
11282     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11283       << OvlExpr->getName()
11284       << OvlExpr->getSourceRange();
11285     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11286                                 /*TakingAddress=*/true);
11287   }
11288
11289   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11290
11291   int getNumMatches() const { return Matches.size(); }
11292
11293   FunctionDecl* getMatchingFunctionDecl() const {
11294     if (Matches.size() != 1) return nullptr;
11295     return Matches[0].second;
11296   }
11297
11298   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11299     if (Matches.size() != 1) return nullptr;
11300     return &Matches[0].first;
11301   }
11302 };
11303 }
11304
11305 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11306 /// an overloaded function (C++ [over.over]), where @p From is an
11307 /// expression with overloaded function type and @p ToType is the type
11308 /// we're trying to resolve to. For example:
11309 ///
11310 /// @code
11311 /// int f(double);
11312 /// int f(int);
11313 ///
11314 /// int (*pfd)(double) = f; // selects f(double)
11315 /// @endcode
11316 ///
11317 /// This routine returns the resulting FunctionDecl if it could be
11318 /// resolved, and NULL otherwise. When @p Complain is true, this
11319 /// routine will emit diagnostics if there is an error.
11320 FunctionDecl *
11321 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11322                                          QualType TargetType,
11323                                          bool Complain,
11324                                          DeclAccessPair &FoundResult,
11325                                          bool *pHadMultipleCandidates) {
11326   assert(AddressOfExpr->getType() == Context.OverloadTy);
11327
11328   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11329                                      Complain);
11330   int NumMatches = Resolver.getNumMatches();
11331   FunctionDecl *Fn = nullptr;
11332   bool ShouldComplain = Complain && !Resolver.hasComplained();
11333   if (NumMatches == 0 && ShouldComplain) {
11334     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11335       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11336     else
11337       Resolver.ComplainNoMatchesFound();
11338   }
11339   else if (NumMatches > 1 && ShouldComplain)
11340     Resolver.ComplainMultipleMatchesFound();
11341   else if (NumMatches == 1) {
11342     Fn = Resolver.getMatchingFunctionDecl();
11343     assert(Fn);
11344     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11345       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11346     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11347     if (Complain) {
11348       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11349         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11350       else
11351         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11352     }
11353   }
11354
11355   if (pHadMultipleCandidates)
11356     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11357   return Fn;
11358 }
11359
11360 /// Given an expression that refers to an overloaded function, try to
11361 /// resolve that function to a single function that can have its address taken.
11362 /// This will modify `Pair` iff it returns non-null.
11363 ///
11364 /// This routine can only realistically succeed if all but one candidates in the
11365 /// overload set for SrcExpr cannot have their addresses taken.
11366 FunctionDecl *
11367 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11368                                                   DeclAccessPair &Pair) {
11369   OverloadExpr::FindResult R = OverloadExpr::find(E);
11370   OverloadExpr *Ovl = R.Expression;
11371   FunctionDecl *Result = nullptr;
11372   DeclAccessPair DAP;
11373   // Don't use the AddressOfResolver because we're specifically looking for
11374   // cases where we have one overload candidate that lacks
11375   // enable_if/pass_object_size/...
11376   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11377     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11378     if (!FD)
11379       return nullptr;
11380
11381     if (!checkAddressOfFunctionIsAvailable(FD))
11382       continue;
11383
11384     // We have more than one result; quit.
11385     if (Result)
11386       return nullptr;
11387     DAP = I.getPair();
11388     Result = FD;
11389   }
11390
11391   if (Result)
11392     Pair = DAP;
11393   return Result;
11394 }
11395
11396 /// Given an overloaded function, tries to turn it into a non-overloaded
11397 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11398 /// will perform access checks, diagnose the use of the resultant decl, and, if
11399 /// requested, potentially perform a function-to-pointer decay.
11400 ///
11401 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11402 /// Otherwise, returns true. This may emit diagnostics and return true.
11403 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11404     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11405   Expr *E = SrcExpr.get();
11406   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11407
11408   DeclAccessPair DAP;
11409   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11410   if (!Found || Found->isCPUDispatchMultiVersion() ||
11411       Found->isCPUSpecificMultiVersion())
11412     return false;
11413
11414   // Emitting multiple diagnostics for a function that is both inaccessible and
11415   // unavailable is consistent with our behavior elsewhere. So, always check
11416   // for both.
11417   DiagnoseUseOfDecl(Found, E->getExprLoc());
11418   CheckAddressOfMemberAccess(E, DAP);
11419   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11420   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11421     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11422   else
11423     SrcExpr = Fixed;
11424   return true;
11425 }
11426
11427 /// Given an expression that refers to an overloaded function, try to
11428 /// resolve that overloaded function expression down to a single function.
11429 ///
11430 /// This routine can only resolve template-ids that refer to a single function
11431 /// template, where that template-id refers to a single template whose template
11432 /// arguments are either provided by the template-id or have defaults,
11433 /// as described in C++0x [temp.arg.explicit]p3.
11434 ///
11435 /// If no template-ids are found, no diagnostics are emitted and NULL is
11436 /// returned.
11437 FunctionDecl *
11438 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11439                                                   bool Complain,
11440                                                   DeclAccessPair *FoundResult) {
11441   // C++ [over.over]p1:
11442   //   [...] [Note: any redundant set of parentheses surrounding the
11443   //   overloaded function name is ignored (5.1). ]
11444   // C++ [over.over]p1:
11445   //   [...] The overloaded function name can be preceded by the &
11446   //   operator.
11447
11448   // If we didn't actually find any template-ids, we're done.
11449   if (!ovl->hasExplicitTemplateArgs())
11450     return nullptr;
11451
11452   TemplateArgumentListInfo ExplicitTemplateArgs;
11453   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11454   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11455
11456   // Look through all of the overloaded functions, searching for one
11457   // whose type matches exactly.
11458   FunctionDecl *Matched = nullptr;
11459   for (UnresolvedSetIterator I = ovl->decls_begin(),
11460          E = ovl->decls_end(); I != E; ++I) {
11461     // C++0x [temp.arg.explicit]p3:
11462     //   [...] In contexts where deduction is done and fails, or in contexts
11463     //   where deduction is not done, if a template argument list is
11464     //   specified and it, along with any default template arguments,
11465     //   identifies a single function template specialization, then the
11466     //   template-id is an lvalue for the function template specialization.
11467     FunctionTemplateDecl *FunctionTemplate
11468       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11469
11470     // C++ [over.over]p2:
11471     //   If the name is a function template, template argument deduction is
11472     //   done (14.8.2.2), and if the argument deduction succeeds, the
11473     //   resulting template argument list is used to generate a single
11474     //   function template specialization, which is added to the set of
11475     //   overloaded functions considered.
11476     FunctionDecl *Specialization = nullptr;
11477     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11478     if (TemplateDeductionResult Result
11479           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11480                                     Specialization, Info,
11481                                     /*IsAddressOfFunction*/true)) {
11482       // Make a note of the failed deduction for diagnostics.
11483       // TODO: Actually use the failed-deduction info?
11484       FailedCandidates.addCandidate()
11485           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11486                MakeDeductionFailureInfo(Context, Result, Info));
11487       continue;
11488     }
11489
11490     assert(Specialization && "no specialization and no error?");
11491
11492     // Multiple matches; we can't resolve to a single declaration.
11493     if (Matched) {
11494       if (Complain) {
11495         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11496           << ovl->getName();
11497         NoteAllOverloadCandidates(ovl);
11498       }
11499       return nullptr;
11500     }
11501
11502     Matched = Specialization;
11503     if (FoundResult) *FoundResult = I.getPair();
11504   }
11505
11506   if (Matched &&
11507       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11508     return nullptr;
11509
11510   return Matched;
11511 }
11512
11513 // Resolve and fix an overloaded expression that can be resolved
11514 // because it identifies a single function template specialization.
11515 //
11516 // Last three arguments should only be supplied if Complain = true
11517 //
11518 // Return true if it was logically possible to so resolve the
11519 // expression, regardless of whether or not it succeeded.  Always
11520 // returns true if 'complain' is set.
11521 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11522                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11523                       bool complain, SourceRange OpRangeForComplaining,
11524                                            QualType DestTypeForComplaining,
11525                                             unsigned DiagIDForComplaining) {
11526   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11527
11528   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11529
11530   DeclAccessPair found;
11531   ExprResult SingleFunctionExpression;
11532   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11533                            ovl.Expression, /*complain*/ false, &found)) {
11534     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11535       SrcExpr = ExprError();
11536       return true;
11537     }
11538
11539     // It is only correct to resolve to an instance method if we're
11540     // resolving a form that's permitted to be a pointer to member.
11541     // Otherwise we'll end up making a bound member expression, which
11542     // is illegal in all the contexts we resolve like this.
11543     if (!ovl.HasFormOfMemberPointer &&
11544         isa<CXXMethodDecl>(fn) &&
11545         cast<CXXMethodDecl>(fn)->isInstance()) {
11546       if (!complain) return false;
11547
11548       Diag(ovl.Expression->getExprLoc(),
11549            diag::err_bound_member_function)
11550         << 0 << ovl.Expression->getSourceRange();
11551
11552       // TODO: I believe we only end up here if there's a mix of
11553       // static and non-static candidates (otherwise the expression
11554       // would have 'bound member' type, not 'overload' type).
11555       // Ideally we would note which candidate was chosen and why
11556       // the static candidates were rejected.
11557       SrcExpr = ExprError();
11558       return true;
11559     }
11560
11561     // Fix the expression to refer to 'fn'.
11562     SingleFunctionExpression =
11563         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11564
11565     // If desired, do function-to-pointer decay.
11566     if (doFunctionPointerConverion) {
11567       SingleFunctionExpression =
11568         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11569       if (SingleFunctionExpression.isInvalid()) {
11570         SrcExpr = ExprError();
11571         return true;
11572       }
11573     }
11574   }
11575
11576   if (!SingleFunctionExpression.isUsable()) {
11577     if (complain) {
11578       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11579         << ovl.Expression->getName()
11580         << DestTypeForComplaining
11581         << OpRangeForComplaining
11582         << ovl.Expression->getQualifierLoc().getSourceRange();
11583       NoteAllOverloadCandidates(SrcExpr.get());
11584
11585       SrcExpr = ExprError();
11586       return true;
11587     }
11588
11589     return false;
11590   }
11591
11592   SrcExpr = SingleFunctionExpression;
11593   return true;
11594 }
11595
11596 /// Add a single candidate to the overload set.
11597 static void AddOverloadedCallCandidate(Sema &S,
11598                                        DeclAccessPair FoundDecl,
11599                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11600                                        ArrayRef<Expr *> Args,
11601                                        OverloadCandidateSet &CandidateSet,
11602                                        bool PartialOverloading,
11603                                        bool KnownValid) {
11604   NamedDecl *Callee = FoundDecl.getDecl();
11605   if (isa<UsingShadowDecl>(Callee))
11606     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11607
11608   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11609     if (ExplicitTemplateArgs) {
11610       assert(!KnownValid && "Explicit template arguments?");
11611       return;
11612     }
11613     // Prevent ill-formed function decls to be added as overload candidates.
11614     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11615       return;
11616
11617     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11618                            /*SuppressUsedConversions=*/false,
11619                            PartialOverloading);
11620     return;
11621   }
11622
11623   if (FunctionTemplateDecl *FuncTemplate
11624       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11625     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11626                                    ExplicitTemplateArgs, Args, CandidateSet,
11627                                    /*SuppressUsedConversions=*/false,
11628                                    PartialOverloading);
11629     return;
11630   }
11631
11632   assert(!KnownValid && "unhandled case in overloaded call candidate");
11633 }
11634
11635 /// Add the overload candidates named by callee and/or found by argument
11636 /// dependent lookup to the given overload set.
11637 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11638                                        ArrayRef<Expr *> Args,
11639                                        OverloadCandidateSet &CandidateSet,
11640                                        bool PartialOverloading) {
11641
11642 #ifndef NDEBUG
11643   // Verify that ArgumentDependentLookup is consistent with the rules
11644   // in C++0x [basic.lookup.argdep]p3:
11645   //
11646   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11647   //   and let Y be the lookup set produced by argument dependent
11648   //   lookup (defined as follows). If X contains
11649   //
11650   //     -- a declaration of a class member, or
11651   //
11652   //     -- a block-scope function declaration that is not a
11653   //        using-declaration, or
11654   //
11655   //     -- a declaration that is neither a function or a function
11656   //        template
11657   //
11658   //   then Y is empty.
11659
11660   if (ULE->requiresADL()) {
11661     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11662            E = ULE->decls_end(); I != E; ++I) {
11663       assert(!(*I)->getDeclContext()->isRecord());
11664       assert(isa<UsingShadowDecl>(*I) ||
11665              !(*I)->getDeclContext()->isFunctionOrMethod());
11666       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11667     }
11668   }
11669 #endif
11670
11671   // It would be nice to avoid this copy.
11672   TemplateArgumentListInfo TABuffer;
11673   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11674   if (ULE->hasExplicitTemplateArgs()) {
11675     ULE->copyTemplateArgumentsInto(TABuffer);
11676     ExplicitTemplateArgs = &TABuffer;
11677   }
11678
11679   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11680          E = ULE->decls_end(); I != E; ++I)
11681     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11682                                CandidateSet, PartialOverloading,
11683                                /*KnownValid*/ true);
11684
11685   if (ULE->requiresADL())
11686     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11687                                          Args, ExplicitTemplateArgs,
11688                                          CandidateSet, PartialOverloading);
11689 }
11690
11691 /// Determine whether a declaration with the specified name could be moved into
11692 /// a different namespace.
11693 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11694   switch (Name.getCXXOverloadedOperator()) {
11695   case OO_New: case OO_Array_New:
11696   case OO_Delete: case OO_Array_Delete:
11697     return false;
11698
11699   default:
11700     return true;
11701   }
11702 }
11703
11704 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11705 /// template, where the non-dependent name was declared after the template
11706 /// was defined. This is common in code written for a compilers which do not
11707 /// correctly implement two-stage name lookup.
11708 ///
11709 /// Returns true if a viable candidate was found and a diagnostic was issued.
11710 static bool
11711 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11712                        const CXXScopeSpec &SS, LookupResult &R,
11713                        OverloadCandidateSet::CandidateSetKind CSK,
11714                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11715                        ArrayRef<Expr *> Args,
11716                        bool *DoDiagnoseEmptyLookup = nullptr) {
11717   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11718     return false;
11719
11720   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11721     if (DC->isTransparentContext())
11722       continue;
11723
11724     SemaRef.LookupQualifiedName(R, DC);
11725
11726     if (!R.empty()) {
11727       R.suppressDiagnostics();
11728
11729       if (isa<CXXRecordDecl>(DC)) {
11730         // Don't diagnose names we find in classes; we get much better
11731         // diagnostics for these from DiagnoseEmptyLookup.
11732         R.clear();
11733         if (DoDiagnoseEmptyLookup)
11734           *DoDiagnoseEmptyLookup = true;
11735         return false;
11736       }
11737
11738       OverloadCandidateSet Candidates(FnLoc, CSK);
11739       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11740         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11741                                    ExplicitTemplateArgs, Args,
11742                                    Candidates, false, /*KnownValid*/ false);
11743
11744       OverloadCandidateSet::iterator Best;
11745       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11746         // No viable functions. Don't bother the user with notes for functions
11747         // which don't work and shouldn't be found anyway.
11748         R.clear();
11749         return false;
11750       }
11751
11752       // Find the namespaces where ADL would have looked, and suggest
11753       // declaring the function there instead.
11754       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11755       Sema::AssociatedClassSet AssociatedClasses;
11756       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11757                                                  AssociatedNamespaces,
11758                                                  AssociatedClasses);
11759       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11760       if (canBeDeclaredInNamespace(R.getLookupName())) {
11761         DeclContext *Std = SemaRef.getStdNamespace();
11762         for (Sema::AssociatedNamespaceSet::iterator
11763                it = AssociatedNamespaces.begin(),
11764                end = AssociatedNamespaces.end(); it != end; ++it) {
11765           // Never suggest declaring a function within namespace 'std'.
11766           if (Std && Std->Encloses(*it))
11767             continue;
11768
11769           // Never suggest declaring a function within a namespace with a
11770           // reserved name, like __gnu_cxx.
11771           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11772           if (NS &&
11773               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11774             continue;
11775
11776           SuggestedNamespaces.insert(*it);
11777         }
11778       }
11779
11780       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11781         << R.getLookupName();
11782       if (SuggestedNamespaces.empty()) {
11783         SemaRef.Diag(Best->Function->getLocation(),
11784                      diag::note_not_found_by_two_phase_lookup)
11785           << R.getLookupName() << 0;
11786       } else if (SuggestedNamespaces.size() == 1) {
11787         SemaRef.Diag(Best->Function->getLocation(),
11788                      diag::note_not_found_by_two_phase_lookup)
11789           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11790       } else {
11791         // FIXME: It would be useful to list the associated namespaces here,
11792         // but the diagnostics infrastructure doesn't provide a way to produce
11793         // a localized representation of a list of items.
11794         SemaRef.Diag(Best->Function->getLocation(),
11795                      diag::note_not_found_by_two_phase_lookup)
11796           << R.getLookupName() << 2;
11797       }
11798
11799       // Try to recover by calling this function.
11800       return true;
11801     }
11802
11803     R.clear();
11804   }
11805
11806   return false;
11807 }
11808
11809 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11810 /// template, where the non-dependent operator was declared after the template
11811 /// was defined.
11812 ///
11813 /// Returns true if a viable candidate was found and a diagnostic was issued.
11814 static bool
11815 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11816                                SourceLocation OpLoc,
11817                                ArrayRef<Expr *> Args) {
11818   DeclarationName OpName =
11819     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11820   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11821   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11822                                 OverloadCandidateSet::CSK_Operator,
11823                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11824 }
11825
11826 namespace {
11827 class BuildRecoveryCallExprRAII {
11828   Sema &SemaRef;
11829 public:
11830   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11831     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11832     SemaRef.IsBuildingRecoveryCallExpr = true;
11833   }
11834
11835   ~BuildRecoveryCallExprRAII() {
11836     SemaRef.IsBuildingRecoveryCallExpr = false;
11837   }
11838 };
11839
11840 }
11841
11842 static std::unique_ptr<CorrectionCandidateCallback>
11843 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11844               bool HasTemplateArgs, bool AllowTypoCorrection) {
11845   if (!AllowTypoCorrection)
11846     return llvm::make_unique<NoTypoCorrectionCCC>();
11847   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11848                                                   HasTemplateArgs, ME);
11849 }
11850
11851 /// Attempts to recover from a call where no functions were found.
11852 ///
11853 /// Returns true if new candidates were found.
11854 static ExprResult
11855 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11856                       UnresolvedLookupExpr *ULE,
11857                       SourceLocation LParenLoc,
11858                       MutableArrayRef<Expr *> Args,
11859                       SourceLocation RParenLoc,
11860                       bool EmptyLookup, bool AllowTypoCorrection) {
11861   // Do not try to recover if it is already building a recovery call.
11862   // This stops infinite loops for template instantiations like
11863   //
11864   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11865   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11866   //
11867   if (SemaRef.IsBuildingRecoveryCallExpr)
11868     return ExprError();
11869   BuildRecoveryCallExprRAII RCE(SemaRef);
11870
11871   CXXScopeSpec SS;
11872   SS.Adopt(ULE->getQualifierLoc());
11873   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11874
11875   TemplateArgumentListInfo TABuffer;
11876   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11877   if (ULE->hasExplicitTemplateArgs()) {
11878     ULE->copyTemplateArgumentsInto(TABuffer);
11879     ExplicitTemplateArgs = &TABuffer;
11880   }
11881
11882   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11883                  Sema::LookupOrdinaryName);
11884   bool DoDiagnoseEmptyLookup = EmptyLookup;
11885   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11886                               OverloadCandidateSet::CSK_Normal,
11887                               ExplicitTemplateArgs, Args,
11888                               &DoDiagnoseEmptyLookup) &&
11889     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11890         S, SS, R,
11891         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11892                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11893         ExplicitTemplateArgs, Args)))
11894     return ExprError();
11895
11896   assert(!R.empty() && "lookup results empty despite recovery");
11897
11898   // If recovery created an ambiguity, just bail out.
11899   if (R.isAmbiguous()) {
11900     R.suppressDiagnostics();
11901     return ExprError();
11902   }
11903
11904   // Build an implicit member call if appropriate.  Just drop the
11905   // casts and such from the call, we don't really care.
11906   ExprResult NewFn = ExprError();
11907   if ((*R.begin())->isCXXClassMember())
11908     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11909                                                     ExplicitTemplateArgs, S);
11910   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11911     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11912                                         ExplicitTemplateArgs);
11913   else
11914     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11915
11916   if (NewFn.isInvalid())
11917     return ExprError();
11918
11919   // This shouldn't cause an infinite loop because we're giving it
11920   // an expression with viable lookup results, which should never
11921   // end up here.
11922   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11923                                MultiExprArg(Args.data(), Args.size()),
11924                                RParenLoc);
11925 }
11926
11927 /// Constructs and populates an OverloadedCandidateSet from
11928 /// the given function.
11929 /// \returns true when an the ExprResult output parameter has been set.
11930 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11931                                   UnresolvedLookupExpr *ULE,
11932                                   MultiExprArg Args,
11933                                   SourceLocation RParenLoc,
11934                                   OverloadCandidateSet *CandidateSet,
11935                                   ExprResult *Result) {
11936 #ifndef NDEBUG
11937   if (ULE->requiresADL()) {
11938     // To do ADL, we must have found an unqualified name.
11939     assert(!ULE->getQualifier() && "qualified name with ADL");
11940
11941     // We don't perform ADL for implicit declarations of builtins.
11942     // Verify that this was correctly set up.
11943     FunctionDecl *F;
11944     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11945         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11946         F->getBuiltinID() && F->isImplicit())
11947       llvm_unreachable("performing ADL for builtin");
11948
11949     // We don't perform ADL in C.
11950     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11951   }
11952 #endif
11953
11954   UnbridgedCastsSet UnbridgedCasts;
11955   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11956     *Result = ExprError();
11957     return true;
11958   }
11959
11960   // Add the functions denoted by the callee to the set of candidate
11961   // functions, including those from argument-dependent lookup.
11962   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11963
11964   if (getLangOpts().MSVCCompat &&
11965       CurContext->isDependentContext() && !isSFINAEContext() &&
11966       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11967
11968     OverloadCandidateSet::iterator Best;
11969     if (CandidateSet->empty() ||
11970         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11971             OR_No_Viable_Function) {
11972       // In Microsoft mode, if we are inside a template class member function then
11973       // create a type dependent CallExpr. The goal is to postpone name lookup
11974       // to instantiation time to be able to search into type dependent base
11975       // classes.
11976       CallExpr *CE = new (Context) CallExpr(
11977           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11978       CE->setTypeDependent(true);
11979       CE->setValueDependent(true);
11980       CE->setInstantiationDependent(true);
11981       *Result = CE;
11982       return true;
11983     }
11984   }
11985
11986   if (CandidateSet->empty())
11987     return false;
11988
11989   UnbridgedCasts.restore();
11990   return false;
11991 }
11992
11993 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11994 /// the completed call expression. If overload resolution fails, emits
11995 /// diagnostics and returns ExprError()
11996 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11997                                            UnresolvedLookupExpr *ULE,
11998                                            SourceLocation LParenLoc,
11999                                            MultiExprArg Args,
12000                                            SourceLocation RParenLoc,
12001                                            Expr *ExecConfig,
12002                                            OverloadCandidateSet *CandidateSet,
12003                                            OverloadCandidateSet::iterator *Best,
12004                                            OverloadingResult OverloadResult,
12005                                            bool AllowTypoCorrection) {
12006   if (CandidateSet->empty())
12007     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12008                                  RParenLoc, /*EmptyLookup=*/true,
12009                                  AllowTypoCorrection);
12010
12011   switch (OverloadResult) {
12012   case OR_Success: {
12013     FunctionDecl *FDecl = (*Best)->Function;
12014     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12015     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12016       return ExprError();
12017     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12018     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12019                                          ExecConfig);
12020   }
12021
12022   case OR_No_Viable_Function: {
12023     // Try to recover by looking for viable functions which the user might
12024     // have meant to call.
12025     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12026                                                 Args, RParenLoc,
12027                                                 /*EmptyLookup=*/false,
12028                                                 AllowTypoCorrection);
12029     if (!Recovery.isInvalid())
12030       return Recovery;
12031
12032     // If the user passes in a function that we can't take the address of, we
12033     // generally end up emitting really bad error messages. Here, we attempt to
12034     // emit better ones.
12035     for (const Expr *Arg : Args) {
12036       if (!Arg->getType()->isFunctionType())
12037         continue;
12038       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12039         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12040         if (FD &&
12041             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12042                                                        Arg->getExprLoc()))
12043           return ExprError();
12044       }
12045     }
12046
12047     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
12048         << ULE->getName() << Fn->getSourceRange();
12049     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12050     break;
12051   }
12052
12053   case OR_Ambiguous:
12054     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
12055       << ULE->getName() << Fn->getSourceRange();
12056     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12057     break;
12058
12059   case OR_Deleted: {
12060     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
12061       << (*Best)->Function->isDeleted()
12062       << ULE->getName()
12063       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12064       << Fn->getSourceRange();
12065     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12066
12067     // We emitted an error for the unavailable/deleted function call but keep
12068     // the call in the AST.
12069     FunctionDecl *FDecl = (*Best)->Function;
12070     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12071     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12072                                          ExecConfig);
12073   }
12074   }
12075
12076   // Overload resolution failed.
12077   return ExprError();
12078 }
12079
12080 static void markUnaddressableCandidatesUnviable(Sema &S,
12081                                                 OverloadCandidateSet &CS) {
12082   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12083     if (I->Viable &&
12084         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12085       I->Viable = false;
12086       I->FailureKind = ovl_fail_addr_not_available;
12087     }
12088   }
12089 }
12090
12091 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12092 /// (which eventually refers to the declaration Func) and the call
12093 /// arguments Args/NumArgs, attempt to resolve the function call down
12094 /// to a specific function. If overload resolution succeeds, returns
12095 /// the call expression produced by overload resolution.
12096 /// Otherwise, emits diagnostics and returns ExprError.
12097 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12098                                          UnresolvedLookupExpr *ULE,
12099                                          SourceLocation LParenLoc,
12100                                          MultiExprArg Args,
12101                                          SourceLocation RParenLoc,
12102                                          Expr *ExecConfig,
12103                                          bool AllowTypoCorrection,
12104                                          bool CalleesAddressIsTaken) {
12105   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12106                                     OverloadCandidateSet::CSK_Normal);
12107   ExprResult result;
12108
12109   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12110                              &result))
12111     return result;
12112
12113   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12114   // functions that aren't addressible are considered unviable.
12115   if (CalleesAddressIsTaken)
12116     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12117
12118   OverloadCandidateSet::iterator Best;
12119   OverloadingResult OverloadResult =
12120       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12121
12122   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12123                                   RParenLoc, ExecConfig, &CandidateSet,
12124                                   &Best, OverloadResult,
12125                                   AllowTypoCorrection);
12126 }
12127
12128 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12129   return Functions.size() > 1 ||
12130     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12131 }
12132
12133 /// Create a unary operation that may resolve to an overloaded
12134 /// operator.
12135 ///
12136 /// \param OpLoc The location of the operator itself (e.g., '*').
12137 ///
12138 /// \param Opc The UnaryOperatorKind that describes this operator.
12139 ///
12140 /// \param Fns The set of non-member functions that will be
12141 /// considered by overload resolution. The caller needs to build this
12142 /// set based on the context using, e.g.,
12143 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12144 /// set should not contain any member functions; those will be added
12145 /// by CreateOverloadedUnaryOp().
12146 ///
12147 /// \param Input The input argument.
12148 ExprResult
12149 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12150                               const UnresolvedSetImpl &Fns,
12151                               Expr *Input, bool PerformADL) {
12152   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12153   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12154   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12155   // TODO: provide better source location info.
12156   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12157
12158   if (checkPlaceholderForOverload(*this, Input))
12159     return ExprError();
12160
12161   Expr *Args[2] = { Input, nullptr };
12162   unsigned NumArgs = 1;
12163
12164   // For post-increment and post-decrement, add the implicit '0' as
12165   // the second argument, so that we know this is a post-increment or
12166   // post-decrement.
12167   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12168     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12169     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12170                                      SourceLocation());
12171     NumArgs = 2;
12172   }
12173
12174   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12175
12176   if (Input->isTypeDependent()) {
12177     if (Fns.empty())
12178       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12179                                          VK_RValue, OK_Ordinary, OpLoc, false);
12180
12181     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12182     UnresolvedLookupExpr *Fn
12183       = UnresolvedLookupExpr::Create(Context, NamingClass,
12184                                      NestedNameSpecifierLoc(), OpNameInfo,
12185                                      /*ADL*/ true, IsOverloaded(Fns),
12186                                      Fns.begin(), Fns.end());
12187     return new (Context)
12188         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12189                             VK_RValue, OpLoc, FPOptions());
12190   }
12191
12192   // Build an empty overload set.
12193   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12194
12195   // Add the candidates from the given function set.
12196   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12197
12198   // Add operator candidates that are member functions.
12199   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12200
12201   // Add candidates from ADL.
12202   if (PerformADL) {
12203     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12204                                          /*ExplicitTemplateArgs*/nullptr,
12205                                          CandidateSet);
12206   }
12207
12208   // Add builtin operator candidates.
12209   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12210
12211   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12212
12213   // Perform overload resolution.
12214   OverloadCandidateSet::iterator Best;
12215   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12216   case OR_Success: {
12217     // We found a built-in operator or an overloaded operator.
12218     FunctionDecl *FnDecl = Best->Function;
12219
12220     if (FnDecl) {
12221       Expr *Base = nullptr;
12222       // We matched an overloaded operator. Build a call to that
12223       // operator.
12224
12225       // Convert the arguments.
12226       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12227         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12228
12229         ExprResult InputRes =
12230           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12231                                               Best->FoundDecl, Method);
12232         if (InputRes.isInvalid())
12233           return ExprError();
12234         Base = Input = InputRes.get();
12235       } else {
12236         // Convert the arguments.
12237         ExprResult InputInit
12238           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12239                                                       Context,
12240                                                       FnDecl->getParamDecl(0)),
12241                                       SourceLocation(),
12242                                       Input);
12243         if (InputInit.isInvalid())
12244           return ExprError();
12245         Input = InputInit.get();
12246       }
12247
12248       // Build the actual expression node.
12249       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12250                                                 Base, HadMultipleCandidates,
12251                                                 OpLoc);
12252       if (FnExpr.isInvalid())
12253         return ExprError();
12254
12255       // Determine the result type.
12256       QualType ResultTy = FnDecl->getReturnType();
12257       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12258       ResultTy = ResultTy.getNonLValueExprType(Context);
12259
12260       Args[0] = Input;
12261       CallExpr *TheCall =
12262         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12263                                           ResultTy, VK, OpLoc, FPOptions());
12264
12265       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12266         return ExprError();
12267
12268       if (CheckFunctionCall(FnDecl, TheCall,
12269                             FnDecl->getType()->castAs<FunctionProtoType>()))
12270         return ExprError();
12271
12272       return MaybeBindToTemporary(TheCall);
12273     } else {
12274       // We matched a built-in operator. Convert the arguments, then
12275       // break out so that we will build the appropriate built-in
12276       // operator node.
12277       ExprResult InputRes = PerformImplicitConversion(
12278           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12279           CCK_ForBuiltinOverloadedOp);
12280       if (InputRes.isInvalid())
12281         return ExprError();
12282       Input = InputRes.get();
12283       break;
12284     }
12285   }
12286
12287   case OR_No_Viable_Function:
12288     // This is an erroneous use of an operator which can be overloaded by
12289     // a non-member function. Check for non-member operators which were
12290     // defined too late to be candidates.
12291     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12292       // FIXME: Recover by calling the found function.
12293       return ExprError();
12294
12295     // No viable function; fall through to handling this as a
12296     // built-in operator, which will produce an error message for us.
12297     break;
12298
12299   case OR_Ambiguous:
12300     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12301         << UnaryOperator::getOpcodeStr(Opc)
12302         << Input->getType()
12303         << Input->getSourceRange();
12304     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12305                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12306     return ExprError();
12307
12308   case OR_Deleted:
12309     Diag(OpLoc, diag::err_ovl_deleted_oper)
12310       << Best->Function->isDeleted()
12311       << UnaryOperator::getOpcodeStr(Opc)
12312       << getDeletedOrUnavailableSuffix(Best->Function)
12313       << Input->getSourceRange();
12314     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12315                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12316     return ExprError();
12317   }
12318
12319   // Either we found no viable overloaded operator or we matched a
12320   // built-in operator. In either case, fall through to trying to
12321   // build a built-in operation.
12322   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12323 }
12324
12325 /// Create a binary operation that may resolve to an overloaded
12326 /// operator.
12327 ///
12328 /// \param OpLoc The location of the operator itself (e.g., '+').
12329 ///
12330 /// \param Opc The BinaryOperatorKind that describes this operator.
12331 ///
12332 /// \param Fns The set of non-member functions that will be
12333 /// considered by overload resolution. The caller needs to build this
12334 /// set based on the context using, e.g.,
12335 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12336 /// set should not contain any member functions; those will be added
12337 /// by CreateOverloadedBinOp().
12338 ///
12339 /// \param LHS Left-hand argument.
12340 /// \param RHS Right-hand argument.
12341 ExprResult
12342 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12343                             BinaryOperatorKind Opc,
12344                             const UnresolvedSetImpl &Fns,
12345                             Expr *LHS, Expr *RHS, bool PerformADL) {
12346   Expr *Args[2] = { LHS, RHS };
12347   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12348
12349   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12350   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12351
12352   // If either side is type-dependent, create an appropriate dependent
12353   // expression.
12354   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12355     if (Fns.empty()) {
12356       // If there are no functions to store, just build a dependent
12357       // BinaryOperator or CompoundAssignment.
12358       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12359         return new (Context) BinaryOperator(
12360             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12361             OpLoc, FPFeatures);
12362
12363       return new (Context) CompoundAssignOperator(
12364           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12365           Context.DependentTy, Context.DependentTy, OpLoc,
12366           FPFeatures);
12367     }
12368
12369     // FIXME: save results of ADL from here?
12370     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12371     // TODO: provide better source location info in DNLoc component.
12372     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12373     UnresolvedLookupExpr *Fn
12374       = UnresolvedLookupExpr::Create(Context, NamingClass,
12375                                      NestedNameSpecifierLoc(), OpNameInfo,
12376                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12377                                      Fns.begin(), Fns.end());
12378     return new (Context)
12379         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12380                             VK_RValue, OpLoc, FPFeatures);
12381   }
12382
12383   // Always do placeholder-like conversions on the RHS.
12384   if (checkPlaceholderForOverload(*this, Args[1]))
12385     return ExprError();
12386
12387   // Do placeholder-like conversion on the LHS; note that we should
12388   // not get here with a PseudoObject LHS.
12389   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12390   if (checkPlaceholderForOverload(*this, Args[0]))
12391     return ExprError();
12392
12393   // If this is the assignment operator, we only perform overload resolution
12394   // if the left-hand side is a class or enumeration type. This is actually
12395   // a hack. The standard requires that we do overload resolution between the
12396   // various built-in candidates, but as DR507 points out, this can lead to
12397   // problems. So we do it this way, which pretty much follows what GCC does.
12398   // Note that we go the traditional code path for compound assignment forms.
12399   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12400     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12401
12402   // If this is the .* operator, which is not overloadable, just
12403   // create a built-in binary operator.
12404   if (Opc == BO_PtrMemD)
12405     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12406
12407   // Build an empty overload set.
12408   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12409
12410   // Add the candidates from the given function set.
12411   AddFunctionCandidates(Fns, Args, CandidateSet);
12412
12413   // Add operator candidates that are member functions.
12414   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12415
12416   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12417   // performed for an assignment operator (nor for operator[] nor operator->,
12418   // which don't get here).
12419   if (Opc != BO_Assign && PerformADL)
12420     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12421                                          /*ExplicitTemplateArgs*/ nullptr,
12422                                          CandidateSet);
12423
12424   // Add builtin operator candidates.
12425   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12426
12427   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12428
12429   // Perform overload resolution.
12430   OverloadCandidateSet::iterator Best;
12431   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12432     case OR_Success: {
12433       // We found a built-in operator or an overloaded operator.
12434       FunctionDecl *FnDecl = Best->Function;
12435
12436       if (FnDecl) {
12437         Expr *Base = nullptr;
12438         // We matched an overloaded operator. Build a call to that
12439         // operator.
12440
12441         // Convert the arguments.
12442         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12443           // Best->Access is only meaningful for class members.
12444           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12445
12446           ExprResult Arg1 =
12447             PerformCopyInitialization(
12448               InitializedEntity::InitializeParameter(Context,
12449                                                      FnDecl->getParamDecl(0)),
12450               SourceLocation(), Args[1]);
12451           if (Arg1.isInvalid())
12452             return ExprError();
12453
12454           ExprResult Arg0 =
12455             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12456                                                 Best->FoundDecl, Method);
12457           if (Arg0.isInvalid())
12458             return ExprError();
12459           Base = Args[0] = Arg0.getAs<Expr>();
12460           Args[1] = RHS = Arg1.getAs<Expr>();
12461         } else {
12462           // Convert the arguments.
12463           ExprResult Arg0 = PerformCopyInitialization(
12464             InitializedEntity::InitializeParameter(Context,
12465                                                    FnDecl->getParamDecl(0)),
12466             SourceLocation(), Args[0]);
12467           if (Arg0.isInvalid())
12468             return ExprError();
12469
12470           ExprResult Arg1 =
12471             PerformCopyInitialization(
12472               InitializedEntity::InitializeParameter(Context,
12473                                                      FnDecl->getParamDecl(1)),
12474               SourceLocation(), Args[1]);
12475           if (Arg1.isInvalid())
12476             return ExprError();
12477           Args[0] = LHS = Arg0.getAs<Expr>();
12478           Args[1] = RHS = Arg1.getAs<Expr>();
12479         }
12480
12481         // Build the actual expression node.
12482         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12483                                                   Best->FoundDecl, Base,
12484                                                   HadMultipleCandidates, OpLoc);
12485         if (FnExpr.isInvalid())
12486           return ExprError();
12487
12488         // Determine the result type.
12489         QualType ResultTy = FnDecl->getReturnType();
12490         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12491         ResultTy = ResultTy.getNonLValueExprType(Context);
12492
12493         CXXOperatorCallExpr *TheCall =
12494           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12495                                             Args, ResultTy, VK, OpLoc,
12496                                             FPFeatures);
12497
12498         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12499                                 FnDecl))
12500           return ExprError();
12501
12502         ArrayRef<const Expr *> ArgsArray(Args, 2);
12503         const Expr *ImplicitThis = nullptr;
12504         // Cut off the implicit 'this'.
12505         if (isa<CXXMethodDecl>(FnDecl)) {
12506           ImplicitThis = ArgsArray[0];
12507           ArgsArray = ArgsArray.slice(1);
12508         }
12509
12510         // Check for a self move.
12511         if (Op == OO_Equal)
12512           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12513
12514         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12515                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12516                   VariadicDoesNotApply);
12517
12518         return MaybeBindToTemporary(TheCall);
12519       } else {
12520         // We matched a built-in operator. Convert the arguments, then
12521         // break out so that we will build the appropriate built-in
12522         // operator node.
12523         ExprResult ArgsRes0 = PerformImplicitConversion(
12524             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12525             AA_Passing, CCK_ForBuiltinOverloadedOp);
12526         if (ArgsRes0.isInvalid())
12527           return ExprError();
12528         Args[0] = ArgsRes0.get();
12529
12530         ExprResult ArgsRes1 = PerformImplicitConversion(
12531             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12532             AA_Passing, CCK_ForBuiltinOverloadedOp);
12533         if (ArgsRes1.isInvalid())
12534           return ExprError();
12535         Args[1] = ArgsRes1.get();
12536         break;
12537       }
12538     }
12539
12540     case OR_No_Viable_Function: {
12541       // C++ [over.match.oper]p9:
12542       //   If the operator is the operator , [...] and there are no
12543       //   viable functions, then the operator is assumed to be the
12544       //   built-in operator and interpreted according to clause 5.
12545       if (Opc == BO_Comma)
12546         break;
12547
12548       // For class as left operand for assignment or compound assignment
12549       // operator do not fall through to handling in built-in, but report that
12550       // no overloaded assignment operator found
12551       ExprResult Result = ExprError();
12552       if (Args[0]->getType()->isRecordType() &&
12553           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12554         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12555              << BinaryOperator::getOpcodeStr(Opc)
12556              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12557         if (Args[0]->getType()->isIncompleteType()) {
12558           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12559             << Args[0]->getType()
12560             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12561         }
12562       } else {
12563         // This is an erroneous use of an operator which can be overloaded by
12564         // a non-member function. Check for non-member operators which were
12565         // defined too late to be candidates.
12566         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12567           // FIXME: Recover by calling the found function.
12568           return ExprError();
12569
12570         // No viable function; try to create a built-in operation, which will
12571         // produce an error. Then, show the non-viable candidates.
12572         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12573       }
12574       assert(Result.isInvalid() &&
12575              "C++ binary operator overloading is missing candidates!");
12576       if (Result.isInvalid())
12577         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12578                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12579       return Result;
12580     }
12581
12582     case OR_Ambiguous:
12583       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12584           << BinaryOperator::getOpcodeStr(Opc)
12585           << Args[0]->getType() << Args[1]->getType()
12586           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12587       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12588                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12589       return ExprError();
12590
12591     case OR_Deleted:
12592       if (isImplicitlyDeleted(Best->Function)) {
12593         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12594         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12595           << Context.getRecordType(Method->getParent())
12596           << getSpecialMember(Method);
12597
12598         // The user probably meant to call this special member. Just
12599         // explain why it's deleted.
12600         NoteDeletedFunction(Method);
12601         return ExprError();
12602       } else {
12603         Diag(OpLoc, diag::err_ovl_deleted_oper)
12604           << Best->Function->isDeleted()
12605           << BinaryOperator::getOpcodeStr(Opc)
12606           << getDeletedOrUnavailableSuffix(Best->Function)
12607           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12608       }
12609       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12610                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12611       return ExprError();
12612   }
12613
12614   // We matched a built-in operator; build it.
12615   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12616 }
12617
12618 ExprResult
12619 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12620                                          SourceLocation RLoc,
12621                                          Expr *Base, Expr *Idx) {
12622   Expr *Args[2] = { Base, Idx };
12623   DeclarationName OpName =
12624       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12625
12626   // If either side is type-dependent, create an appropriate dependent
12627   // expression.
12628   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12629
12630     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12631     // CHECKME: no 'operator' keyword?
12632     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12633     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12634     UnresolvedLookupExpr *Fn
12635       = UnresolvedLookupExpr::Create(Context, NamingClass,
12636                                      NestedNameSpecifierLoc(), OpNameInfo,
12637                                      /*ADL*/ true, /*Overloaded*/ false,
12638                                      UnresolvedSetIterator(),
12639                                      UnresolvedSetIterator());
12640     // Can't add any actual overloads yet
12641
12642     return new (Context)
12643         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12644                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12645   }
12646
12647   // Handle placeholders on both operands.
12648   if (checkPlaceholderForOverload(*this, Args[0]))
12649     return ExprError();
12650   if (checkPlaceholderForOverload(*this, Args[1]))
12651     return ExprError();
12652
12653   // Build an empty overload set.
12654   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12655
12656   // Subscript can only be overloaded as a member function.
12657
12658   // Add operator candidates that are member functions.
12659   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12660
12661   // Add builtin operator candidates.
12662   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12663
12664   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12665
12666   // Perform overload resolution.
12667   OverloadCandidateSet::iterator Best;
12668   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12669     case OR_Success: {
12670       // We found a built-in operator or an overloaded operator.
12671       FunctionDecl *FnDecl = Best->Function;
12672
12673       if (FnDecl) {
12674         // We matched an overloaded operator. Build a call to that
12675         // operator.
12676
12677         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12678
12679         // Convert the arguments.
12680         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12681         ExprResult Arg0 =
12682           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12683                                               Best->FoundDecl, Method);
12684         if (Arg0.isInvalid())
12685           return ExprError();
12686         Args[0] = Arg0.get();
12687
12688         // Convert the arguments.
12689         ExprResult InputInit
12690           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12691                                                       Context,
12692                                                       FnDecl->getParamDecl(0)),
12693                                       SourceLocation(),
12694                                       Args[1]);
12695         if (InputInit.isInvalid())
12696           return ExprError();
12697
12698         Args[1] = InputInit.getAs<Expr>();
12699
12700         // Build the actual expression node.
12701         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12702         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12703         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12704                                                   Best->FoundDecl,
12705                                                   Base,
12706                                                   HadMultipleCandidates,
12707                                                   OpLocInfo.getLoc(),
12708                                                   OpLocInfo.getInfo());
12709         if (FnExpr.isInvalid())
12710           return ExprError();
12711
12712         // Determine the result type
12713         QualType ResultTy = FnDecl->getReturnType();
12714         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12715         ResultTy = ResultTy.getNonLValueExprType(Context);
12716
12717         CXXOperatorCallExpr *TheCall =
12718           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12719                                             FnExpr.get(), Args,
12720                                             ResultTy, VK, RLoc,
12721                                             FPOptions());
12722
12723         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12724           return ExprError();
12725
12726         if (CheckFunctionCall(Method, TheCall,
12727                               Method->getType()->castAs<FunctionProtoType>()))
12728           return ExprError();
12729
12730         return MaybeBindToTemporary(TheCall);
12731       } else {
12732         // We matched a built-in operator. Convert the arguments, then
12733         // break out so that we will build the appropriate built-in
12734         // operator node.
12735         ExprResult ArgsRes0 = PerformImplicitConversion(
12736             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12737             AA_Passing, CCK_ForBuiltinOverloadedOp);
12738         if (ArgsRes0.isInvalid())
12739           return ExprError();
12740         Args[0] = ArgsRes0.get();
12741
12742         ExprResult ArgsRes1 = PerformImplicitConversion(
12743             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12744             AA_Passing, CCK_ForBuiltinOverloadedOp);
12745         if (ArgsRes1.isInvalid())
12746           return ExprError();
12747         Args[1] = ArgsRes1.get();
12748
12749         break;
12750       }
12751     }
12752
12753     case OR_No_Viable_Function: {
12754       if (CandidateSet.empty())
12755         Diag(LLoc, diag::err_ovl_no_oper)
12756           << Args[0]->getType() << /*subscript*/ 0
12757           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12758       else
12759         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12760           << Args[0]->getType()
12761           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12762       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12763                                   "[]", LLoc);
12764       return ExprError();
12765     }
12766
12767     case OR_Ambiguous:
12768       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12769           << "[]"
12770           << Args[0]->getType() << Args[1]->getType()
12771           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12772       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12773                                   "[]", LLoc);
12774       return ExprError();
12775
12776     case OR_Deleted:
12777       Diag(LLoc, diag::err_ovl_deleted_oper)
12778         << Best->Function->isDeleted() << "[]"
12779         << getDeletedOrUnavailableSuffix(Best->Function)
12780         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12781       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12782                                   "[]", LLoc);
12783       return ExprError();
12784     }
12785
12786   // We matched a built-in operator; build it.
12787   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12788 }
12789
12790 /// BuildCallToMemberFunction - Build a call to a member
12791 /// function. MemExpr is the expression that refers to the member
12792 /// function (and includes the object parameter), Args/NumArgs are the
12793 /// arguments to the function call (not including the object
12794 /// parameter). The caller needs to validate that the member
12795 /// expression refers to a non-static member function or an overloaded
12796 /// member function.
12797 ExprResult
12798 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12799                                 SourceLocation LParenLoc,
12800                                 MultiExprArg Args,
12801                                 SourceLocation RParenLoc) {
12802   assert(MemExprE->getType() == Context.BoundMemberTy ||
12803          MemExprE->getType() == Context.OverloadTy);
12804
12805   // Dig out the member expression. This holds both the object
12806   // argument and the member function we're referring to.
12807   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12808
12809   // Determine whether this is a call to a pointer-to-member function.
12810   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12811     assert(op->getType() == Context.BoundMemberTy);
12812     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12813
12814     QualType fnType =
12815       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12816
12817     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12818     QualType resultType = proto->getCallResultType(Context);
12819     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12820
12821     // Check that the object type isn't more qualified than the
12822     // member function we're calling.
12823     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12824
12825     QualType objectType = op->getLHS()->getType();
12826     if (op->getOpcode() == BO_PtrMemI)
12827       objectType = objectType->castAs<PointerType>()->getPointeeType();
12828     Qualifiers objectQuals = objectType.getQualifiers();
12829
12830     Qualifiers difference = objectQuals - funcQuals;
12831     difference.removeObjCGCAttr();
12832     difference.removeAddressSpace();
12833     if (difference) {
12834       std::string qualsString = difference.getAsString();
12835       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12836         << fnType.getUnqualifiedType()
12837         << qualsString
12838         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12839     }
12840
12841     CXXMemberCallExpr *call
12842       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12843                                         resultType, valueKind, RParenLoc);
12844
12845     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12846                             call, nullptr))
12847       return ExprError();
12848
12849     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12850       return ExprError();
12851
12852     if (CheckOtherCall(call, proto))
12853       return ExprError();
12854
12855     return MaybeBindToTemporary(call);
12856   }
12857
12858   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12859     return new (Context)
12860         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12861
12862   UnbridgedCastsSet UnbridgedCasts;
12863   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12864     return ExprError();
12865
12866   MemberExpr *MemExpr;
12867   CXXMethodDecl *Method = nullptr;
12868   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12869   NestedNameSpecifier *Qualifier = nullptr;
12870   if (isa<MemberExpr>(NakedMemExpr)) {
12871     MemExpr = cast<MemberExpr>(NakedMemExpr);
12872     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12873     FoundDecl = MemExpr->getFoundDecl();
12874     Qualifier = MemExpr->getQualifier();
12875     UnbridgedCasts.restore();
12876   } else {
12877     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12878     Qualifier = UnresExpr->getQualifier();
12879
12880     QualType ObjectType = UnresExpr->getBaseType();
12881     Expr::Classification ObjectClassification
12882       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12883                             : UnresExpr->getBase()->Classify(Context);
12884
12885     // Add overload candidates
12886     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12887                                       OverloadCandidateSet::CSK_Normal);
12888
12889     // FIXME: avoid copy.
12890     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12891     if (UnresExpr->hasExplicitTemplateArgs()) {
12892       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12893       TemplateArgs = &TemplateArgsBuffer;
12894     }
12895
12896     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12897            E = UnresExpr->decls_end(); I != E; ++I) {
12898
12899       NamedDecl *Func = *I;
12900       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12901       if (isa<UsingShadowDecl>(Func))
12902         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12903
12904
12905       // Microsoft supports direct constructor calls.
12906       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12907         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12908                              Args, CandidateSet);
12909       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12910         // If explicit template arguments were provided, we can't call a
12911         // non-template member function.
12912         if (TemplateArgs)
12913           continue;
12914
12915         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12916                            ObjectClassification, Args, CandidateSet,
12917                            /*SuppressUserConversions=*/false);
12918       } else {
12919         AddMethodTemplateCandidate(
12920             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12921             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12922             /*SuppressUsedConversions=*/false);
12923       }
12924     }
12925
12926     DeclarationName DeclName = UnresExpr->getMemberName();
12927
12928     UnbridgedCasts.restore();
12929
12930     OverloadCandidateSet::iterator Best;
12931     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12932                                             Best)) {
12933     case OR_Success:
12934       Method = cast<CXXMethodDecl>(Best->Function);
12935       FoundDecl = Best->FoundDecl;
12936       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12937       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12938         return ExprError();
12939       // If FoundDecl is different from Method (such as if one is a template
12940       // and the other a specialization), make sure DiagnoseUseOfDecl is
12941       // called on both.
12942       // FIXME: This would be more comprehensively addressed by modifying
12943       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12944       // being used.
12945       if (Method != FoundDecl.getDecl() &&
12946                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12947         return ExprError();
12948       break;
12949
12950     case OR_No_Viable_Function:
12951       Diag(UnresExpr->getMemberLoc(),
12952            diag::err_ovl_no_viable_member_function_in_call)
12953         << DeclName << MemExprE->getSourceRange();
12954       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12955       // FIXME: Leaking incoming expressions!
12956       return ExprError();
12957
12958     case OR_Ambiguous:
12959       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12960         << DeclName << MemExprE->getSourceRange();
12961       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12962       // FIXME: Leaking incoming expressions!
12963       return ExprError();
12964
12965     case OR_Deleted:
12966       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12967         << Best->Function->isDeleted()
12968         << DeclName
12969         << getDeletedOrUnavailableSuffix(Best->Function)
12970         << MemExprE->getSourceRange();
12971       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12972       // FIXME: Leaking incoming expressions!
12973       return ExprError();
12974     }
12975
12976     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12977
12978     // If overload resolution picked a static member, build a
12979     // non-member call based on that function.
12980     if (Method->isStatic()) {
12981       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12982                                    RParenLoc);
12983     }
12984
12985     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12986   }
12987
12988   QualType ResultType = Method->getReturnType();
12989   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12990   ResultType = ResultType.getNonLValueExprType(Context);
12991
12992   assert(Method && "Member call to something that isn't a method?");
12993   CXXMemberCallExpr *TheCall =
12994     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12995                                     ResultType, VK, RParenLoc);
12996
12997   // Check for a valid return type.
12998   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12999                           TheCall, Method))
13000     return ExprError();
13001
13002   // Convert the object argument (for a non-static member function call).
13003   // We only need to do this if there was actually an overload; otherwise
13004   // it was done at lookup.
13005   if (!Method->isStatic()) {
13006     ExprResult ObjectArg =
13007       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13008                                           FoundDecl, Method);
13009     if (ObjectArg.isInvalid())
13010       return ExprError();
13011     MemExpr->setBase(ObjectArg.get());
13012   }
13013
13014   // Convert the rest of the arguments
13015   const FunctionProtoType *Proto =
13016     Method->getType()->getAs<FunctionProtoType>();
13017   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13018                               RParenLoc))
13019     return ExprError();
13020
13021   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13022
13023   if (CheckFunctionCall(Method, TheCall, Proto))
13024     return ExprError();
13025
13026   // In the case the method to call was not selected by the overloading
13027   // resolution process, we still need to handle the enable_if attribute. Do
13028   // that here, so it will not hide previous -- and more relevant -- errors.
13029   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13030     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13031       Diag(MemE->getMemberLoc(),
13032            diag::err_ovl_no_viable_member_function_in_call)
13033           << Method << Method->getSourceRange();
13034       Diag(Method->getLocation(),
13035            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13036           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13037       return ExprError();
13038     }
13039   }
13040
13041   if ((isa<CXXConstructorDecl>(CurContext) ||
13042        isa<CXXDestructorDecl>(CurContext)) &&
13043       TheCall->getMethodDecl()->isPure()) {
13044     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13045
13046     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13047         MemExpr->performsVirtualDispatch(getLangOpts())) {
13048       Diag(MemExpr->getLocStart(),
13049            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13050         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13051         << MD->getParent()->getDeclName();
13052
13053       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
13054       if (getLangOpts().AppleKext)
13055         Diag(MemExpr->getLocStart(),
13056              diag::note_pure_qualified_call_kext)
13057              << MD->getParent()->getDeclName()
13058              << MD->getDeclName();
13059     }
13060   }
13061
13062   if (CXXDestructorDecl *DD =
13063           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13064     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13065     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13066     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
13067                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13068                          MemExpr->getMemberLoc());
13069   }
13070
13071   return MaybeBindToTemporary(TheCall);
13072 }
13073
13074 /// BuildCallToObjectOfClassType - Build a call to an object of class
13075 /// type (C++ [over.call.object]), which can end up invoking an
13076 /// overloaded function call operator (@c operator()) or performing a
13077 /// user-defined conversion on the object argument.
13078 ExprResult
13079 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13080                                    SourceLocation LParenLoc,
13081                                    MultiExprArg Args,
13082                                    SourceLocation RParenLoc) {
13083   if (checkPlaceholderForOverload(*this, Obj))
13084     return ExprError();
13085   ExprResult Object = Obj;
13086
13087   UnbridgedCastsSet UnbridgedCasts;
13088   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13089     return ExprError();
13090
13091   assert(Object.get()->getType()->isRecordType() &&
13092          "Requires object type argument");
13093   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13094
13095   // C++ [over.call.object]p1:
13096   //  If the primary-expression E in the function call syntax
13097   //  evaluates to a class object of type "cv T", then the set of
13098   //  candidate functions includes at least the function call
13099   //  operators of T. The function call operators of T are obtained by
13100   //  ordinary lookup of the name operator() in the context of
13101   //  (E).operator().
13102   OverloadCandidateSet CandidateSet(LParenLoc,
13103                                     OverloadCandidateSet::CSK_Operator);
13104   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13105
13106   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13107                           diag::err_incomplete_object_call, Object.get()))
13108     return true;
13109
13110   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13111   LookupQualifiedName(R, Record->getDecl());
13112   R.suppressDiagnostics();
13113
13114   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13115        Oper != OperEnd; ++Oper) {
13116     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13117                        Object.get()->Classify(Context), Args, CandidateSet,
13118                        /*SuppressUserConversions=*/false);
13119   }
13120
13121   // C++ [over.call.object]p2:
13122   //   In addition, for each (non-explicit in C++0x) conversion function
13123   //   declared in T of the form
13124   //
13125   //        operator conversion-type-id () cv-qualifier;
13126   //
13127   //   where cv-qualifier is the same cv-qualification as, or a
13128   //   greater cv-qualification than, cv, and where conversion-type-id
13129   //   denotes the type "pointer to function of (P1,...,Pn) returning
13130   //   R", or the type "reference to pointer to function of
13131   //   (P1,...,Pn) returning R", or the type "reference to function
13132   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13133   //   is also considered as a candidate function. Similarly,
13134   //   surrogate call functions are added to the set of candidate
13135   //   functions for each conversion function declared in an
13136   //   accessible base class provided the function is not hidden
13137   //   within T by another intervening declaration.
13138   const auto &Conversions =
13139       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13140   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13141     NamedDecl *D = *I;
13142     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13143     if (isa<UsingShadowDecl>(D))
13144       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13145
13146     // Skip over templated conversion functions; they aren't
13147     // surrogates.
13148     if (isa<FunctionTemplateDecl>(D))
13149       continue;
13150
13151     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13152     if (!Conv->isExplicit()) {
13153       // Strip the reference type (if any) and then the pointer type (if
13154       // any) to get down to what might be a function type.
13155       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13156       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13157         ConvType = ConvPtrType->getPointeeType();
13158
13159       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13160       {
13161         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13162                               Object.get(), Args, CandidateSet);
13163       }
13164     }
13165   }
13166
13167   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13168
13169   // Perform overload resolution.
13170   OverloadCandidateSet::iterator Best;
13171   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13172                                           Best)) {
13173   case OR_Success:
13174     // Overload resolution succeeded; we'll build the appropriate call
13175     // below.
13176     break;
13177
13178   case OR_No_Viable_Function:
13179     if (CandidateSet.empty())
13180       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13181         << Object.get()->getType() << /*call*/ 1
13182         << Object.get()->getSourceRange();
13183     else
13184       Diag(Object.get()->getLocStart(),
13185            diag::err_ovl_no_viable_object_call)
13186         << Object.get()->getType() << Object.get()->getSourceRange();
13187     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13188     break;
13189
13190   case OR_Ambiguous:
13191     Diag(Object.get()->getLocStart(),
13192          diag::err_ovl_ambiguous_object_call)
13193       << Object.get()->getType() << Object.get()->getSourceRange();
13194     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13195     break;
13196
13197   case OR_Deleted:
13198     Diag(Object.get()->getLocStart(),
13199          diag::err_ovl_deleted_object_call)
13200       << Best->Function->isDeleted()
13201       << Object.get()->getType()
13202       << getDeletedOrUnavailableSuffix(Best->Function)
13203       << Object.get()->getSourceRange();
13204     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13205     break;
13206   }
13207
13208   if (Best == CandidateSet.end())
13209     return true;
13210
13211   UnbridgedCasts.restore();
13212
13213   if (Best->Function == nullptr) {
13214     // Since there is no function declaration, this is one of the
13215     // surrogate candidates. Dig out the conversion function.
13216     CXXConversionDecl *Conv
13217       = cast<CXXConversionDecl>(
13218                          Best->Conversions[0].UserDefined.ConversionFunction);
13219
13220     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13221                               Best->FoundDecl);
13222     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13223       return ExprError();
13224     assert(Conv == Best->FoundDecl.getDecl() &&
13225              "Found Decl & conversion-to-functionptr should be same, right?!");
13226     // We selected one of the surrogate functions that converts the
13227     // object parameter to a function pointer. Perform the conversion
13228     // on the object argument, then let ActOnCallExpr finish the job.
13229
13230     // Create an implicit member expr to refer to the conversion operator.
13231     // and then call it.
13232     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13233                                              Conv, HadMultipleCandidates);
13234     if (Call.isInvalid())
13235       return ExprError();
13236     // Record usage of conversion in an implicit cast.
13237     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13238                                     CK_UserDefinedConversion, Call.get(),
13239                                     nullptr, VK_RValue);
13240
13241     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13242   }
13243
13244   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13245
13246   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13247   // that calls this method, using Object for the implicit object
13248   // parameter and passing along the remaining arguments.
13249   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13250
13251   // An error diagnostic has already been printed when parsing the declaration.
13252   if (Method->isInvalidDecl())
13253     return ExprError();
13254
13255   const FunctionProtoType *Proto =
13256     Method->getType()->getAs<FunctionProtoType>();
13257
13258   unsigned NumParams = Proto->getNumParams();
13259
13260   DeclarationNameInfo OpLocInfo(
13261                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13262   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13263   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13264                                            Obj, HadMultipleCandidates,
13265                                            OpLocInfo.getLoc(),
13266                                            OpLocInfo.getInfo());
13267   if (NewFn.isInvalid())
13268     return true;
13269
13270   // Build the full argument list for the method call (the implicit object
13271   // parameter is placed at the beginning of the list).
13272   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13273   MethodArgs[0] = Object.get();
13274   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13275
13276   // Once we've built TheCall, all of the expressions are properly
13277   // owned.
13278   QualType ResultTy = Method->getReturnType();
13279   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13280   ResultTy = ResultTy.getNonLValueExprType(Context);
13281
13282   CXXOperatorCallExpr *TheCall = new (Context)
13283       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13284                           VK, RParenLoc, FPOptions());
13285
13286   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13287     return true;
13288
13289   // We may have default arguments. If so, we need to allocate more
13290   // slots in the call for them.
13291   if (Args.size() < NumParams)
13292     TheCall->setNumArgs(Context, NumParams + 1);
13293
13294   bool IsError = false;
13295
13296   // Initialize the implicit object parameter.
13297   ExprResult ObjRes =
13298     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13299                                         Best->FoundDecl, Method);
13300   if (ObjRes.isInvalid())
13301     IsError = true;
13302   else
13303     Object = ObjRes;
13304   TheCall->setArg(0, Object.get());
13305
13306   // Check the argument types.
13307   for (unsigned i = 0; i != NumParams; i++) {
13308     Expr *Arg;
13309     if (i < Args.size()) {
13310       Arg = Args[i];
13311
13312       // Pass the argument.
13313
13314       ExprResult InputInit
13315         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13316                                                     Context,
13317                                                     Method->getParamDecl(i)),
13318                                     SourceLocation(), Arg);
13319
13320       IsError |= InputInit.isInvalid();
13321       Arg = InputInit.getAs<Expr>();
13322     } else {
13323       ExprResult DefArg
13324         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13325       if (DefArg.isInvalid()) {
13326         IsError = true;
13327         break;
13328       }
13329
13330       Arg = DefArg.getAs<Expr>();
13331     }
13332
13333     TheCall->setArg(i + 1, Arg);
13334   }
13335
13336   // If this is a variadic call, handle args passed through "...".
13337   if (Proto->isVariadic()) {
13338     // Promote the arguments (C99 6.5.2.2p7).
13339     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13340       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13341                                                         nullptr);
13342       IsError |= Arg.isInvalid();
13343       TheCall->setArg(i + 1, Arg.get());
13344     }
13345   }
13346
13347   if (IsError) return true;
13348
13349   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13350
13351   if (CheckFunctionCall(Method, TheCall, Proto))
13352     return true;
13353
13354   return MaybeBindToTemporary(TheCall);
13355 }
13356
13357 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13358 ///  (if one exists), where @c Base is an expression of class type and
13359 /// @c Member is the name of the member we're trying to find.
13360 ExprResult
13361 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13362                                bool *NoArrowOperatorFound) {
13363   assert(Base->getType()->isRecordType() &&
13364          "left-hand side must have class type");
13365
13366   if (checkPlaceholderForOverload(*this, Base))
13367     return ExprError();
13368
13369   SourceLocation Loc = Base->getExprLoc();
13370
13371   // C++ [over.ref]p1:
13372   //
13373   //   [...] An expression x->m is interpreted as (x.operator->())->m
13374   //   for a class object x of type T if T::operator->() exists and if
13375   //   the operator is selected as the best match function by the
13376   //   overload resolution mechanism (13.3).
13377   DeclarationName OpName =
13378     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13379   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13380   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13381
13382   if (RequireCompleteType(Loc, Base->getType(),
13383                           diag::err_typecheck_incomplete_tag, Base))
13384     return ExprError();
13385
13386   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13387   LookupQualifiedName(R, BaseRecord->getDecl());
13388   R.suppressDiagnostics();
13389
13390   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13391        Oper != OperEnd; ++Oper) {
13392     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13393                        None, CandidateSet, /*SuppressUserConversions=*/false);
13394   }
13395
13396   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13397
13398   // Perform overload resolution.
13399   OverloadCandidateSet::iterator Best;
13400   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13401   case OR_Success:
13402     // Overload resolution succeeded; we'll build the call below.
13403     break;
13404
13405   case OR_No_Viable_Function:
13406     if (CandidateSet.empty()) {
13407       QualType BaseType = Base->getType();
13408       if (NoArrowOperatorFound) {
13409         // Report this specific error to the caller instead of emitting a
13410         // diagnostic, as requested.
13411         *NoArrowOperatorFound = true;
13412         return ExprError();
13413       }
13414       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13415         << BaseType << Base->getSourceRange();
13416       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13417         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13418           << FixItHint::CreateReplacement(OpLoc, ".");
13419       }
13420     } else
13421       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13422         << "operator->" << Base->getSourceRange();
13423     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13424     return ExprError();
13425
13426   case OR_Ambiguous:
13427     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13428       << "->" << Base->getType() << Base->getSourceRange();
13429     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13430     return ExprError();
13431
13432   case OR_Deleted:
13433     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13434       << Best->Function->isDeleted()
13435       << "->"
13436       << getDeletedOrUnavailableSuffix(Best->Function)
13437       << Base->getSourceRange();
13438     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13439     return ExprError();
13440   }
13441
13442   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13443
13444   // Convert the object parameter.
13445   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13446   ExprResult BaseResult =
13447     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13448                                         Best->FoundDecl, Method);
13449   if (BaseResult.isInvalid())
13450     return ExprError();
13451   Base = BaseResult.get();
13452
13453   // Build the operator call.
13454   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13455                                             Base, HadMultipleCandidates, OpLoc);
13456   if (FnExpr.isInvalid())
13457     return ExprError();
13458
13459   QualType ResultTy = Method->getReturnType();
13460   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13461   ResultTy = ResultTy.getNonLValueExprType(Context);
13462   CXXOperatorCallExpr *TheCall =
13463     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13464                                       Base, ResultTy, VK, OpLoc, FPOptions());
13465
13466   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13467     return ExprError();
13468
13469   if (CheckFunctionCall(Method, TheCall,
13470                         Method->getType()->castAs<FunctionProtoType>()))
13471     return ExprError();
13472
13473   return MaybeBindToTemporary(TheCall);
13474 }
13475
13476 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13477 /// a literal operator described by the provided lookup results.
13478 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13479                                           DeclarationNameInfo &SuffixInfo,
13480                                           ArrayRef<Expr*> Args,
13481                                           SourceLocation LitEndLoc,
13482                                        TemplateArgumentListInfo *TemplateArgs) {
13483   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13484
13485   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13486                                     OverloadCandidateSet::CSK_Normal);
13487   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13488                         /*SuppressUserConversions=*/true);
13489
13490   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13491
13492   // Perform overload resolution. This will usually be trivial, but might need
13493   // to perform substitutions for a literal operator template.
13494   OverloadCandidateSet::iterator Best;
13495   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13496   case OR_Success:
13497   case OR_Deleted:
13498     break;
13499
13500   case OR_No_Viable_Function:
13501     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13502       << R.getLookupName();
13503     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13504     return ExprError();
13505
13506   case OR_Ambiguous:
13507     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13508     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13509     return ExprError();
13510   }
13511
13512   FunctionDecl *FD = Best->Function;
13513   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13514                                         nullptr, HadMultipleCandidates,
13515                                         SuffixInfo.getLoc(),
13516                                         SuffixInfo.getInfo());
13517   if (Fn.isInvalid())
13518     return true;
13519
13520   // Check the argument types. This should almost always be a no-op, except
13521   // that array-to-pointer decay is applied to string literals.
13522   Expr *ConvArgs[2];
13523   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13524     ExprResult InputInit = PerformCopyInitialization(
13525       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13526       SourceLocation(), Args[ArgIdx]);
13527     if (InputInit.isInvalid())
13528       return true;
13529     ConvArgs[ArgIdx] = InputInit.get();
13530   }
13531
13532   QualType ResultTy = FD->getReturnType();
13533   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13534   ResultTy = ResultTy.getNonLValueExprType(Context);
13535
13536   UserDefinedLiteral *UDL =
13537     new (Context) UserDefinedLiteral(Context, Fn.get(),
13538                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13539                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13540
13541   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13542     return ExprError();
13543
13544   if (CheckFunctionCall(FD, UDL, nullptr))
13545     return ExprError();
13546
13547   return MaybeBindToTemporary(UDL);
13548 }
13549
13550 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13551 /// given LookupResult is non-empty, it is assumed to describe a member which
13552 /// will be invoked. Otherwise, the function will be found via argument
13553 /// dependent lookup.
13554 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13555 /// otherwise CallExpr is set to ExprError() and some non-success value
13556 /// is returned.
13557 Sema::ForRangeStatus
13558 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13559                                 SourceLocation RangeLoc,
13560                                 const DeclarationNameInfo &NameInfo,
13561                                 LookupResult &MemberLookup,
13562                                 OverloadCandidateSet *CandidateSet,
13563                                 Expr *Range, ExprResult *CallExpr) {
13564   Scope *S = nullptr;
13565
13566   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13567   if (!MemberLookup.empty()) {
13568     ExprResult MemberRef =
13569         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13570                                  /*IsPtr=*/false, CXXScopeSpec(),
13571                                  /*TemplateKWLoc=*/SourceLocation(),
13572                                  /*FirstQualifierInScope=*/nullptr,
13573                                  MemberLookup,
13574                                  /*TemplateArgs=*/nullptr, S);
13575     if (MemberRef.isInvalid()) {
13576       *CallExpr = ExprError();
13577       return FRS_DiagnosticIssued;
13578     }
13579     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13580     if (CallExpr->isInvalid()) {
13581       *CallExpr = ExprError();
13582       return FRS_DiagnosticIssued;
13583     }
13584   } else {
13585     UnresolvedSet<0> FoundNames;
13586     UnresolvedLookupExpr *Fn =
13587       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13588                                    NestedNameSpecifierLoc(), NameInfo,
13589                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13590                                    FoundNames.begin(), FoundNames.end());
13591
13592     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13593                                                     CandidateSet, CallExpr);
13594     if (CandidateSet->empty() || CandidateSetError) {
13595       *CallExpr = ExprError();
13596       return FRS_NoViableFunction;
13597     }
13598     OverloadCandidateSet::iterator Best;
13599     OverloadingResult OverloadResult =
13600         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13601
13602     if (OverloadResult == OR_No_Viable_Function) {
13603       *CallExpr = ExprError();
13604       return FRS_NoViableFunction;
13605     }
13606     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13607                                          Loc, nullptr, CandidateSet, &Best,
13608                                          OverloadResult,
13609                                          /*AllowTypoCorrection=*/false);
13610     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13611       *CallExpr = ExprError();
13612       return FRS_DiagnosticIssued;
13613     }
13614   }
13615   return FRS_Success;
13616 }
13617
13618
13619 /// FixOverloadedFunctionReference - E is an expression that refers to
13620 /// a C++ overloaded function (possibly with some parentheses and
13621 /// perhaps a '&' around it). We have resolved the overloaded function
13622 /// to the function declaration Fn, so patch up the expression E to
13623 /// refer (possibly indirectly) to Fn. Returns the new expr.
13624 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13625                                            FunctionDecl *Fn) {
13626   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13627     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13628                                                    Found, Fn);
13629     if (SubExpr == PE->getSubExpr())
13630       return PE;
13631
13632     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13633   }
13634
13635   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13636     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13637                                                    Found, Fn);
13638     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13639                                SubExpr->getType()) &&
13640            "Implicit cast type cannot be determined from overload");
13641     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13642     if (SubExpr == ICE->getSubExpr())
13643       return ICE;
13644
13645     return ImplicitCastExpr::Create(Context, ICE->getType(),
13646                                     ICE->getCastKind(),
13647                                     SubExpr, nullptr,
13648                                     ICE->getValueKind());
13649   }
13650
13651   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13652     if (!GSE->isResultDependent()) {
13653       Expr *SubExpr =
13654           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13655       if (SubExpr == GSE->getResultExpr())
13656         return GSE;
13657
13658       // Replace the resulting type information before rebuilding the generic
13659       // selection expression.
13660       ArrayRef<Expr *> A = GSE->getAssocExprs();
13661       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13662       unsigned ResultIdx = GSE->getResultIndex();
13663       AssocExprs[ResultIdx] = SubExpr;
13664
13665       return new (Context) GenericSelectionExpr(
13666           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13667           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13668           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13669           ResultIdx);
13670     }
13671     // Rather than fall through to the unreachable, return the original generic
13672     // selection expression.
13673     return GSE;
13674   }
13675
13676   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13677     assert(UnOp->getOpcode() == UO_AddrOf &&
13678            "Can only take the address of an overloaded function");
13679     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13680       if (Method->isStatic()) {
13681         // Do nothing: static member functions aren't any different
13682         // from non-member functions.
13683       } else {
13684         // Fix the subexpression, which really has to be an
13685         // UnresolvedLookupExpr holding an overloaded member function
13686         // or template.
13687         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13688                                                        Found, Fn);
13689         if (SubExpr == UnOp->getSubExpr())
13690           return UnOp;
13691
13692         assert(isa<DeclRefExpr>(SubExpr)
13693                && "fixed to something other than a decl ref");
13694         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13695                && "fixed to a member ref with no nested name qualifier");
13696
13697         // We have taken the address of a pointer to member
13698         // function. Perform the computation here so that we get the
13699         // appropriate pointer to member type.
13700         QualType ClassType
13701           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13702         QualType MemPtrType
13703           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13704         // Under the MS ABI, lock down the inheritance model now.
13705         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13706           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13707
13708         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13709                                            VK_RValue, OK_Ordinary,
13710                                            UnOp->getOperatorLoc(), false);
13711       }
13712     }
13713     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13714                                                    Found, Fn);
13715     if (SubExpr == UnOp->getSubExpr())
13716       return UnOp;
13717
13718     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13719                                      Context.getPointerType(SubExpr->getType()),
13720                                        VK_RValue, OK_Ordinary,
13721                                        UnOp->getOperatorLoc(), false);
13722   }
13723
13724   // C++ [except.spec]p17:
13725   //   An exception-specification is considered to be needed when:
13726   //   - in an expression the function is the unique lookup result or the
13727   //     selected member of a set of overloaded functions
13728   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13729     ResolveExceptionSpec(E->getExprLoc(), FPT);
13730
13731   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13732     // FIXME: avoid copy.
13733     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13734     if (ULE->hasExplicitTemplateArgs()) {
13735       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13736       TemplateArgs = &TemplateArgsBuffer;
13737     }
13738
13739     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13740                                            ULE->getQualifierLoc(),
13741                                            ULE->getTemplateKeywordLoc(),
13742                                            Fn,
13743                                            /*enclosing*/ false, // FIXME?
13744                                            ULE->getNameLoc(),
13745                                            Fn->getType(),
13746                                            VK_LValue,
13747                                            Found.getDecl(),
13748                                            TemplateArgs);
13749     MarkDeclRefReferenced(DRE);
13750     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13751     return DRE;
13752   }
13753
13754   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13755     // FIXME: avoid copy.
13756     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13757     if (MemExpr->hasExplicitTemplateArgs()) {
13758       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13759       TemplateArgs = &TemplateArgsBuffer;
13760     }
13761
13762     Expr *Base;
13763
13764     // If we're filling in a static method where we used to have an
13765     // implicit member access, rewrite to a simple decl ref.
13766     if (MemExpr->isImplicitAccess()) {
13767       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13768         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13769                                                MemExpr->getQualifierLoc(),
13770                                                MemExpr->getTemplateKeywordLoc(),
13771                                                Fn,
13772                                                /*enclosing*/ false,
13773                                                MemExpr->getMemberLoc(),
13774                                                Fn->getType(),
13775                                                VK_LValue,
13776                                                Found.getDecl(),
13777                                                TemplateArgs);
13778         MarkDeclRefReferenced(DRE);
13779         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13780         return DRE;
13781       } else {
13782         SourceLocation Loc = MemExpr->getMemberLoc();
13783         if (MemExpr->getQualifier())
13784           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13785         CheckCXXThisCapture(Loc);
13786         Base = new (Context) CXXThisExpr(Loc,
13787                                          MemExpr->getBaseType(),
13788                                          /*isImplicit=*/true);
13789       }
13790     } else
13791       Base = MemExpr->getBase();
13792
13793     ExprValueKind valueKind;
13794     QualType type;
13795     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13796       valueKind = VK_LValue;
13797       type = Fn->getType();
13798     } else {
13799       valueKind = VK_RValue;
13800       type = Context.BoundMemberTy;
13801     }
13802
13803     MemberExpr *ME = MemberExpr::Create(
13804         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13805         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13806         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13807         OK_Ordinary);
13808     ME->setHadMultipleCandidates(true);
13809     MarkMemberReferenced(ME);
13810     return ME;
13811   }
13812
13813   llvm_unreachable("Invalid reference to overloaded function");
13814 }
13815
13816 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13817                                                 DeclAccessPair Found,
13818                                                 FunctionDecl *Fn) {
13819   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13820 }